happymappy
happymappy

Reputation: 181

Calculate number of Mondays since the start of the year

I'd like to obtain, from today's date, how many Mondays have occurred during the year so far.

x <- Sys.Date()
format(x, "%V")

# [1] "02"

This returns a value of "02", telling me it is the second week of the year. However, what I need is a value of "01" telling me that only one Monday has occurred during the year so far.

Any ideas?

Upvotes: 0

Views: 441

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 101383

Here is a base R solution, using weekdays() + sum()

w <- weekdays(seq(as.Date("2020-01-01"),as.Date(Sys.Date()),by = "1 day"))
r <- sum(w == "måndag")

such that

> r
[1] 1

Since my system is in Swedish, so the key word for Monday is "måndag". You can check how weekdays gives for Monday according to the language of your system.

Upvotes: 2

Nareman Darwish
Nareman Darwish

Reputation: 1261

Here is a function built using lubridate, the idea is to build a vector of Monday dates and get how many time it occurred;

library(lubridate)

get_occurance <- function(date, weekday){
  # Get year of the date
  this_year <- paste0(year(date), "-01-01")

  # Create list of days
  all_dates <- strftime(as.Date(1:365, origin = this_year))

  # Create list of specific weekday
  weekday_days <- all_dates[strftime(all_dates,"%A") == weekday]

  # Return number
  which((weekday_days <= date) & weekday_days > as.character(ymd(date) %m-% days(7)))
}

# Try it with today
today <- Sys.Date()
get_occurance(today, "Monday")
[1] 1

# Try it with other dates
get_occurance(as.Date("2020-01-28"), "Monday")
[1] 4

get_occurance(as.Date("2020-01-27"), "Monday")
[1] 4 

Upvotes: 1

happymappy
happymappy

Reputation: 181

I think I've found an answer to my own question using Lubridate:

library(lubridate)

x <- Sys.Date()

start <- as.Date(cut(x, "month"))
end <- Sys.Date()
all_dates <- seq(from = start, to = end, by = "days")

week <- length(which(wday(all_dates)==2)) # number of Mondays in date sequence

In my particular case, I also needed a leading zero, so I could also do the following:

library(stringr)

week <- as.character(week)
week <- str_pad(week, 2, pad = "0")

week

#[1] "01"

Upvotes: 2

Related Questions