| overwrite | R Documentation |
Utility function to overwrite an object, and bypass the assignment operator.
overwrite(objname, content, environment)
objname |
Character, the name of the object to overwrite. |
content |
An R object |
environment |
The environment where to perform the overwrite procedure. |
assign() is sufficient when objname is a simple object name,
such as "bar". It is not sufficient when the target is an expression,
such as "bar$A". A call such as assign(bar$A, 1, envir =
parent.frame()) fails because assign() expects its first argument to
evaluate to a character string. If that expression is first deparsed, for
instance to "bar$A", then assign() would create an object
literally named "bar$A" in the target environment rather than
replacing component A inside bar.
This function handles both situations. For simple names, it overwrites the object directly in the target environment. For expressions, it reconstructs and evaluates the corresponding assignment call in that environment.
This function does not return anything.
Adrian Dusa
foo <- function(object, x) {
objname <- deparse(substitute(object))
overwrite(objname, x, parent.frame())
}
bar <- 1
foo(bar, 2)
bar
# [1] 2
bar <- list(A = bar)
foo(bar$A, 3)
bar
# $A
# [1] 3
foo_assign <- function(object, x) {
objname <- deparse(substitute(object))
assign(objname, x, envir = parent.frame())
}
bar <- list(A = 1)
try(assign(bar$A, 3, envir = parent.frame()))
bar <- 1
foo_assign(bar, 2)
bar
# [1] 2
bar <- list(A = 1)
foo_assign(bar$A, 3)
bar
# $A
# [1] 1
`bar$A`
# [1] 3
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.