“argument is of length zero” in if statement

前端 未结 2 378
小鲜肉
小鲜肉 2021-01-17 01:48

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   6         


        
相关标签:
2条回答
  • 2021-01-17 02:17

    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
    
    0 讨论(0)
  • 2021-01-17 02:35

    Here's a rather bizarre approach, which does work just fine:

    library(sfsmisc)

    foo<- c('2','23', 'W4','W53','17')
    bar<-sapply(foo, function(x)AsciiToInt(x))
    barw<-sapply(bar,function(x)x[x!=87])
    bard<-logical(length(foo))
    for (i in 1:length(foo) ) bard[i]<-length(barw[[i]])== length(bar[[i]])
    
    foow<-vector()
    for(i in 1:length(foo)) foow[i]<-as.numeric(paste0(chars8bit(barw[[i]]),collapse='') ) *(1+!bard[i])
    
    0 讨论(0)
提交回复
热议问题