如何合并 2 个矩阵以获得单个 data.frame

How to merge 2 matrices to get a single data.frame

我想知道从 x1x2 到下面显示的我想要的 data.frame 输出的最短路径是什么?

(x1 = matrix(c(1,3,2, 3,7,2),3,2)  )  
(x2 = matrix(c(4,6,6,5,5,4, 6,8,8,10,10,6),6,2)  ) 
colnames(x1) <- colnames(x2) <- c("SA", "CSA")


#-- Desired `data.frame` output:
#SA   CSA  group
#1    3     1
#3    7     1
#2    2     1
#4    6     2
#6    8     2
#6    8     2
#5    10    2
#5    10    2
#4    6     2
library(dplyr)
x1<-as_tibble(x1)
x2<-as_tibble(x2)

a <- bind_rows(x1, x2, .id = "id")
# A tibble: 9 x 3
  id       SA   CSA
  <chr> <dbl> <dbl>
1 1         1     3
2 1         3     7
3 1         2     2
4 2         4     6
5 2         6     8
6 2         6     8
7 2         5    10
8 2         5    10
9 2         4     6

如果只使用 base R,你可以这样做:

do.call(rbind.data.frame,mapply(cbind,list(x1,x2),group = 1:2))

  SA CSA group
1  1   3     1
2  3   7     1
3  2   2     1
4  4   6     2
5  6   8     2
6  6   8     2
7  5  10     2
8  5  10     2
9  4   6     2

或者,您也可以这样做。

df <- data.frame(rbind(x1, x2), 
                 "group" = rep(c(1, 2), 
                               times = c(dim(x1)[1], dim(x2)[1])))

一个选项可以是将矩阵转换为数据帧列表,然后使用 library(plyr) 中的 ldply() 按 id 对每个列表进行透视:

library(plyr)

# convert matrices in a list #
x <-list(x1=data.frame(x1),
         x2=data.frame(x2))

# pivot list elements by id #
ldply(x)

控制台输出:

#  .id SA CSA
#1  x1  1   3
#2  x1  3   7
#3  x1  2   2
#4  x2  4   6
#5  x2  6   8
#6  x2  6   8
#7  x2  5  10
#8  x2  5  10
#9  x2  4   6