rttr

TTR runSD returns all NA


I think this came from an R/package update but now when I try to calculate the running standard deviation of a timeseries with an NA in it all I get is NA (current is R version 4.0.3, and TTR_0.24.2)

How do I get:

TTR::runSD(x = c(NA, 1:10), n = 1, cumulative = TRUE)

to exclude / ignore NA instead of returning:

 [1] NA NA NA NA NA NA NA NA NA NA NA

To something more like:

 [1] NA NaN 0.7071068 1.0000000 1.2909944 1.5811388 1.8708287 2.1602469 2.4494897 2.7386128 3.0276504

EDIT ideally return what it did under R version 3.5.2 and TTR_0.23-4 :

> TTR::runSD(x = c(NA, 1:10), n = 1, cumulative = TRUE)
 [1]       NA       NA 1.000000 1.172604 1.414214 1.677051 1.949359 2.226732 2.507133 2.789489 3.073181

Solution

  • An option is to create a function and update only those elements having non-NA elements

    f1 <- function(vec) {
          i1 <- !is.na(vec)
          vec[i1] <- TTR::runSD(x = vec[i1], n = 1, cumulative = TRUE)
          vec
      }
    
    f1(c(NA, 1:10))
    #[1]        NA       NaN 0.7071068 1.0000000 1.2909944 1.5811388 1.8708287 2.1602469 2.4494897 2.7386128 3.0276504