我想将R函数读入环境,并将其依赖的函数导入roxygen2内联文档中列出。这模仿了加载R程序包的行为,但对于 程序包中不包含的R脚本则这样做。
如何在包外部获取R函数并导入包中所依赖的R函数?
gh_file.R
是一种R函数,可从GitHub存储库下载文件。它不是软件包的一部分,而是以GitHub gist的形式提供。
对roxygen2注释的浏览一眼表明,gh_file.R
应该从其他软件包中导入几个函数。
#' @importFrom gh gh
#' @importFrom stringi stri_match_all_regex
#' @importFrom purrr %||% keep
#' @importFrom base64enc base64decode
# read in the R function from GitHub Gist
library(devtools)
devtools::source_gist("gist.github.com/noamross/73944d85cad545ae89efaa4d90b049db",
filename = "gh_file.R")
# attempt to use new R function to import a .csv file from GitHub (FAILS)
ghurl <- "github.com/wpetry/RockyMountainAphids/blob/master/Palmer1952hostlist.csv"
aphids <- read.csv(text = readBin(gh_file(url = ghurl, to_disk = FALSE)))
返回错误:
Error in stri_match_all_regex(url, "(github\\.com/)?([^\\/]+)/([^\\/]+)/[^\\/]+/([^\\/]+)/([^\\?]+)") :
could not find function "stri_match_all_regex"
# load packages from which gh_file.R function imports
library(gh)
library(stringi)
library(purrr)
library(base64enc)
aphids <- read.csv(text = readBin(gh_file(url = ghurl, to_disk = FALSE), "character"))
head(aphids)
有效!
host host_common aphid
1 Abies concolor White Fir Cinara curvipes
2 Abies concolor White Fir Cinara occidentalis
3 Abies lasiocarpa Alpine Fir Cinara curvipes
4 Abies lasiocarpa Alpine Fir Cinara lasiocarpae
5 Abies lasiocarpa Alpine Fir Cinara occidentalis
6 Abies lasiocarpa Alpine Fir Mindarus abietinus
答案 0 :(得分:0)
您可以解析脚本以获得库列表,然后加载它们。
loadlib <- function(fpath) {
l <- readLines(fpath)
libs <- lapply(strsplit(l[grepl("@import", l)], " "), `[[`, 3)
lapply(libs, library, character.only=TRUE)
}
loadlib("gh_file.R")