Skip to content
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: Variable with all NA levels causes error #1973

Open
szimmer opened this issue Sep 13, 2024 · 2 comments
Open

Bug Report: Variable with all NA levels causes error #1973

szimmer opened this issue Sep 13, 2024 · 2 comments

Comments

@szimmer
Copy link
Contributor

szimmer commented Sep 13, 2024

Per discussion on Posit Community forum, a error is yielded when a column consists entirely of missing data. This should be handled more gracefully


library(tidyverse)
library(gtsummary)

set.seed(8675309)

mydf <- tibble(
  Group=rep(1:4, each=20),
  CatValid=as.factor(sample(letters[1:4], 80, replace=TRUE)),
  CatNA=factor(NA)
)

mydf %>%
  select(-CatNA) %>%
  tbl_summary(by="Group")
Characteristic 1
N = 20
1
2
N = 20
1
3
N = 20
1
4
N = 20
1
CatValid



    a 5 (25%) 3 (15%) 4 (20%) 4 (20%)
    b 4 (20%) 8 (40%) 6 (30%) 4 (20%)
    c 8 (40%) 4 (20%) 6 (30%) 6 (30%)
    d 3 (15%) 5 (25%) 4 (20%) 6 (30%)
1 n (%)
mydf %>%
  tbl_summary(by="Group")
#> Error in names(df) <- repaired_names(c(names2(dimnames(x)), n), repair_hint = TRUE, : 'names' attribute [3] must be the same length as the vector [2]

Created on 2024-09-13 with reprex v2.1.0

@ddsjoberg
Copy link
Owner

Thank you @szimmer for the clear and minimal reprex!

We had already planned to add better messaging for factors with NA levels, but hadn't noted factors with no levels. This will be updated here FYI insightsengineering/cards#255

Having all NAs is ok when the levels of the factor are available.

library(gtsummary)
set.seed(8675309)

mydf <- dplyr::tibble(
  Group=rep(1:4, each=20),
  CatValid=as.factor(sample(letters[1:4], 80, replace=TRUE)),
  CatNA=factor(NA, levels = c("Hello", "There"))
)

tbl_summary(mydf, by = Group) |> 
  bold_labels() |> 
  as_kable()
Characteristic 1 N = 20 2 N = 20 3 N = 20 4 N = 20
CatValid
a 5 (25%) 3 (15%) 4 (20%) 4 (20%)
b 4 (20%) 8 (40%) 6 (30%) 4 (20%)
c 8 (40%) 4 (20%) 6 (30%) 6 (30%)
d 3 (15%) 5 (25%) 4 (20%) 6 (30%)
CatNA
Hello 0 (NA%) 0 (NA%) 0 (NA%) 0 (NA%)
There 0 (NA%) 0 (NA%) 0 (NA%) 0 (NA%)
Unknown 20 20 20 20

Created on 2024-09-13 with reprex v2.1.0

@ddsjoberg
Copy link
Owner

NOTE FOR gtsummary DEVS: Once the {cards} update is complete, add a unit test for the messaging in this situation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants