[R] Data frame transpose
Thomas W Blackwell
tblackw at umich.edu
Mon Sep 29 20:29:03 CEST 2003
Dave -
I'm not sure whether there is already a function which does
exactly what you want, because this is kind of a special case.
The functions I wold look at are: "by", "aggregate", "tapply",
"mapply", and, in the package "nlme" one I didn't know about
before called "gapply".
But, in your case, the part that makes it doable is that all
of the columns in that part of the dataframe which you want
to transpose are numeric. (At least, it looks that way from
your email.) And you have the same number of time points in
every site x date. So you could extract just the three columns
"time", "obs", "mod" as a numeric matrix, cast it to an array,
use aperm(), then cast it back to a matrix and then back to a
dataframe. The basic tools for this are: "data.matrix", "array",
"aperm", "matrix" and "data.frame".
I've got to let you work out the details yourself. The key
when planning this is to remember that multi-dimensional arrays
in R use Fortran storage order: the first index varies fastest.
Some one else may be able to come up with a much more direct
solution.
HTH - tom blackwell - u michigan medical school - ann arbor -
On Mon, 29 Sep 2003 Kang.Daiwen at epamail.epa.gov wrote:
> I want to ask if there is a transpose function for data frame like the
> procedure of transpose in SAS? Because I want to partially transpose a
> data frame which contains 5 columns (siteid, date, time, obs, mod), what
> I want to do is to put time as the column variables along with siteid,
> and date, and put obs and mod in the row names. specifically to
> transpose a data frame:
>
> siteid date time obs mod
> A 7/8 01 2 5
> A 7/8 02 3 8
> A 7/8 03 5 8
> A 7/9 01 3 6
> A 7/9 02 5 8
> A 7/9 03 6 7
> ......
> B 7/8 01 4 7
> B 7/8 02 7 19
> B 7/8 03 4 9
> ......
> To
>
> siteid date name 01 02 03 ....
> A 7/8 obs 2 3 5
> A 7/8 mod 5 8 8
> A 7/9 obs 3 5 6
> A 7/9 mod 6 8 7
> .......
> B 7/8 obs 4 7 4
> B 7/8 mod 7 19 9
> ........
>
> Thank you very much!
>
> Dave
More information about the R-help
mailing list