View source: R/misc.utilities.R
modify_in_place | R Documentation |
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.
modify_in_place(x, value = x)
x |
the argument (not its name!) to be modified |
value |
the value to assign (defaulting to the current value of |
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
, invisibly, while attempting to modify x
in place
## 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)))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.