Dinoop Nair
Dinoop Nair

Reputation: 2773

sharing variables between 2 packages in R

I have created 2 packages in R. The variables in one package are using in functions of the other package. So i declared variables globally like var <<- "value". Now every functions are working properly. But the variables are now accessible to everyone. If the value of variable is changed by any user, lot of functions wont work properly. Is it possible to create a variable and use that variable only within some particular packages?

Upvotes: 3

Views: 250

Answers (2)

Dinoop Nair
Dinoop Nair

Reputation: 2773

It is possible by creating new environment. http://digitheadslabnotebook.blogspot.in/2011/06/environments-in-r.html

>cacheEnv <- new.env()
> url <- "http://mytext.com"
> file <- "This is the content I downloaded"
> cacheEnv <- new.env()
> assign(url, file, envir=cacheEnv)
> get(url, envir=cacheEnv)
[1] "This is the content I downloaded"

The users cannot edit variables directly. They can edit the variables only using the name of the environment.

Upvotes: 1

daroczig
daroczig

Reputation: 28632

Store the settings in options instead of variables in the .GlobalEnv. You can use options as a key-value storage or assign e.g. a list to a key (maybe your package's name) like I do in pander package. As you can see I even created some helper functions to update/query those list elements.

Quick example:

> options(foo = list(a = pi, b = 1:3))
> getOption('foo')
$a
[1] 3.141593

$b
[1] 1 2 3

> getOption('foo')['a']
$a
[1] 3.141593

Upvotes: 4

Related Questions