首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在dplyr管道中,以编程方式重命名列(左侧和右侧)。

在dplyr管道中,以编程方式重命名列(左侧和右侧)。
EN

Stack Overflow用户
提问于 2019-01-06 17:14:02
回答 1查看 236关注 0票数 2

我想以编程方式重命名dplyr管道中的列(使用一个传递的变量)。我在下面建立了一个最小的例子,并给出了一些评论。最后一对尝试成功。但他们觉得很奇怪。这真的是达到我在潮间文学中的效果的最佳实践方法吗?如果不是,什么是?另外,为什么!!在左边而不是str_c()上进行评估?

我仍然觉得我没有在思考如何去思考--尤其是当涉及到这些:=!!!!!~vars()funs()enquo()等等,操作符和函数。

代码语言:javascript
复制
library(tidyverse) 

OLD_COL_NAME <- "disp"
NEW_COL_NAME <- "PREFIX_disp"

# Gives desired result, but would prefer not to pass `NEW_COL_NAME`
mtcars %>%
  rename(!!NEW_COL_NAME := !!OLD_COL_NAME)
# mpg cyl PREFIX_disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4           21.0   6       160.0 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag       21.0   6       160.0 110 3.90 2.875 17.02  0  1    4    4

# Thought this would give BOTH desired result and functionality. 
# Surprisingly to me, didn't work. 
mtcars %>%
  rename(str_c("PREFIX_", !!OLD_COL_NAME) := !!OLD_COL_NAME)
# Error: The LHS of `:=` must be a string or a symbol

# Also surprinsigly, this didn't work either
mtcars %>%
  rename(!!str_c("PREFIX_", !!OLD_COL_NAME) := !!OLD_COL_NAME)
# Error in !OLD_COL_NAME : invalid argument type

# Gives desired result. But clunky. Is this really the best-practices approach 
# in the tidyverse?
mtcars %>%
  rename_at(vars(!!OLD_COL_NAME), funs(str_c("PREFIX_", !!OLD_COL_NAME)))

# Gives desired result. Less clunky. Again, is this the best-practices approach?
mtcars %>%
  rename_at(vars(!!OLD_COL_NAME), ~ str_c("PREFIX_", .x))
EN

回答 1

Stack Overflow用户

发布于 2021-04-23 07:13:32

我们现在可以:

代码语言:javascript
复制
mtcars %>% 
  rename("PREFIX_{ OLD_COL_NAME }" := !! OLD_COL_NAME)

参见关于结果名称中的粘合字符串的公告

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54063993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档