joidegn
joidegn

Reputation: 1068

create list programmatically with tags from character vector

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

Answers (4)

Hong Ooi
Hong Ooi

Reputation: 57696

Surprised that noone's mentioned structure:

structure(as.list(values.vector), names=character.vector)

Upvotes: 5

Simon O&#39;Hanlon
Simon O&#39;Hanlon

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

user1609452
user1609452

Reputation: 4444

character.vector <- c('first.element', 'second.element')
values.vector <- c(1, 2)

as.list(setNames(values.vector, character.vector))

Upvotes: 17

harkmug
harkmug

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

Related Questions