Search code examples
rfunctionuser-defined-functionsdate-conversion

R function which converts the time of the day to the total minutes


I have to write my own R function "time", which converts the time of the day(in "hh:mm:ss") in hours, minutes or seconds. The daytime and the wished conversion time("h","m","s") is an argument/input. At example, if you want call the function with the arguments "05:37:26", "m" the result should be 337.4333 minutes.

I'm a total newbie and overwhelmed with writing own functions, can anybody give me a hint?


Solution

  • Assuming this is a homework question and we are looking for a simple function that relies on string parsing and arithmetic rather than using existing date-time functionality in R, the steps we can take are:

    1. Specify your function as taking two arguments; one for the string containing the time you wish to parse, and one for the units you want to convert to. We can call these arguments daytime and units
    2. Split the daytime string at the colons using strsplit and unlist the result. In your example, this will turn the input string "05:37:26" into the character vector c("05", "37", "26")
    3. Convert this vector into numeric values using as.numeric
    4. Multiply this result by the vector c(3600, 60, 1) and get the sum of the result. This will be the number of seconds you will use for your answer.
    5. Divide the number of seconds by either 3600, 60 or 1 depending on whether the units argument is "h", "m" or "s". You can get this by using the match function.

    Putting all this together, we have the following short function:

    time <- function(daytime, units) {
      sec <- sum(as.numeric(unlist(strsplit(daytime, ":"))) * c(3600, 60, 1))
      sec / c(3600, 60, 1)[match(units, c("h", "m", "s"))]
    }
    

    Testing this, we have:

    time("05:37:26", "m")
    #> [1] 337.4333
    
    time("05:37:26", "h")
    #> [1] 5.623889