我有2个数据框,我想要协调列名。有些变量在大写/小写方面有所不同,有些变量的名称相同,有些变量是唯一的。我想保留我的第一个数据帧的名称,即第二个数据帧的变量名称应该转换为第一个数据帧的大/小的情况。因此,典型的toupper
或tolower
函数不起作用。
考虑以下可重现的例子:
# Data frame A
df_a <- data.frame(Col1 = rnorm(5),
cOL2 = rnorm(5),
col3 = rnorm(5),
COL4 = rnorm(5),
unique_a = rnorm(5))
# Data frame B
df_b <- data.frame(COL1 = rnorm(5), # Should be converted to Col1
COL2 = rnorm(5), # Should be converted to cOL2
col3 = rnorm(5), # Should be kept as it is
COL4 = rnorm(5), # Should be kept as it is
unique_b = rnorm(5)) # Should be kept as it is
# Vectors of column names
vec_a <- colnames(df_a)
vec_b <- colnames(df_b)
# If there is a match, vec_b should be converted to vec_a
# The final result shoul look as follows:
# vec_b
# [1] "Col1" "cOL2" "col3" "COL4" "unique_b"
问题:如何将数据框B的匹配列名转换为数据框A的列名?
答案 0 :(得分:1)
一种选择是对转换为单个案例的名称使用match
,然后执行作业
i1 <- match(toupper(vec_a), toupper(vec_b), nomatch = 0)
i2 <- match(toupper(vec_b), toupper(vec_a), nomatch = 0)
names(df_b)[i2] <- names(df_a)[i1]
names(df_b)
#[1] "Col1" "cOL2" "col3" "COL4" "unique_b"
答案 1 :(得分:1)
您可以使用plyr::mapvalues
:
plyr::mapvalues(x = tolower(names(df_b)),
from = tolower(names(df_a)),
to = names(df_a),
warn_missing = FALSE)