[R] Reshape from long to wide

aly alyabadia at gmail.com
Tue Mar 20 00:01:09 CET 2012


Hi,

I'm a total beginner in R and this question is probably very simple but I've
spent hours reading about it and can't find the answer. I'm trying to
reshape a data table from long to wide format. I've tried reshape() and
cast() but I get error messages every time and I can't figure why. In my
data, I have the length of two fish from each family. My data table (called
fish) looks like this:

family	length
14	18
14	7
15	7
15	21
17	50
17	21
18	36
18	21
20	36
20	42
24	56
24	42
25	43
25	56
27	15
27	42
28	7
28	42
29	56
29	49

I want it to look like this:

family kid1 kid2
14	18	7
15	7	21
17	50	21
18	36	21
28	36	42
24	56	42
25	43	56
27	15	42
28	7	42
29	56	49

I've tried:

>cast( fish, fam~length)

and got the error message:

Using length as value column.  Use the value argument to cast to override
this choice
Error in `[.data.frame`(data, , variables, drop = FALSE) : 
  undefined columns selected

Then I rename the columns:

>myvars<-c("fam","length")
>fish<-fish[myvars]

and try the cast() again with no luck (same error)

By using reshape() I don't get the results I want:

>reshape(rdm1, timevar="fam", idvar=c("length"), direction="wide")
> head(first)
               length
14.20        14
14.19         7
15.25        21
17.30        50
18.32        36
20.36        42

Can someone help with this? Thanks a lot!




--
View this message in context: http://r.789695.n4.nabble.com/Reshape-from-long-to-wide-tp4486875p4486875.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list