【问题标题】:Change column name based on named vector (R)根据命名向量 (R) 更改列名
【发布时间】:2021-10-19 15:09:29
【问题描述】:

我有以下数据框:

   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

【问题讨论】:

    标签: r vector columnsorting


    【解决方案1】:

    我们可能会使用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))
    

    【讨论】:

    • 这可行,但可能会导致问题。原始数据框中的 df1$a 返回第一列,而返回版本中的 df1$1 返回错误。要获得第一列,您需要 df1$'1'。
    猜你喜欢
    • 1970-01-01
    • 2022-10-15
    • 2021-12-29
    • 2020-02-04
    • 2020-10-24
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    相关资源
    最近更新 更多