1

so I am trying to write a function in R to ask the user for an input value of time in seconds from user and then convert it back to hours minutes and seconds. here is my function for this below:

startT <- function(x) {
    t <-(readline(prompt = "Please provide the inital time in seconds: "))
    t <- as.numeric(t)
    return (t)
}

time_conversion <- function(t) {
    h = t%/%3600
    m = (t%%3600)%/%60
    s = (t%%3600)%%60
    final <- c(h, m, s)
    return (final)
}    

Then using the following I can get the function to print my results as a list and then restore it as global variable:

initialT<- startT(t)
print(time_conversion(initialT))
TimeF <-time_conversion(initialT)

However, I was hoping (like I could in python) to print my out put as:

xx seconds, xx minutes, and xx seconds

in my python version I used:

return "%i hours, %i minutes, and %i seconds." %(hour, minutes, seconds)

I know based on my output from R I dont need to control for the output as variables. But can someone help me get this? We just started R so while I am sure there are more advanced stuff but I can't use that.

Thank you!!!!

Rachel Cyr
  • 429
  • 1
  • 5
  • 15

2 Answers2

0

In base R you can use

sprintf("%i hours, %i minutes, and %i seconds.", TimeF[1], TimeF[2], TimeF[3])
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
0

Have a look at this answer:

Convert seconds to days: hours:minutes:seconds

It uses the lubridate package and even has a formatting example using sprintf().

-Emanuel

Emanuel V
  • 143
  • 8