Skip to content

Instantly share code, notes, and snippets.

@mkearney
Last active December 15, 2016 05:50
Show Gist options
  • Save mkearney/cd5ccc6de748163a4f28f71d5423784d to your computer and use it in GitHub Desktop.
Save mkearney/cd5ccc6de748163a4f28f71d5423784d to your computer and use it in GitHub Desktop.
Easy as df
dots <- function(...) {
as.character(eval(substitute(alist(...))))
}
unL <- function(x) unlist(x, use.names = FALSE)
## easy as df
as.df <- function(x, ...) {
vars <- dots(...)
if (identical(vars, "FALSE")) {
as.data.frame(x, stringsAsFactors = FALSE)
} else if (identical(length(vars), 0L)) {
if (is.matrix(x)) {
x <- lapply(seq_len(ncol(x)), function(i) x[,i])
}
vars <- unL(lapply(x, function(x) class(x)[[1]]))
vars <- abbreviate(vars, 3)
vars <- mapply(paste0, vars,
rep(".", length(vars)),
seq_along(vars))
structure(as.data.frame(
x, stringsAsFactors = FALSE), names = vars)
} else {
if (any(grepl("^c\\(", vars),
identical("varnames", vars))) vars <- unL(list(...))
structure(as.data.frame(
x, stringsAsFactors = FALSE), names = vars)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment