[R] weighed mean of a data frame row-by-row
Vassilis
vdimitrakas at gmail.com
Thu Jan 6 14:33:18 CET 2011
Dear list,
This must be an easy one. I have a data frame like this one:
test.df <- data.frame(x1=c(2,3,5), x2=c(5, 3, 4), w=c(0.8, 0.3, 0.5))
and I want to construct a weighted mean of the first two columns using the
third column for weighting; i.e.
y[1] = x1[1]*w[1] + x2[1]*(1-w[1])
y[2] = ...
One way to do this is to use a loop like
test.df$y <-numeric(3)
with(test.df,
for(i in 1:length(w)) {
test.df$y[[i]] <<- weighted.mean(c(x1[[i]],x2[[i]]),c(w[[i]],1-w[[i]]) ) }
)
My question is whether you can suggest a way to do the same without using a
`for' loop, a vectorized version of this snippet - My actual dataset is
large and it involves calculating the weighted mean of many columns. Such a
loop becomes ugly to write and quite slow....
Thanks in advance,
Vassilis
--
View this message in context: http://r.789695.n4.nabble.com/weighed-mean-of-a-data-frame-row-by-row-tp3177421p3177421.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list