在R中交织两个data.frames

Ale*_*lex 7 merge r dataframe rbind do.call

我想data.frame在R中交织两个.例如:

a = data.frame(x=1:5, y=5:1)
b = data.frame(x=2:6, y=4:0)
Run Code Online (Sandbox Code Playgroud)

我希望结果看起来像:

> x y
  1 5
  2 4
  2 4
  3 3
  3 3
  ...  
Run Code Online (Sandbox Code Playgroud)

由得到的cbind荷兰国际集团x[1]y[1],x[2]y[2]

最干净的方法是什么?现在我的解决方案涉及吐出到列表和合并.这很难看:

lst = lapply(1:length(x), function(i) cbind(x[i,], y[i,]))
res = do.call(rbind, lst)
Run Code Online (Sandbox Code Playgroud)

A5C*_*2T1 12

当然,interleave"gdata"包中有这个功能:

library(gdata)
interleave(a, b)
#    x y
# 1  1 5
# 6  2 4
# 2  2 4
# 7  3 3
# 3  3 3
# 8  4 2
# 4  4 2
# 9  5 1
# 5  5 1
# 10 6 0
Run Code Online (Sandbox Code Playgroud)


RJ-*_*RJ- 5

您可以通过提供索引来实现此目的,x并按y索引rbind排序.

a = data.frame(x=1:5, y=5:1)
b = data.frame(x=2:6, y=4:0)
df <- rbind(data.frame(a, index = 1:nrow(a)), data.frame(b, index = 1:nrow(b)))
df <- df[order(df$index), c("x", "y")]
Run Code Online (Sandbox Code Playgroud)