Search code examples
rlistvectorcharacter

Use character from vector to name object in list


I have a vector of characters.

char_vec = c("hello","world","foo","bar")

How can I assign a character (or index) from that vector to name an object in a list?

So instead of doing list("hello"=1,"world"=2)

$hello  1
$world  2

I want to do:

list(as.character(char_vec[1])=1,as.character(char_vec[2])=2)

For this I get an error

Error in parse(text = x, srcfile = src): <text>:1:31: unexpected '='
1: list(as.character(char_vec[1])=
                                  ^
Traceback:

Solution

  • char_vec = c("hello","world","foo","bar")
    setNames(list(1,2), char_vec[1:2])
    #> $hello
    #> [1] 1
    #> 
    #> $world
    #> [1] 2