Skip to content

About matrix manipulation

2 messages · Thiago Gonçalves-Souza, Rui Barradas

#
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: