Hello,
Try the following.
library(reshape2)
# Don't need 'cbind'
mat <- data.frame(sp1=c(rep(0, 5), rep(1, 5)),
sp2=sample(c(rep(0, 6),rep(1, 4))),
fac=c(rep("a", 3), rep("b", 3), rep("c",
4)))
mat.new <- matrix (c(0, 1, 1, 1, 1, 1), nrow=2, ncol=3)
rownames(mat.new) <- c("sp1", "sp2")
colnames(mat.new) <- c("a", "b", "c")
m <- melt(mat, id.vars = "fac")
result <- xtabs(value ~ variable + fac, data = m)
result <- apply(result, 2, function(x) ifelse(x == 0, 0, 1))
Hope this helps,
Rui Barradas
Em 21-08-2012 20:29, Thiago Gon?alves-Souza escreveu:> Dear list,
>
> I'm trying to create a matrix by combining the sites that species occur
in
> a new matrix with species as rows and sites as columns.
>
> The main matrix is "mat":
>
> mat <- as.data.frame(cbind(sp1=c(rep(0, 5), rep(1,
5)),sp2=sample(c(rep(0,
> 6),rep(1, 4))),
> fac=c(rep("a", 3), rep("b", 3),rep("c", 4))))
>
> The first two columns are species and the third one is the site that
> species occur (value 1) or not (value 0).
>
> The resulting matrix ("mat.new") should be like this one:
>
> mat.new <- matrix (c(0, 1, 1, 1, 1, 1), nrow=2, ncol=3)
> rownames(mat.new) <- c("sp1", "sp2")
> colnames(mat.new) <- c("a", "b", "c")
> mat.new
>
> So, species are now the rownames and sites are colnames and the values
> within this matrix are the presence/absence of each species. I've tried
> aggregate, tapply, sapply functions but I wasn't able to re-create that
> matrix.
>
> Thanks in advance,
>
> Thiago.
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.