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

Define data frame method for dw_data_xtabulates object? #517

Merged
merged 15 commits into from
Jun 22, 2024
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Generated by roxygen2: do not edit by hand

S3method(as.data.frame,dw_data_tabulates)
S3method(as.data.frame,dw_data_xtabulate)
strengejacke marked this conversation as resolved.
Show resolved Hide resolved
S3method(as.double,parameters_kurtosis)
S3method(as.double,parameters_skewness)
S3method(as.double,parameters_smoothness)
Expand Down
32 changes: 32 additions & 0 deletions R/data_tabulate.R
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#' percentages to be calculated. Only applies to crosstables, i.e. when `by` is
#' not `NULL`. Can be `"row"` (row percentages), `"column"` (column percentages)
#' or `"full"` (to calculate relative frequencies for the full table).
#' @param add_total Add total.
#' @param ... not used.
#' @inheritParams extract_column_names
#'
Expand Down Expand Up @@ -380,6 +381,37 @@ insight::print_html
insight::print_md


#' @rdname data_tabulate
#' @export
as.data.frame.dw_data_tabulates <- function(x, add_total = FALSE, ...) {
# extract variables of frequencies
selected_vars <- lapply(x, function(i) attributes(i)$varname)
# coerce to data frame, remove rownames
data_frames <- lapply(x, function(i) {
if (add_total) {
out <- as.data.frame(format(i))
for (i in 2:ncol(out)) {
out[[i]] <- as.numeric(out[[i]])
}
out <- remove_empty_rows(out)
} else {
out <- as.data.frame(i)
}
rownames(out) <- NULL
out
})
# create nested data frame
data.frame(
var = selected_vars,
table = I(data_frames),
stringsAsFactors = FALSE
)
}

#' @export
as.data.frame.dw_data_xtabulate <- as.data.frame.dw_data_tabulates


#' @export
format.dw_data_tabulate <- function(x, format = "text", big_mark = NULL, ...) {
# convert to character manually, else, for large numbers,
Expand Down
1 change: 1 addition & 0 deletions R/data_xtabulate.R
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
attr(out, "total_n") <- total_n
attr(out, "weights") <- weights
attr(out, "proportions") <- proportions
attr(out, "varname") <- obj_name

class(out) <- c("dw_data_xtabulate", "data.frame")

Expand Down
5 changes: 5 additions & 0 deletions man/data_tabulate.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading