Last active
October 18, 2018 19:41
-
-
Save alistaire47/8bf30e30d66fd0a9225d5d82e0922757 to your computer and use it in GitHub Desktop.
read markdown table into R data frame
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
# 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