Kuni
Kuni

Reputation: 865

How to convert a list to string in r?

I have a vector with the following data

ids <- list(memberPersonID = c("2892056", "2894545", "2894546", "2894548", 
"2894550", "2894551", "2894553", "2894555", "2894556"))

I need to convert use this in a string such that it's output like the following:

select * from data where id in ('2892056', '2894545', '2894546', '2894548', '2894550', '2894551', '2894553', '2894555', '2894556')

so, I did the following:

ids <- paste0(ids, collapse="','")
query <- paste0("select * from data where id in (", ids, ")")

I keep getting the following error:

select * from teams where teamID = '3246492' and assessmentStatus = 'C' and memberPersonID in (c("2892056", "2894544", "2894545", "2894546", "2894547", "2894548", "2894550", "2894553", "2894555", "2894556"))
<Rcpp::exception: no such function: c>

How do I get rid of 'c(' from the vector so that it looks like the one shown above in the desired output?

Upvotes: 0

Views: 211

Answers (2)

m0nhawk
m0nhawk

Reputation: 24300

Because ids is a list, you need to use it like this:

ids <- paste0(ids$memberPersonID, collapse="','")

And you need extra ' before and after ids.

query <- paste0("select * from data where id in ('", ids, "')")

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389335

You could paste the memberPersonID value into one comma-separated string.

sprintf("select * from data where id in (%s)", paste0(ids$memberPersonID, collapse = ','))
#[1] "select * from data where id in (2892056,2894545,2894546,2894548,2894550,2894551,2894553,2894555,2894556)"

If you want the ids to be surrounded by quotes :

sprintf("select * from data where id in ('%s')", paste0(ids$memberPersonID, collapse = "','")) 
#[1] "select * from data where id in ('2892056','2894545','2894546','2894548','2894550','2894551','2894553','2894555','2894556')" 

Upvotes: 2

Related Questions