R按数据框匹配并替换列名

时间:2016-08-10 13:13:18

标签: r dataframe

我有两个数据框。我有一个数据框NAME中的列名列表。然后我有另一个数据帧DF,其中列名对应于下一列中的数据帧NAME。我需要将这些名称替换为DF中的列名。

DF:
        A   B   C   D   E
 H001   947 95  10  10  678
 H002   647 40  10  10  806
 H003   840 20  99  53  21
 H004   105 10  97  12  44
 H005   595 59  76  76  67

NAME:
Name Real.name
A    Pete
B    May
C    Jon
D    Paul
E    Emma
F    Fuchs
G    George

Desired output:
        Pete May    Jon Paul Emma
 H001   947  95     10  10   678
 H002   647  40     10  10   806
 H003   840  20     99  53   21
 H004   105  10     97  12   44
 H005   595  59     76  76   67

3 个答案:

答案 0 :(得分:4)

这样的事情怎么样?

编辑:@PierreLafortune建议的更好的选择:

names(df) <- name$Real.name[match(names(df), name$Name)]

最初的方法:

names(df)<-merge(data.frame(Name=names(df)),name,all.x=T)[,"Real.name"]

df
     Pete May Jon Paul Emma
H001  947  95  10   10  678
H002  647  40  10   10  806
H003  840  20  99   53   21
H004  105  10  97   12   44
H005  595  59  76   76   67

数据:

df <- structure(list(A = c(947L, 647L, 840L, 105L, 595L), B = c(95L, 
40L, 20L, 10L, 59L), C = c(10L, 10L, 99L, 97L, 76L), D = c(10L, 
10L, 53L, 12L, 76L), E = c(678L, 806L, 21L, 44L, 67L)), .Names = c("A", 
"B", "C", "D", "E"), class = "data.frame", row.names = c("H001", 
"H002", "H003", "H004", "H005"))

name <- structure(list(Name = structure(1:7, .Label = c("A", "B", "C", 
"D", "E", "F", "G"), class = "factor"), Real.name = structure(c(7L, 
5L, 4L, 6L, 1L, 2L, 3L), .Label = c("Emma", "Fuchs", "George", 
"Jon", "May", "Paul", "Pete"), class = "factor")), .Names = c("Name", 
"Real.name"), class = "data.frame", row.names = c(NA, -7L))

答案 1 :(得分:1)

可能有很多解决方案。我会使用plyr::mapvalues

names(DF) <- plyr::mapvalues(names(DF), from = NAME$Name, to = NAME$Real.name)

答案 2 :(得分:1)

这也可以通过dplyr

完成
library(dplyr)

df <- df %>%
      rename_at(as.vector(na.omit(name$Name[match(names(df), name$Name)])), 
               ~as.vector(na.omit(name$Real.name[match(names(df), name$Name)])))