rfunctionglobal-variablesuser-defined-functionslintr

Is the 'No visible binding for global variable' warning a serious problem?


I have started working with lintr recently, but there is one warning that keeps coming up [object_usage_lintr] No visible binding for global variable - it occurs in functions either when I refer to specific column names or to global constants that I have set. I am wondering why this is a problem and if so what I can do to fix it.

For example,

globalconst = 5

examplefunction = function(df){
  df %>%
    select(dist) %>%
    mutate(power = globalconst)
  }

examplefunction(cars)

In this case, it would flag that I had used the column name dist without binding and also the globalconst value. I was led to understand that local environments could happily draw from the global environment. The functions are only going to be used on dataframes with the columns mentioned in the function, so I don't see what the issue is there either. If it is a problem, I also have no idea how to fix it.


Solution

  • This appears to be a lintr bug or design flaw.

    When I put your code in a file and run library(dplyr); lintr::lint("sample.R"), I get a sequence of warnings about the formatting, as well as the global variable warning:

    sample.R:1:13: style: [assignment_linter] Use <-, not =, for assignment.
    globalconst = 5
                ^
    sample.R:3:17: style: [assignment_linter] Use <-, not =, for assignment.
    examplefunction = function(df){
                    ^
    sample.R:3:31: style: [brace_linter] There should be a space before an opening curly brace.
    examplefunction = function(df){
                                  ^
    sample.R:3:31: style: [paren_body_linter] There should be a space between a right parenthesis and a body expression.
    examplefunction = function(df){
                                  ^
    sample.R:6:20: warning: [object_usage_linter] no visible binding for global variable 'globalconst'
        mutate(power = globalconst)
                       ^~~~~~~~~~~
    

    Following the formatting advice makes your source look like this:

    globalconst <- 5
    
    examplefunction <- function(df) {
      df %>%
        select(dist) %>%
        mutate(power = globalconst)
    }
    
    examplefunction(cars)
    

    That also makes the global variable warning go away. So apparently the assignment using = is insufficient for lintr to recognize the assignment to a global. I'd call that a bug, but maybe they are just very serious about wanting you to use <-.