Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
strengejacke committed Feb 13, 2024
1 parent e44b9de commit 57579a9
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 19 deletions.
11 changes: 9 additions & 2 deletions R/data_tabulate.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")

Expand Down
18 changes: 1 addition & 17 deletions R/data_xtabulate.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -158,25 +154,13 @@ 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
} else {
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, ...),
Expand Down

0 comments on commit 57579a9

Please sign in to comment.