0

I want to make an R package called my_package with the following with the following behavior:

library(my_package)
my_package::get_username() # should throw error "no username set"
my_package::set_username("john doe")
my_package::get_username() # should print "john doe"

I'm not sure how to do this. I tried with the following inside an R file test.R and using source('test.R') it works. But I don't know what would be the proper way to do this when creating a package.

pkg_env <- new.env()
pkg_env$username <- NULL

set_username <- function(username) {
    pkg_env$username <- username
}

get_username <- function() {
    if (is.null(pkg_env$username)) {
        print("ERROR")
    } else {
        print(pkg_env$username)
    }
}
latorrefabian
  • 1,077
  • 3
  • 9
  • 19
  • 1
    It's common for a package to create `options()` variables of the form `package_name.variable_name`, possibly initializing them when the [package is loaded](https://github.com/hadley/dplyr/blob/master/R/zzz.r#L1-L11). – nrussell Aug 26 '16 at 23:51

1 Answers1

0

The easiest way of doing what you want is to use options. For example, in devtools, you can set a variety of options using this technique - package?devtools

If you want to use environments, then you need to create the environment when the package is loaded, using the .onLoad function

csgillespie
  • 59,189
  • 14
  • 150
  • 185