Skip to contents

This function checks if a given variable exists in the specified environment (global environment by default). If the variable does not exist, it assigns a given value to it. If the variable already exists, it prints the current value of the variable. The function is designed to prevent overwriting existing variables unintentionally.

Usage

AssignIfNotExist(Variable, Value, Env = globalenv())

Arguments

Variable

Character; the name of the variable to be checked and potentially assigned a value.

Value

any; the value to be assigned to the variable if it does not already exist.

Env

environment; the environment in which to check for the existence of the variable and potentially assign the value. Defaults to the global environment.

Value

The function explicitly returns NULL, but its primary effect is the side-effect of assigning a value to a variable in an environment or printing the current value of an existing variable.

Author

Ahmed El-Gabbas

Examples

AssignIfNotExist(Variable = "x", Value = TRUE)
print(x)
#> [1] TRUE

# --------------------------------------------------

y <- 10
# y exists and thus its value was not changed
AssignIfNotExist(Variable = "y", Value = TRUE)
print(y)
#> [1] 10