There is R base function like weekdays that can return the name of the weekday. But what if you want to get the day of the week number in R to do calculations? Here is how to do that by using one of the most popular R packages.

If you want to test the **weekdays** function, then here it is. That will return the full name of the weekday as it is defined in the regional settings.

weekdays(Sys.Date())

### Day of the week number in R

If you want to get the day of the week number in R then one of the best options is the **wday **function from **data.table** or **lubridate** package. In both of them, functions do the same, but I would like to recommend **wday** from **lubridate**. Just because there are some handy options, like the week_start option. Of course, you can also do the necessary adjustments mathematically.

lubridate::wday(Sys.Date(), week_start = 1) #[1] 1

### Extract the date of first Monday from a list of dates in R

If you want to select data from the first occurring Monday to group by week numbers or do other things, then it is good to know how to get a number of the weekday.

Here is a data frame that contains dates for the last 30 days.

x <- data.frame('date' = seq(Sys.Date()-30, Sys.Date(), by="days")) head(x) # date #1 2021-01-23 #2 2021-01-24 #3 2021-01-25 #4 2021-01-26 #5 2021-01-27 #6 2021-01-28

What is the date of the first Monday in the previous 30 days? You can do it in many ways in here is one.

require(dplyr) x %>% mutate(wd = lubridate::wday(date, week_start = 1)) %>% filter(wd == 1) %>% distinct(wd, .keep_all = T) # date wd #1 2021-01-25 1

I hope it was helpful for you. Especially if you have Excel knowledge, then it looks similar to what you can get with a function called WEEKDAY.

If you are transitioning from Excel to R then this post might be helpful for you.

If not, then a few tips and tricks in RStudio are always useful.