library(dplyr)
library(DBI)
library(RSQLite)
# Toy Database-------
toy_table <- tibble(id = seq(1:100),
grade = rep(c("A", "B"), each = 50))
# DB connection: In-memory SQLite database and copy over toy_table-------
con_db <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
copy_to(con_db, toy_table)
# ID (data required for these ids only)-------
id_wanted <- c("'15', '17', '26', '50', '61', '97', '99', '100'")
# Prepare query-------
query <- paste("select * from toy_table where id in (", id_wanted, ")")
# Get data-------
DBI::dbGetQuery(
con_db,
query)
#> id grade
#> 1 15 A
#> 2 17 A
#> 3 26 A
#> 4 50 A
#> 5 61 B
#> 6 97 B
#> 7 99 B
#> 8 100 B
In the example above, I am retrieving data only for the IDs stored in the vector id_wanted.
How can I "break down" id_wanted and retrieve data for all the wanted ids? In other words, without manually creating SQL statements, how can I programmatically retrieve the desired data given the constraint?