[R] Hmisc: Using stratified weighted means (wtd.mean) within a function

Greg Blevins
2004-10-21T14:55:24Z

Hello list,

I have the following function which, as you can see, uses mean:

meanratings <-  round(apply(stack03[,c(102:121)],2,function(x) (tapply(x
,actcode, mean, na.rm=T))), digits=1)

The above function yields the following output:

   q27a q27b q27c q27d q27e q27f q27g q27h q27i q27j q27k q27l q27m q27o q27p
1   7.8  8.1  7.7  7.9  7.9  NaN  NaN  8.4  7.8  7.0  7.6  NaN  NaN  7.1  6.0
2   8.3  8.6  8.5  8.2  8.3  NaN  NaN  8.8  NaN  7.5  NaN  7.7  7.4  8.1  7.4
3   8.1  8.5  7.7  8.2  7.8  NaN  NaN  8.2  8.3  7.1  7.8  NaN  NaN  7.7  6.3
4   7.9  8.1  7.0  7.6  8.1  8.1  NaN  8.5  NaN  7.2  NaN  NaN  NaN  7.6  7.2
5   7.9  8.2  7.5  7.8  7.8  8.2  NaN  8.5  NaN  7.3  NaN  NaN  NaN  8.0  7.2
6   7.6  8.2  7.2  7.2  7.2  8.1  NaN  8.1  8.2  6.7  NaN  7.8  NaN  7.5  6.9
7   8.2  8.3  7.5  8.2  7.2  7.9  NaN  8.2  NaN  7.2  NaN  NaN  NaN  8.0  6.7
8   7.3  7.5  7.1  7.0  6.6  8.0  7.3  7.7  NaN  6.5  NaN  NaN  NaN  6.8  7.1
9   7.6  7.9  7.6  7.1  7.2  NaN  NaN  7.9  8.6  7.7  NaN  7.9  NaN  7.2  7.1
10  8.2  8.2  8.1  8.0  7.5  NaN  NaN  8.2  NaN  7.5  NaN  NaN  NaN  7.5  7.0
etc.

For my current situation, I need to have this function use a weighted mean and I
am trying to incorporate the 'wtd.mean' function from Hmisc.  I have
tried various scenarios relying on the documentation for 'wtd.mean' in
the Hmisc (shown below), but to no avail.  Any assistance would be much
appreciated.

set.seed(1)
x <- runif(500)
wts <- sample(1:6, 500, TRUE)
xg <- cut2(x,g=4)
# Here is a method for getting stratified weighted means
y <- runif(500)
g <- function(y) wtd.mean(y[,1],y[,2])
summarize(cbind(y, wts), llist(xg), g, stat.name='y')


Greg Blevins
The Market Solutions Group
Windows XP, 512 memory, Pentium 4.