0
votes

given a character vector:

myvec <- c("one", "two", "three")

I would like to turn it into a list such that names of the elements of the list come from the character vector and the list itself is empty. Note that I do not know the length of the character vector a priori. I need this because later on I programatically fill in each element of this list.

My desired output:

str(mylist)

$one
NULL

$two
NULL

$three
NULL

I came up with this:

turnList <- function(x){map(as.list(set_names(x)), ~NULL)}

And it works and all is well but I have a feeling it can be done more simply...? Solutions with purrr and tidyverse in general would be ideal...

3

3 Answers

1
votes
setNames(vector("list", length(myvec)), myvec)
0
votes

We can use vector

setNames(vector("list", length = length(myvec)), myvec)

#$one
#NULL

#$two
#NULL

#$three
#NULL

Or replicate

setNames(replicate(length(myvec), NULL), myvec)
0
votes

1) Base R No packages are used.

Map(function(x) NULL, myvec)

2) gsubfn At the expense of using a package we can slightly shorten it further:

library(gsubfn)
fn$Map(. ~ NULL, myvec)

3) purrr or using purrr (at the expense of a package and a few more characters in code length). This is similar to the approach in the question but simplifies it by eliminating the as.list which is not needed.

library(purrr)
map(set_names(myvec), ~ NULL)

Note

A comment below this answer points out that NULL can be replaced with {}. That will save two characters and applies to any of the above.