Skip to contents

Facilitates the one-time setting of a variable in R, ensuring its immutability thereafter.

Usage

setOnce(., val = 1L, envir = NULL)

Arguments

.

variable to set

val

the value to set for the variable

envir

environment where variables resides

Value

the variable set to the new variable, along with a class of once added to the output

Details

With this function, users can establish the change to the initial value of a variable, and it guarantees that any subsequent attempts to modify the variable are ignored. This feature ensures that the variable remains constant and immutable once it has been set, preventing unintentional changes and promoting code stability. This function simplifies the process of managing immutable variables in R, providing a reliable mechanism for enforcing consistency in data throughout the course of a program or script.

Examples

# set the value of vector_x1, vector_y1, vector_z1
init(vector_x1, vector_y1, vector_z1, value = 85)

# view the initial values of the variables
vector_x1
#> [1] 85
vector_y1
#> [1] 85
vector_z1
#> [1] 85

# task 1: change the value vector_x1 and prevent further changes
vector_x1 # check value of unchanged
#> [1] 85
vector_x1 * 0.56 # check value when x 0.56
#> [1] 47.6

setOnce(vector_x1, val = 4500) # set vector_x1
#> Error in parent.env(e): the empty environment has no parent
vector_x1 # check value
#> [1] 85
vector_x1 * 0.56 # check value when x 0.56
#> [1] 47.6

setOnce(vector_x1, val = 13) # set vector_x1 AGAIN, should not change
#> Error in parent.env(e): the empty environment has no parent
vector_x1 # check value
#> [1] 85
vector_x1 * 0.56 # check value when x 0.56
#> [1] 47.6

# task 2: In for loop, change vector_y1 and use later
vector_y1 # check value of unchanged
#> [1] 85

for(i in 1:20){
setOnce(vector_y1,as.numeric(Sys.time()))
# now let's see the difference between vector_y1
# and the current time as it changes
message("current vector_y1: ",vector_y1,"; subtraction res: ",as.numeric(Sys.time()) - vector_y1)
}
#> Error in parent.env(e): the empty environment has no parent

# task 3: In for lapply, change vector_z1 and use later
vector_z1 # check value of unchanged
#> [1] 85

invisible(
lapply(1:20, function(i){
setOnce(vector_z1,as.numeric(Sys.time()))
# now let's see the difference between vector_z1
# and the current time as it changes
message("current vector_z1: ",vector_z1,"; subtraction res: ",as.numeric(Sys.time()) - vector_z1)
})
)
#> Error in parent.env(e): the empty environment has no parent

# result of all the tasks
vector_x1
#> [1] 85
vector_y1
#> [1] 85
vector_z1
#> [1] 85