Skip to content

Help with reshape/reShape and indexing

1 message · Ista Zahn

#
Hi Dana,
There are usually many ways to accomplish any given task in R, and
which one you use is a matter of preference. I've settled on use the
reshape package for these kinds of tasks. If you're comfortable with
the solutions already suggested there's no need to continue reading.
Otherwise here's another approach:
Easy enough with the plyr package (loaded with reshape):

df = data.frame(Name=c("a", "a", "a", "b", "b", "c"), X1=c("12", "13",
"14", "20", "25", "30"), X2 = c(200, 250, 300, 600, 700, 4))
library(reshape)
df$Index <- ddply(df, "Name", colwise(seq_along))[,1]
I don't really understand this. What happened to X2? Anyway, I would
do it like this:
Name variable  1    2    3
1    a       X1 12   13   14
2    b       X1 20   25 <NA>
3    c       X1 30 <NA> <NA>

But I don't see why you want to drop X2, so I would actually do

df = data.frame(Name=c("a", "a", "a", "b", "b", "c"), X1=c("12", "13",
"14", "20", "25", "30"), X2 = c(200, 250, 300, 600, 700, 4))
df$Index <- ddply(df, "Name", colwise(seq_along))[,1]
df$X2 <- as.character(df$X2)
m.df <- melt(df, measure.vars=c("X1","X2"))
df.final <- cast(m.df, ... ~ Index)
df.final
  Name variable   1    2    3
1    a       X1  12   13   14
2    a       X2 200  250  300
3    b       X1  20   25 <NA>
4    b       X2 600  700 <NA>
5    c       X1  30 <NA> <NA>
6    c       X2   4 <NA> <NA>

All the best,
Ista