Maksym Maksym - 3 months ago 15
R Question

expand.grid function for data.frames in R

I have 2 data.frames with the following columns.

1) A,B,C,D
2) E,F,G,H

What I'd like to do, is create a new data.frame, which has a row for each element of expand.grid(1[,B]2[,F]) and would keep all other columns and values associated with the values of col B and col F from the original data.frames

I am currently doing this using 2 for loops and this is creating a pretty large running time since the data.frames I'm dealing with are rather large.

Here is a screenshot of what I am looking for:

> aa
A B C D
1 1 x 3 5
2 2 y 4 6
> bb
E F G H
1 7 j 9 11
2 8 k 10 12
> cc
A B C D E F G H
1 1 x 3 5 7 j 9 11
2 2 y 4 6 7 j 9 11
3 1 x 3 5 8 k 10 12
4 2 y 4 6 8 k 10 12

Answer

I think , you are looking for :

merge(aa,bb)

  A B C D E F  G  H
1 1 x 3 5 7 j  9 11
2 2 y 4 6 7 j  9 11
3 1 x 3 5 8 k 10 12
4 2 y 4 6 8 k 10 12