Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading