Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variables in packages in R

I'm developing a package in R. I have a bunch of functions, some of them need some global variables. How do I manage global variables in packages?

I've read something about environment, but I do not understand how it will work, of if this even is the way to go about the things.

like image 398
bskard Avatar asked Sep 26 '12 09:09

bskard


People also ask

Does R have global variables?

Overview. Global variables in R are variables created outside a given function. A global variable can also be used both inside and outside a function.

How can I see all global variables?

Once setup, open jslinter and go to Options->check everything on the left column except "tolerate unused parameters". Then run jslinter on the webpage and scroll down in the results. You will have a list of unused variables (global and then local to each function).

Can global variables be used in different files?

A global variable is accessible to all functions in every source file where it is declared. To avoid problems: Initialization — if a global variable is declared in more than one source file in a library, it should be initialized in only one place or you will get a compiler error.


2 Answers

You can use package local variables through an environment. These variables will be available to multiple functions in the package, but not (easily) accessible to the user and will not interfere with the users workspace. A quick and simple example is:

pkg.env <- new.env()  pkg.env$cur.val <- 0 pkg.env$times.changed <- 0  inc <- function(by=1) {     pkg.env$times.changed <- pkg.env$times.changed + 1     pkg.env$cur.val <- pkg.env$cur.val + by     pkg.env$cur.val }  dec <- function(by=1) {     pkg.env$times.changed <- pkg.env$times.changed + 1     pkg.env$cur.val <- pkg.env$cur.val - by     pkg.env$cur.val }  cur <- function(){     cat('the current value is', pkg.env$cur.val, 'and it has been changed',          pkg.env$times.changed, 'times\n') }  inc() inc() inc(5) dec() dec(2) inc() cur() 
like image 93
Greg Snow Avatar answered Oct 10 '22 05:10

Greg Snow


You could set an option, eg

options("mypkg-myval"=3) 1+getOption("mypkg-myval") [1] 4 
like image 33
James Avatar answered Oct 10 '22 03:10

James