[英]interweave two data.frames in R
I would like to interweave two data.frame
in R. For example: 我想在R中交织两个data.frame
。例如:
a = data.frame(x=1:5, y=5:1)
b = data.frame(x=2:6, y=4:0)
I would like the result to look like: 我希望结果看起来像:
> x y
1 5
2 4
2 4
3 3
3 3
...
obtained by cbind
ing x[1]
with y[1]
, x[2]
with y[2]
, etc. 通过获得cbind
荷兰国际集团x[1]
与y[1]
x[2]
与y[2]
等等。
What is the cleanest way to do this? 最干净的方法是什么? Right now my solution involves spitting everthing out to a list and merging. 现在我的解决方案涉及吐出到列表和合并。 This is pretty ugly: 这很难看:
lst = lapply(1:length(x), function(i) cbind(x[i,], y[i,]))
res = do.call(rbind, lst)
There is, of course, the interleave
function in the "gdata" package: 当然,“gdata”包中有interleave
函数:
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
You can do this by giving x
and y
an index, rbind
them and sort by the index. 你可以通过给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")]
This is how I'd approach: 这就是我的方法:
dat <- do.call(rbind.data.frame, list(a, b))
dat[order(dat$x), ]
do.call
was unnecessary in the first step but makes the solution more extendable. do.call
在第一步中是不必要的,但使解决方案更具可扩展性。
也许这是作弊,但ggplot2中的(非导出)函数interleave
是我之前为自己使用而被盗的东西:
as.data.frame(mapply(FUN=ggplot2:::interleave,a,b))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.