Skip to content

Instantly share code, notes, and snippets.

@randy3k
Last active July 25, 2017 04:21
Show Gist options
  • Save randy3k/e1bded10e4d54dbe0be1db208e92695f to your computer and use it in GitHub Desktop.
Save randy3k/e1bded10e4d54dbe0be1db208e92695f to your computer and use it in GitHub Desktop.
Parsing R documentation file
topic_rd <- function(pkg_name, topic) {
rd_file <- as.character(help((topic), (pkg_name)))
utils:::.getHelpFile(rd_file)
}
topic_section <- function(rd, section) {
ret <- rd[sapply(rd, function(x) attr(x, "Rd_tag") == paste0("\\", section))]
if (length(ret) == 0) {
list()
} else {
ret[[1]]
}
}
parse_arguments <- function(x) {
out <- list()
for (d in x) {
attr(d[[1]][[1]], "Rd_tag") %in% c("TEXT", "\\dots") || next
out <- c(out, list(parse_argument(d)))
}
out
}
parse_argument <- function(x){
if (attr(x[[1]][[1]], "Rd_tag") == "\\dots") {
argument_name <- "..."
} else {
argument_name <- trimws(as.character(x[[1]][[1]]))
}
list(
arg = argument_name,
content = parse_text(x[[2]])
)
}
parse_text <- function(x){
y <- trimws(paste(unlist(x), collapse = ""))
y <- gsub("\\\\", "\\\\\\\\", y)
gsub("\n", "\\\\n", y)
}
# args <- commandArgs(TRUE)
args <- list("car", "Anova.mlm")
rd <- topic_rd(args[[1]], args[[2]])
rd_description_section <- topic_section(foo, "description")
rd_args_section <- topic_section(foo, "argument")
rd_args <- parse_arguments(rd_args_section)
rd_value_section <- topic_section(foo, "value")
cat("description:", parse_text(rd_description_section))
cat("\n")
for (b in boo) {
cat("arg:", b$arg)
cat("\n")
cat("content:", gsub("\n", "\\\\n", b$content))
cat("\n")
}
cat("value:", parse_text(rd_value_section))
cat("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment