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.
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.
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).
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.
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()
You could set an option
, eg
options("mypkg-myval"=3) 1+getOption("mypkg-myval") [1] 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With