[英]How to replace data.frame column names with string in corresponding lookup table in R
I have the following data.frame: 我有以下data.frame:
set.seed(126)
df <- data.frame(a=sample(c(1:100, NA), 10), b=sample(1:100, 10), c=sample(1:100, 10), d = c(1:10))
a b c d
1 18 27 53 1
2 44 16 66 2
3 58 47 3 3
...
And the following lookup table: 以下查找表:
varnames <- data.frame(old = c("a", "b", "c"), new = c("dog", "cat", "mouse"))
old new
1 a dog
2 b cat
3 c mouse
What I am trying to do is replace the names(df)
with the corresponding varnames$new
... If a names(df)
is not in varnames$old
, then retain the colname in df... 我想要做的是将
names(df)
替换为相应的varnames$new
...如果names(df)
不在varnames$old
,则将colname保留在df中...
The resulting data.frame I would like returned would look like this: 我想要返回的结果data.frame看起来像这样:
dog cat mouse d
1 57 10 83 1
2 53 99 94 2
3 99 60 39 3
...
Any and all help appreciated. 任何和所有帮助表示赞赏。
How about using the match()
function 如何使用
match()
函数
mm <- match(names(df), varnames$old)
names(df)[!is.na(mm)] <- as.character(varnames$new[na.omit(mm)])
head(df)
# dog cat mouse d
# 1 65 48 19 1
# 2 46 15 80 2
# 3 NA 47 84 3
# 4 68 34 46 4
# 5 23 75 42 5
# 6 92 87 68 6
If you are interested, you could also use the dplyr
rename()
function 如果您有兴趣,还可以使用
dplyr
rename()
函数
library(dplyr)
df %>% rename_(.dots=with(varnames, setNames(as.list(as.character(old)), new)))
Or one more option, the data.table
package has a setnames
function 或者另外一个选项,
data.table
包有一个setnames
函数
library(data.table)
setnames(df, as.character(varnames$old), as.character(varnames$new))
One more option is mapvalues()
from the plyr package: 还有一个选项是plyr包中的
mapvalues()
:
library(plyr)
names(df) <- mapvalues(names(df),
from = varnames$old,
to = as.character(varnames$new))
If you are using the dplyr package, you can call this with plyr::mapvalues()
so you don't have to load plyr on top of dplyr (which causes problems). 如果您使用的是dplyr包,可以使用
plyr::mapvalues()
调用它,这样就不必在dplyr上加载plyr(这会导致问题)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.