R get object from global environment from function if object exists in global but use different default if not R get object from global environment from function if object exists in global but use different default if not r r

R get object from global environment from function if object exists in global but use different default if not


You can modify your function to check if x exists in the .GlobalEnv and get it from there if it does, otherwise return the default value.

myfunc <- function(x = 30) {  if ("x" %in% ls(envir = .GlobalEnv)) {    get("x", envir = .GlobalEnv)  } else {    x  }}

So if "x" %in% ls(envir = .GlobalEnv) is FALSE it would return

myfunc()[1] 30

If x is found it would return it. if x <- 100:

myfunc()[1] 100

Edit after comment

If you want to make sure to only return x from the global environment if x is not specified as an argument to myfunc, you can use missing(). It returns TRUE if x was not passed and FALSE if it was:

myfunc <- function(x = 30) {  if ("x" %in% ls(envir = .GlobalEnv) & missing(x)) {    get("x", envir = .GlobalEnv)  } else {    x  }} 

So for your example:

x <- 100myfunc(x=300)[1] 300


The simplest method would be to set an appropriate default argument:

myfunc <- function(x=get("x", globalenv()){    x}> x <- 100> f()[1] 100> f(30)[1] 30> rm(x)> f()Error in get("x", globalenv()) : object 'x' not found