How can I rbind vectors matching their column names?

后端 未结 7 1989
醉话见心
醉话见心 2020-12-01 16:04

rbind does not check for column names when binding together vectors:

l = list(row1 = c(10, 20), row2 = c(20, 10))
names(l$row1) = c(\"A\", \"B\")
names(l$row         


        
相关标签:
7条回答
  • 2020-12-01 16:42

    You can use match:

    l <- list(row1 = setNames(1:3, c("A", "B", "C")),
              row2 = setNames(1:3, c("B", "C", "A")),
              row3 = setNames(1:3, c("C", "A", "B")))
    
    do.call(rbind, lapply(l, function(x) x[match(names(l[[1]]), names(x))]))
    

    The result:

         A B C
    row1 1 2 3
    row2 3 1 2
    row3 2 3 1
    
    0 讨论(0)
提交回复
热议问题