[R] Suggestion on how to make permanent changes to a singleobject in a list?

Gabor Grothendieck ggrothendieck at gmail.com
Fri Jan 4 01:07:09 CET 2008


On Jan 3, 2008 6:58 PM, Charilaos Skiadas <cskiadas at gmail.com> wrote:
>
> On Jan 3, 2008, at 5:08 PM, Bert Gunter wrote:
>
> > Gentlemen:
> >
> > I'm sorry, I don't see the problem. R's is Lisp (or Scheme)-
> > inspired, so you
> > need to think in terms of lists, or equivalently, trees. So what
> > you seem to
> > want to do is easily navigate down a tree to modify a node. This is
> > fairly
> > easy to do with list indexing:
> >
> > ## First create a tree with 5 top nodes each of which has 3 child
> > leaf nodes
> >
> > ## each of which is an empty list.
> >
> > fooStack<-lapply(1:5,function(x)lapply(1:3,function(x)list()))
> >
> > ## Now modify the <4,2> leaf list:
> >
> > fooStack[[c(4,2)]]$bar <- "bar"
> > ## Note: This is shorthand for fooStack[[4]][[2]]$bar <- "bar"
>
> But you want to do this inside a function, i.e. to have function
> that, when passed an argument which is a list, sets the "bar" item of
> this list to the string value "bar" (or perhaps something more
> complicated).
>
> Probably the correct way to do this would be to do
>
> fooStack[[1]]  <- fooModifier(fooStack[[1]])
>
> But the OP was asking, effectively, if we can make it so that the <-
> part is not necessary. I have often found myself wanting to do this,
> and admittedly R, with its LISP functional programming inspiration,
> does not make this very easy.
>
> I should point out here that my suggestion of using `fooModifier<-`
> was purely for showing the potential, I think it would be very bad
> form to actually use it (unless the "<- NULL" part is going to be
> used in the assignment somehow), since it does not use the value that
> it pretends to be assigning to things.
>
> Peter, perhaps it would help if you gave us more context into why you
> wanted this done, and perhaps then someone can suggest a more natural
> approach. Perhaps there is a more "R" way to solve your original
> problem.
>
> One gotcha if you use the proto package (which I do highly recommend,
> it is a wonderful package). I found that mysterious things happen if
> you name your proto object x:
>
>  > library(proto)
>  > x<-proto(y=5)
>  > x$y
> Error in get("y", env = x, inherits = TRUE) : invalid 'envir' argument
>
> Took me a while to figure out that the problem was caused by naming
> the object x.
>

That is fixed in the devel version of proto:

> library(proto)
> # source file from devel version that includes fix
> source("http://r-proto.googlecode.com/svn/trunk/R/proto.R")
> x <- proto(y = 5)
> x$y
[1] 5




More information about the R-help mailing list