[R] question about combining data in two frames

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Aug 7 19:30:00 CEST 2001


On 7 Aug 2001, Michael A. Miller wrote:

> Dear R Experts,
>
> I am still learning the subtleties or R programming and have a
> question about the best (==most elegant) way to combine data in
> two frames.  One frame is a table of measurements of sizes of
> objects in multiple image fields and the other is a table of
> areas for each field.  I want to calculate densities by dividing
> total number of objects in each field by the appropriate area.  I
> can do this like this:
>
> sizes <- read.table("marked/combined.meas", header=T)
> areas <- read.table("areas", header=T)
>
> # Number of objects in each field
> counts <- tapply( sizes$Diameter, factor(sizes$Field), length)
>
> # Density in each field
> for ( field in names(counts) ) {
>   print( counts[field]/areas$Area[areas$Field==field] )
> }
>
> I'd like to get my densities as a vector though.  It feels like
> there might be some way for me to use tapply (or some other R
> idiom) to do the same thing as this for-loop, but I haven't been
> able to hit upon it.  Can anyone offer suggestions?

>From what you have said, I think

counts / areas[match(names(counts), areas$Field), "Area"]

is what want.

> Also, are there other ways to get my sums than the way I'm using
> tapply above?

sapply(split(sizes$Diameter, sizes$Field), length)

is one.  However, I think table(sizes$Field) is all you need.


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list