我想以编程方式重命名dplyr管道中的列(使用一个传递的变量)。我在下面建立了一个最小的例子,并给出了一些评论。最后一对尝试成功。但他们觉得很奇怪。这真的是达到我在潮间文学中的效果的最佳实践方法吗?如果不是,什么是?另外,为什么!!在左边而不是str_c()上进行评估?
我仍然觉得我没有在思考如何去思考--尤其是当涉及到这些:=,!!!,!!,~,vars(),funs(),enquo()等等,操作符和函数。
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))发布于 2021-04-23 07:13:32
https://stackoverflow.com/questions/54063993
复制相似问题