Search code examples
rlistfunctionparameter-passingnaming

Dynamically name list elements from function argument


I'm trying to dynamically name list elements within a function from a given argument:

This works with static names (non-function):

list(comp1 =
         c("setosa" = 1,
           "versicolor" = 0,
           "virginica" = -1))

$comp1
group1 group2 group3 
     1      0     -1 

But when I want to feed a string ("group1", etc.) from group names (e.g., cyl from the mtcars dataset) that would usually come from a function:

list(comp1 =
         c(levels(iris$Species)[1] = 1,
           levels(iris$Species)[2] = 0,
           levels(iris$Species)[3] = -1))

I get this error:

Error: unexpected '=' in:
"list(comp1 =
         c(levels(iris$Species)[1] ="
Error: unexpected ',' in "           levels(iris$Species)[2] = 0,"
Error: unexpected ')' in "           levels(iris$Species)[3] = -1)"

Yet the output should be the same:

> levels(iris$Species)[1]
[1] "setosa"
> levels(iris$Species)[2]
[1] "versicolor"
> levels(iris$Species)[3]
[1] "virginica"

Question: Is there any way to name these list elements from the given function argument (e.g., group names)?


Solution

  • You can use setNames to assign the names.

    list(comp1 = setNames(c(1, 0, -1), levels(iris$Species)))
    
    #$comp1
    #    setosa versicolor  virginica 
    #         1          0         -1