How to Check If Object (Variable) Is Defined in R

How to check if object (variable) is defined in R?

You want exists():

R> exists("somethingUnknown")
[1] FALSE
R> somethingUnknown <- 42
R> exists("somethingUnknown")
[1] TRUE
R>

How to check if any variable is defined in argument (...) in R?

Does this suffice?

# Define a function for remaining scenarios
f = function(...){"a" %in% names(list(...))}

# Scenario 3
f()
# [1] FALSE

# Scenario 4
a <- 10
f()
# [1] FALSE

# Scenario 5
f(a = 5)
# [1] FALSE

f(a = 5)
[1] TRUE

R : Check if R object exists before creating it

You should use exists("mydf") instead exists(mydf)

R: How to check whether object exists inside function?

We can do this by specifying a specific environment for exists to search in and tell it to only look there, and not in the enclosing environments.

The where= argument tells exists where to look for that object. We can either specify it explicitly with environment() (which returns the current environment), or use the default value of -1 which drops the R_GlobalEnv from the list of environments to search.

Either way, the key is to set inherits=FALSE to limit it to only the specified environment. Otherwise, it also looks in the enclosing environments (like R_GlobalEnv) which we don't want:

x <- 1
fun <- function(){exists("x", inherits = F)}

fun()
[1] FALSE

However if we define x in the enviroment of the function, it returns TRUE:

fun <- function(){
x<-3;
exists("x", inherits = F)}
fun()
[1] TRUE

The example mentioned with explicitly defined environment:

fun <- function(){exists("x", where = environment(), inherits = F)}

What's happening with the default where=-1 argument? The documentation says that if you provide it with an integer, it selects the environment based on "the position in the search list". We can see that .GlobalEnv is at position 1, followed by attached packages

rm(list=ls()) # clear .GlobalEnv
x <- 3 # Add x to .GlobalEnv
ls() # Show that x is the only thing in .GlobalEnv
[1] "x"

search() # Show the search list
[1] ".GlobalEnv" "package:lubridate" "package:forcats" "package:stringr"
[5] "package:dplyr" "package:purrr" "package:readr" "package:tidyr"
[9] "package:tibble" "package:ggplot2" "package:tidyverse" "tools:rstudio"
[13] "package:stats" "package:graphics" "package:grDevices" "package:utils"
[17] "package:datasets" "package:methods" "Autoloads" "package:base"

Now we run this function which checks for different objects in different environments by integer value:

fun <- function(){
y <- 3
k <- function(){
z <- 3
print(exists('z', -1, inherit=FALSE))
print(exists('x', 1, inherit=FALSE))
print(exists('y', parent.frame(), inherit=FALSE))}
k()
print(exists('x', -1, inherit=FALSE))
print(exists('y', -1, inherit=FALSE))
print(exists('x', 1, inherit=FALSE))
print(exists('ymd', 2, inherit=FALSE))
print(exists('last2', 3, inherit=FALSE))
print(exists('str_detect', 4, inherit=FALSE))
}

> fun()
[1] TRUE # Inside k(), -1 is the function env for k() - z is there
[1] TRUE # 1 is .GlobalEnv, x is there
[1] TRUE # to choose parent env with y, we need to specify it with parent.frame()
[1] FALSE # -1 is the function env, x not in function env
[1] TRUE # -1 is the function env, y is in function env
[1] TRUE # 1 is .GlobalEnv, x is in .GlobalEnv
[1] TRUE # position 2 is the lubridate package
[1] TRUE # position 3 is the forcats package
[1] TRUE # position 4 is the stringr package

From this we can see that -1 is always the local environment of the current function, while 1 is .GlobalEnv and higher numbers are attached packages as listed by search(). If you want to specify with more detail, for instance to look in fun() from within k(), then you need to specify the environment explicitly, either with a relative function like parent.frame() as above or by getting the environment as an object and referring directly as below:

fun <- function(){
y <- 3
env <- environment()
k <- function(e){
z <- 3
print(exists('y', inherit=FALSE))
print(exists('y', where=e, inherit=FALSE))
}
k(env)
}
fun()
[1] FALSE
[1] TRUE

R - Inside function check if object exists

The R interpreter evaluates first the line f(x) and then what is in the function. The interpreter finds an unknown element x and stops immediately evaluating the rest of the code.

Therefore, it won't work in any scenario you've given, as the problem comes before the function evaluation.

You have to put your check outside the function:

if(exists("x")) {
f(x)
}

Or, depending on your needs, you can do:

f <- function(x) {
if(!missing("x")) { return(x * 2) }
}

f() // do nothing
f(2) // return 4

Check if object is Null or undefined

{{ is the combination of enquo() and !! in one step. To inspect the contents of var, you need to decompose these two steps. enquo() defuses the argument and returns a quosure that you can inspect. !! injects the quosure into other calls.

Below we enquo() the argument at the start of the function. Inspect it with quo_is_null() (you could also use quo_get_expr() to see what's inside it). Then inject it inside group_by() with !!:

myfun <- function(dat, group = NULL, var = NULL) {
var <- enquo(var)

if (!quo_is_null(var)) {
print("It works!")
}

# Use `!!` instead of `{{` because we have decomposed the
# `enquo()` and `!!` steps that `{{` bundles
dat %>%
group_by({{ group }}, !!var) %>%
summarize(mean = mean(value), .groups = "drop")
}

Verify object existence inside a function in R

You should have checked ?exists:

Usage:

exists(x, where = -1, envir = , frame, mode = "any",
inherits = TRUE)

Arguments:

x: a variable name (given as a character string).

Do exists("y")

Check if object exists in multi-level list at specified path

The assignment to address_value can be outside of the eval, which avoids the undeclared variable nag in the CMD check.

check_address <- function(address) {

expr_str <- paste0("l", address)

# evaluate the call
address_value <- eval(str2lang(expr_str))

if(is.null(address_value)){
warning("Address is NULL or not found in list")
}

address_value
}

Which results in:

check_address("$c$cat$fish")
#> [1] 3

check_address("$c$cat$banana")
#> NULL
#> Warning message:
#> In check_address("$c$cat$banana") : Address is NULL or not found in list

How to check if object (variable) is defined in R?

You want exists():

R> exists("somethingUnknown")
[1] FALSE
R> somethingUnknown <- 42
R> exists("somethingUnknown")
[1] TRUE
R>


Related Topics



Leave a reply



Submit