0

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?

lmo
  • 37,904
  • 9
  • 56
  • 69
  • You should not define global variables in packages. CRAN will probably not accept it. – Rich Scriven Jun 26 '16 at 20:22
  • 3
    It's in the [CRAN Repository Policy](https://cran.r-project.org/web/packages/policies.html), in the last section of *Source Packages* it reads *Packages should not modify the global environment (user’s workspace).* – Rich Scriven Jun 26 '16 at 20:55

2 Answers2

4

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.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
1

Another way of defining global variable is like assign('prev_id', id, envir = .GlobalEnv) where id is assignee variable or some value and prev_id is global variable

abhiieor
  • 3,132
  • 4
  • 30
  • 47