Dplyr in Packages and Global Variables

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

random-code-snippets
packages
dplyr
rlang
R
development
Author

Robert M Flight

Published

January 6, 2022

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.

References

“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.

Reuse

Citation

BibTeX citation:
@online{mflight2022,
  author = {Robert M Flight},
  title = {Dplyr in {Packages} and {Global} {Variables}},
  date = {2022-01-06},
  url = {https://rmflight.github.io/posts/2022-01-06-dplyr-in-packages-and-global-variables},
  langid = {en}
}
For attribution, please cite this work as:
Robert M Flight. 2022. “Dplyr in Packages and Global Variables.” January 6, 2022. https://rmflight.github.io/posts/2022-01-06-dplyr-in-packages-and-global-variables.