0

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.

2
  • Can you post the output of dput(head(mydf)) (or whatever the name of your data frame that's not working is?) Dec 3, 2012 at 16:27
  • If you send the data frame you've shown through apply, you will convert each row to a character vector because of the first column. Instead, run it with apply(mydf[, 2:length(mydf)], 1, practice).
    – Justin
    Dec 3, 2012 at 16:32

2 Answers 2

6

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)
    
2
  • Even better would probably be to turn the first column into rownames, usually the right choice for a data frame where every column except one is numeric. That would let you keep the column. Dec 3, 2012 at 16:34
  • wow I have used apply so many times and I never new that it. Thats a kicker. Thank you very much. Dec 3, 2012 at 16:36
4

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)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.