user1320502
user1320502

Reputation: 2570

binary operator error in `if` function

I wrote the following function:

x    <- 1:4
y    <- c(1,2,7,4)
mydf <- data.frame(a=x,b=x,c=x,d=x,y=y)

practice  <-  function(x) if( x[1] == x[5]) {

             foo <- (x[2])
             return(foo)

              } else {

              bar     <- x[3] + x[4]                
              foobar <- x[2] - bar

               return(foobar)
              }       

newmydf <- apply( mydf, 1, practice)

this works fine on the data.frame provided. However I have another data.frame and I keep getting

Error in x[3] + x[4] : non-numeric argument to binary operator

despite the following str()

'data.frame':   133 obs. of  19 variables:
 $  : chr   ...
 $ : int   ...
 $ : int  ...
 $ : int  ...
 $ : int   ...
 $ : int   ...
 $ : int   ...
 $ : int   ...
 $ : int  ...
 $ : int  ...
 $ : int   ...
 $ : int   ...
 $ : int  ...
 $ : int  ...
 $ : int   ...
 $ : int  ...
 $ : num  ...
 $ : int  
 $ : int  

What possible little slip ups can I be making? I have started with a new session and I still get the same issue.

Upvotes: 0

Views: 275

Answers (2)

nograpes
nograpes

Reputation: 18323

Another solution would be to use by:

# Put in a character to mydf to test
mydf$foo<-'a'
# Run by
by(mydf,seq(nrow(mydf)),practice)

Upvotes: 4

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

The values in the first column of second data frame are of type "character". As a result, the command apply turns the whole data frame into a character matrix. The operator + is not defined for character values.

There are two possible solutions:

  1. Transform the first column to type numeric (if possible):

    mydf[ , 1] <- as.numeric(mydf[ , 1])
    
  2. Do not use the first column of the data frame:

    apply(mydf[ , -1], 1, practice)
    

Upvotes: 6

Related Questions