[R] Deparse substitute assign with list elements

William Dunlap wdunlap at tibco.com
Fri May 15 16:49:27 CEST 2015


        txt <- paste( nm, '<-', tmp, sep='' )
        eval( parse(text=txt), parent.frame() )

        in `foo()` will do the trick.

Yuck.

If you use that sort of syntax your code becomes hard to understand and
you risk changing variables that users do not want changed.  When the
use uses something like bar(x)<-newValue she knows that 'bar' is going to
change.

Your new code will also fail if you try something like foo(b+10).


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Fri, May 15, 2015 at 1:50 AM, <soeren.vogel at posteo.ch> wrote:

> Thanks, Bill, I should have googled more carefully:
>
>
> http://stackoverflow.com/questions/9561053/assign-values-to-a-list-element-in-r
>
> So, remove
>
>         assign(nm, tmp, parent.frame())
>
> and add
>
>         txt <- paste( nm, '<-', tmp, sep='' )
>         eval( parse(text=txt), parent.frame() )
>
> in `foo()` will do the trick.
>
> Bests
> Sören
>
> > On 15.05.2015, at 00:02, William Dunlap <wdunlap at tibco.com> wrote:
> >
> > You could use a 'replacement function' named 'bar<-', whose last argument
> > is called 'value', and use bar(variable) <- newValue where you currently
> > use foo(variable, newValue).
> >
> > bar <- function(x) {
> >     x + 3
> > }
> > `bar<-` <- function(x, value) {
> >     bar(value)
> > }
> >
> > a <- NA
> > bar(a) <- 4
> > a
> > # [1] 7
> > b <- list(NA, NA)
> > bar(b[[1]]) <- 4
> > b
> > #[[1]]
> > #[1] 7
> > #
> > #[[2]]
> > #[1] NA
> >
> >
> > Bill Dunlap
> > TIBCO Software
> > wdunlap tibco.com
> >
> > On Thu, May 14, 2015 at 11:28 AM, <soeren.vogel at posteo.ch> wrote:
> > Hello,
> >
> > When I use function `foo` with list elements (example 2), it defines a
> new object named `b[[1]]`, which is not what I want.  How can I change the
> function code to show the desired behaviour for all data structures passed
> to the function?  Or is there a more appropriate way to sort of "pass by
> references" in a function?
> >
> > Thanks
> > Sören
> >
> > <src>
> > bar <- function(x) {
> >         return( x + 3 )
> > }
> >
> > foo <- function(x, value) {
> >         nm <- deparse(substitute(x))
> >         tmp <- bar( value )
> >         assign(nm, tmp, parent.frame())
> > }
> >
> > # 1)
> > a <- NA
> > foo(a, 4)
> > a # 7, fine :-)
> >
> > # 2)
> > b <- list(NA, NA)
> > foo(b[[1]], 4) # the first list item should be 7
> > b # wanted 7 but still list with two NAs :-(
> > </src>
> >
> > ______________________________________________
> > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> >
>
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list