Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mutate/transform in R dplyr (Pass custom function)

Tags:

r

dplyr

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 ?

like image 378
prog_guy Avatar asked Feb 18 '15 08:02

prog_guy


People also ask

What is the difference between transform and mutate function in R?

mutate() adds new variables and preserves existing ones; transmute() adds new variables and drops existing ones. New variables overwrite existing variables of the same name.

How do you create a new variable in mutate in R?

To create the new variable, we start with the data frame with the pipe operator and use mutate() function. Inside mutate() function, we specify the name of the new variable we are creating and how exactly we are creating.


2 Answers

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") 
          }
     })}
like image 86
Mathew Hall Avatar answered Sep 21 '22 18:09

Mathew Hall


I think you could also use group_by() to tease apart the rows by unique values and subsequently do your computation, like so:

df %>% group_by(digit) %>% mutate(isOdd = IsItOdd(digit))
like image 31
Extrapolator Avatar answered Sep 19 '22 18:09

Extrapolator