Dplyr in Packages and Global Variables

random-code-snippets packages dplyr rlang R

How to include dplyr in a package, and avoid warnings around global variables.

Robert M Flight true
2022-01-06

I was recently cleaning up a development package so it would actually pass checks so it could be hosted on our labs new r-universe (“The ’Moseleybioinformaticslab’ Universe,” n.d.), and was getting warnings about global variables due to using {dplyr} operations, without {enquoting} variables.

There are a few approaches to handling this.

  1. Using {utils::globalvariables} in an R file somewhere.
  2. Using {rlang::.data} and importing it into the package.

I went with option 2, see (“How to Solve ’No Visible Binding for Global Variables’,” n.d.).

In the original version of {dplyr} and other packages like {ggplot2}, there was an option to use “string” arguments, normally by calling the {*_str} or {*_} version of a function name.

That has gone out of fashion, and the way to do it now is to use the .data pronoun (“Programming with Dplyr,” n.d.).

So now the code looks like this:

# an example filtering operation
dplyr::filter(.data$varname == "value")

The easiest way to include this correctly in your package, is by importing the {rlang::.data}.

#' @importFrom rlang .data

And all the warnings should go away during package checking.

“How to Solve ’No Visible Binding for Global Variables’.” n.d. https://community.rstudio.com/t/how-to-solve-no-visible-binding-for-global-variable-note/28887/3.
“Programming with Dplyr.” n.d. https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html.
“The ’Moseleybioinformaticslab’ Universe.” n.d. https://moseleybioinformaticslab.r-universe.dev/ui#builds.

References

Corrections

If you see mistakes or want to suggest changes, please create an issue on the source repository.

Reuse

Text and figures are licensed under Creative Commons Attribution CC BY 4.0. Source code is available at https://github.com/rmflight/researchBlog_distill, unless otherwise noted. The figures that have been reused from other sources don't fall under this license and can be recognized by a note in their caption: "Figure from ...".

Citation

For attribution, please cite this work as

Flight (2022, Jan. 6). Deciphering Life: One Bit at a Time: Dplyr in Packages and Global Variables. Retrieved from https://rmflight.github.io/posts/2022-01-06-dplyr-in-packages-and-global-variables/

BibTeX citation

@misc{flight2022dplyr,
  author = {Flight, Robert M},
  title = {Deciphering Life: One Bit at a Time: Dplyr in Packages and Global Variables},
  url = {https://rmflight.github.io/posts/2022-01-06-dplyr-in-packages-and-global-variables/},
  year = {2022}
}