如何在函数中使用mutate_if

时间:2018-11-07 19:56:00

标签: r tidyverse mutate

我想使用功能d将数据帧result转换成下面的结果(replace_by_sym)。我在做什么错了?

library(tidyverse)

d <- data.frame(dir = c(-1,1,-1,1,1), a = rep(100,5), b = 105:109, c = 108:112)

replace_by_sym <- function(x){
  x <- x * (-1) + 200
}

d %>%
  mutate_if(dir=-1, vars(a:c),
            funs(replace_by_sym(.))) -> result

获得

   dir   a   b   c
1  -1   100  95  92
2   1   100 106 109
3  -1   100  93  90
4   1   100 108 111
5   1   100 109 112

1 个答案:

答案 0 :(得分:4)

可以通过ifelse

完成
d %>% 
  mutate_at(vars(a:c), funs( ifelse (dir == -1, (dir * .)  + 200, .)))
#   dir   a   b   c
#1  -1 100  95  92
#2   1 100 106 109
#3  -1 100  93  90
#4   1 100 108 111
#5   1 100 109 112

或与case_when

d %>% 
   mutate_at(vars(a:c), funs(case_when(dir == -1 ~ (dir * .) + 200, 
                                       TRUE ~ as.numeric(.))))