Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

r - "argument is of length zero" in if statement

I want to compute my data according to rule that number+W is number*2.

dat="1W   16   2W   16
      1   16   2W    0
     1W   16   16    0
      4   64   64    0"     
data=read.table(text=dat,header=F)
apply(data,c(1,2),function(y){
     if(grep(pattern="W",y) ==1 )
     {  gsub("W",paste("*",2,sep=""),y)->s;
         eval(parse(text=s));
      } else 
        {y <- y }
      })

But I get the output:

Error in if (grep(pattern = "W", y) == 1) { : argument is of length zero

Why? If y matches "W" then the value is 1, what is wrong with my code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your query can be illustrated with the following example:

grep(pattern="W","huh")
# integer(0)

No match results in a vector of length 0, hence the error. Instead use grepl, i.e. if( grepl( "W" , y ) ).

grepl has the return value TRUE or FALSE.

As a side note, eval( parse( "sometext" ) ) is variously thought of as not a good idea. You could try using the following untidy lapply statement instead (which will be better than apply because you don't have to convert to a matrix first):

data.frame( lapply( data , function(x) 
                                ifelse( grepl("W",x) , 
                                        as.integer( gsub("W","",x) ) * 2L , 
                                        x ) ) )
#  V1 V2 V3 V4
#1  2 16  4 16
#2  1 16  4  0
#3  2 16  1  0
#4  3 64  3  0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...