首页 > 解决方案 > 根据命名向量 (R) 更改列名

问题描述

我有以下数据框:

   a b c d e f g h i j
   1 1 1 1 1 1 1 1 1 1
   1 1 1 1 1 1 1 1 1 1
   1 1 1 1 1 1 1 1 1 1
   1 1 1 1 1 1 1 1 1 1

以及以下向量(或数据框)

sample     name
a          1
b          2
c          3
d          4
e          5
f          6
g          7
h          8
i          9
j          10

我想根据第二个数据帧重命名第一个数据帧上的列:

   1 2 3 4 5 6 7 8 9 10
   1 1 1 1 1 1 1 1 1 1
   1 1 1 1 1 1 1 1 1 1
   1 1 1 1 1 1 1 1 1 1
   1 1 1 1 1 1 1 1 1 1

标签: rvectorcolumnsorting

解决方案


我们可能会使用match

names(df1) <- df2$name[match(names(df1), df2$sample)]

-输出

> df1
  1 2 3 4 5 6 7 8 9 10
1 1 1 1 1 1 1 1 1 1  1
2 1 1 1 1 1 1 1 1 1  1
3 1 1 1 1 1 1 1 1 1  1
4 1 1 1 1 1 1 1 1 1  1

或者使用命名向量来匹配

names(df1) <- setNames(df2$name, df2$sample)[names(df1)]

数据

df1 <- structure(list(a = c(1L, 1L, 1L, 1L), b = c(1L, 1L, 1L, 1L), 
    c = c(1L, 1L, 1L, 1L), d = c(1L, 1L, 1L, 1L), e = c(1L, 1L, 
    1L, 1L), f = c(1L, 1L, 1L, 1L), g = c(1L, 1L, 1L, 1L), h = c(1L, 
    1L, 1L, 1L), i = c(1L, 1L, 1L, 1L), j = c(1L, 1L, 1L, 1L)), 
class = "data.frame", row.names = c(NA, 
-4L))

df2 <- structure(list(sample = c("a", "b", "c", "d", "e", "f", "g", 
"h", "i", "j"), name = 1:10), class = "data.frame", row.names = c(NA, 
-10L))

推荐阅读