Creating a named list from two vectors (names, values)

Jon Claus picture Jon Claus · Jul 24, 2013 · Viewed 33.3k times · Source

Is there a way to use mapply on two vectors to construct a named list? The first vector would be of type character and contain the names used for the list while the second contains the values.

So far, the only solution I have is:

> dummyList = list()
> addToList <- function(name, value) {
+ dummyList[[name]] <- value
+ }
> mapply(addToList, c("foo", "bar"), as.list(c(1, 2))
$foo
`1`

$bar
`2`

This seems like a rather contrived solution, but I can't figure out how to do it otherwise. The problems I have with it are:

  1. It requires the creation of dummyList even though dummyList is never changed and is an empty list after the call to mapply.

  2. If the numeric vector, c(1, 2), is not converted to a list, then the result of the call to mapply is a named vector of doubles.

To get around problem 2, I can always just call mapply on two vectors and then call as.list on the result, but it seems like there should be a way to directly create a list with the values being in a vector.

Answer

Ben Bolker picture Ben Bolker · Jul 24, 2013

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)