使用外部列表替换col名称和行值

时间:2017-05-31 15:29:35

标签: r

我有一个数据框:

<div id="contents">
  <div id="nav"></div>
  <div id="container"></div>
</div>

我想根据列表替换单元格的值:

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))

是否可以在列名中使它?

1 个答案:

答案 0 :(得分: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"