简体   繁体   中英

mutate/transform in R dplyr (Pass custom function)

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 ?

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

我想你也可以使用group_by()来按行分隔行,然后进行计算,如下所示:

df %>% group_by(digit) %>% mutate(isOdd = IsItOdd(digit))

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM