Skip to content

reshape data.frame

5 messages · Trevor Davies, William Dunlap, David Winsemius +1 more

#
You can use the reshape() in core R (the stats package)
name amount.1971 amount.1972 amount.1973 amount.1974
1     a           1           2           3           4
11    b          11          12          13          14
   amount.1975 amount.1976 amount.1977 amount.1978
1            5           6           7           8
11          15          16          17          18
   amount.1979 amount.1980 amount.1981 amount.1982
1            9          10          NA          NA
11          19          20          21          22
   amount.1983 amount.1984 amount.1985
1           NA          NA          NA
11          23          24          25

(Was naming the output columns "X.<year>" instead of "amount.<year>"
important?)

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#
On Nov 18, 2011, at 7:04 PM, Trevor Davies wrote:

            
wide.a <- reshape(a , direction="wide", idvar="name", timevar="year")
  names(wide.a) <- sub("amount", "x", names(wide.a) )
  wide.a
# -------------------
    name x.1971 x.1972 x.1973 x.1974 x.1975 x.1976 x.1977 x.1978 x. 
1979 x.1980 x.1981 x.1982 x.1983 x.1984 x.1985
1     a      1      2      3      4      5      6      7      8       
9     10     NA     NA     NA     NA     NA
11    b     11     12     13     14     15     16     17     18      
19     20     21     22     23     24     25
 >
David Winsemius, MD
West Hartford, CT
#
This is very straightforward using the reshape2 package:

library('reshape2')
dc <- dcast(a, name ~ year, value_var = 'amount')

  name 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
1    a    1    2    3    4    5    6    7    8    9   10   NA   NA   NA   NA
2    b   11   12   13   14   15   16   17   18   19   20   21   22   23   24
  1985
1   NA
2   25

dcast() returns a data frame; a companion function acast() returns a
matrix. If you want to change the names afterward, use

names(dc)[-1] <- paste('X', 1971:1985, sep = '.')

HTH,
Dennis
On Fri, Nov 18, 2011 at 4:04 PM, Trevor Davies <davies.trevor at gmail.com> wrote: