简体   繁体   中英

Convert a numeric value to a time in R

I have been given a file with time, in minutes.seconds, in the following format:

TimeInput <- c(13.66, 14.08, 12.86)

How do I convert a numeric value, for example 13.66, to minutes:seconds format Specifically, 14:06 or 14 minutes and 6 seconds?

My anticipated output would be:

TimeInput <- c(14:06, 14:08, 13:26)

We can try without using any external package

v1 <- (TimeInput-floor(TimeInput)) - 0.60
v2 <- ifelse(v1 > 0, floor(TimeInput) + 1 + v1, TimeInput)
d1 <- data.frame(MinSec = sub(".", ":", v2, fixed = TRUE), 
           TimeRound = floor(v2), stringsAsFactors=FALSE)
d1
#  MinSec TimeRound
#1  14:06        14
#2  14:08        14
#3  13:26        13

You can achieve this using the POSIX.ct and format

TimeInput <- c(13.66, 14.08, 12.86,0)
pct <- as.POSIXct(TimeInput*60,origin = "1960-01-01 00:00:00","GMT")
format(pct,format="%M:%S")
[1] "13:40" "14:05" "12:52" "00:00"

The solution is a bit annoying due to timezone/ having to set an arbitrary origin. On the positive side it will deal with all kinds of problem(?) like overflows. If this is intended

If you, however, do want to have minutes higher then 60

We can also use functions from lubridate package

library(lubridate)
timeFormt <- ms(TimeInput)
seconds_to_period(minute(timeFormt) * 60 + second(timeFormt))

#[1] "14M 6S"  "14M 8S"  "13M 26S"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM