Home > OS >  R function which converts the time of the day to the total minutes
R function which converts the time of the day to the total minutes

Time:01-21

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?

CodePudding user response:

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

CodePudding user response:

Beginnings are hard. Something like this. The simplest version without error monitoring. Please check the correctness of the recalculation.

my.time.function <- function(h, m, s) {
  hours <- s / (60 ^ 2)   m / 60   h
  minutes <- s / 60   m   h * 60 
  seconds <- s   m * 60   h * 60 ^ 2
  return(list('hours' = hours, 'minutes' = minutes, 'seconds' = seconds))
}

my.time.function(5, 36, 26)
my.time.function(5, 36, 26)$minutes
  • Related