[R] grouping

Berend Hasselman bhh at xs4all.nl
Tue Apr 3 20:53:22 CEST 2012


On 03-04-2012, at 20:21, Val wrote:

> Hi All,
> 
> On the same data  points
> x=c(46, 125 , 36 ,193, 209, 78, 66, 242 , 297,45 )
> 
> I want to have have the following output  as data frame
> 
> x       group   group mean
> 46       1        42.3
> 125     2        89.6
> 36       1        42.3
> 193     3        235.25
> 209     3        235.25
> 78       2        89.6
> 66       2        89.6
> 242     3        235.25
> 297     3        235.25
> 45       1        42.3
> 
> I tried the following code
> 
> 
> dat <- data.frame(xc=split(x, cut(x, quantile(x, prob=c(0, .333, .66 ,1))))
> gxc <- with(dat, tapply(xc, group, mean))
> dat$gxc <- gxce[as.character(dat$group)]
> txc=dat$gxc
> 
> it did not work for me.
> 

I'm not surprised.

In the line dat <- there are 5 opening parentheses and 4 closing )'s.
In the line dat$gxc <- you reference an object gxce. Where was it created?

So I tried this

> dat <- data.frame(x, group=findInterval(x, quantile(x, prob=c(0, .333, .66 ,1)), all.inside=TRUE))
> dat$gmean <- ave(dat$x, as.factor(dat$group))
> dat
     x group     gmean
1   46     1  42.33333
2  125     2  89.66667
3   36     1  42.33333
4  193     3 235.25000
5  209     3 235.25000
6   78     2  89.66667
7   66     2  89.66667
8  242     3 235.25000
9  297     3 235.25000
10  45     1  42.33333

Berend



More information about the R-help mailing list