dplyr mutate_each_标准评估

时间:2016-01-14 15:40:59

标签: r dplyr

我在dplyr的mutate_each_的SE实现上绞尽脑汁。我想要做的是从DF中的每一列中减去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 个答案:

答案 0 :(得分:8)

您要找的是funs的SE版本,即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

如果你想提供我写的&#34; -Species&#34;你可以使用mutate_each_作为字符串/变量。

请注意.dotsmutate_each_中没有summarise_each_参数。

答案 1 :(得分:1)

你试过吗

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

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