how to solve "no visible binding for global variable" note?

#1

When I run devtools::check() for my package I get the following notes:

❯ checking R code for possible problems ... NOTE
  IMPosterior: no visible binding for global variable ‘section’
  IMPosterior: no visible binding for global variable ‘y’
  IMPosterior: no visible binding for global variable ‘prob’
  Undefined global functions or variables:
    prob section y

How can I solve that? I believe this is the code that generates the problem:

  # Calculate density values for input data
  dens <- data.frame(stats::density(x, n=2^10, adjust=1)[c("x","y")]) %>%
    dplyr::mutate(section = cut(x, breaks=breaks)) %>%
    dplyr::group_by(section) %>%
    dplyr::mutate(prob = paste0(round(sum(y)*mean(diff(x))*100),"%"))

Thanks!

0 Likes

#2

You can put the following R code somewhere in your package, perhaps an R/globals.R script.

utils::globalVariables(c("prob", "section", "y"))
2 Likes

#3

I see this has been solved but here is a dplyr/rlang specific suggestion: you can use the .data pronoun cf this dplyr vignette, " If this function is in a package, using .data also prevents R CMD check from giving a NOTE about undefined global variables (provided that you’ve also imported rlang::.data with @importFrom rlang .data )."

  dens <- data.frame(stats::density(x, n=2^10, adjust=1)[c("x","y")]) %>%
    dplyr::mutate(section = cut(.data$x, breaks=breaks)) %>%
    dplyr::group_by(.data$section) %>%
    dplyr::mutate(prob = paste0(round(sum(.data$y)*mean(diff(.data$x))*100),"%"))

Note that I don't think the code you posted generates the NOTE for prob, you must use prob somewhere else as well?

2 Likes

closed #4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

0 Likes