如何重命名多列,给定字符向量的列名称和替换在dplyr 0.6.0? [英] How to rename multiple columns given character vectors of column names and replacement in dplyr 0.6.0?
本文介绍了如何重命名多列,给定字符向量的列名称和替换在dplyr 0.6.0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
虽然这很容易在data.table 或 setnames
在
。由于 dplyr
中重命名_ rename _
已被弃用,所以在 dplyr
0.6.0中找不到一个简单的方法。 p>
以下是一个例子。我想将 col.from
中的列名替换为 col.to
中的相应值:
col.from< - c(wt,hp,vs)
col.to< - c foo,bar,baz)
df< - mtcars
头(df,2)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#>马自达RX4 21 6 160 110 3.9 2.620 16.46 0 1 4 4
#>马自达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
#>马自达RX4 21 6 160 110 3.9 2.620 16.46 0 1 4 4
#>马自达RX4 Wag 21 6 160 110 3.9 2.875 17.02 0 1 4 4
code>重命名或 rename_at
在 dplyr
0.6.0?
解决方案
我不知道这是否是正确的方法,但是
$($)
df%>%rename_at(vars(col.from),function(x)col.to)%>%head(2)
#mpg cyl disp bar drat foo qsec baz am gear carb
#马自达RX4 21 6 160 110 3.9 2.620 16.46 0 1 4 4
#马自达RX4 Wag 21 6 160 110 3.9 2.875 17.02 0 1 4 4
另请注意,我将来会住:
#packageVersion(dplyr)
##[1]'0.7.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.
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
Expected output:
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
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’
这篇关于如何重命名多列,给定字符向量的列名称和替换在dplyr 0.6.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文