In R, how can I construct an anonymous list containing an element whose name is contained in a variable?

StackOverflow https://stackoverflow.com/questions/16906002

  •  30-05-2022
  •  | 
  •  

Pergunta

I would like to insert an element into a list in R. The problem is that I would like it to have a name contained within a variable.

> list(c = 2)
$c
[1] 2

Makes sense. I obviously want a list item named 'c', containing 2.

> a <- "b"
> list(a = 1)
$a
[1] 1

Whoops. How do I tell R when i want it to treat a word as a variable, instead of as a name, when I am creating a list?

Some things I tried:

> list(eval(a)=2)
Error: unexpected '=' in "list(eval(a)="
> list(a, 2)
[[1]]
[1] "b"

[[2]]
[1] 2
> list(get(a) = 2)
Error: unexpected '=' in "list(get(a) ="

I know that if I already have a list() laying around, I could do this:

> ll<-list()
> ll[[a]]=456
> ll
$b
[1] 456

...But:

> list()[[a]]=789
Error in list()[[a]] = 789 : invalid (NULL) left side of assignment

How can I construct an anonymous list containing an element whose name is contained in a variable?

Foi útil?

Solução

One option:

a <- "b"
> setNames(list(2),a)
$b
[1] 2

or the somewhat more "natural":

l <- list(2)
names(l) <- a

and if you look at the code in setNames you'll see that these two methods are so identical that "the way to do this" in R really is basically to create the object, and then set the names, in two steps. setNames is just a convenient way to do that.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top