Dynamic "string" in R
Asked Answered
R

4

5

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.

Reede answered 5/8, 2010 at 16:32 Comment(0)
R
8

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)
Rosemari answered 5/8, 2010 at 16:35 Comment(0)
E
2

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 = \",\"})")
Eupatrid answered 18/10, 2019 at 1:50 Comment(0)
G
1

If you have multiple or reused arguments and a query that contains % you can use something like the following:

sprintf("SELECT * FROM test WHERE id = %1$s AND name = %2$s and type like ‘%%tall%%’”, id, name)
Grearson answered 19/4, 2018 at 18:29 Comment(0)
K
1

Use glue_sql(). Example:

Id <- 25

Df <- sqlQuery(ch, glue_sql("SELECT * FROM tblTest WHERE Id= {Id}", .con = ch))

More info here.

Kreager answered 13/9, 2020 at 20:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.