在R中交织两个数据帧

在R中交织两个数据帧,r,merge,dataframe,rbind,do.call,R,Merge,Dataframe,Rbind,Do.call,我想在R中交织两个data.frame。例如: a = data.frame(x=1:5, y=5:1) b = data.frame(x=2:6, y=4:0) 我希望结果如下所示: > x y 1 5 2 4 2 4 3 3 3 3 ... 通过cbindingx[1]和y[1],x[2]和y[2]等方式获得 最干净的方法是什么?现在我的解决方案是把所有的东西都吐到一个列表中,然后合并。这很难看: lst = lapply(1:length(x), fu

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

a = data.frame(x=1:5, y=5:1)
b = data.frame(x=2:6, y=4:0)
我希望结果如下所示:

> x y
  1 5
  2 4
  2 4
  3 3
  3 3
  ...  
通过
cbind
ing
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)

这就是我的方法:

dat <- do.call(rbind.data.frame, list(a, b))
dat[order(dat$x), ]

dat您可以通过给
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")]
a=data.frame(x=1:5,y=5:1)
b=数据帧(x=2:6,y=4:0)

df也许这有点作弊,但是ggplot2中的(非导出的)函数
interleave
是我以前为自己的使用偷来的:

as.data.frame(mapply(FUN=ggplot2:::interleave,a,b))

当然,“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