Search code examples
rlistvector

Create a named list, with the values as a character vector


I am trying to create a named list in R where the contents of each named list element is a character vector of two values.

What I have is like this:

list_vec <- c('item1', 'item2', 'item3')
val_vec <- c(0.5, 3)

What I want is a list like this:

$item1
[1] 0.5  3

$item2
[1] 0.5  3

$item3
[1] 0.5  3

I've tried combinations of as.list and setNames, but I can't seem to find the right syntax. Ideally the solution would be base R or tidyverse please.


Solution

  • I think the point is to repeat your val_vec (you have to make it a list at this stage) according to the length of list_vec.

    setNames(rep(list(val_vec), length(list_vec)), list_vec)
    $item1
    [1] 0.5 3.0
    
    $item2
    [1] 0.5 3.0
    
    $item3
    [1] 0.5 3.0