Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions R/helper-margins.r
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,15 @@ add_margins <- function(df, vars, margins = TRUE) {
# Loop through all combinations of margin variables, setting
# those variables to (all)
margin_dfs <- llply(margin_vars, function(vars) {
df[vars] <- rep(list(factor("(all)")), length(vars))
for (var in vars) {
# Need '[]' to coerce '(all)' into the existing structure of the LHS,
# as opposed to overwriting with character. In particular, that inserts
# '(all)' as an element of the existing factor, e.g. respecting the
# is.ordered()-ness of that factor as well.
df[[var]][] <- "(all)"
}
df
})

rbind.fill(margin_dfs)
bind_rows(margin_dfs)
}
2 changes: 1 addition & 1 deletion R/melt.r
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ melt.default <- function(data, ..., na.rm = FALSE, value.name = "value") {
#' melt(list(list(1:3), 1, list(as.list(3:4), as.list(1:2))))
melt.list <- function(data, ..., level = 1) {
parts <- lapply(data, melt, level = level + 1, ...)
result <- rbind.fill(parts)
result <- bind_rows(parts)

# Add labels
names <- names(data) %||% seq_along(data)
Expand Down
18 changes: 18 additions & 0 deletions R/utils.r
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,21 @@ normalize_melt_arguments <- function(data, measure.ind, factorsAsStrings) {
is.string <- function(x) {
is.character(x) && length(x) == 1
}

# base-only drop-in for rbind.fill()
bind_rows <- function(dfs) {
df_sizes <- lengths(dfs)
if (length(unique(df_sizes)) > 1L) {
# NB: rbind() _does_ use name matching for columns, so we don't need to
# reorder all the ourselves.
out_names <- character()
for (df in dfs) {
out_names <- c(out_names, setdiff(names(df), out_names))
}
# for (df in dfs) doesn't work; 'df' gets copy-on-written.
for (ii in seq_along(dfs)) {
dfs[[ii]][setdiff(out_names, names(dfs[[ii]]))] <- NA
}
}
do.call(rbind, dfs)
}