joe
joe

Reputation: 87

R Unlist named list into one string with preserving list names

I want to convert one dimensional named list into one single string - row. Names should be preserved and stored as NAME=VALUE pairs separated by semicolon.

my test list

nl = list(case1="master2", case2=5, case3="master", case4=345)

I tried the following

sapply(names(nl),function(x) paste(x,paste(nl[[x]],collapse="=")))
          case1           case2           case3           case4 
"case1 master2"       "case2 5"  "case3 master"     "case4 345"

what I need is

"case1=master2;case2=5;case3=master;case4=345"

Upvotes: 2

Views: 1557

Answers (1)

Wil
Wil

Reputation: 3178

You can use paste() to create the "=" separator and collapse with ";". names() allows you to access the names in the list.

UPDATED with @Dason's suggestion.

paste(names(nl),nl,sep="=",collapse=";" )

[1] "case1=master2;case2=5;case3=master;case4=345"

Upvotes: 4

Related Questions