RE: [R] data transformation

From: Liaw, Andy <andy_liaw_at_merck.com>
Date: Sun 05 Jun 2005 - 12:20:51 EST


Try:

> da$z <- da$x - ave(da$x, da$y)
> da

    x y z
1 1 a -2
2 2 a -1
3 3 a 0
4 4 a 1
5 5 a 2
6 6 b -2
7 7 b -1
8 8 b 0
9 9 b 1
10 10 b 2

Andy

> From: ronggui
>
> i have data fame da:
> > da
> x y
> 1 1 a
> 2 2 a
> 3 3 a
> 4 4 a
> 5 5 a
> 6 6 b
> 7 7 b
> 8 8 b
> 9 9 b
> 10 10 b
> > str(da)
> `data.frame': 10 obs. of 2 variables:
> $ x: num 1 2 3 4 5 6 7 8 9 10
> $ y: Factor w/ 2 levels "a","b": 1 1 1 1 1 2 2 2 2 2
>
> and i want to generate new variable da$z,when
> y=="a",da$z=da$x-mean(x[y=="a"]) ,when
> y=="b",da$z=da$x-mean(x[y=="b"]).
>
> this data frame is simple and i can do it by hand,if the y
> has many levels and i have x1,x2....
> can i do it quickly?
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>
>
>



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Sun Jun 05 12:26:47 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:32:22 EST