Generating named lists in R

advertisements

If I want to create a named list, where I have named literals, I can just do this:

list(foo=1,bar=2,baz=3)

If instead I want to make a list with arbitrary computation, I can use lapply, so for example:

lapply(list(1,2,3), function(x) x)

However, the list generated by lapply will always be a regular numbered list. Is there a way I can generate a list using a function like lapply with names.

My idea is something along the lines of:

lapply(list("foo","bar","baz), function(key) {key=5}

==>

list(foo=5,bar=5,baz=5)

That way I don't have to have the keys and values as literals.

I do know that I could do this:

res = list()
for(key in list("foo","bar","baz") {
    res[key] <- 5;
}

But I don't like how I have to create a empty list and mutate it to fill it out.

Edit: I would also like to do some computation based on the key. Something like this:

lapply(c("foo","bar","baz"), function(key) {paste("hello",key)=5})


sapply will use its argument for names if it is a character vector, so you can try:

sapply(c("foo","bar","baz"), function(key) 5, simplify=F)

Which produces:

$foo
[1] 5

$bar
[1] 5

$baz
[1] 5