Vkara
Vkara

Reputation: 7

Convert from time character to time numerical variable in r

Tibble

Hello! I am trying to change the Start.time variable from the character format of "4:00 PM" and take out the PM/AM and leave it as 4:00 as a numerical variable if possible. Thanks!

Upvotes: 0

Views: 128

Answers (2)

Ben Wynne-Morris
Ben Wynne-Morris

Reputation: 141

gsub("\\s*[APM]", "", start.time) can be used to replace the string part after HH:MM with an empty string, leaving only the HH:MM bit.

trimws(x) replaces any leading whitespace in the string x.

> start.time
[1] "4:00 PM"  "12:00 AM" " 4:00 AM"

> trimws(gsub("\\s*[APM]", "", start.time))
[1] "4:00"  "12:00" "4:00"

Upvotes: 1

akrun
akrun

Reputation: 886938

One option is to use str_remove to match zero or more space (\\s*) followed by the letters 'A', 'P', 'M' at the end ($) of the string

library(stringr)
library(dplyr)
df1 %>%
     mutate(Start.time = str_remove(Start.time, "\\s*[APM]+$"))

In base R, this can be done with sub

df1$Start.time <- sub("\\s*[APM]+$", "", df1$Start.time)

Or with substr

trimws(substr(df1$Start.time, 1, 5))

Upvotes: 1

Related Questions