Skip to content

Instantly share code, notes, and snippets.

@mrdwab
Created June 15, 2020 06:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrdwab/0b177579fea74748afe75b05c072d859 to your computer and use it in GitHub Desktop.
Save mrdwab/0b177579fea74748afe75b05c072d859 to your computer and use it in GitHub Desktop.
`as.data.table` but adding in `names` from named `list` columns.
library(data.table)
## Sample data
L <- list(A = 1:2, B = NULL, C = 3:4)
DF <- data.frame(ID = 1:3, V1 = I(L), V2 = I(unname(L)), V3 = I(setNames(L, c("X", "Y", "Z"))))
DF2 <- data.frame(ID = 1:3, V1 = letters[1:3], V2 = letters[4:6], V3 = letters[7:9])
DF3 <- do.call(rbind, replicate(1000, DF, FALSE))
set.seed(1)
DF4 <- data.frame(ID = 1:300000, V1 = I(rep(L, 100000)), V2 = I(rep(unname(L), 100000)),
V3 = I(setNames(rep(L, 100000), sample(c(LETTERS, letters), 300000, TRUE))))
ASDT <- function(input, keep.rownames = FALSE) {
if (!is.list(input)) stop("ASDT is only for lists, data.frames, and data.tables")
if (is.data.table(input)) {
output <- input
} else {
if (!is.data.frame(input)) {
input <- setNames(data.frame(I(input)), deparse(substitute(input)))
}
output <- as.data.table(input, keep.rownames = keep.rownames)
lsts <- vapply(input, is.list, logical(1L))
if (any(lsts)) {
namd <- vapply(input[lsts], function(x) !is.null(names(x)), logical(1L))
tofix <- names(namd)[namd]
for (i in tofix) {
set(output, j = sprintf("%s_names", i), value = names(input[[i]]))
}
}
}
output[]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment