Little useless-useful R functions – Drawing calendar

This time around, since first half of the 2021 is behind us, we are making Calendar in R.

Simple outline of current month in calendar for 2021

This will be achieved with two useless functions.

Function to draw a month (with optional parameter as current date)

DrawCalendarMonth <- function(InDate=NULL) {
  if(is.null(InDate)){
    date <- Sys.Date()
  } else {
    date <- as.Date(InDate)
  }
  t <- format(date, "%m")
  TT <- format(date, "%B")
  year <- as.integer(format(date, "%Y"))
  
# Leap year calculation
  if((year %% 4) == 0) {
    if((year %% 100) == 0) {
      if((year %% 400) == 0) {
        leap <- TRUE
      } else { leap <- FALSE }
    } else { leap <- TRUE }
  } else { leap <- FALSE }
  
#number of days in month
  if (t %in% c("01","03","05", "07", "08", "10", "12")){
    nofDays <- 31
  } 
  if (t %in% c("04","06","09", "11")){
    nofDays <- 30
  }
  if (t %in% c("02") & leap == TRUE){
    nofDays <- 29
  } 
  if (t %in% c("02") & leap == FALSE){
    nofDays <- 28
  }
  
  firstDay <- as.Date(paste0(format(date, "%Y-%m"), "-01"))
  name1D <- weekdays(firstDay)
  num1D <- as.POSIXlt(firstDay)$wday
  n.col <- 7 #number of days; constant
  n.row <- 5 #depends on month, number of days and first day in month; must be calculated
  M_y <- 35  # Default matrix size (product of n.col * n.row)
  
  if (num1D > 5 & nofDays > 29) {
    n.row <- 6 #nrow correction
    M_y <- 42
  } 
  
  if (num1D %in% c(1) & nofDays %in% c(28)) {
    n.row <- 4 #nrow correction
    M_y <- 28
  } 
  
  mat <- matrix(1:M_y, nrow = n.row, ncol = n.col, T) #Matrix structure for month
  for(column in 1:n.col){ mat[, column] <- 00 }   #Reset values to 00
  i <- 1 #running value
  
  for(row in 1:n.row){
    for(column in 1:n.col){
      if(row >= 1 & column >= num1D | row > 1) {
        if(i > nofDays){
          mat[row,column] <- 0
          } else {
        mat[row,column] <- i
        i= i + 1
          }
      }
    }
  }
  dd <- as.data.frame(mat)
  colnames(dd) <- c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
  cat(paste0("\n", "Month: ",TT, "\n", "Year: ", year, "\n"))
 
  return(dd)
}

Running this function as:

DrawCalendarMonth() 
DrawCalendarMonth("2021-02-21")

Function takes into consideration
1. calculation of leap years,
2. the number of weeks per month and
3. most obvious – number of days per month.

Function to draw a year (with optional parameter year)

Next step is no brainer. Creating calendar for complete year is just 12-times iteration of DrawCalendarMonth function.

DrawYear <- function(Year=NULL){
  if(is.null(Year)){
    year <- as.integer(format(Sys.Date(), "%Y"))
  } else {
    year <- as.integer(Year)
  }
  dateFrom <- as.Date(paste0(year,"0101"), "%Y%m%d")
  dateTo <- as.Date(paste0(year,"1201"), "%Y%m%d")
  FirstOfMonth <- format(seq(dateFrom,dateTo,by="month"), "%Y-%m-%d")

  for (i in 1:length(FirstOfMonth)){
    r <- DrawCalendarMonth(FirstOfMonth[i])
    print(r)
    }
}

Running it as:

# Draw years' calendar
DrawYear(2020)
DrawYear()

And result is a complete calendar 🙂

Useless calendar for 2021

As always, code is available in at the Github in same Useless_R_function repository. And this function is here.

Happy R-coding!

What are next step for these two functions:

  • Create export to Markdown (because why not)
  • Sort out the week enumerator (in both functions)
  • Set the start of week (Sunday or Monday)
  • Draw it with ggplot2 library and colour all important dates, bank holidays and festivals

Tagged with: , , , , , , , ,
Posted in Uncategorized, Useless R functions
4 comments on “Little useless-useful R functions – Drawing calendar
  1. […] by data_admin [This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page […]

    Like

  2. hp says:

    system(‘cal’)

    Like

  3. Lipatz says:

    Nice, but I am wondering why you show code that may be interpreted as some code written by somebody coming directly from C. For example the beginning of y our first function may be rewritten as :
    date <- if(is.null(InDate)) Sys.Date() else as.Date(InDate)

    leap <- if((year %% 4) == 0)
    if((year %% 100) == 0) ((year %% 400) == 0) else TRUE
    else FALSE

    more R-y (no instructions, only functions) and shorter to be read.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Follow TomazTsql on WordPress.com
Programs I Use: SQL Search
Programs I Use: R Studio
Programs I Use: Plan Explorer
Rdeči Noski – Charity

Rdeči noski

100% of donations made here go to charity, no deductions, no fees. For CLOWNDOCTORS - encouraging more joy and happiness to children staying in hospitals (http://www.rednoses.eu/red-noses-organisations/slovenia/)

€2.00

Top SQL Server Bloggers 2018
TomazTsql

Tomaz doing BI and DEV with SQL Server and R, Python, Power BI, Azure and beyond

Discover

A daily selection of the best content published on WordPress, collected for you by humans who love to read.

Revolutions

Tomaz doing BI and DEV with SQL Server and R, Python, Power BI, Azure and beyond

tenbulls.co.uk

tenbulls.co.uk - attaining enlightenment with the Microsoft Data and Cloud Platforms with a sprinkling of Open Source and supporting technologies!

SQL DBA with A Beard

He's a SQL DBA and he has a beard

Reeves Smith's SQL & BI Blog

A blog about SQL Server and the Microsoft Business Intelligence stack with some random Non-Microsoft tools thrown in for good measure.

SQL Server

for Application Developers

Business Analytics 3.0

Data Driven Business Models

SQL Database Engine Blog

Tomaz doing BI and DEV with SQL Server and R, Python, Power BI, Azure and beyond

Search Msdn

Tomaz doing BI and DEV with SQL Server and R, Python, Power BI, Azure and beyond

R-bloggers

Tomaz doing BI and DEV with SQL Server and R, Python, Power BI, Azure and beyond

MsSQLGirl

Bringing meaning to data & insights through experiences users love

R-bloggers

R news and tutorials contributed by hundreds of R bloggers

Data Until I Die!

Data for Life :)

Paul Turley's SQL Server BI Blog

sharing my experiences with the Microsoft data platform, SQL Server BI, Data Modeling, SSAS Design, Power Pivot, Power BI, SSRS Advanced Design, Power BI, Dashboards & Visualization since 2009

Grant Fritchey

Intimidating Databases and Code

Madhivanan's SQL blog

A modern business theme

Alessandro Alpi's Blog

DevOps could be the disease you die with, but don’t die of.

Paul te Braak

Business Intelligence Blog

Sql Server Insane Asylum (A Blog by Pat Wright)

Information about SQL Server from the Asylum.

Gareth's Blog

A blog about Life, SQL & Everything ...

SQLPam's Blog

Life changes fast and this is where I occasionally take time to ponder what I have learned and experienced. A lot of focus will be on SQL and the SQL community – but life varies.

%d bloggers like this: