首页 > 解决方案 > 包内函数在缺少可见绑定时产生警告

问题描述

在包中的函数内部使用witin会强制返回警告R CMD check

代表

功能:

# Test within

hello <- function(x = data.frame(valA = 1, valB = 2)) {
  within(data = x,
         expr = {
             res = valA + valB
         })
}

将产生以下警告R CMD check

❯ checking R code for possible problems ... NOTE
  hello: no visible binding for global variable ‘valA’
  hello: no visible binding for global variable ‘valB’
  Undefined global functions or variables:
    valA valB

解决方法(解决方案)

添加valA <- valB <- NULL将使警告静音。

hello <- function(x = data.frame(valA = 1, valB = 2)) {
    valA <- valB <- NULL

  within(data = x,
         expr = {
             res = valA + valB
         })
}

问题

这种恶作剧valA <- valB <- NULL对我来说感觉很糟糕。处理这种情况的正确方法是什么?

我想使用within该功能适合更广泛的功能设计。消除警告的正确方法是什么。我在 GitHub 上遇到了类似的讨论,建议with在稍微不同的情况下使用。

标签: rbindingscopepackagewith-statement

解决方案


一种解决方案是globalVariables(c('valA', 'valB'))在包中的某处包含,例如在文件夹中的单独.R文件中R

否则我会这样做:

hello <- function(valA = 1, valB = 2) {

  within(data = data.frame(valA, valB),
         expr = {
           res = valA + valB
         })
}

推荐阅读