[R] long format with reshape

Daisy Englert Duursma daisy.duursma at gmail.com
Thu Jan 24 11:06:56 CET 2013


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


do.call(rbind, dat2)


Daisy Englert Duursma
Department of Biological Sciences
Room E8C156
Macquarie University, North Ryde, NSW 2109

More information about the R-help mailing list