Reputation: 971
I am trying to create a function, in which a named list is created (I need to use this specific structure, as it is required to call a downstream function). However, despite the name being defined as an argument of the function, it is not being carried through. Here is a minimal example:
make_list = function(first, second){
return(list(first=second))
}
make_list("name", "value")
#$`first`
#[1] "value"
Note the name "first", rather than "name". First was intended to just be an argument in the function, but it is not being used as such. Any suggestions are much appreciated.
Upvotes: 2
Views: 86
Reputation: 99331
You could do this in one line using setNames
.
make_list <- function(first, second) {
setNames(list(second), first)
}
make_list("name", "value")
# $name
# [1] "value"
Upvotes: 2
Reputation: 6438
In the declaration of list(first=second)
, the "first
" is the attribute name but not the variable first
.
make_list = function(first, second){
ret = list()
ret[[first]] = second
return(ret)
}
make_list("name", "value")
#$name
#[1] "value"
Upvotes: 5