[英]How to use 'unexported' datasets from an R package within another package
我正在使用包含大量人口統計數據集的包wpp2019
。 我希望能夠在我的包中的某些函數中使用這些數據集。 不幸的是,這些數據集不能用get
(或wpp2019::
)引用,而只能通過data
wpp2019::
。
由於wpp2019
的全部意義是做一個數據包,所以我很猶豫是否在內部保存數據並在本地引用它。 雖然這個問題暗示了我想要什么,但 OP 沒有只能通過data
導出data
。
我一直在使用data("name of data", package = "wpp2019)
在我的代碼中,但devtools::check()
通過no visible binding for global variable 'name of data'
尖叫。
有人知道解決方法嗎?
我不確定您為什么會收到此錯誤。 我創建了一個只有以下功能的小型測試包,並檢查運行沒有任何問題:
#' Loads random dataset from wpp2019
#'
#' @export
#'
#' @importFrom utils data
load_random_data <- function() {
# check if package is installed
if (requireNamespace("wpp2019", quietly = TRUE)) {
# get name of random dataset
rand <- sample(data(package = "wpp2019")[["results"]][, 3], 1)
x <- utils::data(list = rand, package = "wpp2019", envir = environment())
return(get(x))
} else {
stop("Install package from https://github.com/PPgp/wpp2019 first.")
}
}
我發現data
評估數據集名稱的方式有點令人困惑。 所以也許示例函數有助於澄清問題。
@user2554330 促使我編寫一個更通用的函數來從包中加載數據集。 所以這里有一些額外的花里胡哨:
#' Load dataset from from a package
#'
#' @param title character. Title of a dataset in the package
#' @param package character. Name of a package in which the dataset is present.
#'
#' @export
#'
#' @importFrom utils data
load_data <- function(title, package = "wpp2019") {
# check if package is installed
if (requireNamespace(package, quietly = TRUE)) {
# check if dataset is in the package
if (title %in% data(package = package)[["results"]][, 3]) {
return(get(utils::data(list = title,
package = package,
envir = environment())))
} else {
stop("Dataset '", title, "' not found in package ", package, ".")
}
} else {
stop("Package '", package, "' not installed.")
}
}
並快速測試這是否有效:
dat <- load_data("UNlocations")
ncol(dat)
#> 32
load_data("UNLocations")
#> Error in load_data("UNLocations"): Dataset 'UNLocations' not found in package wpp2019.
load_data("UNLocations", "not_installed")
#> Error in load_data("UNLocations", "not_installed"): Package 'not_installed' not installed.
如您所見,函數失敗並顯示更易於理解的錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.