r - Reshape three column data frame to matrix ("long" to "wide" format) -
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 make plot. result should like:
       b    c x   1    2    3 y   3    3    2 i have tried cast reshape package , have tried writing manual function not seem able right.
there many ways this. answer 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 use 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: https://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 data 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 
Comments
Post a Comment