3

Let's say I have a function in my package

my_fn <- function() {
  mtcars_dt <- data.table::data.table(mtcars)
  mtcars_dt[, mpg_div_hp := mpg / hp]
  mtcars_dt
}

In my .Renviron I have the setting _R_CHECK_CODETOOLS_PROFILE_="suppressUndefined=TRUE". This will ensure that when the codetools package is ran during the R CMD check, it will not return any warnings such as

my_fn: no visible binding for global variable 'mpg_div_hp'

However, if I have defined some global variables, such as

utils::globalVariables(c("mpg", "hp"))

within my package documentation, the R CMD check will identify all variables as unbound. It is almost as if the globalVariables() function is overwriting the "suppressUndefined=TRUE" option within my .Renviron file.

My question is why is this happening? For more context, please read on.

There are seemingly two "simple" soluitons:

  1. Do not define any variables within my package.R file and allow the codetools option to handle them all.
  2. Define all global variables within the globalVariables() function and don't use the codetools option.

Unfortunately the first option isn't great if you want to use the lintr package as lintr only checks the RHS of the mpg_div_hp := mpg / hp part of the function. So including the variables "mpg" and "hp" in the globalVariables function is why I have come across this issue. Of course I can use the object_usage_linter=NULL option for lintr, but this feels unsatisfactory. The second option would require a vector of >1000 variables which does not feel like a nice solution.

nathaneastwood
  • 3,664
  • 24
  • 41
  • Known scoping issue with R that arises from `data.table` use, and the recommendation has always been to "silence" it by listing all affected variables. So to me that suggests it is partially self-inflicted (you skipped `mpg_div_hp`), and partially the fault of `lintr`. – Dirk Eddelbuettel Jun 18 '19 at 11:47

0 Answers0