[R] melt with complications

arun smartpink111 at yahoo.com
Mon Mar 18 22:25:21 CET 2013


HI,
Not sure whether this is what you wanted.
library(reshape2)
result.dcast<-dcast(meltTest,A+D~H,value.var="M")
attr(result.reshape,"reshapeWide")<-NULL
 row.names(result.reshape)<-1:nrow(result.reshape)
 identical(result.reshape,result.dcast)
#[1] TRUE
result.dcast
#  A D  I  J  K  L
#1 B E  1  2  3  4
#2 B F  5  6  7  8
#3 B G  9 10 11 12
#4 C E 13 14 15 16
#5 C F 17 18 19 20
#6 C G 21 22 23 24

A.K.





----- Original Message -----
From: Richard M. Heiberger <rmh at temple.edu>
To: r-help <r-help at r-project.org>; Hadley Wickham <h.wickham at gmail.com>
Cc: 
Sent: Monday, March 18, 2013 1:15 PM
Subject: [R] melt with complications

## Can someone suggest a simpler expression than either of these, with the
goal
## of taking a long matrix into a wide one with exactly one of the factors
converted to
## columns and all the rest retained as factors.  I want something that
generalizes beyond
## the three factors illustrated here.

## Rich

meltTest <- data.frame(A=rep(c("B","C"), each=12),
                       D=rep(c("E","F","G"), each=4, times=2),
                       H=rep(c("I","J","K","L"), times=6),
                       M=1:24)

meltTest

result.melt <- do.call("rbind", {
  tmp <- cast(D ~ H | A, value="M", data=meltTest)
  lapply(names(tmp), function(x) cbind(A=x, tmp[[x]])) ## explicit use of
name "A"
})
result.melt

result.reshape <- reshape(meltTest, direction="wide", timevar="H",
idvar=c("A","D"))
names(result.reshape)[3:6] <- unique(as.character(meltTest$H))  ## explicit
use of name "H"
result.reshape

    [[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.




More information about the R-help mailing list