简体   繁体   中英

Replace the first characters in a vector of strings in R

So I have a vector of character strings (not formatted as time intentionally).

TIME
00:35 AM
08:34 AM
10:10 AM
10:00 PM
09:45 PM
02:00 PM
07:47 PM
12:22AM

I would like to make it so that the leading 0's are gone. If there are two leading 0's then it must be 12. Notice the extra space in the final entry, some data is formatted like that so the solution must take that into account.

Final outcome desired:

TIME
12:35 AM
 8:34 AM
10:10 AM
10:00 PM
 9:45 PM
 2:00 PM
 7:47 PM
12:22 AM

Tidyverse solution preferred but I attempted using str_remove to no avail.

library(magrittr) # Other packages import the %>% also nowadays
x %>% sub("^00", "12", .) %>% sub("^0", "", .)
# [1] "12:35 AM"  "8:34 AM"   "10:10 AM"  "10:00 PM"  "9:45 PM"   "2:00 PM"   "7:47 PM"   "12:22  AM"

Reproducible data:

x <- c("00:35 AM", "08:34 AM", "10:10 AM", "10:00 PM", "09:45 PM", "02:00 PM", "07:47 PM", "12:22  AM")

use base sub and regex to substitute 00:00 for 12:00 at the start of the string:

sub("^00", "12", "00:35 AM")

will return ""12:35 AM". To remove leading 0s use sub afterwards:

sub("^0", "", "03:35 AM")"

will return "3:35 AM" Hope you get the idea

Best

You can use this:

Time <- c("00:35 AM", "08:34 AM", "10:10 AM", "22:00 PM", "21:45 PM", "02:00 AM", "07:47 AM", "14:22  PM")

Time2 <- ifelse(substring(Time,1,1)=='0',substring(Time,2,nchar(Time)),Time)

This is a solution that takes into consideration also the cases where AM or PM is attached to the digit part of the variable TIME

data %>% 
  mutate(TIME = ifelse(!grepl(" ", TIME),
                       sub("(AM$)|(PM$)", " \\1\\2", sub("^0", "", sub("^00", "12", TIME))),
                       sub("^0", "", sub("^00", "12", TIME)))) 

The " \\1\\2" replacement means that it takes either the first or the second parenthesized subexpressions - (AM$) or (PM$) - of the regex pattern.

Output

#       TIME
# 1 12:35 AM
# 2  8:34 AM
# 3 10:10 AM
# 4 10:00 PM
# 5  9:45 PM
# 6  2:00 PM
# 7  7:47 PM
# 8 12:22 AM

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