Home > other >  Convert a named list into a single string r
Convert a named list into a single string r

Time:02-17

I have a named list of websites that I am trying to apply a function to with sapply, but I get the following when I try:

Error: `x` must be a string of length 1. 

I've tried several methods to unlist my data, but none have worked correctly. Here's some example data.

list <- list("volume 1" = c("www.example1.com","www.example2.com","www.example3.com"),
        "volume 2"=c("www.randomwebsite1.com,www.randomwebsite2.com"),
        "volume 3" = c("website1.com","website2.com","website3.com","website4.com"))

I've tried:

w<-paste( unlist(list), collapse=',"') 

This adds in \ prior to url strings after the first one.

[1] "www.example1.com,\"www.example2.com,\"www.example3.com,\"www.randomwebsite1.com,\"www.randomwebsite2.com,\"website1.com,\"website2.com,\"website3.com,\"website4.com"

x <- paste(list, collapse = ", ")
y<-toString(list)
z<-str_c(list,collapse=',') 

x,y,&z all produce the same thing:

[1] "c(\"www.example1.com\", \"www.example2.com\", \"www.example3.com\"), c(\"www.randomwebsite1.com\", \"www.randomwebsite2.com\"), c(\"website1.com\", \"website2.com\", \"website3.com\", \"website4.com\")"

My desired outcome is

[1] "www.example1.com"       "www.example2.com"       "www.example3.com"      
[4] "www.randomwebsite1.com" "www.randomwebsite2.com" "website1.com"          
[7] "website2.com"           "website3.com"           "website4.com"

CodePudding user response:

When you unlist() your list you get a vector, it's just named. If you strip off the names you'll have your desired output.

x <- unlist(your_list)
names(x) <- NULL 

You can do this in one step with:

x <- unlist(your_list, use.names = FALSE)
  • Related