I have the following data set (a simple version of my actual data), “data” and would like to calculate the weighted means for the variables x1 and x2, using the weights w1 and w2, respectively, divided into two groups (groups defined by the variable n).
data <- data.frame(n = c(1,1,1,2,2,2), x1 = c(4,5,4,7,5,5), x2 = c(7,10,9,NaN,11,12), w1 = c(0,1,1,1,1,1), w2 = c(1,1,1,0,0,1))
I try to do this with (), but I get an error message at startup:
with(data, aggregate(x = list(x1=x1, x2=x2), by = list(n = n), FUN = weighted.mean, w = list(w1 = w1,w2 = w2)))
On the other hand, if no scales are specified, it works, but in this case the default weights are used (for example, using FUN = mean).
with(data, aggregate(x = list(x1=x1, x2=x2), by = list(n = n), FUN = weighted.mean))
This question is similar to weighted means by group and column , except that my question includes different weight values for different columns. I tried using a data table, but it came up with the same weighting errors as with (). Thanks in advance for any help.