Search code examples
rdifftime

how to calculate MTD in R for a different month


The task is to find number of days in MTD for two months, the month that had highest inflow numbers (July) in my case and the present month. Because I plan to run the statement as a script everyday, I don't want to hardcode anything.

The dataframe is like this:

SERVICE              BEST MONTH TOTAL    BEST MONTH MTD  CURR. MONTH MTD
No of Working Days
..
..
..

For "BEST MONTH TOTAL", I used following statement:

report[1,2] <- sum(!weekdays(seq(as.Date('2019-07-01'), as.Date('2019-07- 
31'), 'days')) %in% c('Sunday','Saturday'))

For current month no of days MTD, the number of days I calculated using:

difftime(Sys.Date(),'2019-09-01',units = "days" )

This gives the output:

Time difference of 12.22917 days

Is there a way that I can get just the interger 12?

And how do I calculate BEST MONTH MTD? Is there a function that'll help go back to same date as sys.date() in the month of July to calculate number of working days MTD? i.e. essentially what I need is:

difftime('2019-07-13','2019-07-01', units = "days")

But don't want to hardcode '2019-07-13' as I want to run this as a script and want to avoid changing date every day. Also I just need the difference in integer without "Time difference of ... days".


Solution

  • To convert to the number of days, as a numeric:

    as.numeric(difftime(Sys.Date(),'2019-09-01',units = "days" ))