在R中,对两个匹配数据帧的每一行进行排序

时间:2016-03-03 17:38:39

标签: r sorting

我有两个匹配单元格的数据框。

    v <- data.frame(c1=c(30,15,3), c2=c(10,25,2), c3=c(20,35,4))
    w <- data.frame(c1=c("thirty","fifteen","three"), c2=c("ten","twenty-five","two"), c3=c("twenty","thirty-five","four"))

我需要对两者的每一行进行排序而不采用(慢)循环。要排序v(也将确定其他数据框的顺序),我使用建议的方法here

    v.sorted <- t(apply(v, 1, sort))

如何操作数据框w,使其与v的排序版本匹配?

提前致谢!

1 个答案:

答案 0 :(得分:1)

我们可以将lapplyorder

一起使用
do.call(rbind, lapply(seq_len(nrow(v)), function(i) 
     as.character(unlist(w[i,])[order(unlist(v[i,]))])))
#     [,1]      [,2]          [,3]         
#[1,] "ten"     "twenty"      "thirty"     
#[2,] "fifteen" "twenty-five" "thirty-five"
#[3,] "two"     "three"       "four"