Let's say I have the following dataframe:
df <- as.data.frame(rbind(c(5, NA, NA, 1, NA, NA),
c(NA, 2, 2, NA, 0.5, 0.5),
c(NA, NA, NA, NA, NA, NA),
c(1, 1, 1, 0.33, 0.33, 0.33)))
colnames(df) <- c("V1", "V2", "V3", "W1", "W2", "W3")
I would like to add a weighted mean to the dataframe, discarding the NA when they exist. For example, in the first line, we would only take V1 and W1 to calculate the weighted mean.
My final dataframe would look like this:
V1 V2 V3 W1 W2 W3 Wmean
1 5 NA NA 1 NA NA 5
2 NA 2 2 NA 0.5 0.5. 2
3 NA NA NA NA NA NA NA
4 1 1 1 .33 .33 .33 1
Note that the weighted mean is calculated as such: Wmean = (V1*W1 + V2*W2 + V3*W3)/(W1 + W2 + W3)