Created
July 2, 2020 03:26
-
-
Save muschellij2/bf895026dc3904acbe444b1e514e964d to your computer and use it in GitHub Desktop.
Turn an rmd to a df, extracting the knitr chunks and caches.
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
# remotes::install_github('muschellij2/knitr') | |
library(knitr) | |
rmd_to_df = function(file) { | |
x = xfun::read_utf8(file) | |
on.exit(knitr::knit_code$restore(), add = TRUE) | |
res = knitr:::split_file(x, patterns = knitr::all_patterns$md) | |
classes = sapply(res, attr, "class") | |
blocks = res[classes %in% "block"] | |
params = lapply(blocks, function(el) { | |
if (attr(el, "class") %in% "block") { | |
knitr:::block_params(el, verbose = FALSE) | |
} else { | |
NULL | |
} | |
}) | |
df = lapply(params, function(x) { | |
if (!is.null(x)) { | |
keep_names = c("eval", "echo", "engine", | |
"label", "code", "hash", "cache", | |
"cache.path", "cache.vars", | |
"error", | |
"cache.lazy", "fig.path", "fig.ext", | |
"fig.env", "error", "warning", "message", | |
"include", "params.src", "purl") | |
x$code = paste(x$code, collapse = "\n") | |
x = lapply(keep_names, function(r) { | |
xx = x[[r]] | |
if (is.null(xx)) { | |
xx = NA | |
} | |
xx | |
}) | |
names(x) = keep_names | |
as.data.frame(x[keep_names]) | |
} else { | |
NULL | |
} | |
}) | |
df = do.call("rbind", df) | |
return(df) | |
} | |
tfile = tempfile(fileext = ".Rmd") | |
curl::curl_download( | |
"https://raw.githubusercontent.com/muschellij2/neuroc/master/brain_extraction/index.Rmd", | |
destfile = tfile) | |
res = rmd_to_df(tfile) | |
head(res, 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment