Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interweave two data.frames in R

I would like to interweave two data.frame in 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:

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

obtained by cbinding x[1] with y[1], x[2] with y[2], etc.

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)
like image 520
Alex Avatar asked Feb 09 '13 04:02

Alex


People also ask

How do I combine two data frames in R?

To join two data frames (datasets) vertically, use the rbind function. The two data frames must have the same variables, but they do not have to be in the same order. If data frameA has variables that data frameB does not, then either: Delete the extra variables in data frameA or.

How do I join more than two data frames in R?

To join more than two (multiple) R dataframes, then reduce() is used. It is available in the tidyverse package which will convert all the dataframes to a list and join the dataframes based on the column.

How do I combine two Tibbles in R?

Use full_join() , left_join() , right_join() and inner_join() to merge two tables together. Specify the column(s) to match between tables using the by option. Use anti_join() to identify the rows from the first table which do not have a match in the second table.

How do I merge two Dataframes based on a column in R?

The merge() function in base R can be used to merge input dataframes by common columns or row names. The merge() function retains all the row names of the dataframes, behaving similarly to the inner join. The dataframes are combined in order of the appearance in the input function call.


2 Answers

There is, of course, the interleave function in the "gdata" package:

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
like image 129
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 22 '22 03:09

A5C1D2H2I1M1N2O1R2T1


You can do this by giving x and y an index, rbind them and sort by the 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")]
like image 38
R J Avatar answered Sep 22 '22 03:09

R J