-
Notifications
You must be signed in to change notification settings - Fork 130
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Bug Report: tbl_summary "is variable class supported?" error for numeric variables #1403
Comments
Hmmm, can you show the results of calling |
Both of those appear to work fine... library(tidyverse)
library(gtsummary)
df <-
structure(list(swallowing = structure(c(NA, 53, 100, 0, 100),
names = c("", "", "", "", "")),
salivation = structure(c(NA, 100, 46, 62, 100),
names = c("", "", "", "", ""))),
row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))
# median and quantile both appear to work fine on their own
quantile(df$swallowing, c(0.25, 0.75), na.rm = TRUE)
#> 25% 75%
#> 39.75 100.00
median(df$swallowing, na.rm = TRUE)
#> [1] 76.5 Created on 2022-12-15 by the reprex package (v2.0.1) |
The issue here has to do with some nonsense I had written in to keep the attributes of the original vector. I am trying to add the attr back to the result after the summary stat is calculated. But in this case, the attribute is an empty names attribute whose length does not match the summary statistic...therefore erring. I wonder if it would be simpler to just unclass everything before passing it to the summary function? I think this would destroy date summaries...probably something else too. Ugh, there is always something! safe_summarise_at <- function(data, variable, fns) {
tryCatch({
# ref for all this `.keep_attr()` nonsense stackoverflow.com/questions/67291199
dplyr::summarise_at(data,
vars("variable"),
map(
fns,
function(.x) {
if (identical(.x, stats::median))
return(rlang::inject(function(x) .keep_attr(x, .f = !!.x)))
else return(.x)
}
))
},
error = function(e) {
# replace p[0:100] stats with `quantile`
fns_names <- stringr::str_replace(names(fns), "^p\\d+$", "quantile") %>% unique()
paste(
"There was an error calculating the summary statistics",
"for {.val {variable}}. Is this variable's class",
"supported by {.code {fns_names}}?"
) %>%
cli::cli_alert_danger()
abort(e)
}
)
}
.keep_attr <- function(x, .f) {
x_att <- attributes(x)
res <- .f(x)
attributes(res) <- x_att
res
} |
When running tbl_summary() with the "continuous" option for all variables, I am getting an error that states there was an issue calculating summary statistics and asks whether the variable's class is supported by "median" and "quantile". However this is simply a numeric variable. The code works correctly for categorical variables and if I use
as.numeric
on the swallowing variable.Created on 2022-12-14 by the reprex package (v2.0.1)
The text was updated successfully, but these errors were encountered: