2013-02-09 11 views
7

vorrei intrecciare due data.frame in R. Per esempio:intrecciano due data.frames in R

a = data.frame(x=1:5, y=5:1) 
b = data.frame(x=2:6, y=4:0) 

Vorrei il risultato a guardare come:

> x y 
    1 5 
    2 4 
    2 4 
    3 3 
    3 3 
    ... 

ottenuto dalla cbind ing x[1] con y[1], x[2] con y[2], ecc

Qual è il modo più pulito per fare questo? In questo momento la mia soluzione implica sputare tutto in un elenco e unire. Questo è abbastanza brutto:

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

risposta

5

È possibile eseguire questa operazione fornendo x e un indice, rbind e ordinarli per l'indice.

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

Questo è come mi piacerebbe avvicino:

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

do.call era inutile nella prima fase, ma rende la soluzione più estensibile.

3

Forse questo è barare un po ', ma la funzione (non esportato) interleave da ggplot2 è qualcosa che ho rubato per i miei usi prima:

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

C'è, Naturalmente, la funzione interleave nel pacchetto "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