根据列名的字符向量和替换来重命名多列 [英] Rename multiple columns given character vectors of column names and replacement
本文介绍了根据列名的字符向量和替换来重命名多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用base R或 setnames
在data.table
或 dplyr
0.5中>重命名_ 。由于不建议使用重命名_
,因此在 dplyr
0.6.0中找不到简单的方法。
While this is easy to do with base R or setnames
in data.table
or rename_
in dplyr
0.5. Since rename_
is deprecated, I couldn't find an easy way to do this in dplyr
0.6.0.
下面是一个示例。我想将 col.from
中的列名替换为 col.to
中的对应值:
Below is an example. I want to replace column name in col.from
with corresponding values in col.to
:
col.from <- c("wt", "hp", "vs")
col.to <- c("foo", "bar", "baz")
df <- mtcars
head(df, 2)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 21 6 160 110 3.9 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21 6 160 110 3.9 2.875 17.02 0 1 4 4
预期产量:
names(df)[match(col.from, names(df))] <- col.to
head(df, 2)
#> mpg cyl disp bar drat foo qsec baz am gear carb
#> Mazda RX4 21 6 160 110 3.9 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21 6 160 110 3.9 2.875 17.02 0 1 4 4
如何使用重命名
或 dplyr
0.6.0中的 rename_at
?
How can I do this with rename
or rename_at
in dplyr
0.6.0?
推荐答案
我不知道这是否是正确的处理方法,但
I don't know if this is the right way to approach it, but
library(dplyr)
df %>% rename_at(vars(col.from), function(x) col.to) %>% head(2)
# mpg cyl disp bar drat foo qsec baz am gear carb
# Mazda RX4 21 6 160 110 3.9 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21 6 160 110 3.9 2.875 17.02 0 1 4 4
还请注意,我生活在未来:
Also note that I live in the future:
# packageVersion("dplyr")
# # [1] ‘0.7.0’
这篇关于根据列名的字符向量和替换来重命名多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文