Interweaving of two data. Frames in R

I would like to weave two data.frame into R. For example:

 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 this:

 > xy 1 5 2 4 2 4 3 3 3 3 ... 

it turns out cbind ing x[1] with y[1] , x[2] with y[2] , etc.

What is the cleanest way to do this? Right now, my solution includes splashing out the entire list and merging. This is pretty ugly:

 lst = lapply(1:length(x), function(i) cbind(x[i,], y[i,])) res = do.call(rbind, lst) 
+7
source share
4 answers

You can do this by specifying the x and y index, rbind them and sort by index.

 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")] 
+5
source

The "gdata" package has an interleave function:

 library(gdata) interleave(a, b) # xy # 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 
+12
source

Here's how I fit:

 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 extensible.

+4
source

This may change a bit, but the (non-exporting) interleave function from ggplot2 is what I stole for my own purposes before:

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

All Articles