[R] splitting and reorganising a data.frame

jim holtman jholtman at gmail.com
Tue Apr 26 18:37:02 CEST 2011


try this:

> x
   nr height age Seed
1   1   4.51   3  301
2  15  10.89   5  301
3  29  28.72  10  301
4  43  41.74  15  301
5  57  52.70  20  301
6  71  60.92  25  301
7   2   4.55   3  303
8  16  10.92   5  303
9  30  29.07  10  303
10 44  42.83  15  303
11 58  53.88  20  303
12 72  63.39  25  303
13  3   4.79   3  305
14 17  11.37   5  305
15 31  30.21  10  305
16 45  44.40  15  305
17 59  55.82  20  305
18 73  64.10  25  305
> xtabs(height ~ Seed + age, x)
     age
Seed      3     5    10    15    20    25
  301  4.51 10.89 28.72 41.74 52.70 60.92
  303  4.55 10.92 29.07 42.83 53.88 63.39
  305  4.79 11.37 30.21 44.40 55.82 64.10
>


On Tue, Apr 26, 2011 at 10:57 AM, Lutze <lutzeputze at googlemail.com> wrote:
> Hey,
>
> i have a question about how to reorganize a data frame in the easiest way.
>
> my example:  what would be the easiest way to bring a data.frame such like this:
>
> ----
>   nr height age Seed
> 1   1   4.51   3  301
> 2  15  10.89   5  301
> 3  29  28.72  10  301
> 4  43  41.74  15  301
> 5  57  52.70  20  301
> 6  71  60.92  25  301
> 7   2   4.55   3  303
> 8  16  10.92   5  303
> 9  30  29.07  10  303
> 10 44  42.83  15  303
> 11 58  53.88  20  303
> 12 72  63.39  25  303
> 13  3   4.79   3  305
> 14 17  11.37   5  305
> 15 31  30.21  10  305
> 16 45  44.40  15  305
> 17 59  55.82  20  305
> 18 73  64.10  25  305
>
> ----- (the loblolly data)
>
> into this form:
>
> ----
>      3     5    10    15    20    25
> 301 4.51 10.89 28.72 41.74 52.70 60.92
> 303 4.55 10.92 29.07 42.83 53.88 63.39
> 305 4.79 11.37 30.21 44.40 55.82 64.10
> ---
> the columns contain the height for each age level and the row the seed level
>
>
> right now im doing it like this:
>
> groups <- split(data,Seed)
> data2 <- data.frame()
> for (group in groups)
> {
>  row <- data.frame(t(group[,2]))
>  colnames(row) <- group$age
>  rownames(row) <- group$Seed[1]
>  data2 <- rbind(data2,row)
> }
>
> but isnt there any nicer way? i need to teach some people how to do this, and i think this solution might be a bit confusing for the start.
>
> Thanks a lot,
> Lutz
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?



More information about the R-help mailing list