我想在函数中使用rename_
(或rename
?)从小标题中重命名列。例如,假设我rename(as_tibble(iris)
在类似下面的函数中具有,花瓣= 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句