19

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 ?

1
  • 2
    transform(df,isOdd=vapply(digit, IsItOdd, "")) or transform(df,isOdd=Vectorize(IsItOdd)(digit))? Commented Feb 18, 2015 at 8:55

3 Answers 3

15

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") } })} 
Sign up to request clarification or add additional context in comments.

4 Comments

Can you explain why with transform/mutate the function operates on the entire vector rather than on the individual values? This isn't true with base functions (e.g. sin() or log()).
@rmcd I'm very interested in your question, maybe worth another thread? I guess dplyr::mutate is parsing the function and trying to guess whether to pass in a single value or the whole vector?
btw you can force the proper behavior by using dplyr::rowwise but it's still an interesting question
@WillCornwell Thanks for the response and the pointer to rowwise, which I was't aware of. I've posted a question here stackoverflow.com/questions/49967559/…
9

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

Comments

2

You do not need to use mutate, you can do it in R base or in purr

get_rango_edad <- function(x) { if (x <= 25) { return("18-25") } else{ return("26+") } } encuestas$rango_edad <- map_chr(encuestas$edad,get_rango_edad) 

or

encuestas$rango_edad <- sapply(encuestas$edad,get_rango_edad) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.