On Sun, 11 Oct 2009, Ozan Bak???~_ wrote:

Hi R-users,

I would like to calculate weighted mean of several
variables by two factors where the weight vector is
the same for all variables.

Below, there is a simple example where I have only two
variables: "v1","v2" both weighted by "wt" and my factors
are "gender" and "year".

set.seed(1)
df <- data.frame(gender = rep(c("M", "F"),each = 5),
     year = rep(c(1999, 2000), 5), v1 = rnorm(10,10),
     v2 = rnorm(10,6), wt = runif(10))
df
g <- function(x) weighted.mean(x[, 1], x[, 2])
by(df[,c("v1","wt")],df[,c("year","gender")],g)

I can use as above by command for each variable (v1,v2)
separately but I wonder if there is some simpler way
that yields a table/data frame of weigted means for all
"vi"s where i=1...N.



This is R; There are lots of ways.

Here is one:

lm( cbind( v1, v2 ) ~ 0 + gender:factor(year), df, weight=wt)

Call:
lm(formula = cbind(v1, v2) ~ 0 + gender:factor(year), data = df, weights = wt)

Coefficients:
                          v1      v2
genderF:factor(year)1999  10.573   6.795
genderM:factor(year)1999   9.534   6.633
genderF:factor(year)2000   9.741   6.422
genderM:factor(year)2000  10.834   5.190

HTH,

Chuck


Thank you very much,
ozan

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Charles C. Berry                            (858) 534-2098
                                            Dept of Family/Preventive Medicine
E mailto:cbe...@tajo.ucsd.edu               UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to