合并R中的两个数据帧

时间:2022-11-16 18:34:41

I want to merge two data frames with approximately same number of rows. But the merging needs to be done in a special way.

我想合并两个具有大致相同行数的数据帧。但合并需要以特殊方式完成。

Suppose the two data frames are A and B. and Ai, Bi represent the ith row of the respective data frames.

假设两个数据帧是A和B.并且Ai,Bi表示各个数据帧的第i行。

Then I want a new dataframe with the following rows:

然后我想要一个包含以下行的新数据帧:

A1

B1 

A2 

B2 

...

Here is a toy example:

这是一个玩具示例:

A <- data.frame(col1 = paste("A", 1:5, sep = ""), col2 = rivers[1:5])
B <- data.frame(col1 = paste("B", 1:6, sep = ""), col2 = rivers[1:6])

I want a new data frame C such that

我想要一个新的数据帧C.

> C

   col1 col2

1    A1  735

6    B1  735

2    A2  320

7    B2  320
...

How do I efficiently do it in R? Please note, there are no empty rows between two rows, as it appears here.

我如何在R中有效地做到这一点?请注意,两行之间没有空行,如此处所示。

1 个解决方案

#1


5  

Put them all together, and then resort them:

把它们放在一起,然后诉诸它们:

ord <- order(c(1:nrow(A), 1:nrow(B)))
AB <- rbind(A,B)[ord,]

#1


5  

Put them all together, and then resort them:

把它们放在一起,然后诉诸它们:

ord <- order(c(1:nrow(A), 1:nrow(B)))
AB <- rbind(A,B)[ord,]