overwrite: Overwrite an object in a given environment.

overwriteR Documentation

Overwrite an object in a given environment.

Description

Utility function to overwrite an object, and bypass the assignment operator.

Usage

overwrite(objname, content, environment)

Arguments

objname

Character, the name of the object to overwrite.

content

An R object

environment

The environment where to perform the overwrite procedure.

Details

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.

Value

This function does not return anything.

Author(s)

Adrian Dusa

Examples

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

admisc documentation built on March 27, 2026, 9:06 a.m.

Related to overwrite in admisc...