[R] tapply and weighted.mean

Jan.Schelling@hydro.com Jan.Schelling at hydro.com
Fri Nov 26 08:42:47 CET 1999



Try passing an index rather than the data itself:


tapply(seq(along=wage), list(Educc,Year), function(i, x=wage, w=weight)
weighted.mean(x[i], w[i]))



regards

Jan

--

Jan Schelling
Norsk Hydro
Research Centre
N - 3925 Porsgrunn



----------question:----------------

mjantti at ra.abo.fi on 99-11-25 04:48 PM GMT

I am trying to use tapply to estimate the average wage in a set of
      Year*Education cells using sampling weights, as well as some other
      other statistics using the weights). I am having trouble trying
      to figure out how to pass the weights to the function, using:

> tapply(wage,list(Educc,Year),weighted.mean, w=weight)

whieh produces warnings of the type:

3: longer object length
     is not a multiple of shorter object length in: x * w

The reason for this became obvious on inspecting the code for
tapply. The extra argument 'w=weight' gets passed in its entirety to
FUN ('weighted.mean'), as of course would be expected for an argument
such as 'trim'. Thus, apparently all of 'weight' gets passed to the
function weighted.mean and thus only the first n(i,j) weights in every
cell, rather than the weight that apply to the observations in a
particular cell.

I am unable, unfortunately, to figure out how to implement a function
that would take the weights as an argument. For instance,
experimentation showed that

> tapply(cbind(wage,weight),list(Educc,Year),
     function(x) weighted.mean(x[,1],x[,2]))

was just as unsuccessful. I suspect there is a fairly simple solution
to this, but I fail to see what it is and trial-and-error has not been
helpful.  I would greatly appreciate any help.



Regards,

Markus
--
Markus Jantti                 |    Department of Statistics
markus.jantti at abo.fi               |     Abo Akademi University
http://www.abo.fi/~mjantti         |     FIN 20500 Turku, Finland
358-9-643 747  (Home/Voice)        |     358-2-2154 161      (Office/Voice)
                         |    358-2-2154 677  (Office/Fax)
PGP public key: http://www.abo.fi/~mjantti/pubring.as


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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