Javier Landa-Torres Javier Landa-Torres - 3 months ago 14
R Question

Define Global Variables when creating packages

I have this problem. I am creating a new package with name "mypackagefunction" for R whose partial code is this

mypackagefunction<-function(){

##This is the constructor of my package
##1st step: define variables

gdata <<- NULL

#...
#below of this, there are more functions and code
}


So, I build and reload in R Studio and then check and in this step I receive this warning:


mypackagefunction: no visible binding for '<<-' assignment to ‘gdata’


But when I run my package with:

mypackagefunction()


I can use call that variable which is into the package with this results

> mypackagefunction()
> gdata
NULL


How can I remove this NOTE or Warning when I check my package? or another way to define Global Variables?

Answer

There are standard ways to include data in a package - if you want some particular R object to be available to the user of the package, this is what you should do. Data is not limited to data frames and matrices - any R object(s) can be included.

If, on the other hand, your intention was to modify the global environment every time a a function is called, then you're doing it wrong. In R's functional programming paradigm, functions return objects that can be assigned into the global environment by the user. Objects don't just "appear" in the global environment, with the programmer hoping that the user both (a) knows to look for them and (b) didn't have any objects of the same name that they wanted to keep (because they just got overwritten). It is possible to write code like this (using <<- as in your question, or explicitly calling assign as in @abhiieor's answer), but it will probably not be accepted to CRAN as it violates CRAN policy.