首页 > 解决方案 > 在 mutate_all 的函数内部使用 one_of/vars

问题描述

我需要用其中一列减去数据集的所有列。我需要的列的名称是动态的,存储在数据集之外,c("a")如下所示。

dataset <- data.frame(a = c(0.021, 0.011, -0.031, -0.021, -0.041, 0.061), 
                      b = c(0.022, 0.012, -0.032, -0.022, -0.042, 0.062), 
                      c = c(0.010, 0.000, -0.020, 0.010, -0.030, 0.070))
dataset %>% mutate_all(funs( (. - one_of(c("a"))) ))

当我运行它时,产生的错误是Evaluation error: Variable context not set.我知道这必须与调用one_of()inside of funs(). 一个稍微不那么优雅的解决方案是:

dataset - dataset %>% select(one_of("a")) %>% pull

不过,我很好奇为什么我不能做前者。

标签: rdplyr

解决方案


你可以这样做:

dataset %>% mutate_all(`-`,.$a)
#   a      b      c
# 1 0  0.001 -0.011
# 2 0  0.001 -0.011
# 3 0 -0.001  0.011
# 4 0 -0.001  0.031
# 5 0 -0.001  0.011
# 6 0  0.001  0.009

或类似于@Miha 的评论:

dataset %>% transmute_all( funs(new=. - a))
#   a_new  b_new  c_new
# 1     0  0.001 -0.011
# 2     0  0.001 -0.011
# 3     0 -0.001  0.011
# 4     0 -0.001  0.031
# 5     0 -0.001  0.011
# 6     0  0.001  0.009

我跳过new=, a 首先从自身中减去,不能用于其他变量(感谢@aosmith)。


推荐阅读