Context: I compute summary statistics by group, I need to use hmisc::wtd.quantile()
function because I have frequency of each value.
Problem: sometimes, all values are NAs and/or all weights are 0s or NAs. Then, wtd.quantile()
fails if weights = ...
is filled. The error message is:
Error in approx(cumsum(wts), x, xout = c(low, high), method = "constant", :
zero non-NA points
Question: do you know how to avoid this behaviour and get the expected NA
output (as all values are NA...)?
Here is some code to reproduce the error:
library(Hmisc)
# ex dataset
set.seed(555)
df_NA = data.frame(values = rep(NA, 5),
weights = rnorm(5))
# the problem
with(df_NA, wtd.quantile(values, weights = weights, na.rm = TRUE)) # does not work
with(df_NA, wtd.quantile(values, na.rm = TRUE)) # work
# same as
with(df_NA, stats::quantile(values, na.rm = TRUE)) # work
The outputs and the error:
> with(df_NA, wtd.quantile(values, weights = weights, na.rm = TRUE)) # does not work
Error in approx(cumsum(wts), x, xout = c(low, high), method = "constant", :
zero non-NA points
> with(df_NA, wtd.quantile(values, na.rm = TRUE)) # work
0% 25% 50% 75% 100%
NA NA NA NA NA
> # same as
> with(df_NA, stats::quantile(values, na.rm = TRUE)) # work
0% 25% 50% 75% 100%
NA NA NA NA NA