Source: http://adv-r.had.co.nz/Environments.html

Just as you can use a list to pass data between functions, you can also use an environment. When creating your own environment, note that you should set its parent environment to be the empty environment. This ensures you don’t accidentally inherit objects from somewhere else:

# when we create an environment, it inherits the object that existed before
x <- 1            # create x
e1 <- new.env()   # create new environment
get("x", envir = e1)  # x in inside
# [1] 1
# this will produce an error because x doesn't exist in the new environment
e2 <- new.env(parent = emptyenv())
get("x", envir = e2)
# Error in get("x", envir = e2) : object 'x' not found

Environments are data structures useful for solving three common problems:

source("VLP.R")

set.project.environment()

ls(project.env)
project.env$data.file.hdf5
project.env$data.file.rda
project.env <- new.env()
project.env
ls(project.env)
assign("wellFile", "./data", envir = project.env)
ls(project.env)
project.env$wellFile
parent.env(project.env)
get("wellFile", envir = project.env)
search()
project.env$data.folder <- "./data"
project.env[["data.folder"]] <- "./inst/data"
project.env[["data.folder"]]
exists("data.folder", envir = project.env)
exists("datar", envir = project.env)
# an environment created inside a function is not accesible from outside
callingEnvInside  <- function() {
    myEnv <<- new.env()              # create new environment for project
    MyEnv[["data.folder"]] <- dataFolder   
}

search()

environment(callingEnvInside)

Source: http://adv-r.had.co.nz/Environments.html

# create an empty environment
my_env <- new.env(parent = emptyenv())
my_env$dataFolder <- "./data"          # assign a value to dataFolder


# getter function
get_value <- function() {
    my_env$dataFolder
}

# setter function
set_value <- function(value) {
    old <- my_env$dataFolder
    my_env$dataFolder <- value
    invisible(old)
}

get_value()
set_value("./inst/extdata")
get_value()
old_value <- set_value("./newer/extdata")   # this will return the old value
old_value


f0nzie/rNodal documentation built on May 6, 2019, 10:14 a.m.