I need to calculate the moving, weighted average by group in R.
Below is a sample of my code:
df %>% arrange(Type, Year)group_by(Type) %>% mutate("weighted.rolling.mean" = rollapplyr( df %>% select(Value, Area), width = 50, function(z){ return( weighted_mean = weighted.mean(z[,"Value"],z[,"Area"], partial = TRUE) ) }, by.column = FALSE, align = "right", fill=NA ))
Without the group_by
argument, the code works fine.
If I group_by
inside the rollapplyr
function, I get the error below:
Error in `mutate()`:ℹ In argument: `weighted.rolling.mean = rollapplyr(...)`.ℹ In group 1: `Type = "Etageadskillelse"`.Caused by error in `x * w`:! non-numeric argument to binary operatorBacktrace: 1. ... %>% ... 9. zoo::rollapplyr(...) 11. zoo:::rollapply.default(..., align = align) 14. zoo:::rollapply.zoo(zoo(data), ...) 15. base::mapply(...) 16. zoo (local) `<fn>`(dots[[1L]][[50L]], dots[[2L]][[50L]], data = `<chr[,4]>`) 17. FUN(data[posns, ], ...) 19. stats:::weighted.mean.default(z[, "Value"], z[, "Area"], partial = TRUE)
Many thanks in advance!