Skip to content
Prev 260152 / 398502 Next

reshaping issue

Hi:

Here's one way, using an abbreviated example:

du <- data.frame(v1 = factor(rep(1:10, each = 4)),
                 v2 = factor(rep(rep(1:2, each = 2), 10)),
                 v3 = factor(rep(1:2, 20)),
                 x1 = rnorm(40),
                 y1 = rnorm(40),
                 x2 = rnorm(40),
                 y2 = rnorm(40),
                 x3 = rnorm(40),
                 y3 = rnorm(40))

ds1 <- du[, grep('^[v,x]', names(du))]
ds2 <- du[, grep('^[v,y]', names(du))]

library(reshape2)
dm1 <- melt(ds1, id = grep('^v', names(ds1)), variable_name = 'xvars',
value_name = 'x')
dm2 <- melt(ds2, id = grep('^v', names(ds2)), variable_name = 'yvars',
value_name = 'y')

dm <- dm1
dm$y <- dm2$y
dm <- dm[with(dm, order(v1, v2, v3, xvars)), ]

If you already have the reshape package loaded, the value_name =
specification won't work; it requires reshape2 without the presence of
reshape. (Otherwise, you'll have to rename the value variable in each
of dm1 and dm2). The variable name vector may not be necessary, but is
included to show which variables have been reshaped into which rows.

The main trick is the grep() function: its use in the above code is to
pick out the variables whose names begin with v or x in the
construction of ds1, and to pick out the variables beginning with v or
y in ds2. Both ds1 and ds2 are then melted so that the values of the x
and y variables end up in one column in each melted data set. Since
they were melted the same way and have the same dimension, rather than
merging, it's simple enough to copy the y variable from the second
melted data frame to the first. A reordering of the rows produces the
final result.

HTH,
Dennis

On Tue, May 17, 2011 at 10:31 AM, Stijn Van Daele
<Stijn.VanDaele at ugent.be> wrote: