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 ?
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.
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.
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")
}
})}
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With