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

how to not hardcode list item name in R?

im pretty new to R, i wonder how can do something like the following:

a = 'vol'
b = list(a=c(1,2,3))

actual output:

> b
$a
[1] 1 2 3

the output that I wish to have:

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

> b
$vol
[1] 1 2 3

>Solution :

Mid-definition

a = 'vol'
b = setNames(list(c(1,2,3)), a)
b
# $vol
# [1] 1 2 3

The list(.) can have names if you like, they will be overwritten. For instance, this produces the same result: setNames(list(a=c(1,2,3)), a) (the initial name a= is moot, and has nothing to do with the a referenced as the second argument to setNames).

Post-definition

a = 'vol'
b = list(a=c(1,2,3))
names(b) <- a
b
# $vol
# [1] 1 2 3
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