【问题标题】:dplyr mutate_each_ standard evaluationdplyr mutate_each_ 标准评估
【发布时间】:2016-01-14 15:40:59
【问题描述】:

我正在为 dplyr 中 mutate_each_ 的 SE 实现绞尽脑汁。我想要做的是从 DF 中的每一列中减去 DF 中一列中的值。

这是我希望使用 iris 数据集完成的最小工作示例(我删除了“物种”列,使其全部为数字)。我从每一列中减去 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))

请提前提供帮助,非常感谢。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    你要找的是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
    

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

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

    【讨论】:

      【解决方案2】:

      你试过了吗

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

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

      【讨论】:

      • 嗨 Marcin - 感谢您的评论,但我仍然收到“vars”缺失错误。 (ps - 您的代码中有一个小错字:pate0 vs paste0)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-23
      • 1970-01-01
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 2020-09-17
      相关资源
      最近更新 更多