user2716568
user2716568

Reputation: 1946

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)

Upvotes: 3

Views: 982

Answers (3)

akrun
akrun

Reputation: 887851

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

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389235

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"

Upvotes: 0

CAFEBABE
CAFEBABE

Reputation: 4101

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

Upvotes: 1

Related Questions