Get value from function call or specific environment in that order

get_fn_envir(x, envir = NULL, verbose = FALSE, ...)

Arguments

x

character string indicating the name of an R object.

envir

environment or list of environment objects.

verbose

logical indicating whether to print verbose output.

...

additional arguments are ignored.

assign_to_envir

logical indicating whether to assign values to environment envir, if envir is not NULL. This option is helpful to combine function arguments with environment values.

Value

object represented by variable name given in x from either the calling function, or the environment envir, or NULL if not defined in either case.

Details

This function is a helper function intended to return a variable value, if it exists and is not NULL, by searching these locations in order:

  1. The calling function, which is the environment of the function that called get_fn_envir().

  2. The environment or environments provided in envir.

  3. It returns NULL if the previous steps do not find the object named by x.

Examples

x <- 10; get_fn_envir("x")
#> [1] 10
test_x <- function(x=NULL, envir=NULL, verbose=FALSE, ...) { get_fn_envir("x", envir, verbose=verbose) } test_x()
#> NULL
test_x(envir=globalenv())
#> NULL
test_x(x=5)
#> [1] 5
test_x(x=5, envir=globalenv())
#> [1] 5
test_x(x=NULL, envir=globalenv())
#> NULL
test_x(envir=globalenv())
#> NULL
# create new environment testenv <- new.env(); testenv$x <- 100; test_x(envir=testenv, verbose=TRUE)
#> ## (17:22:59) 27Jul2021: get_fn_envir(): Variable 'x' found in the provided envir
#> [1] 100
test_x(x=1000, envir=testenv, verbose=TRUE)
#> ## (17:22:59) 27Jul2021: get_fn_envir(): Variable 'x' found in parent.frame(1)
#> [1] 1000
# search testenv then globalenv() test_x(x=12, envir=c(testenv, globalenv()), verbose=TRUE)
#> ## (17:22:59) 27Jul2021: get_fn_envir(): Variable 'x' found in parent.frame(1)
#> [1] 12
test_x(envir=c(testenv, globalenv()), verbose=TRUE)
#> ## (17:22:59) 27Jul2021: get_fn_envir(): Variable 'x' found in the provided envir[[1]]
#> [1] 100
testenv$x <- NULL; test_x(envir=c(testenv, globalenv()), verbose=TRUE)
#> NULL
rm("x", envir=testenv); test_x(envir=c(testenv, globalenv()), verbose=TRUE)
#> ## (17:22:59) 27Jul2021: get_fn_envir(): Variable 'x' found in the provided envir[[1]]
#> [1] 10