|
| 1 | +# Inlined from reshape2 |
| 2 | +reshape_add_margins <- function(df, vars, margins = TRUE) { |
| 3 | + margin_vars <- reshape_margins(vars, margins) |
| 4 | + |
| 5 | + # Return data frame if no margining necessary |
| 6 | + if (length(margin_vars) == 0) return(df) |
| 7 | + |
| 8 | + # Prepare data frame for addition of margins |
| 9 | + addAll <- function(x) { |
| 10 | + x <- addNA(x, TRUE) |
| 11 | + factor(x, levels = c(levels(x), "(all)"), exclude = NULL) |
| 12 | + } |
| 13 | + vars <- unique(unlist(margin_vars)) |
| 14 | + df[vars] <- lapply(df[vars], addAll) |
| 15 | + |
| 16 | + rownames(df) <- NULL |
| 17 | + |
| 18 | + # Loop through all combinations of margin variables, setting |
| 19 | + # those variables to (all) |
| 20 | + margin_dfs <- lapply(margin_vars, function(vars) { |
| 21 | + df[vars] <- rep(list(factor("(all)")), length(vars)) |
| 22 | + df |
| 23 | + }) |
| 24 | + |
| 25 | + do.call("rbind", margin_dfs) |
| 26 | +} |
| 27 | + |
| 28 | +reshape_margins <- function(vars, margins = NULL) { |
| 29 | + if (is.null(margins) || identical(margins, FALSE)) return(NULL) |
| 30 | + |
| 31 | + all_vars <- unlist(vars) |
| 32 | + if (isTRUE(margins)) { |
| 33 | + margins <- all_vars |
| 34 | + } |
| 35 | + |
| 36 | + # Start by grouping margins by dimension |
| 37 | + dims <- lapply(vars, intersect, margins) |
| 38 | + |
| 39 | + # Next, ensure high-level margins include lower-levels |
| 40 | + dims <- mapply(function(vars, margin) { |
| 41 | + lapply(margin, downto, vars) |
| 42 | + }, vars, dims, SIMPLIFY = FALSE, USE.NAMES = FALSE) |
| 43 | + |
| 44 | + # Finally, find intersections across all dimensions |
| 45 | + seq_0 <- function(x) c(0, seq_along(x)) |
| 46 | + indices <- expand.grid(lapply(dims, seq_0), KEEP.OUT.ATTRS = FALSE) |
| 47 | + # indices <- indices[rowSums(indices) > 0, ] |
| 48 | + |
| 49 | + lapply(seq_len(nrow(indices)), function(i){ |
| 50 | + unlist(mapply("[", dims, indices[i, ], SIMPLIFY = FALSE)) |
| 51 | + }) |
| 52 | +} |
| 53 | + |
| 54 | + |
| 55 | +upto <- function(a, b) { |
| 56 | + b[seq_len(match(a, b, nomatch = 0))] |
| 57 | +} |
| 58 | +downto <- function(a, b) { |
| 59 | + rev(upto(a, rev(b))) |
| 60 | +} |
0 commit comments