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!
Asked
Active
Viewed 120 times
0
-
[See here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making an R question that folks can help with. That includes a sample of data (not a picture of it), all necessary code, and a clear explanation of what hasn't worked. – camille Sep 20 '19 at 18:06
2 Answers
1
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))

akrun
- 874,273
- 37
- 540
- 662
1
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"

Ben Wynne-Morris
- 141
- 1
- 3
-
May I request you to please add some more context around your answer. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post. See also [Explaining entirely code-based answers](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers). – help-info.de Sep 21 '19 at 16:29