I am trying to generate an SQL query with multiple embedded variables with sprintf.
I store SQL (it is large one) with parameters as %s
as a separate file, and then read it from within r. To improve readability, I've created a helper:
fillSQLQuery <- function(query, params){
#' fill query with params
do.call(sprintf, as.list(c(query, params)))
}
My parameters are dates, factors, and strings. When I pass them to the function directly, my dates are replaced with an integer, and my factor - with its index (?). On the other side, when I convert the whole vector with as.character
, it tries to process all elements to string as dates, and return NA or wrong results for all non-strings).
do.call(sprintf,
as.list(c(query,
c(as.character(startDateSequence[1]), # POSix DATE
as.character(endDateSequence[1]), # POSix DATE
lotTypes[1], id_list[1] )))) # string, factor
The only way to solve that I've found so far is to manually convert dates and types to characters beforehand. However, I wonder if there is any "clear" way to do that, something as simple and robust as pythons:
'query {p1}, {p2}'.format(p1=X, p2=Y)
params
vector. Please make a minimal reproducible example. - Gregor Thomasparams
in, as a vector? What does the vector look like before you runas.character
on it - it probably gets messed up as soon as you usec()
on objects of different types. - Gregor Thomasquery
and these "parameters" would have as values? - IRTFM