How to substract n workdays from today to get a past date with user prompt?

*爱你&永不变心* 提交于 2021-02-19 20:54:36

问题


I'm trying to count n workdays backwards from today to get an specific date.

I'd like to get a user input with the days to count backwards and let the system calculate that date.

Let's say I would like to count 100 (workdays) backwards from today.

A <- readline(prompt = "How many days backwards do you want to count? ")

#user input: 100

Date to be calculated <- Today date-A (format yyyy/mm/dd)

#Date to be calculated = 2018-03-02 

Then I'll use the date to get some values of a dataset stored for that date.

Any comments will be highly appreciated


回答1:


An option is to write a recursive function to subtract weekdays. The chron::is.weekend function can be used to decide if a day is working-day. Other option to decide weekend/working-day could be based on day starting with S as suggested by @Ryan.

library(chron)
substractWorkingDays <- function(x, n){
  v <- seq(x, x -n, by="-1 day")
  workingDays <- sum(!is.weekend(v[-1])) #One can check day name start with `S`
  if(workingDays == n){
    return(v[length(v)])
  }else{
    substractWorkingDays(v[length(v)], n-workingDays)
  }
}

#Testing it

substractWorkingDays(as.Date("2018-06-10"), 5)
#[1] "2018-06-04"
substractWorkingDays(as.Date("2018-06-10"), 10)
#[1] "2018-05-28"
substractWorkingDays(as.Date("2018-06-10"), 12)
#[1] "2018-05-24"


来源:https://stackoverflow.com/questions/50785263/how-to-substract-n-workdays-from-today-to-get-a-past-date-with-user-prompt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!