[R] aggregate question...

Marc Schwartz MSchwartz at MedAnalytics.com
Thu Mar 31 20:17:34 CEST 2005


On Thu, 2005-03-31 at 09:17 -0800, Jeff D. Hamann wrote: 
> R-folks,
> 
> Is there a function, like aggregate, that allows users to bin values?
> 
> I've got to break down a data frame into classes of 5cm (or something like
> it), and I only know how to do it using code like,
> 
> signif <- symnum( stems$dbh,
>                  corr = FALSE,
>                  na = FALSE,
>                  cutpoints = c(0,10,20,30,40,999),
>                  symbols = c(0,10,20,30,40) )
> 
> 
> rt <- data.frame( stems$expf,
> 		  signif = ordered( signif,
>                     levels = c(0,10,20,30,40) )
> 
> st <- aggregate( rt$stems.expf, by=list(signif), sum )
> 
> Is there a one line command to do this?

Jeff,

Sometimes the notion of a single line command is in the eye of the
beholder, since things can become easily obfuscated. However, something
like the following could work:

stems <- data.frame(expf = 1:100, 
                    dbh = sample(1:500, 100, replace = TRUE))

st <- aggregate(stems$expf, 
                by=list(cut(stems$dbh, 
                            breaks = c(0, 10, 20, 30, 40, 999))),
                sum)


> st
   Group.1    x
1   (0,10]   69
2  (10,20]  172
3  (20,30]  181
4  (30,40]  131
5 (40,999] 4497


Note that in the use of cut(), there are additional arguments relative
to including or not including the left and/or right hand interval values
in the respective intervals and what the labels should be. See ?cut for
more information.

HTH,

Marc Schwartz




More information about the R-help mailing list