Create lists programmatically with tags from a character vector

I'm probably going to tip my head onto the table, because it's obvious, but how do you arbitrarily create a list from a character vector, so the character vector provides the tags and the carrier vector with values. For example.

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) 
+8
r
source share
4 answers
 character.vector <- c('first.element', 'second.element') values.vector <- c(1, 2) as.list(setNames(values.vector, character.vector)) 
+13
source share

You can install:

  > names(values.vector) <- character.vector > values.vector first.element second.element 1 2 

and, of course, convert it to a list if necessary:

 > as.list(values.vector) $first.element [1] 1 $second.element [1] 2 
+6
source share

Other answers covered this better, but only for completeness, another way would be to build an expression that 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 
+5
source share

Surprised that no one mentioned structure :

 structure(as.list(values.vector), names=character.vector) 
+5
source share

All Articles