5.4 Checking values

Calculating weighted means

mean_wt <- function(x, w) {
  sum(x * w) / sum(w)
}
mean_wt(1:6, 1:6)
## [1] 4.333333

If you expect the lengths to be the same, then you should test for it in the function

mean_wt(1:6, 1:3)
## [1] 7.666667
mean_wt <- function(x, w) {
  if (length(x) != length(w)) {
    stop("`x` and `w` should be the same length")
  }
  sum(x * w) / sum(w)
}
mean_wt(1:6, 1:3)
## Error in mean_wt(1:6, 1:3): `x` and `w` should be the same length