Search code examples
rsubsetr6

Setting equivalent of .subset2 in R?


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?


Solution

  • 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