Calculate previous date

I have list of days when wages are taken
e.g. wages_days <- "Tuesday,Thursday"

I want to compare wages between the two days

for example if we run wages today 17/05/2022 which is a tuesday I want to know the previous date in the list which will of course be Thursday 12/05/2022

So if we know the date which is todays date which we can calculate is a tuesday using R how do we find the date for the previous thursday

the list could change
ie e.g. wages_days <- "Monday,Tuesday,Thursday"

Thanks

Can you clarify a bit what exactly you are trying to do? After reading your question, I am a bit unsure which of the following problems you are trying to solve:

• How many days are between a given weekday and a prior second given weekday (so if you give a function a "Friday" and a "Tuesday", the function would return 3)?
• You have one vector of dates, and you want to figure out what weekday each date is on?

Or something else? Maybe a Reprex would help?

Sorry for my very poor explanation

These could be any days

wages_days <- "Monday,Wednesday, Friday"

3. If it is then get the previous date based on the list

``````     e.g. In aboves case if todays date is a Wednesday we would want the date of the Monday
if todays date is a Monday we would want the date of the previous Friday
``````

Does that make more sense ?

``````
my_calc <- function(wages_days, today) {
(wd_v <- unlist(strsplit(wages_days, ",|, ")))
(lwd <- length(wd_v))
(todayw <- weekdays(today))

(prev <- ((which(todayw == wd_v) + 1) %% lwd) + 1)

if (identical(prev, numeric(0))) {
stop("invalid date to lookup")
}

(prev_v <- wd_v[prev])

(back_6 <- seq.Date(from = today - 7,
length.out = 6,
by = 1))
(back_6w <- weekdays(back_6))
back_loc <- which(back_6w == prev_v)

list(
date = back_6[ back_loc],
wd   = back_6w[back_loc]
)
}

my_calc(
"Monday,Wednesday, Friday",
Sys.Date() + 0 # move around today by adding or subtracting
)``````

Thanks for the hard work on this..

But I dont want in your example the Week before but the previous day in the list ie if Today is a monday in your example I would want the prev date to be the Friday the week before

I think if today wqs monday my code gives the previous friday. By adding the weekbefore you mean it should be more than 7 days apart ? I.e. two fridays ago ?

If you always want a firther 7 days back just add -7 at the end
I.e

``````list(
date = back_6[ back_loc] -7,
wd   = back_6w[back_loc]
)``````

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.