Updated with reproducible example and sample data.
Hi,
In the database, I have a column of dates (posixct). I am trying to create a new column by subtracting 12 months from the column of dates. But it seems lubridate package is not supported.
Is there a way around to achieve that result using dbplyr or another packages?
I am connecting to the database using RPostgreSQL package and use dbplyr package to run queries.
dbplyr translates dplyr commands into sql commands but unfortunately it can't translate other libraries commands into sql, if you are comfortable writing sql queries you can use this in PostgreSQL
query <- "select (date - interval '12 months') as minus_12_months from public.sample"
result <- dbGetQuery(con, query)
A quick comment: there are RDBMSes that have a function to add / subtract months from a date - DATEADD() in SQL server and ADD_MONTHS() in Oracle come to my mind.
These should work with dbplyr. Unfortunately the Postgres way of adding interval and a string breaks dplyr code
Yay! I'm glad that worked! I hope that we'll eventually have support for a lot of these date functions, but In the meanwhile we can emulate how dbplyr puts together vector expressions by using build_sql() or sql_expr() , and force evaluation via !!.
One more trick is to use the fact that infix operators will be translated into SQL directly. It allows for slightly (IMHO) less busy code that can be even converted into small DSL under the hood: