Reputation: 1764
I am trying to build a process that accepts user input parameter and then produces things accordingly.
I need to be able to:
1. Input a variable
2. Pull max date for that variable
3. Pull all data less than or equal to that date
dates <- c('2001-01-08', '2015-01-07', '2013-03-03', '2001-01-01', '2013-07-25', '2000-09-20', '2017-02-20')
groups <- c('A', 'A', 'A', 'B', 'B', 'C', 'D')
dat <- data.frame(groups, dates)
dat$dates <- as.Date(dat$dates)
The following piece works for what I want to do....
querydate <- sqldf(
"SELECT max(dates) as x
FROM dat
WHERE groups == 'A'")
But I want to edit this to do something like this....where I specify a value and query references...
group_i_want <- 'A'
querydate <- sqldf(
"SELECT max(dates) as x
FROM dat
WHERE groups == group_i_want")
How can I get R to recognize this value?
Upvotes: 0
Views: 313
Reputation: 26
You can look into using sprintf
to do string formatting on values you collect at runtime. For example:
g <- "A"
if (invalid.input(g)) stop("Error") # Make sure input was valid
query <- sprintf("SELECT max(dates) as x FROM dat WHERE groups == '%s'", g)
querydate <- sqldf(query)
Here the %s
will be substituted by the string contained in g
. You can also substitute numbers with specific formatting, check out ?sprintf
for more information on it.
Upvotes: 1