Creating named lists in R

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

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

      

If, instead, I want to make a list with an arbitrary calculation, I can use lapply

, for example, for example:

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

      

However, the list generated lapply

will always be a regular numbered list. Is there a way to create a list using a lapply

named type function .

My idea is something like:

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

      

==>

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

      

This way I don't need to have keys and values ​​as literals.

I know I can do this:

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

      

But I don't like how I need to create an empty list and modify it to fill it.

Edit: I would also like to do some key based calculations. Something like that:

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

      

+3


source to share


2 answers


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)

      



What produces:

$foo
[1] 5

$bar
[1] 5

$baz
[1] 5

      

+5


source


If your list has names in the first place, lapply will keep them

lapply(list(a=1,b=2,c=3), function(x) x)

      

or you can set the names before or after with setNames()

#before
lapply(setNames(list(1,2,3),c("foo","bar","baz")), function(x) x)

#after
setNames(lapply(list(1,2,3), function(x) x), c("foo","bar","baz"))

      



Another "option" is Map()

. Map

will try to take names from the first parameter you pass. You can ignore the value in the function and only use it for the side effect of saving the name

Map(function(a,b) 5, c("foo","bar","baz"), list(1:3))

      

But the names cannot be changed during the lapply / Map steps. They can only be copied from another location. if you need to change the names, you need to do it as a separate step.

+2


source







All Articles