[R] sorted reshaping?

ivo welch ivowel at gmail.com
Sat Jan 23 14:25:04 CET 2010


thank you, dennis.  your example was much better than my own, too.

for everyone else's benefit who will be searching for the answers for
this problem on r-help, let me extend this a little.   the problem
arises primarily in data sets that are sparse.  in my case, the first
(ordered) firm does not have data in the first (ordered) year.

> firm <- c(0,rep(1:10, each = 5))
> year <- c(2004,rep(2002:2006, 10))
> resp <- c(1.0,rnorm(50))
> dat.long <- data.frame(firm = firm, year = year, resp = resp)
> dat.wide <- reshape(dat.long, direction = 'wide', idvar = 'firm', timevar= 'year')
> head(dat.wide)

yields

   firm resp.2004 resp.2002 resp.2003 resp.2005 resp.2006
1     0    1.0000        NA        NA        NA        NA
2     1   -0.4483   -0.7623    1.0625    0.4654  -0.36041
7     2   -0.1373   -0.8648    0.7272    0.1637  -0.09235
12    3    1.0835    0.4544    0.1577   -1.6991  -1.04559
17    4    1.1390    2.1633   -1.2298    0.9460  -0.28682
22    5   -0.8906    1.0084   -0.1948   -0.6801  -0.47192


in contrast, the library(reshape) function did yield the desired order:

> library(reshape)
Loading required package: plyr
> dat.cast <- cast(dat.long, firm ~ year)
Using resp as value column.  Use the value argument to cast to
override this choice
> head(dat.cast)
  firm    2002    2003    2004    2005     2006
1    0      NA      NA  1.0000      NA       NA
2    1 -0.7623  1.0625 -0.4483  0.4654 -0.36041
3    2 -0.8648  0.7272 -0.1373  0.1637 -0.09235
4    3  0.4544  0.1577  1.0835 -1.6991 -1.04559
5    4  2.1633 -1.2298  1.1390  0.9460 -0.28682
6    5  1.0084 -0.1948 -0.8906 -0.6801 -0.47192


I think this example would make a nice addition to "?reshape".  for
"see also", I would add library(reshape).  finally, it would be nice
if an email would be on each R help (in R documentation) to make
suggestions for improvements.

regards,

/iaw
----
Ivo Welch (ivo.welch at brown.edu, ivo.welch at gmail.com)



More information about the R-help mailing list