Home > Enterprise >  zoo::rollapply generates an error when applying a function from another package to a column of a dat
zoo::rollapply generates an error when applying a function from another package to a column of a dat

Time:09-11

Here's a miminal example:

df_1 <- data. Frame( a = 1:10)

I have no trouble computing a rolling mean on a using zoo::rollapply

zoo::rollapply(df_1$a, 5, "mean", fill = NA, align = "right")
 [1] NA NA NA NA  3  4  5  6  7  8

But if I try to do the same with the HodgesLehmann function in DescTools, I generate an error:

> zoo::rollapply(df_1$a, 5, "DescTools::HodgesLehmann", fill = NA, align = "right")
Error in get(as.character(FUN), mode = "function", envir = envir) : 
  object 'DescTools::HodgesLehmann' of mode 'function' was not found

But i have no difficulty computing the Hodges Lehmann mean for df_1$a:

DescTools::HodgesLehmann(df_1$a)
[1] 5.5

What I am doing wrong, and how can I correct my error?

Sincerely and with many thanks in advance

Thomas Philips

CodePudding user response:

Try setting as an anonymous function.

zoo::rollapply(df_1$a, 5, function(x) DescTools::HodgesLehmann(x), fill = NA, align = "right")

#
[1] NA NA NA NA  3  4  5  6  7  8

CodePudding user response:

Remove the quotation marks around DescTools::HodgesLehmann:

zoo::rollapply(df_1$a, 5, DescTools::HodgesLehmann, fill = NA, align = "right")

You need to pass a function, not a character string.

It is surprising that FUN = "mean" works, but importantly FUN = mean works too. Perhaps zoo::rollapply has a few functions that it knows the name of.

  • Related