2013-02-09 36 views
7

交織2個data.frames我想交織2 data.frame在R.例如:中的R

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) 

回答

5

您可以通過給xy索引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")] 
4

這是我想的辦法:

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

do.call是在第一個步驟沒有必要,而且使得該解決方案更加擴展。

3

也許這是欺騙了一點,但(非出口)函數interleaveGGPLOT2的東西之前,我已經偷了我自己的用途:

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

有,的當然,在「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