dplyr mutate_each_标准评估

4
我正在思考dplyr中mutate_each_函数的SE实现。我想要做的是从DF中的一个列中减去每个列中的值。
以下是使用鸢尾花数据集的最小工作示例(我删除了'Species'列,以便所有数据都是数字)。我从每一列中减去了Petal.Width列。但我需要将列名作为变量,例如"My.Petal.Width"。
# Remove Species column, so that we have only numeric data
iris_numeric <- iris %>% select(-Species)

# This is the desired result, using NSE
result_NSE <- iris_numeric %>% mutate_each(funs(. - `Petal.Width`))

# This is my attempt at using SE 
SubtractCol <- "Petal.Width"
result_SE <- iris_numeric %>% mutate_each_(funs(. - as.name(SubtractCol)))

# Second attempt
SubtractCol <- "Petal.Width"
Columns <- colnames(iris_numeric)
mutate_call = lazyeval::interp(~.-a, a = as.name(SubtractCol))
result_SE <- iris_numeric %>% mutate_each_(.dots = setNames(list(mutate_call), Columns))

我遇到了各种错误:

Error in colwise_(tbl, funs_(funs), vars) : 
  argument "vars" is missing, with no default

Error in mutate_each_(., .dots = setNames(list(mutate_call), Columns)) : 
  unused argument (.dots = setNames(list(mutate_call), Columns))

请帮忙,非常感谢。

2个回答

8
你要找的是SE版的funs,也就是funs_
library(lazyeval); library(dplyr)
SubtractCol <- "Petal.Width"
iris %>% mutate_each(funs_(interp(~.-x, x = as.name(SubtractCol))), -Species) %>% head
#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1          4.9         3.3          1.2           0  setosa
#2          4.7         2.8          1.2           0  setosa
#3          4.5         3.0          1.1           0  setosa
#4          4.4         2.9          1.3           0  setosa
#5          4.8         3.4          1.2           0  setosa
#6          5.0         3.5          1.3           0  setosa

如果您想提供我所写的“-Species”作为字符串/变量,您将使用mutate_each_

请注意,在mutate_each_summarise_each_中没有.dots参数。


1

你试过了吗

result_SE <- iris_numeric %>% 
mutate_each_(funs(paste0('. - ',as.name(SubtractCol)))

应该指定字符,而不是带有字符片段的公式


2
嗨Marcin - 感谢您的评论,但我仍然收到“vars”缺失错误。(ps-您的代码中有一个小错别字:pate0与paste0) - csrvermaak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接