[R] Data frame transpose

Gabor Grothendieck ggrothendieck at myway.com
Mon Sep 29 23:47:18 CEST 2003



Sorry about the formatting in that previous email.  Here it is
again, hopefully with the correct formatting this time.

Assuming that the data frame is called m, you can 
- split the data frame by the values of siteid and date
- apply a function to create the new data frame for each such group and 
- use rbind to put it back together like this: 

fn <- function(x) {
  y <- t(x[,4:5])
  data.frame( siteid=x[1,1], date=x[1,2], name=colnames(x)[4:5], x01=y[,1], x02=y[,2], x03=y[,3] )
 }
m <- do.call( "rbind", lapply(split(m,list(m$siteid,m$date)),fn) )

If order matters, add this:

m <- m[order(m$siteid,m$date),]





 --- On Mon 09/29,  < Kang.Daiwen at epamail.epa.gov > wrote:
From:  [mailto: Kang.Daiwen at epamail.epa.gov]
To: r-help at stat.math.ethz.ch
Date: Mon, 29 Sep 2003 13:15:36 -0400
Subject: [R] Data frame transpose

<br><br><br><br>Hi All,<br><br>I want to ask if there is a transpose function for data frame like the<br>procedure of transpose in SAS? Because I want to partially transpose a<br>data frame which contains 5 columns (siteid, date, time, obs, mod), what<br>I want to do is to put time as the column variables along with siteid,<br>and date, and put obs and mod in the row names. specifically to<br>transpose a data frame:<br><br>siteid     date    time   obs     mod<br>    A       7/8        01       2         5<br>    A       7/8        02        3        8<br>    A       7/8        03        5        8<br>     A       7/9       01       3          6<br>   A         7/9      02        5          8<br>   A         7/9       03       6           7<br>                       ......<br>   B         7/8      01          4         7<br>    B        7/8      02        7        19<br>   B         7/8     03         4        9<br>                      ......<br><br>To<br><br>siteid    date    name     01    02     03   ....<br>A              7/8       obs       2      3        5<br>A              7/8       mod      5      8        8<br>A              7/9       obs       3      5         6<br>A              7/9       mod      6      8        7<br>                 .......<br>B              7/8        obs       4      7        4<br>B              7/8        mod      7      19      9<br>                ........<br><br><br>Thank you very much!<br><br>Dave<br><br>______________________________________________<br>R-help at stat.math.ethz.ch mailing list<br>https://www.stat.math.ethz.ch/mailman/listinfo/r-help<br>

_______________________________________________
No banners. No pop-ups. No kidding.
Introducing My Way - http://www.myway.com




More information about the R-help mailing list