Reputation: 1068
I am probably going to knock my head against the table because its obvious but how do you create a list programatically from a character vector such that the character vector provides the tags and a nother vector the values. E.g.
character.vector <- c('first.element', 'second.element')
values.vector <- c(1, 2)
a.list <- list(//magic here//)
print(a.list) // prints the same as list(first.element=1, second.element=2)
Upvotes: 10
Views: 2844
Reputation: 57696
Surprised that noone's mentioned structure
:
structure(as.list(values.vector), names=character.vector)
Upvotes: 5
Reputation: 59980
The other answers covered it better, but just for completeness, another way would be to construct the expression you want to evaluate using parse
and use eval
to evaluate it....
# tag and values for list elements
tag <- c('first.element', 'second.element')
val <- c(1, 2)
content <- paste( tag , "=" , val , collapse = " , " )
content
# [1] "first.element = 1,second.element = 2"
eval( parse( text = paste0("list( " , content , " )" ) ) )
# $first.element
# [1] 1
#
# $second.element
# [1] 2
Upvotes: 5
Reputation: 4444
character.vector <- c('first.element', 'second.element')
values.vector <- c(1, 2)
as.list(setNames(values.vector, character.vector))
Upvotes: 17
Reputation: 2785
You could set:
> names(values.vector) <- character.vector
> values.vector
first.element second.element
1 2
and, of course, convert it into a list if necessary:
> as.list(values.vector)
$first.element
[1] 1
$second.element
[1] 2
Upvotes: 6