使用旧的select_()
函数,我可以将一个命名向量传递到select中,同时更改位置和列名称:
my_data <- data_frame(foo = 0:10, bar = 10:20, meh = 20:30)
my_newnames <- c("newbar" = "bar", "newfoo" = "foo")
move_stuff <- function(df, newnames) {
select_(df, .dots = newnames)
}
move_stuff(my_data, newnames = my_newnames) )
# this is the desired output
# A tibble: 4 x 2
newbar newfoo
<int> <int>
1 10 0
2 11 1
3 12 2
4 13 3
我尝试使用quosures和splicing做类似的事情--选择列非常有效,但向量的名称(从而同时重命名列)似乎被忽略了。以下两个示例返回具有名为bar
和foo
的列的数据帧,但没有newbar
和newfoo
:
move_stuff2 <- function(df, newnames) {
select(df, !!!newnames)
}
# returns df with columns bar and foo
move_stuff2(my_data, quo(my_newnames))
move_stuff2(my_data, quos(my_newnames))
有没有一种方法可以使用新的 NSE 方法来重命名和重新排序列,以便使用命名向量?