0

I have a data set with id and dates. I take the today date into a variable.

today=Sys.date()

Now I want to calculate the latest data in my data set which is less than today date.

Date=sqldf(paste0("SELECT * FROM DATA WHERE MAX(DATE) <",TODAY))

I'm getting error and not able to resolve it.

2
  • I hope this is a very-simplified example ... otherwise, that query makes no sense, selecting either all or nothing. (Isn't max only allowed in the result set (left of where)?) Commented Mar 29, 2018 at 7:13
  • @r2evans Agreed, the query makes no sense. Commented Mar 29, 2018 at 7:24

1 Answer 1

2

You probably need single quotes around the value returned from Sys.Date(). This should work

TODAY <- Sys.Date()
sqldf(paste0("SELECT * FROM DATA",
        " WHERE DATE < '", TODAY, "'",
        " ORDER BY DATE DESC LIMIT 1"))

This would generate the following raw query:

SELECT *
FROM DATA
WHERE DATE < '2018-03-29'
ORDER BY DATE DESC
LIMIT 1

This query will return the most recent record in your data happening before today.

Note that building a SQL string using raw concatenation like is generally bad. But if you are just doing it from your R console for some data analysis, then it should be acceptable.

data

DATA <- data.frame(DATE = c(Sys.Date() + 5:10, Sys.Date() - 5:10))
Sign up to request clarification or add additional context in comments.

7 Comments

Than you for the quick response. But I'm getting the below error "Error in rsqlite_send_query(conn@ptr, statement) : misuse of aggregate function max()"
@akrun What is the error you see when you run my code?
It is the same error vipinder mentioned earlier. Looks like you have changed the code. THis code is not yet completed. May be some quotes missing?
I'm not in front of an R console. If you can examine the raw output from paste, and if it matches my expected raw query, then this should work.
I think you forgot one quote. I updated it. Hope you don't mind
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.