首页 文章

R - 从另一个数据框中的值修改数据框列名[重复]

提问于
浏览
1

这个问题在这里已有答案:

假设我有一个名为df1的数据框,类似于以下内容:

Year S4 S1 S2 S3
1 2001  2  5  4  4
2 2002  5  2  2  0
3 2003  7  9  3  6
4 2004  9  6  8  7
5 2005  2  2  6  4
6 2006 10  5  7  5

和另一个数据框df2像这样:

ID    Name
1 S1    John
2 S2   Sarah
3 S3    Kate
4 S4 Michael

我想将df1的相关列名(即不是年份)更改为df2中的相应名称,以便df 1看起来像这样:

Year Michael John Sarah Kate
1 2001       2    5     4    4
2 2002       5    2     2    0
3 2003       7    9     3    6
4 2004       9    6     8    7
5 2005       2    2     6    4
6 2006      10    5     7    5

我尝试过以下方法:

cols <- names(df1)
cols <- cols[2:length(cols)]
newCols = df2[cols == df2$ID, "Name"]
names(df1) <- c("Year", newCols)

但是,如果df1中的列和df2中的行的顺序相同,那么第三行似乎才有效 . 在R中有一个简单的方法吗?

1 回答

  • 2

    我们可以用 match

    names(df1)[-1] <-  df2$Name[match(names(df1)[-1], df2$ID)]
    

相关问题