Skip to content
Advertisement

Count based on multiple conditions using sqldf

Hi all I’m writing a sql query on R using sqldf and seem to hit a roadblock. I have a table with an Id column, two dates columns and a grouping by column.

The query I’m writing is

From this query the result I’m getting is

Whichis correct based on the query. What I want to achieve is if my 2nd condition is false ie AppointmentDate is less than AlertDate+7. Instead of dropping the count it should be counted in the next group depending on date. Example if the alertdate is 01/01/20 and appointment date is 23/01/20 then it should be counted in W4. ceil((Appointmentdate-alertdate)/7) SO in the end I want the result as

The second row should be counted in W2 and 4th should be in W4 rather than being discarded. I was trying to achieve this in sql using sqldf in R. Any possible solution using R or Sql would work for me.

Output of dput(test)

enter image description here

Advertisement

Answer

Here is one way to do it using data.table

I am converting this to data.table and creating a new column for your logic.

Here is the resulting table

This is the goupby result..

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement