Search code examples
rfunctiondatetimelubridate

Custom functions in R


I am trying to write a greeting function that takes two arguments, a time and a name, and says "good morning ", "good afternoon ", or "good evening ", depending on the time of day.

I also want to use the lubridate::now() as default for the time argument. But not sure if this the correct practice or are there any better alternatives?

greet <- function(time = lubridate::now(), name) {
  hour <- parse_number(str_sub(time, 12, 13))
  if (hour < 12) {
    cat("good morning", name)
  } else if (hour < 17) {
    cat("good afternoon", name)
  } else {
    cat("good evening", name)
  }
}

#sanity check

greet(name = "User 1")
#> [1] "good afternoon User 1"
greet(ymd_h("2021-03-31 05"), "User 2")
#> [1] "good morning User 2"
greet(ymd_h("2021-03-31 13"), "User 3")
#> [1] "good afternoon User 3"
greet(ymd_h("2021-03-31 20"), "User 4")
#> [1] "good evening User 4"

Solution

  • greet <- function(time = lubridate::now(), name) {
      hour <- parse_number(str_sub(time, 12, 13))
      if(hour < 0 || hour > 23) {
        stop("Please define a correct time")
      }
      if (hour < 12) {
        cat("good morning", name)
      } else if (hour < 17) {
        cat("good afternoon", name)
      } else {
        cat("good evening", name)
      }
    }
    
    greet("2020-01-01 25:45:32", "User 5")
    greet("2020-01-01 -1:45:32", "User 5")