1

I would like to expand a grid in R such that the expansion occurs for unique values of one variable but joint values for two variables. For example:

frame <- data.frame(id = seq(1:2),id2 = seq(1:2), year = c(2005, 2008))

I would like to expand the frame for each year, but such that id and id2 are considered jointly (e.g. (1,1), and (2,2) to generate an output like:

  id id2 year
   1  1   2005
   1  1   2006
   1  1   2007
   1  1   2005
   2  2   2006
   2  2   2007
   2  2   2008

Using expand.grid(), does someone know how to do this? I have not been able to wrangle the code past looking at each id uniquely and producing a frame with all combinations given the following code:

 with(frame, expand.grid(year = seq(min(year), max(year)), id = unique(id), id2 = unique(id2)))

Thanks for any and all help.

Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
coding_heart
  • 1,245
  • 3
  • 25
  • 46

2 Answers2

1

You could do this with reshape::expand.grid.df

require(reshape)
expand.grid.df(data.frame(id=1:2,id2=1:2), data.frame(year=c(2005:2008)))
> expand.grid.df(data.frame(id=1:2,id2=1:2), data.frame(year=c(2005:2008)))
  id id2 year
1  1   1 2005
2  2   2 2005
3  1   1 2006
4  2   2 2006
5  1   1 2007
6  2   2 2007
7  1   1 2008
8  2   2 2008
cdeterman
  • 19,630
  • 7
  • 76
  • 100
1

Here is another way using base R

 indx <- diff(frame$year)+1
 indx1 <- rep(1:nrow(frame), each=indx)
 frame1 <- transform(frame[indx1,1:2], year=seq(frame$year[1], length.out=indx, by=1))
 row.names(frame1) <- NULL
  frame1
  #  id id2 year
  #1  1   1 2005
  #2  1   1 2006
  #3  1   1 2007
  #4  1   1 2008
  #5  2   2 2005
  #6  2   2 2006
  #7  2   2 2007
  #8  2   2 2008
akrun
  • 874,273
  • 37
  • 540
  • 662