R-从另一个数据框中的值修改数据框列名
假设我有一个名为df1的数据帧,类似于以下内容:R-从另一个数据框中的值修改数据框列名,r,R,假设我有一个名为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 cols <- names(df1) cols <- cols[2:length(cols)] newCols = df2[cols == df2$ID, "Name"]
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
cols <- names(df1)
cols <- cols[2:length(cols)]
newCols = df2[cols == df2$ID, "Name"]
names(df1) <- c("Year", newCols)
另一个数据帧df2如下所示:
ID Name
1 S1 John
2 S2 Sarah
3 S3 Kate
4 S4 Michael
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
我想将df1的相关列名(即不是年份)更改为df2中的相应名称,以便df1看起来像这样:
ID Name
1 S1 John
2 S2 Sarah
3 S3 Kate
4 S4 Michael
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
我尝试了以下方法:
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
cols <- names(df1)
cols <- cols[2:length(cols)]
newCols = df2[cols == df2$ID, "Name"]
names(df1) <- c("Year", newCols)
cols我们可以使用match
names(df1)[-1] <- df2$Name[match(names(df1)[-1], df2$ID)]
names(df1)[-1]不幸的是,这对我不起作用。这似乎是因为df2$name的类型为“factor”,因此不会维护顺序,而且也会为列分配整数值,而不是字符串。我是R新手,不太明白为什么会发生这种情况,但列名是3、1、4、2,而不是Michael、John、Sarah、Kate。@Rorydevit这是一个很容易解决的问题<代码>as.character(df2$Name[匹配(名称(df1)[-1],as.character(df2$ID))]