6

Suppose I have

label <- 'My val'

and I try to create the list

Output <- list(
  label = pi
)

I get that the name of the first (only) object in the list is "label" but I want "My val".

I understand I can do

names(Output) <- label

But the list is quite long and I'd rather name it in the list function.

1

4 Answers 4

6

Another option is lst from dplyr

library(dplyr)
lst(!!label := pi)
#$`My val`
#[1] 3.141593
Sign up to request clarification or add additional context in comments.

Comments

3

No, you can't reference variables for names when using the list() function to create a list. It will just interpret any variable name as name for the entry. But after constructing the list, you can change the names:

label <- 'My val'
Output <- list(pi)
names(Output)=label

Comments

1

Maybe this could help you, but it would've been much better if you could share a more detailed sample as I thought there might be more variable names involved:

label <- 'My val'

Output <- list(
  label = pi
)

Output |> 
  setNames(label)

$`My val`
[1] 3.141593

Comments

0

data.tables substitute2() might help:

library(data.table)
labels <- list(l1 =  'My val', l2 = 'Other label')
Output <- eval(data.table::substitute2( 
  list( l1 = pi, 
        l2 = exp(1)), 
  env = labels 
) )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.