Hi Toby,
Have a look at the reshape package, http://had.co.nz.
Code something like the following should do what you want:
library(reshape)
dfm <- melt(data, id=1:3)
dfm <- rename(dfm, c(variable = "month")) # to make it more obvious
cast(dfm, ... ~ var)
Hadley
On 12/20/06, Toby Gass <tobygass at warnercnr.colostate.edu>
wrote:> Dear HelpeRs:
>
> I have a data set in the following format,
> which will be familiar to those of you working
> with NCDC climate data.
>
> Example:
>
> Year <- rep(1:3, each = 3)
> Year <- c(Year,Year)
> ID <- rep(1:2, each = 9)
> Jan <- runif(18, min = 0, max = 20)
> Feb <- runif(18, min = 0, max = 20)
> Mar <- runif(18, min = 0, max = 20)
> var <- gl(3,1,18,label =
c("snow","rain","temp"))
> data <-data.frame(row.names = c(1:18),ID, Year, var, Jan,
> Feb, Mar)
>
>
> The actual dataset has 12 months, about 100 years, 6 ID's,
> many more levels in "var", and includes NA's.
>
>
> I would like to convert the data to the following format:
>
> ID Year Month Rain Snow Temp
> 1 1 Jan value value value
> 1 1 Feb value value value
> 1 1 Mar value value value
> . . . . .
> . . . . .
> . . . . .
> 1 2 Jan value value value
> 1 2 Feb value value value
> 1 2 Mar value value value
> . . . . . .
> . . . . . .
> . . . . . .
> 1 3 Jan value value value
> 1 3 Feb value value value
> 1 3 Mar value value value
> . . . . . .
> . . . . . .
> 2 1 Jan value value value
> 2 1 Feb value value value
> 2 1 Mar value value value
> . . . . .
> . . . . .
> . . . . .
> 2 2 Jan value value value
> 2 2 Feb value value value
> 2 2 Mar value value value
>
> and so on.
>
> I'd appreciate some code that would help accomplish this.
> Since I'm not an R expert, code that is somewhat transparent
> might be more helpful to me than the shortest possible
> option.
>
> Thank you.
>
>
> Toby Gass
> Department of Forest, Rangeland, and Watershed Stewardship
> Warner College of Natural Resources
> Colorado State University
> Fort Collins, CO 80523
> Phone: 970-491-7257
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>