Skip to content

Commit

Permalink
fix printing issues
Browse files Browse the repository at this point in the history
  • Loading branch information
strengejacke committed Aug 10, 2023
1 parent acb6d8d commit 8a68e7d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 11 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ S3method(print,dw_data_peek)
S3method(print,dw_data_tabulate)
S3method(print,dw_data_tabulates)
S3method(print,dw_groupmeans)
S3method(print,dw_groupmeans_list)
S3method(print,dw_transformer)
S3method(print,parameters_distribution)
S3method(print,parameters_kurtosis)
Expand Down
38 changes: 27 additions & 11 deletions R/means_by_group.R
Original file line number Diff line number Diff line change
Expand Up @@ -74,17 +74,6 @@ means_by_group.numeric <- function(x, group = NULL, weights = NULL, digits = NUL
# if weights are NULL, set weights to 1
if (is.null(weights)) weights <- rep(1, length(x))

# create string with variable names
data <- stats::na.omit(data.frame(
x = x,
group = to_factor(group),
weights = weights,
stringsAsFactors = FALSE
))

# get grouped means table
out <- .means_by_group(data)

# retrieve labels
var_mean_label <- attr(x, "label", exact = TRUE)
var_grp_label <- attr(group, "label", exact = TRUE)
Expand All @@ -97,6 +86,24 @@ means_by_group.numeric <- function(x, group = NULL, weights = NULL, digits = NUL
var_grp_label <- deparse(substitute(group))
}

# coerce group to factor if numeric, or convert labels to levels, if factor
if (is.factor(group)) {
group <- tryCatch(labels_to_levels(group, verbose = FALSE), error = function(e) group)
} else {
group <- to_factor(group)
}

# create string with variable names
data <- stats::na.omit(data.frame(
x = x,
group = group,
weights = weights,
stringsAsFactors = FALSE
))

# get grouped means table
out <- .means_by_group(data)

# attributes
attr(out, "var_mean_label") <- var_mean_label
attr(out, "var_grp_label") <- var_grp_label
Expand Down Expand Up @@ -148,6 +155,7 @@ means_by_group.data.frame <- function(x,
means_by_group(x[[i]], group = x[[group]], weights = w, digits = digits, ...)
})

class(out) <- c("dw_groupmeans_list", "list")
out
}

Expand Down Expand Up @@ -244,3 +252,11 @@ print.dw_groupmeans <- function(x, digits = NULL, ...) {

cat(insight::export_table(x, caption = caption, footer = footer, ...))
}

#' @export
print.dw_groupmeans_list <- function(x, digits = NULL, ...) {
for (i in seq_along(x)) {
if (i > 1) cat("\n")
print(x[[i]], digits = digits, ...)
}
}

0 comments on commit 8a68e7d

Please sign in to comment.