r - 在 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
不过,我很好奇为什么我不能做前者。
解决方案
你可以这样做:
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)。
推荐阅读
- c++ - C++在父类成员函数中使用子成员变量
- javascript - 从现有应用程序的样式表中排除 Vue 组件
- microsoft-teams - 如果您的邮箱在本地,团队聊天实际上存储在哪里?
- jquery - DataTables 括号-带动态列的负数插件
- r - 如果重复,按名称排序
- .net - .net NEST 中的 Elasticsearch 查询未初始化对象
- python - Python ctype:当c函数向其写入值时,未更新到c函数的char数组
- spring - 在 Spring WebClient 中流上传“POST”
- python - 当 n_jobs > 1 时,Joblib 不调用自定义函数
- javascript - 不可见的 reCaptcha iframe 未显示,表单卡住