Shraddha Pai
Shraddha Pai

Reputation: 1

R package can see variables not passed to it

I am writing a new R package and find that variables that I have not explicitly passed to a function in the package (as input argument) are visible within it, e.g.:

myFunc <- function(a,b,c) {
  print(d)
}

where d is in the caller .R script, but has not been passed to myFunc, is visible.

Any help would be great, thanks; I'm using R 3.2.4 and have been using roxygen2 (via devtools::document()) to create the NAMESPACE if that helps.

Upvotes: 0

Views: 91

Answers (2)

Shraddha Pai
Shraddha Pai

Reputation: 1

Very useful link, thanks. It looks like forcing limited scoping within a function (i.e. getting a function to not access the global scope) is not a default property of R.

I found a similar question here: R force local scope

Using the checkStrict function posted by the main responder to that question seems to have worked; it found an unintended use of a global variable.

> require(myCustomPackage)
> checkStrict(showDendro)
Warning message:
In checkStrict(showDendro) : global variables used: palName

where showDendro is a function inside my custom package.

So it seems the solution to my problem is:

1) while you can stop R from moving up to the global environment by enclosing all your functions in the local() function , that seems like a tedious solution.

2) when moving code from the general environment into its own function, run something like checkStrict to remove unintended use of global variables.

Upvotes: 0

Zachary Cross
Zachary Cross

Reputation: 2318

Isn't this just a consequence of the scoping rules in R?

Your function defines a new myFunc environment. When you try to reference d in print(d), the interpreter first checks the myFunc environment for an object called d. Because no such object exists, the interpreter next checks the calling environment for an object called d. It finds the variable defined in your .R script and then prints it.

Here's a link with more info and a pile of examples.

Upvotes: 1

Related Questions