0

I am having an issue merging 2 dataframes in R - one is a time series cross-section (i.e. a panel) and the other is a simple time series. Suppose I have two dataframes, df1 and df2, that I would like to merge. The panel dataframe df1 is given by

id year var1
1   80    3
1   81    5
1   82    7
1   83    9
2   80    5
2   81    5
2   82    7
2   83    5
3   80    9
3   81    9
3   82    7
3   83    3

while the time series dataframe df2 is given by

year var2
80   10
81   15
82   17
83   19

I would like to merge df1 and df2 into a third dataframe df, while preserving the time series cross-section row ordering of df1. However, when I use the command

df <- merge(df1, df2, by="year")

the new dataframe clusters the observations by year.

year id var1 var2
80  1    3   10
80  2    5   10
80  3    9   10
81  1    5   15
81  2    5   15
81  3    9   15
82  1    7   17
82  2    7   17
82  3    7   17
83  1    9   19
83  2    5   19
83  3    3   19

Does anyone know how I can make the row ordering in df the same as in df1? Thanks in advance!

Larry
  • 45
  • 5
  • Is your question all about ordering your merged data frame? Perhaps this is a misunderstanding, but just in case, here's a link to the many ways in which you can order data frames: http://stackoverflow.com/questions/1296646/how-to-sort-a-dataframe-by-columns-in-r – maj Jul 05 '14 at 23:25
  • Thanks! The link you provided was very helpful indeed. Problem solved. – Larry Jul 06 '14 at 00:50

0 Answers0