Reputation: 806
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 ?
Upvotes: 19
Views: 25041
Reputation: 21
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)
Upvotes: 2
Reputation: 423
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))
Upvotes: 9
Reputation: 1004
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")
}
})}
Upvotes: 15