rstringlistnamed

A better way to combine name and value of a named list into a string


Given a named list:

values <- list( a=1, b=2 )

I want to produce a comma-separated string that includes the names:

"a=1,b=2"

The following works, but seems awfully clunky:

library( iterators )
library( itertools )
fieldnames <- names(values)
sublist <- list()
iter_fieldnames <- ihasNext( iter( fieldnames ) )
iter_values <- ihasNext( iter( values ) )
while( hasNext( iter_fieldnames ) & hasNext( iter_values ) ) {
  sublist <- append( sublist, paste0( nextElem( iter_fieldnames ), "=", nextElem( iter_values ) ) )
}
paste0( sublist, collapse="," )
[1] "a=1,b=2"

The 'collapse' option on 'paste' seems so elegant and gets close, but I cannot figure out if it can be made hierarchical (i.e., "First, collapse the name and value with '=', then collapse with ','):

paste0( paste0(names(values), values, collapse='='), collapse="," )
[1] "a1=b2"

Or

paste0( paste0( c(names(values), values), collapse='=' ), collapse=',' )
[1] "a=b=1=2"

Trying lapply and paste0 produced:

paste0( lapply( values, function(x) paste0( names(x), "=", x ) ), collapse=',' )
[1] "=1,=2" 

Is there a simpler way to do this, or do I just stick with the clunky way?


Solution

  • Not sure how are you going to use this but we could create a string by concatenating names of the list , "=" and the actual values of the list elements together.

    paste0(names(values), "=", unlist(values), collapse = ",")
    #[1] "a=1,b=2"
    

    Trying it on bigger list

    values <- list(a=1, b=2, c = 12, d = 5)
    
    paste0(names(values), "=", unlist(values), collapse = ",")
    #[1] "a=1,b=2,c=12,d=5"
    

    Thanks to @Fábio Batista for a simpler suggestion.