2017-05-31 34 views
0

更换山坳名和行值我有一个数据帧:使用外部列表

dput(df1) 
structure(list(column1 = structure(1:2, .Label = c("text1", "text3" 
), class = "factor"), column2 = structure(c(2L, 1L), .Label = c("text1", 
"text2"), class = "factor")), .Names = c("column1", "column2" 
), class = "data.frame", row.names = c(NA, -2L)) 

而且我想更换电池的基础列表中的值:

dput(df2) 
structure(list(current_values = structure(1:5, .Label = c("column1", 
"column2", "text1", "text2", "text3"), class = "factor"), new_values = structure(1:5, .Label = c("c1", 
"c2", "t1", "t2", "t3"), class = "factor")), .Names = c("current_values", 
"new_values"), class = "data.frame", row.names = c(NA, -5L)) 

,并有作为最后输出这个:

dput(finalout) 
structure(list(c1 = structure(1:2, .Label = c("t1", "t3"), class = "factor"), 
    c2 = structure(c(2L, 1L), .Label = c("t1", "t2"), class = "factor")), .Names = c("c1", 
"c2"), class = "data.frame", row.names = c(NA, -2L)) 

是否有可能使它也在列名?

回答

2

你可以使用match做到这一点:

res = apply(df1,2,function(x) df2[match(x,df2[,1]),2]) 
colnames(res) = df2[match(colnames(res),df2[,1]),2] 

这将返回:

 c1 c2 
[1,] "t1" "t2" 
[2,] "t3" "t1"