Fixing function arguments

# Update the function definition to fix the na.rm argument
calc_harmonic_mean <- function(x, na.rm = FALSE) {
  assert_is_numeric(x)
  if(any(is_non_positive(x), na.rm = TRUE)) {
    stop("x contains non-positive values, so the harmonic mean makes no sense.")
  }
  # Use the first value of na.rm, and coerce to logical
  na.rm <- coerce_to(use_first(na.rm), target_class = "logical")
  x %>%
    get_reciprocal() %>%
    mean(na.rm = na.rm) %>%
    get_reciprocal()
}

# See what happens when you pass it malformed na.rm
calc_harmonic_mean(std_and_poor500$pe_ratio, na.rm = 1:5)

When na.rm=1:5, I know we just use its first element 1. Then my problem is what the true or false now? I think 1 means true and 0 means false. But what about 2 (a number neither 0 nor 1)?

This test suggests any non zero value is TRUE.

MyFunc <- function(x){
  if(x) {
    print("True")
  } else {
    print("False")
  }
}
MyFunc(0)
#> [1] "False"
MyFunc(1)
#> [1] "True"
MyFunc(2)
#> [1] "True"
MyFunc(-1)
#> [1] "True"

Created on 2020-08-01 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.