gpt4 book ai didi

在另一个包中导入时 R 包数据不可用

转载 作者:行者123 更新时间:2023-12-01 05:51:31 26 4
gpt4 key购买 nike

我有一个包“testing”,数据对象“test_data”保存在文件名为“test_data.RData”的数据文件夹中。

测试包含一个使用此数据对象的函数 hello()

#' hello
#'
#' @return Prints hello "your_name"
#' @export
#'
#' @examples
#' hello()
hello <- function(your_name = "") {

print(paste("test_data has", nrow(test_data), "rows"))
print(sprintf("Hello %s!", your_name))
}

以下代码工作正常:
require(testing)
testing::hello()
[1] "test_data has 32 rows"
[1] "Hello !"

但这失败了:
testing::hello()
Error in nrow(test_data) : object 'test_data' not found

实际上我不直接使用它,而是在另一个导入此函数的包 testingtop 中使用它:
#' Title
#'
#' @export
#' @importFrom testing hello
hello2 <- function(){

hello()
}

我在描述的导入部分进行了测试,但失败了。
require(testingtop)
testingtop::hello2()
Error in nrow(test_data) : object 'test_data' not found

如果我把它放在 Depends 中,如果我用 library() 加载包,它就可以工作
否则它仍然失败:
> library(testingtop)
Loading required package: testing
> testingtop::hello2()
[1] "test_data has 32 rows"
[1] "Hello !"

Restarting R session...

> testingtop::hello2()
Error in nrow(test_data) : object 'test_data' not found

如果它是一个函数而不是数据对象导入就可以了,为什么它与数据对象不同,我需要加载导入的包?我错过了什么?它与 LazyData 和 LazyLoad 相关吗?

可能是 this question 的副本

最佳答案

所以我想我已经从数据函数的文档中找到了解决方案 ?data

Use of data within a function without an envir argument has the almost always undesirable side-effect of putting an object in the user's workspace (and indeed, of replacing any object of that name already there). It would almost always be better to put the object in the current evaluation environment by data(..., envir = environment()). However, two alternatives are usually preferable, both described in the ‘Writing R Extensions’ manual. For sets of data, set up a package to use lazy-loading of data. For objects which are system data, for example lookup tables used in calculations within the function, use a file ‘R/sysdata.rda’ in the package sources or create the objects by R code at package installation time. A sometimes important distinction is that the second approach places objects in the namespace but the first does not. So if it is important that the function sees mytable as an object from the package, it is system data and the second approach should be used.



把数据放在内部数据文件里让我的函数hello2()看到了
> testingtop::hello2()
[1] "test_data has 32 rows"
[1] "Hello !"

关于在另一个包中导入时 R 包数据不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53548994/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com