I want to compute a weighted mean over factors with the code below
factor <- factor(cut(var1, quantile(var1, seq(0,1,0.1))))
var2_split = split(vat2, factor)
weight_split = split(weight, factor)
sapply(var2_split, weighted.mean, weight_split)
I get the following error
Error in FUN(X[[1L]], ...) : 'x' and 'w' must have the same length
How do I format my vector and weights for sapply?
As an example
suppose I have a matrix m with 3 columns x,y,z where x is a set of target values, y is a set of weights, and z is a set of values over which I want to bucket weighted.mean(x,y). Specifically I want weighted.mean(x,y) bucketed by quartiles of z.
# Code that doesn't work
x <- c(1,2,3,4,5,6)
y <- c(6,3,4,2,3,4)
z <- c(1,1,2,3,3,4)
m <- as.matrix(c(x,y,z),nrow=6,ncol=3))
# bucket z by quartile.
z.factor <- cut(z, quantile(z, seq(0,1,0.25)), include.lowest=TRUE)
x.split = split(x, z.factor)
y.split = split(y, z.factor)
# want to bucket weighted.mean(x,y) on quartiles of z
sapply(x.split, weighted.mean, y.split)