MetaPhilosopher
MetaPhilosopher

Reputation: 131

How to convert a column of character type of minutes and seconds to time?

I'm trying to convert a column of character to time. The column has observations in only minutes and seconds.

The dataset I try it on is this:

data <- data.frame(
  time = c("1:40", "1:55", "3:00", "2:16"),
          stringsAsFactors = FALSE
)

data

  time
1 1:40
2 1:55
3 3:00
4 2:16

I have checked other questions about converting character to time on here, but haven't found a solution to my problem.

The output I want is this:

  time
1 00:01:40
2 00:01:55
3 00:03:00
4 00:02:16

Upvotes: 0

Views: 3154

Answers (3)

alistaire
alistaire

Reputation: 43334

hms is a time class that happens to have the print method you're asking for:

data <- data.frame(
  time = c("1:40", "1:55", "3:00", "2:16"),
          stringsAsFactors = FALSE
)

data$time <- hms::as.hms(paste0('00:', data$time))

data
#>       time
#> 1 00:01:40
#> 2 00:01:55
#> 3 00:03:00
#> 4 00:02:16

str(data)
#> 'data.frame':    4 obs. of  1 variable:
#>  $ time: 'hms' num  00:01:40 00:01:55 00:03:00 00:02:16
#>   ..- attr(*, "units")= chr "secs"

You can convert to hms in other ways, if you like, e.g. by parsing with as.POSIXct or strptime and then coercing with as.hms.

Upvotes: 1

phiver
phiver

Reputation: 23608

strptime + as.character formatting will give you the expected result. But realise that it is a character value.

data$time <- as.character(strptime(data$time, "%M:%S"), "%H:%M:%S")
data
      time
1 00:01:40
2 00:01:55
3 00:03:00
4 00:02:16

Upvotes: 2

G. Grothendieck
G. Grothendieck

Reputation: 269441

Convert to chron times class and if you want a character column format it.

library(chron)

transform(data, time = times(paste0("00:", time)))

transform(data, time = format(times(paste0("00:", time))))

Upvotes: 1

Related Questions