r - dplyr 'rename' 标准评估函数没有按预期工作?

标签 r dplyr

更新:从这篇文章下面的评论来看,这现在按预期工作,没有我在这里列出的问题。

以下是使用 rename_ 的玩具示例来自 dplyr。我希望能够使用下面的第二个示例将列名改回原来的名称,但我猜函数参数评估规则在某种程度上阻止了它以我认为的方式工作。使用原始 plyr 包 rename 有一个简单的解决方法函数(以及使用基本包 names 函数),但我觉得我缺少 dplyr 解决方案。

我有一个如下所示的解决方法,但我欢迎第二个示例的 dplyr 解决方案按我的预期工作,或者解释为什么我不应该期望它按照我想要的方式工作。

谢谢,
马特

编辑:我在下面使用 rename_ 添加了一个示例使这项工作,但很复杂。我假设如果 Hadley 在下面提到的错误得到修复,这将如下所示。但在那之前,我笨拙的方式确实如此,但最好使用标准 plyr方法。最后还添加了基础 R 技术,例如完整性。

library(plyr)
library(dplyr)

# dataframe to operate on
dat <- data_frame(a=1, b=1)

# identifier with string of column name in dat
x <- "a"


# Renaming using standard evaluation this way works
dat %>%
    rename_("new" = x)
# Source: local data frame [1 x 2]
# 
#   new b
# 1   1 1


# But changing it back does not
# I expect "a" to be the name, not the identifier x
dat %>%
    rename_("new" = x) %>%
    rename_(x = "new")
# Source: local data frame [1 x 2]
# 
#   x b
# 1 1 1


# This works, but seems really awkward...
dat %>%
    rename_("newname" = x) %>%
    do(do.call(rename_, setNames(list(., "newname"), c(".data", x))))

# Source: local data frame [1 x 2]
# 
#   a b
# 1 1 1


# This works fine
dat %>%
    rename_("new" = x) %>%
    plyr::rename(c("new" = x))
# Source: local data frame [1 x 2]
# 
#   a b
# 1 1 1


# Base R way
datrn <- dat %>%
    rename_("newname" = x)
names(datrn)[names(datrn) == "newname"] = x
datrn
# Source: local data frame [1 x 2]
# 
#   a b
# 1 1 1

最佳答案

有几件事让这很痛苦:

  • c(x = "new")c("x" = "new") 相同,而不是相反
    c(new = x) .
  • 您可以使用 setNames(x, "new") 构建您想要的向量,
    但是...
  • 我忘了添加 .dots论据 rename_ (错误报告在
    https://github.com/hadley/dplyr/issues/708 ) 所以你不能这样做:
    rename_(dat, .dots = setNames(x, "new"))
    

    相反,您需要使用 do.call :
    do.call(rename_, c(list(quote(dat)), list(setNames(x, "new"))))
    
  • 关于r - dplyr 'rename' 标准评估函数没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26619329/

    相关文章:

    r - R 中预测的预处理比例 - 没有获得相同的预测比例

    r - parLapply - 如何解决错误 "Could not find function "bindToEnv""?

    c++ - 作为 S4 对象的一部分返回时避免复制 Armadillo 矩阵

    r - 过滤时间范围内的所有天数

    r - 使用 dplyr::mutate 计算到数据点的地理距离

    r - 收集虚拟变量和重新编码因子

    将部分日期重置为 R 中的默认完整日期

    r - 对 dplyr 中具有相同编号的相同分组值进行编号

    r - 根据值和分隔符拆分数据框中的所有列

    r - 如何在 R 中使用 ChartJSRadar 保存为 png?