[R] long format with reshape
Gerrit Eichner
Gerrit.Eichner at math.uni-giessen.de
Thu Jan 24 11:24:16 CET 2013
Hi, Daisy,
try
dat2 <- reshape( dat, varying = c( "species1", "species2", "species3"),
v.name = "presence", timevar = "species",
times = c( "species1", "species2", "species3"),
direction="long")
dat2[ rev( order( dat2$region)), ]
Hth -- Gerrit
On Thu, 24 Jan 2013, Daisy Englert Duursma wrote:
> Hello,
>
> I tried using reshape to rearrange my data to long format but I could
> not get the output the table they way I wanted it. Anyway I came up
> with a hack that does works, but I still would like to know if I can
> do it with reshape.
>
> Here is my code and a dummy set of data. It returns the data in the
> format I would like it.
>
>
> dat <- read.table(text="region state species1 species2 species3
> sydney nsw 0 1 1
> canberra act 1 1 0", header=T)
>
> nonspecvars <- c("region","state")
>
> dats <- split(dat, 1:nrow(dat))
> dat2 <- lapply(dats,function(x){
>
> datspec <- x[,-match(nonspecvars,names(x))]
> specnames <- names(datspec)
> presence <- unname(unlist(datspec))
>
> x2 <- x[rep(1,length(specnames)),match(nonspecvars,names(x))]
> x2$species <- specnames
> x2$presence <- presence
> return(x2)
>
> })
>
> do.call(rbind, dat2)
>
>
> Cheers,
> Daisy
>
>
>
> --
> Daisy Englert Duursma
> Department of Biological Sciences
> Room E8C156
> Macquarie University, North Ryde, NSW 2109
> Australia
>
> ______________________________________________
> R-help at r-project.org 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.
More information about the R-help
mailing list