I have a vector of weight and a list of the same length as weight. I want to calculate
the weighted average of each element of the list using the weight as shown below:
wt <- c(0.3, 0.5, 0.2)
temp_ls <- list(x = c(1, 2, 3, 4), y = c(5, 6, 7, 8), z = c(9, 10, 11, 12))
result_vec <- rep(length(temp_ls$x))
for(i in seq_along(temp_ls$x)){
temp_vec <- rep(NA, length(temp_ls))
for(j in seq_along(temp_ls)){
temp_vec[j] <- temp_ls[[j]][i]
}
result_vec[i] <- weighted.mean(temp_vec, wt)
}
result_vec
# 4.6 5.6 6.6 7.6
This approach seems way too complicated and long and wondered if any shorter method is there
using lapply family.