Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何将mutate_if与函数一起使用_R_Tidyverse_Mutate - Fatal编程技术网

R 如何将mutate_if与函数一起使用

R 如何将mutate_if与函数一起使用,r,tidyverse,mutate,R,Tidyverse,Mutate,我想使用函数replace\u by_sym将数据帧d转换为下面的结果(result)。我做错了什么 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

我想使用函数
replace\u by_sym
将数据帧
d
转换为下面的结果(
result
)。我做错了什么

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

可以使用
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

或在

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

可以使用
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

或在

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

如果要进行比较,则希望
dir==-1
,而不是
dir=-1
mutate\u If()
对满足谓词的列而不是行进行操作。如果要进行比较,则希望
dir=-1
,而不是
dir=-1
mutate\u If()
对满足谓词的列而不是行进行操作。