R, RPostgreSQL: a vector in a query

891 views Asked by At

Using RPostgreSQL package I have to do a query with a vector in the string:

dbGetQuery(con, "select from id_table where id_user in tmp")

Where tmp should be a list or a vector of length= 10k, how can I do this? Thanks.

2

There are 2 answers

0
jonrobinson2 On BEST ANSWER

You can use paste0. Here is an example where I take the state.abb dataset

valid_state_logic=paste0("(",paste0("'",state.abb,"'", collapse=","),")")

print(valid_state_logic)
[1] "('DC','AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY')"
0
Abdou On

Try this:

query = sprintf("select * from id_table where id_user in (%s)", paste("'",tmp, "'",collapse=","))

dbGetQuery(con, query)

Hope this helps.