[R] grouping

Berend Hasselman bhh at xs4all.nl
Tue Apr 3 21:07:37 CEST 2012


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

> 
> 
> On Tue, Apr 3, 2012 at 2:53 PM, Berend Hasselman <bhh at xs4all.nl> wrote:
> 
> 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))

And the as.factor is not necessary. This will do

dat$gmean <- ave(dat$x, dat$group)

Berend



More information about the R-help mailing list