Skip to content
Prev 370720 / 398498 Next

define a list with names as variables

> Hello Thomas, Ulrik,
    > thanks for your suggestions.

There's also the
	setNames(<obj>, names)
which is a trivial wrapper to achieve this.
I had provided it for R (in package 'stats') just to help people
to write more nicely readable code:

Your function f()  below then becomes a simple one-liner:

   f <- function(foo, bar)  setNames(list(bar), foo)

Martin Maechler
ETH Zurich and R Core


    > Giovanni

    > On Fri, Aug 4, 2017 at 12:13 PM, Thomas Mailund
> <thomas.mailund at gmail.com> wrote:
>> Do you mean like this?
    >> 
    >> 
    >>> f <- function(foo, bar) {
    >> +   result <- list(bar)
    >> +   names(result) <- foo
    >> +   result
    >> + }
    >> 
    >>> (x <- f("hello", "world"))
    >> $hello
    >> [1] "world"
    >> 
    >>> names(x)
    >> [1] "hello"
> On Fri, Aug 4, 2017 at 12:14 PM, Ulrik Stervbo <ulrik.stervbo at gmail.com> wrote:
>> Hi Giovani,
    >> 
    >> I would create an unnamed list and set the names after.
    >> 
    >> Best,
    >> Ulrik

    > ______________________________________________
    > 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.