RcppRoll roll_median na.rm = TRUE gives unexpected results

Viewed 21

I am confused as to why roll_median(..., na.rm=TRUE) returns NA in the following reprex when there are 11 NA values, but returns a value when there are 10 NA values.

Please note: The dplyr window function vignette references using RcppRoll for computing rolling aggregates. As such, I am assuming the usage of RcppRoll with dplyr for computing rolling aggregates is fairly common and primarily interested in understanding the rationale for the behavior shown below. Here is a screenshot from dplyr window functions vignette.

enter image description here

First, basic computation with 0 NA values.

suppressPackageStartupMessages(library(dplyr))
library(RcppRoll)

mtcars %>%
  transmute(myroll = roll_medianr(mpg, n = nrow(mtcars), na.rm = TRUE)) %>%
  tail(1)
# myroll
# Volvo 142E   19.2

Now, with 10 NA rows, we still get a computed median value.

mtcars %>%
  mutate(mpg = ifelse(row_number() <= 10, NA, mpg)) %>%
  transmute(myroll = roll_medianr(mpg, n = nrow(mtcars), na.rm = TRUE)) %>%
  tail(1)
# myroll
# Volvo 142E   15.1

However, with 11 NA rows, we get an NA.

mtcars %>%
  mutate(mpg = ifelse(row_number() <= 11, NA, mpg)) %>%
  transmute(myroll = roll_medianr(mpg, n = nrow(mtcars), na.rm = TRUE)) %>%
  tail(1)
# myroll
# Volvo 142E     NA

Completely ignoring the actual values returns and simply focusing on NA vs . an actual value returned, why would 10 NAs in the data above return a value, but 11 NAs induce an NA return value?

Thus far, I am unable to find any explanations for this behavior looking in documentation or searching online. I am primarily interested in understanding the behavior as I know I can easily use other packages to do accomplish the rolling median, such as zoo as shown here.

suppressPackageStartupMessages(library(zoo))
# 10 NAs using rollapplyr
mtcars %>%
  mutate(mpg = ifelse(row_number() <= 10, NA, mpg)) %>%
  transmute(myroll = rollapplyr(mpg, width = nrow(mtcars), FUN = median, na.rm = TRUE, fill = NA)) %>%
  tail(1)
# myroll
# Volvo 142E  17.55

# 11 NAs using rollapplyr
mtcars %>%
  mutate(mpg = ifelse(row_number() <= 11, NA, mpg)) %>%
  transmute(myroll = rollapplyr(mpg, width = nrow(mtcars), FUN = median, na.rm = TRUE, fill = NA)) %>%
  tail(1)
# myroll
# Volvo 142E   17.3
0 Answers
Related