Setting equivalent of .subset2 in R?

Viewed 328

In R, I can use .subset2 to act as a [[ or $ without dispatch.

> a <- new.env()
> a$foo  <- 3
> .subset2(a, "foo")
[1] 3

However, I can't seem to find an equivalent for the setting operation without dispatch:

> .subset2(a, "foo") <- 5

Error in .subset2(a, "foo") <- 5 : could not find function ".subset2<-"

How can I set something without the implicit dispatching of using the [[<- or $<- operators?

3 Answers

You may be looking for assign:

Description: Assign a value to a name in an environment.

assign("foo", 5, envir = a)

By the way, instead of using .subset2 (which is an internal function in the Base Package and can be confused with subset), you might want to use get:

get("foo", envir = a)
# [1] 5

Maybe we can try

with(a,assign("foo",5))

or

with(a, `<-`(foo, 5))

or

a$foo <- 5

I'm not entirely sure this is what you're after, but it does meet the pre-reqs of setting the value for foo in the a environment without explicitly using the $, [, [[, <- operators:

# Your code:
a <- new.env()
a$foo  <- 3
.subset2(a, "foo")
# Solution:
list2env(
  list(
    foo = 5
  ), 
  env = a
)
# Proof:
a$foo
Related