Skip to content

Instantly share code, notes, and snippets.

@alistaire47
Last active October 18, 2018 19:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alistaire47/8bf30e30d66fd0a9225d5d82e0922757 to your computer and use it in GitHub Desktop.
Save alistaire47/8bf30e30d66fd0a9225d5d82e0922757 to your computer and use it in GitHub Desktop.
read markdown table into R data frame
# base R version
read.markdown <- function(file, stringsAsFactors = FALSE, strip.white = TRUE, ...){
if (length(file) > 1) {
lines <- file
} else if (grepl('\n', file)) {
con <- textConnection(file)
lines <- readLines(con)
close(con)
} else {
lines <- readLines(file)
}
lines <- lines[!grepl('^[\\:\\s\\+\\-\\=\\_\\|]*$', lines, perl = TRUE)]
lines <- gsub('(^\\s*?\\|)|(\\|\\s*?$)', '', lines)
read.delim(text = paste(lines, collapse = '\n'), sep = '|',
stringsAsFactors = stringsAsFactors, strip.white = strip.white, ...)
}
# readr version
read_markdown <- function(file, trim_ws = TRUE, ...){
if (length(file) > 1) {
lines <- file
} else {
lines <- readr::read_lines(file)
}
lines <- lines[!grepl('^[\\:\\s\\+\\-\\=\\_\\|]*$', lines, perl = TRUE)]
lines <- gsub('(^\\s*?\\|)|(\\|\\s*?$)', '', lines)
readr::read_delim(paste(lines, collapse = '\n'), delim = '|',
trim_ws = trim_ws, ...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment