r - Reshape three column data frame to matrix -



r - Reshape three column data frame to matrix -

i have data.frame looks this.

x 1 x b 2 x c 3 y 3 y b 3 y c 2

i want in matrix form can feed heatmap create plot. result should like:

b c x 1 2 3 y 3 3 2

i have tried cast reshape bundle , have tried writing manual function not seem able right.

there many ways this. reply starts favorite ways, collects various ways answers similar questions scattered around site.

tmp <- data.frame(x=gl(2,3, labels=letters[24:25]), y=gl(3,1,6, labels=letters[1:3]), z=c(1,2,3,3,3,2))

using reshape2:

library(reshape2) acast(tmp, x~y, value.var="z")

using matrix indexing:

with(tmp, { out <- matrix(nrow=nlevels(x), ncol=nlevels(y), dimnames=list(levels(x), levels(y))) out[cbind(x, y)] <- z out })

using xtabs:

xtabs(z~x+y, data=tmp)

you can utilize reshape, suggested here: convert table matrix column names, though have little manipulation afterwards remove columns , names right (not shown).

> reshape(tmp, idvar="x", timevar="y", direction="wide") x z.a z.b z.c 1 x 1 2 3 4 y 3 3 2

there's sparsematrix within matrix package, seen here: r - convert big table matrix column names

> with(tmp, sparsematrix(i = as.numeric(x), j=as.numeric(y), x=z, + dimnames=list(levels(x), levels(y)))) 2 x 3 sparse matrix of class "dgcmatrix" b c x 1 2 3 y 3 3 2

the daply function plyr library used, here: http://stackoverflow.com/a/7020101/210673

> library(plyr) > daply(tmp, .(x, y), function(x) x$z) y x b c x 1 2 3 y 3 3 2

dcast reshape2 works, here: reshape info values in 1 column, data.frame column x value.

> dcast(tmp, x~y, value.var="z") x b c 1 x 1 2 3 2 y 3 3 2

similarly, spread "tidyr" work such transformation:

library(tidyr) spread(tmp, y, z) # x b c # 1 x 1 2 3 # 2 y 3 3 2

r matrix data.frame plyr reshape

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -