From 57579a9bb50c0db09a817254624b12200aebb905 Mon Sep 17 00:00:00 2001 From: Daniel Date: Tue, 13 Feb 2024 11:52:08 +0100 Subject: [PATCH] fix --- R/data_tabulate.R | 11 +++++++++-- R/data_xtabulate.R | 18 +----------------- 2 files changed, 10 insertions(+), 19 deletions(-) diff --git a/R/data_tabulate.R b/R/data_tabulate.R index 9e64bec2f..7af135c11 100644 --- a/R/data_tabulate.R +++ b/R/data_tabulate.R @@ -158,7 +158,14 @@ data_tabulate.default <- function(x, } out$`Raw %` <- 100 * out$N / sum(out$N) - out$`Valid %` <- c(100 * out$N[-nrow(out)] / sum(out$N[-nrow(out)]), NA) + # if we have missing values, we add a row with NA + if (include_na) { + out$`Valid %` <- c(100 * out$N[-nrow(out)] / sum(out$N[-nrow(out)]), NA) + valid_n <- sum(out$N[-length(out$N)], na.rm = TRUE) + } else { + out$`Valid %` <- 100 * out$N / sum(out$N) + valid_n <- sum(out$N, na.rm = TRUE) + } out$`Cumulative %` <- cumsum(out$`Valid %`) # add information about variable/group names @@ -187,7 +194,7 @@ data_tabulate.default <- function(x, attr(out, "weights") <- weights attr(out, "total_n") <- sum(out$N, na.rm = TRUE) - attr(out, "valid_n") <- sum(out$N[-length(out$N)], na.rm = TRUE) + attr(out, "valid_n") <- valid_n class(out) <- c("dw_data_tabulate", "data.frame") diff --git a/R/data_xtabulate.R b/R/data_xtabulate.R index f26a06f0d..35f9750c5 100644 --- a/R/data_xtabulate.R +++ b/R/data_xtabulate.R @@ -50,9 +50,6 @@ out <- as.data.frame(stats::ftable(x_table)) colnames(out) <- c("Value", "by", "N") - total_n <- sum(out$N, na.rm = TRUE) - valid_n <- sum(out$N[!is.na(out$N)], na.rm = TRUE) - out <- data_to_wide(out, values_from = "N", names_from = "by") # use variable name as column name @@ -68,8 +65,7 @@ out <- cbind(out[1], data.frame(Group = var_info, stringsAsFactors = FALSE), out[-1]) } - attr(out, "total_n") <- total_n - attr(out, "valid_n") <- valid_n + attr(out, "total_n") <- sum(out$N, na.rm = TRUE) attr(out, "weights") <- weights attr(out, "proportions") <- proportions @@ -158,10 +154,6 @@ format.dw_data_xtabulate <- function(x, format = "text", digits = 1, big_mark = #' @export print.dw_data_xtabulate <- function(x, big_mark = NULL, ...) { - a <- attributes(x) - a$total_n <- .add_commas_in_numbers(a$total_n, big_mark) - a$valid_n <- .add_commas_in_numbers(a$valid_n, big_mark) - # grouped data? if yes, add information on grouping factor if (is.null(x[["Group"]])) { caption <- NULL @@ -169,14 +161,6 @@ print.dw_data_xtabulate <- function(x, big_mark = NULL, ...) { caption <- paste0("Grouped by ", x[["Group"]][1]) } - # summary of total and valid N (we may add mean/sd as well?) - summary_line <- sprintf( - "\ntotal N=%s valid N=%s%s\n", - a$total_n, - a$valid_n, - ifelse(is.null(a$weights), "", " (weighted)") - ) - # print table cat(insight::export_table( format(x, big_mark = big_mark, ...),