我想在函数中使用 rename_
(或 rename
?)来重命名 tibble 中的列。例如,假设我在如下函数中有 rename(as_tibble(iris)
, petal = Petal.Width)`
rr <- function(toRename, newName, dt) {
rename_(dt, .dots = rlang::expr(list(!! newName = toRename)))
}
我可以在其中传递要重命名的数据集,并将重命名的元素作为字符串传递给我可以调用的数据集:
rr('petal', 'Petal.Width', dt = as_tibble(iris))
将 Petal.Width
重命名为 petal
。
我该怎么做?
最佳答案
我们可以将 sym
与 :=
一起使用
rr <- function(dt, oldName, newName) {
rename(dt, !!rlang::sym(newName) := !! rlang::sym(oldName))
}
rr(dt = as_tibble(iris), oldName = 'Petal.Width', newName = 'petal') %>%
head(., 2)
# A tibble: 2 x 5
# Sepal.Length Sepal.Width Petal.Length petal Species
# <dbl> <dbl> <dbl> <dbl> <fctr>
#1 5.10 3.50 1.40 0.200 setosa
#2 4.90 3.00 1.40 0.200 setosa
关于r - 如何在 dplyr 中进行功能重命名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48676397/