modify_in_place: Modify the argument in the calling environment of the calling...

View source: R/misc.utilities.R

modify_in_placeR Documentation

Modify the argument in the calling environment of the calling function

Description

This is a helper function that enables a function to modify its argument in place, emulating behavior of R6 classes and methods in the network. It should typically be the last line of the calling function.

Usage

modify_in_place(x, value = x)

Arguments

x

the argument (not its name!) to be modified

value

the value to assign (defaulting to the current value of x)

Details

This function determines whether the argument can be assigned to by actually attempting to do so. If this results in an error, for example, because the argument is anonymous, the error is silently ignored.

It can be called multiple times by the same function to modify multiple arguments. It uses the on.exit() mechanism, adding to the list. Thus, if some other function calls on.exit(..., add = FALSE) (the default) afterwards, modify_in_place() will fail silently.

Value

value, invisibly, while attempting to modify x in place

Examples

## A function that increments its argument in place:
inc <- function(x){
  modify_in_place(x, x+1)
}

y <- 1
z <- 1

stopifnot(inc(z) == 2)
stopifnot(z == 2)
stopifnot(inc(y) == 2)
stopifnot(y == 2)
stopifnot(inc(z) == 3)
stopifnot(z == 3)

stopifnot(inc(identity(z)) == 4)
stopifnot(z == 3) # Not updated!

## Modify an argument that's been updated in place:
inc2 <- function(y){
  y <- y + 1
  modify_in_place(y)
}

z
stopifnot(inc2(z) == 4)
stopifnot(z == 4)

## Decrement the first argument, increment the second:
incdec <- function(x,y){
  modify_in_place(x, x-1)
  modify_in_place(y, y+1)
}

c(y,z)
incdec(y,z)
stopifnot(all(c(y,z) == c(1,5)))

statnet.common documentation built on April 3, 2025, 7:38 p.m.