You can pass function (in this example mean) to rollapply at least in two different ways (note round brackets in 2nd example) as it is shown here:
> sub.as.avg.1 <- rollapply(sub.as, width = 1, by = 1, FUN = mean, align = "left")
> sub.as.avg.1 <- rollapply(sub.as, width = 1, by = 1, FUN = (mean), align = "left")
Now I want to pass function from variable. This one is working:
> fun
[1] "mean"
> r2 <- rollapply(sub.as, width = 1, by = 1, FUN = (fun), align = "left")
>
But this one is not:
> fun
[1] "(mean)"
> r2 <- rollapply(sub.as, width = 1, by = 1, FUN = fun, align = "left")
Error in get(as.character(FUN), mode = "function", envir = envir) :
object '(mean)' of mode 'function' was not found
How to make this work? What does round brackets mean for rollapply? Are they rollapply specific or it is something general to R?
EDIT: Based on @DavidGo answer I've tried following:
library(zoo)
sub.as <- c(1, 0.75, 0.9, 0.475, 0.925, 0.975, 1, 1, 0.525, 1, 0.2, 0.2,
0.2, 0.2, 0.15, 0.15, 0.15, 0.15, 0.15, 0.45, 0.875, 0.175, 0.15,
0.15, 0.15, 0.1, 0.1, 0.1, 0.1, 0.35, 1)
my.func <- function(x, fun){
result.vec <- rollapply(x, width = 1, by = 1, FUN = fun, align = "left")
result.vec
}
r1 <- my.func(sub.as, mean)
r2 <- my.func(sub.as, (mean))
But it seems like if I were using (mean) in both cases:
> sub.as - r1
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
> sub.as - r2
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
> identical(sub.as, r1)
[1] TRUE
> identical(sub.as, r2)
[1] TRUE