Last active
June 14, 2020 21:32
-
-
Save mrdwab/a5d826ceffee463756e12a1a99f972fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(data.table) | |
library(SOfun) | |
ragged <- function(indt, keys, blank = "") { | |
require(data.table) | |
indt <- setkeyv(as.data.table(indt), keys) | |
vals <- setdiff(names(indt), keys) | |
nams <- paste0(keys, "_copy") | |
for (i in seq_along(nams)) { | |
indt[, (nams[i]) := c(as.character(get(key(indt)[i])[1]), | |
rep(blank, .N-1)), by = eval(keys[seq(i)])] | |
} | |
out <- cbind(indt[, ..nams], indt[, ..vals]) | |
out <- setnames(out, nams, keys)[] | |
out <- list(indt = indt[, (nams) := NULL][], out = out, keys = keys, blank = blank) | |
class(out) <- c("ragged", class(out)) | |
out | |
} | |
print.ragged <- function(x, ...) { | |
print(x$out) | |
} | |
`[.ragged` <- function(inragged, ...) { | |
out <- inragged$indt[...] | |
out <- ragged(out, keys = intersect(inragged$keys, names(out)), blank = inragged$blank) | |
out | |
} | |
x <- xtabs(cbind(ncases, ncontrols) ~ ., data = esoph) | |
ragged(ftable2dt(x), c("agegp", "alcgp", "tobgp"), ".") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment