list(a = 'first', b = 'second', d = c(3,4))
$a
[1] "first"
$b
[1] "second"
$d
[1] 3 4
Galen Holt
I often end up wanting to build a list with named items, and the names come in as variables.
For example, instead of the typical
I might have the names defined elsewhere. This is particularly common inside functions.
We can’t pass those in as usual- this uses name#
as the name, not the value of the variable.
$name1
[1] "first"
$name2
[1] "second"
$name3
[1] 3 4
We can use setNames
$a
[1] "first"
$b
[1] "second"
$d
[1] 3 4
we can do it in two steps with names
, which I think is what setNames wraps, and is just extra verbose and requires carrying data copies around.
$a
[1] "first"
$b
[1] "second"
$d
[1] 3 4
Can we unquote/eval?
I can almost never get !!
or !!!
to work. this doesn’t, as usual.
Nor this
Nor this, despite the eval working
How about tibble::lst
? I often use it for lists of variables because it self-names them, so maybe it’s the answer here. Yep. That’s just cleaner.
$name1
[1] "first"
$name2
[1] "second"
$name3
[1] 3 4
And, that self-naming I was describing, which solves a different problem- having to write list(name = name, age = age)
.