Home > Software design >  Indirectly defined objects to a list
Indirectly defined objects to a list

Time:06-27

I have a variable whose name and value are both determined dynamically. I want to append that variable to a list, so I need to express it in the form list(x). My difficulty is defining what x should be. So, for example, if the value of the name is given by the variable a, and the value is b, I have both

a <- "name"
b <- 3

But then I get this result:

list(a = b)

$a [1] 3

The value is correct but the name is not. I want the list to look behind the variable a to its current value, which is "name". How do I do that, please?

CodePudding user response:

Use lst from dplyr as the expression on the lhs of = is only evaluated literally and not the value stored int it.

library(dplyr)
lst(!! a:= b)
$name
[1] 3

Or with setNames/names<- from base R

setNames(list(b), a)
$name
[1] 3
`names<-`(list(b), a)
$name
[1] 3

Or create the list first and then rename

lst1 <- list(b)
names(lst1) <- a

CodePudding user response:

We may use structure.

a <- 'name'; b <- 3

structure(as.list(b), names=a)
# $name
# [1] 3

It generalizes well for multiple pair-wise values.

a <- c('name1', 'name2'); b <- c(3, 4)

structure(as.list(b), names=a)
# $name1
# [1] 3
# 
# $name2
# [1] 4
  • Related