0

I'm trying to convert an r list containing names into a string for an sql insert for a Postgresql text[] column.

name_list <- list("bob smith", "joe bob", "jim bob") 

The goal is to create an sql insert statement suck as:

INSERT INTO players (name) value ({"bob smith", "joe bob", "jim bob"}) 

I've tried:

> name_str <- paste('{', unlist(name_list), '}', collapse=", ") 

Which produces:

[1] "{ bob smith }, { joe bob }, { jim bob }"

Any thoughts as to how I can produce: {"bob smith", "joe bob", "jim bob"} ?

1 Answers1

0

Try package glue which is perfect for string operations like this. Or you can use paste0 function:

paste0('INSERT INTO players (name) value ({',
       paste0('"', name_list, '"', collapse = ', '), '})')

but you can always go wit any database-related package to put the values into the db for you

Jan Kislinger
  • 1,441
  • 14
  • 26
  • This is close, but the array needs to have ' appear before and after the {} brackets. Something like: paste0("INSERT INTO players (name) value('{", paste0('"', name_list, '"', collapse = ", "), "}')") – Mark Gannon Dec 16 '17 at 16:35
  • are you sure about that? at least it is not stated in your question – Jan Kislinger Dec 17 '17 at 23:33