Skip to content

Commit

Permalink
update count_by so split factors are in its own column
Browse files Browse the repository at this point in the history
  • Loading branch information
emitanaka committed Sep 13, 2023
1 parent 33751bf commit e5e6bef
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
20 changes: 16 additions & 4 deletions R/pivot.R
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ pivot_wider_by <- function(data,
#' spd %>% split_by(trt1)
#' spd %>% split_by(trt2)
#' spd %>% split_by(mainplot)
#' spd %>% count_by(trt1)
#'
#' fac <- takeout(menu_factorial(trt = c(2, 2, 2)))
#' fac %>% count_by(where(~is_trt(.x)))
#'
#' @return A named list.
#' @seealso [pivot_wider_by()]
Expand Down Expand Up @@ -124,14 +128,22 @@ print.split_by <- function(x, ...) {
#' @rdname split_by
#' @export
count_by <- function(.data, ...) {
out <- split_by(.data, ...)
# pick a dummy sep that is unlikely used
dummy_sep <- "#####SEP#####"
out <- split_by(.data, ..., .sep = dummy_sep)
by <- attr(out, "by")
paste_by <- paste(by, collapse = ":")
n <- function(.x) length(unique(.x))
out2 <- as.data.frame(do.call(rbind, lapply(out, function(df) lapply(df, n))))
out2[[paste_by]] <- rownames(out2)
if(length(by) == 1) {
out2[[by]] <- rownames(out2)
} else {
rnames <- strsplit(rownames(out2), dummy_sep)
for(i in seq_along(by)) {
out2[[by[i]]] <- map_chr(rnames, function(x) x[i])
}
}
rownames(out2) <- NULL
out2[c(paste_by, setdiff(names(out2), paste_by))]
out2[c(by, setdiff(names(out2), by))]
}

#' Pivot treatments to a wider list or table format
Expand Down
4 changes: 4 additions & 0 deletions man/split_by.Rd

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

0 comments on commit e5e6bef

Please sign in to comment.