[R] reshape

juli pausas
Sun, 10 Feb 2008 21:58:01 -0000

Dear colleagues,
I'd like to reshape a datafame in a long format to a wide format, but
I do not quite get what I want. Here is an example of the data I've
have (dat):

sp <- c("a", "a", "a", "a",
"b", "b", "b", "c", "d",
"d", "d", "d")
tr <- c("A", "B", "B", "C",
"A", "B", "C", "A", "A",
"B", "C", "C")
code <- c("a1", "a2", "a2", "a3",
"a3", "a3", "a4", "a4", "a4",
"a5",
"a5", "a6")
dat <- data.frame(id=1:12, sp=sp, tr=tr, val=31:42, code=code)

and below is what I'd like to obtain. That is, I'd like the tr
variable in different columns (as a timevar) with their value (val).

sp  code  tr.A  tr.B  tr.C
a    a1   31    NA    NA
a    a2   NA    32    NA
a    a2   NA    33    NA    **
a    a3   NA    NA    34
b    a3   35    36    NA
b    a4   NA    NA    37
c    a4   38    NA    NA
d    a4   39    NA    NA
d    a5   NA    40    41
d    a6   NA    NA    42

Using reshape:

reshape(dat[,2:5], direction="wide", timevar="tr",
idvar=c("code","sp" ))

I'm getting very close. The only difference is in the 3rd row (**),
that is when sp and code are the same I only get one record. Is there
a way to get all records? Any idea?

Thank you very much for any help

Juli Pausas

--