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?
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:
daytime
and units
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")
as.numeric
c(3600, 60, 1)
and get the sum
of the result. This will be the number of seconds you will use for your answer.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