[R] reshape

arun smartpink111 at yahoo.com
Sun Nov 17 18:50:38 CET 2013


Hi Felipe,
You may try ?mutate() with ?ddply() from library(plyr)
library(plyr)
library(reshape2)

res <- dcast(ddply(z,.(week),mutate,ID=seq_along(week)),ID~week,value.var="length")[,-1]

If you have multiple years, probably you may need:
z1 <- z ##using the same example
z1[,1] <- gsub("(.\\/.*\\/).*","\\1/2011",z1[,1]) ##changed the year
 z2 <- rbind(z,z1)

 res1 <- dcast(ddply(z2,.(year=gsub(".*\\/.*\\/","",date),week),mutate,ID=seq_along(week)),ID+year~week,value.var="length")

res1[with(res1,order(year,ID)),-1]

A.K.



On Sunday, November 17, 2013 12:00 PM, Felipe Carrillo <mazatlanmexico at yahoo.com> wrote:

The last one without the date seems to work for me, I have multiple years, I will try it on a bigger dataset.
I guess the trick is adding "ID" to the dataset with ave.  Is there anything similar to 'ave' in plyr?
Thanks Arun for your help, really appreciate it.

Felipe D. Carrillo
Supervisory Fishery Biologist
Department of the Interior
US Fish & Wildlife Service
California, USA
http://www.fws.gov/redbluff/rbdd_jsmp.aspx



On Sunday, November 17, 2013 10:38 AM, arun <smartpink111 at yahoo.com> wrote:
Felipe,

I get the results like this by running the code:
z <-read.table(text="date week length
7/13/2010 28 34
7/13/2010 28 35
7/14/2010 28 35
7/14/2010 28 35
7/14/2010 28 36
7/14/2010 28 36
7/20/2010 29 31
7/16/2010 29 34
7/18/2010 29 34
7/18/2010 29 34
7/21/2010 29 35
7/20/2010 29 36
7/21/2010 29 36
7/22/2010 29 36
7/16/2010 29 37
7/18/2010 29 37
7/20/2010 29 37
7/21/2010 29 37
7/21/2010 29 37
7/22/2010 29 37
7/22/2010 29 37",header=TRUE)

z$ID <- with(z,ave(seq_along(date),date,week,FUN=seq_along))

library(reshape2)
dcast(z,date+ID~week,value.var="length")[,-2]
        date 28 29
1  7/13/2010 34 NA
2  7/13/2010 35 NA
3  7/14/2010 35 NA
4  7/14/2010 35 NA
5  7/14/2010 36 NA
6  7/14/2010 36 NA
7  7/16/2010 NA 34
8  7/16/2010 NA 37
9  7/18/2010 NA 34
10 7/18/2010 NA 34
11 7/18/2010 NA 37
12 7/20/2010 NA 31
13 7/20/2010 NA 36
14 7/20/2010 NA 37
15 7/21/2010 NA 35
16 7/21/2010 NA 36
17 7/21/2010 NA 37
18 7/21/2010 NA 37
19 7/22/2010 NA 36
20 7/22/2010 NA 37
21 7/22/2010 NA 37

##Also, didn't got any error with ?reshape()
If you don't want the `dates`, then:
 z$ID <- with(z,ave(seq_along(week),week,FUN=seq_along))
dcast(z,ID~week,value.var="length")[,-1]
   28 29
1  34 31
2  35 34
3  35 34
4  35 34
5  36 35
6  36 36
7  NA 36
8  NA 36
9  NA 37
10 NA 37
11 NA 37
12 NA 37
13 NA 37
14 NA 37
15 NA 37

A.K.



More information about the R-help mailing list