I have a survey with missing responses and calculated weights to account for attrition. I want to be able to display both tables without weights and with weights side-by-side for comparison. I therefore want to merge the tables created with tbl_summary() and tbl_svysummary() using tbl_merge(), but end up with an error:
Error in dplyr::rows_update(): ! Can't convert from y$modify_stat_N \<double\> to x$modify_stat_N \<integer\> due to loss of precision. • Locations: 1, 2
Below is a reproducible example. I have already found that the error does not occur when using the by
argument in tbl_summary()
or tbl_svysummary()
.
Many thanks
set.seed(123)
library(tidyverse)
library(gtsummary)
library(srvyr)
num_rows <- 10000
item1 <- sample(c("Never", "Sometimes", "All the time"), num_rows, replace = TRUE)
item2 <- sample(c("Never", "Sometimes", "All the time"), num_rows, replace = TRUE)
item3 <- sample(c("Never", "Sometimes", "All the time"), num_rows, replace = TRUE)
surveystatus <- sample(c("Respondent", "Non-respondent"), num_rows, replace = TRUE)
gender <- sample(c("Male", "Female"), num_rows, replace = TRUE)
weight <- rnorm(num_rows, mean = 0, sd = 1)
toy_data <- data.frame(item1, item2, item3, gender, weight, surveystatus)
# Create a survey object
toy_dataw <- toy_data %>%
srvyr::as_survey_design(weights = weight)
####
# Tbl merge that works ! :D
t1 <- toy_data %>%
filter(surveystatus == "Respondent") %>%
select(item1, item2, item3, gender) %>%
tbl_summary(by = gender)
t2 <- toy_dataw %>%
srvyr::filter(surveystatus == "Respondent") %>%
srvyr::select(item1, item2, item3, gender) %>%
tbl_svysummary(by = gender)
tbl_merge(tbls = list(t1, t2))
# Tbl merge that does not work ! :(
t3 <- toy_data %>%
filter(surveystatus == "Respondent") %>%
select(item1, item2, item3) %>%
tbl_summary()
t4 <- toy_dataw %>%
srvyr::filter(surveystatus == "Respondent") %>%
srvyr::select(item1, item2, item3) %>%
tbl_svysummary()
tbl_merge(tbls = list(t3, t4))
it looks like you've identified a bug. I'll address it in the next release. In the meantime, here's a workaround. Happy Programming
library(survey) |> suppressPackageStartupMessages()
library(gtsummary)
#> #BlackLivesMatter
data(api)
#stratified sample
dstrat <- svydesign(id=~1,strata=~stype, weights=~pw, data=apistrat, fpc=~fpc)
t1 <- tbl_summary(apistrat, include = api00)
t2 <- tbl_svysummary(dstrat, include = api00)
# convert `modify_stat_N` and `modify_stat_n` to a double
for (int_col in c("modify_stat_N", "modify_stat_n")) {
t1$table_styling$header[[int_col]] <-
t1$table_styling$header[[int_col]] |> as.numeric()
}
final_tbl <-
list(t1, t2) |>
tbl_merge()
Created on 2024-04-14 with reprex v2.1.0