Last active
December 15, 2016 05:50
-
-
Save mkearney/cd5ccc6de748163a4f28f71d5423784d to your computer and use it in GitHub Desktop.
Easy as df
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
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