Reputation: 273
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...
Upvotes: 0
Views: 543
Reputation: 270195
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)
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.
Upvotes: 0
Reputation: 389235
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)
Upvotes: 1