R – mutate/transform in R dplyr (Pass custom function)

dplyrr

I am using the new package , dplyr and facing some difficulties.

mutate(df,isOdd=digit%%2) or transform(df,isOdd=digit%%2)

Both of which work perfectly.

I am asking a question on passing custom method.

IsItOdd <- function(x) {
  if(x%%2==0)
     result<-"even"
  else
     result<-"odd"
  return(result)
}

transform(df,isOdd=IsItOdd(digit))

This doesnt work because the whole column of all the digit is passed to the function.
Is there a way to make this work by just passing that one cell to the function instead of the whole column ?

Best Solution

With transform your function has to operate on the vector. You can use ifelse instead, which works on vectors:

 isOdd <- function(x){ ifelse(x %% 2 == 0, "even", "odd") }

Alternatively you can apply the function to every value in the column with one of the apply functions:

 isOdd <- function(x){
     sapply(x, function(x){
          if(x %% 2 == 0){
               return("even") 
          }else{
               return("odd") 
          }
     })}
Related Question