Creating a named list from two vectors (names, values)
I share Ben's puzzlement about why you might want to do this, and his recommendation.
Just for curiosity's sake, there is a sort of "hidden" feature in mapply
that will allow this:
x <- letters[1:2]
y <- 1:2
mapply(function(x,y) { y }, x, y, SIMPLIFY = FALSE,USE.NAMES = TRUE)
$a
[1] 1
$b
[1] 2
Noting that the documentation for USE.NAMES
says:
USE.NAMES logical; use names if the first ... argument has names, or if it is a character vector, use that character vector as the names.
What I propose is made in 2 steps, and it's quite straightforward, so maybe it's easier to understand:
test_list <- list(1, 2)
names(test_list) <- c("foo", "bar")
What @ben-bolker proposes works, but just wanted to share an alternative, in case you prefer it.
Happy coding!
You can use setNames()
setNames(as.list(c(1, 2)), c("foo", "bar"))
(for a list) or
setNames(c(1, 2), c("foo", "bar"))
(for a vector)