【发布时间】:2019-05-07 17:18:16
【问题描述】:
更新:从下面对这篇文章的评论来看,这现在按预期工作,没有我在此处列出的问题。
下面是使用来自 dplyr 的 rename_ 的玩具示例。我期望能够使用下面的第二个示例将列名更改回原来的名称,但我猜函数参数评估规则在某种程度上阻止了它按我想的方式工作。使用原始 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
【问题讨论】:
-
如果有人想知道,
rename_(dat, .dots = setNames(x, "new"))现在可以按预期工作。 -
在非标准评估的 dplyr 小插图中提供了有关此类内容的更多信息:cran.r-project.org/web/packages/dplyr/vignettes/nse.html