[R] Help with package reshape, wide to long

Don MacQueen macq at llnl.gov
Thu Feb 7 17:40:11 CET 2008


Hello,

I am having difficulty figuring out how to use functions in the 
reshape package to perform a wide to long transformation

I have a "wide" dataframe whose columns are like this example:

   id1 id2 subject treat height weight age

id1 and id2 are unique for each row
subject and treat are not unique for each row
height, weight, and age are different types of measurements made on 
each unique combination of subject and treatment

I want to reshape to a long format which will look like this:

  id1 id2 subject treat measurement.type value

where

measurement.type identifies the type of measurement, i.e. 'height', 
'weight', 'age'
value contains the values of those measurements
and the other variables are replicated as necessary

To put it another way, can I use reshape() to transform my original 
dataframe, which has 45 rows, into a "long" form that has 3*45  = 135 
rows:  45 rows for height, 45 for weight, 45 for age, with the other 
variables carried along as is within each set of 45, and a new 
variable that identifies the type of measurement in each row of the 
long form, i.e., 'height' in 45 rows, 'weight' in 45 rows, and 'age' 
in 45 rows.

I know it's not difficult to do this with explicit looping, using 
rbind(), but it seems like reshape() is a natural tool. But I'm not 
getting it, so I'd appreciate some help.

(in case anyone is wondering whether it makes sense to do this, 
height, weight, and age are just examples; it makes more sense with 
my actual measurements)

Thanks
-Don
-- 
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062



More information about the R-help mailing list