如何在创建新的R包时解决“没有可见的全局函数定义”问题

5

我尝试构建一个使用库tidyverse的R包。

描述文件如下:

Package: myFirstPackage
Title: A initial package
Version: 0.0.1.0
Authors@R: 
    person(given = "Test",
           family = "Test",
           role = c("aut", "cre"),
           email = "first.last@example.com",
           comment = c(ORCID = "YOUR-ORCID-ID"))
Description: a description.
Imports: tidyverse
License: GPL-2
Encoding: UTF-8
LazyData: true
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.1.1

所以我将tidyverse添加到Imports部分。

我的R代码如下:

myfunction<-function(){

  x<-tibble(
    id = c(1, 2, 3, 4),
    name = c("Louisa", "Jonathan", "Luigi", "Rachel"),
    female = c(TRUE, FALSE, FALSE, TRUE)
  )
  x %>% pull(id)
}

#' MyDemoFunction
#'
#'
#' @import tidyverse
#' @export

say_hello<-function(){
  cat("here1")
  myfunction()
}

在这里,我有导入。

我正在使用R-Studio工作,一旦我按下“检查”按钮,我会得到以下结果:

> checking R code for possible problems ... NOTE
  myfunction: no visible global function definition for 'tibble'
  myfunction: no visible global function definition for '%>%'
  myfunction: no visible global function definition for 'pull'
  myfunction: no visible binding for global variable 'id'
  Undefined global functions or variables:
    %>% id pull tibble

你可以在这里找到该项目的存储库。
那个问题中,通过逐个导入函数来解决了问题,但我希望完全导入整个包:我只想使用tidyverse的所有函数,而不需要显式定义每个函数。在这个问题中提到,导入必须在描述中完成,而我已经做到了!

你可以创建一个带有全局变量的文件。 - akrun
我添加了一个包含以下内容的额外r文件 if(getRversion() >= "2.15.1") utils::globalVariables(c(".")) 然而,它并没有起到帮助作用(请参见https://github.com/anewruser/r_package_project/blob/master/R/globalR.R) - user3579222
1个回答

2

我提供了一种干净的检查解决方案。您需要使用 R 4.1.0 版本才能使用 |> 运算符。

plainSrc.R:

####This File represents a package used for Index Management

### Overall approach of this package ###
# In order to avoid a static hard coding of the index members
# we use a web-based approach based on finanzen.de from there we
# get the index members for which we offer the data.

#' @import dplyr
#'
myfunction<-function(){

  x <- dplyr::tibble(
    id = c(1, 2, 3, 4),
    name = c("Louisa", "Jonathan", "Luigi", "Rachel"),
    female = c(TRUE, FALSE, FALSE, TRUE)
  )
  x |> dplyr::pull(one_of("id"))
}

#' MyDemoFunction
#'
#'
#' @export
#'
say_hello<-function(){
  cat("here1")
  myfunction()
}

并且在 DESCRIPTION 中将 Imports 从 tidyverse 改为 dplyr。


代码可以运行,但为什么tidyverse无法工作 - 它应该是dplyr的超集 (https://dplyr.tidyverse.org/#installation)。 - user3579222
3
TL;DR:tidyverse是一个简单的包装器,可以一次性使用多个库。这很棘手但值得理解。tidyverse不是针对在其他包中使用而设计的。它是一个提供一种简单方法来一次性引入多个包的包,可以查看onAttach函数(在library(tidyverse)时被调用)-https://github.com/tidyverse/tidyverse/blob/master/R/zzz.R。例如,从dplyr导入的函数不能通过tidyverse内部的::访问。顺便说一下,请小心不要在包的.R文件中使用library。有时我们使用`if(!require(“package”))stop(“你需要x才能继续”)`。 - polkas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接