Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic "string" in R

Tags:

sql

r

rodbc

Simple question, but cannot find the answer.

Instead of:

Df <- sqlQuery(ch, "SELECT * FROM tblTest WHERE Id=25")

I want a more dynamic piece of code. Something like:

Id <- 25
Df <- sqlQuery(ch, c("SELECT * FROM tblTest WHERE Id=", Id))

But this is not correct.

like image 458
waanders Avatar asked Jan 21 '23 15:01

waanders


2 Answers

We can use paste:

Df <- sqlQuery(ch, paste("SELECT * FROM tblTest WHERE Id =", Id))

c concatenates into a vector, paste is for string concatenation.

Or we can use sprintf:

sprintf("SELECT * FROM tblTest WHERE Id = %s", Id)
like image 73
Joshua Ulrich Avatar answered Jan 28 '23 12:01

Joshua Ulrich


Just want to update this with a more modern answer using dplyr/tidyverse which uses string interpolation via the str_glue command:

str_glue("SELECT * FROM tblTest WHERE Id = {Id}")

You can put any expression you want in there. For example, if you wanted to select multiple Id's using a vector:

str_glue("SELECT * FROM tblTest WHERE Id IN ({str_c(id_vector, collapse = \",\"})")
like image 32
Justin Avatar answered Jan 28 '23 12:01

Justin