[R] long format with reshape

arun smartpink111 at yahoo.com
Thu Jan 24 14:35:23 CET 2013


HI,

You could use:
library(reshape)
 res<-melt(dat,id.var=c("region","state"))
names(res)[3:4]<-c("species","presence")
res<-res[rev(order(res$region,res$state)),]
 row.names(res)<- 1:nrow(res)
 res
  #  region state  species presence
#1   sydney   nsw species3        1
#2   sydney   nsw species2        1
#3   sydney   nsw species1        0
#4 canberra   act species3        0
#5 canberra   act species2        1
#6 canberra   act species1        1
A.K.




----- Original Message -----
From: Daisy Englert Duursma <daisy.duursma at gmail.com>
To: "r-help at R-project.org" <r-help at r-project.org>
Cc: 
Sent: Thursday, January 24, 2013 5:06 AM
Subject: [R] long format with reshape

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