Skip to content

Instantly share code, notes, and snippets.

@joranE
Last active March 4, 2020 21:58
Show Gist options
  • Save joranE/305b545035e4a175efc04a6b79c85c1c to your computer and use it in GitHub Desktop.
Save joranE/305b545035e4a175efc04a6b79c85c1c to your computer and use it in GitHub Desktop.
Create column spec for a data frame not already read in by readr
create_spec <- function(x,condense = TRUE){
v_inherits <- Vectorize(FUN = inherits,vectorize.args = "what")
col_map <- c(logical = "l",
integer = "i",
numeric = "d",
factor = "f",
character = "c",
Date = "D",
POSIXct = "T")
x_spec <- rep("?",times = ncol(x))
for (i in seq_along(x)){
cl <- col_map[which(v_inherits(x[[i]],names(col_map)))]
if (length(cl) == 1){
x_spec[i] <- cl
}
}
x_spec <- do.call(readr::cols,as.list(setNames(x_spec,colnames(x))))
if (condense){
x_spec <- readr::cols_condense(x_spec)
}
x_spec
}
dat <- data.frame(x1 = 1:5,
x2 = letters[1:5],
x3 = sample(c(T,F),size = 5,replace = TRUE),
x4 = LETTERS[1:5],
x5 = Sys.Date() + 1:5,
x6 = Sys.time() + 1:5,
x7 = runif(5),
x8 = I(list(a = 1:2,b = 3:4,c = 1:2,d = 1,e = "a")))
dat$x4 <- as.character(dat$x4)
create_spec(dat)
create_spec(dat,condense = FALSE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment