[Rd] Assignment in environment
Duncan Murdoch
murdoch.duncan at gmail.com
Sun Feb 7 14:46:47 CET 2016
On 07/02/2016 8:08 AM, Daniel Kaschek wrote:
> Dear all,
>
> I have a function "fn" with its own environment, i.e.
>
> env <- environment(fn)
>
> and env is not .GlobalEnv. And another function
>
> getValue <- function(x) environment(x)$mylist
>
> which returns the list object "mylist" which is in "env". If I want to
> modify "mylist", I could write
>
> 'getValue<-' <- function(x, value) { environment(x)$mylist <- value}
>
> which gives not the desired result, e.g.
>
> getValue(fn)[[1]] <- 3
>
> will set the first list entry of "mylist" to 3. But then "fn" will also
> be 3!
>
> environment(fn)$mylist[[1]] <- 3
>
> does set the list entry correctly while keeping "fn". What's the
> difference?
An assignment function should return the modified value. So it looks
like you would need
'getValue<-' <- function(x, value) {
environment(x)$mylist <- value
x
}
but in fact, this doesn't work:
getValue(fn)[[1]] <- 3
Error in getValue(fn)[[1]] <- 3 : could not find function "getValue"
I suspect this is a parser problem. However, it does suggest a simple
workaround for you:
Just define
getValue <- function(x) environment(x)$mylist
and then your expression works as expected.
Duncan Murdoch
More information about the R-devel
mailing list