相对于向量A转换向量B的大小写

问题描述 投票:0回答:2

我有2个数据框,我想要协调列名。有些变量在大写/小写方面有所不同,有些变量的名称相同,有些变量是唯一的。我想保留我的第一个数据帧的名称,即第二个数据帧的变量名称应该转换为第一个数据帧的大/小的情况。因此,典型的touppertolower函数不起作用。

考虑以下可重现的示例:

# 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的列名?

r string dataframe
2个回答
1
投票

你可以使用plyr::mapvalues

plyr::mapvalues(x = tolower(names(df_b)), 
                from = tolower(names(df_a)), 
                to = names(df_a), 
                warn_missing = FALSE)

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"
© www.soinside.com 2019 - 2024. All rights reserved.