Mutate / transform in R dplyr (Pass custom function)

I am using the new dplyr package and am encountering some difficulties.

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

Both of them work great.

I ask a question about passing a custom method.

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

This does not work, because the entire column of the entire digit is passed to the function. Is there a way to make this work by simply passing this cell to a function instead of the entire column?

+8
r dplyr
source share
2 answers

With conversion, your function should work with a vector. Instead, you can use ifelse , which works on vectors:

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

Alternatively, you can apply a function to each value in a column using one of the apply functions:

  isOdd <- function(x){ sapply(x, function(x){ if(x %% 2 == 0){ return("even") }else{ return("odd") } })} 
+9
source share

I think you could also use group_by () to split the strings by unique values ​​and subsequently do your calculations, for example:

 df %>% group_by(digit) %>% mutate(isOdd = IsItOdd(digit)) 
+6
source share

All Articles