2

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?

Mark Bower
  • 569
  • 2
  • 16

1 Answers1

7

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.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    Thanks, I was looking for a simple solution like this for weeks. BTW, it can be further simplified as `paste0(names(values), "=", unlist(values), collapse = ",")` – Fábio Batista Aug 25 '22 at 00:33
  • 1
    Yep, I feel stupid using two `paste`'s here. Thanks for the suggestion, updated the answer. @FábioBatista – Ronak Shah Aug 25 '22 at 04:59