CGN
CGN

Reputation: 707

Merging datasets of different lengths by Year in R

I have a very basic question about merging two datasets of unequal length. One is a standard Panel

ID Time 
 1   1    
 1   2  
 1   3  
 2   1  
 2   2  
 2   3  

The second set has unequal lengths and looks like this

ID  Time X
 1   2   2
 2   1   3
 2   3   4

How can I combine these two by ID and time so that

ID Time  X 
 1   1   NA 
 1   2   2
 1   3   NA
 2   1   3
 2   2   NA
 2   3   4

Upvotes: 3

Views: 3059

Answers (1)

dickoa
dickoa

Reputation: 18437

Hi maybe you should look at the all.x or all.y options in the merge function.

Data1 <- data.frame(ID = rep(c(1,2), each = 3),
                    Time = rep(c(1, 2, 3), 2))
Data2 <- data.frame(ID = c(1, 2, 2),
                    Time = c(2, 1, 3),
                    X = c(2, 3, 4))
merge(Data2, Data1, all.y = TRUE)
  ID Time  X
1  1    1 NA
2  1    2  2
3  1    3 NA
4  2    1  3
5  2    2 NA
6  2    3  4

or using the plyr function join which faster than merge but lack some options :

join(Data2, Data1, type = "full")
Joining by: ID, Time
  ID Time  X
1  1    2  2
2  2    1  3
3  2    3  4
4  1    1 NA
5  1    3 NA
6  2    2 NA

Upvotes: 10

Related Questions