Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Append characters to strings in column which match expression R

I have a date/time column in an inconsistent format:

df <- data.frame(date.time=c("10-29-2022 09:46:40", "02-27-2023 22:53:53", "12-15-2022 02:54:03", "01-09-2023 14:44", "03-05-2023 14:58", "02-18-2023 19:46:35", "12-10-2022 16:50"))

I want to add ":00" to the time stamps that don’t include seconds (notice some strings are shorter than others). I can find the strings without seconds using gsubs(pattern=) but when I try to add on ":00" to the end I’m replacing the whole string:

df %>%
  mutate_at(.vars = "date.time", 
            .funs = gsub,
            pattern = "^\\d\\d-\\d\\d-\\d\\d\\d\\d \\d\\d:\\d\\d$",
            replacement = "\\d\\d-\\d\\d-\\d\\d\\d\\d \\d\\d:\\d\\d:00")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In this case, you can use a simple ifelse with nchar and paste0 with no need for regex:

df$date.time_new <- ifelse(nchar(df$date.time) < max(nchar(df$date.time)), 
                           paste0(df$date.time, ":00"), 
                           df$date.time)

Output:

            date.time       date.time_new
1 10-29-2022 09:46:40 10-29-2022 09:46:40
2 02-27-2023 22:53:53 02-27-2023 22:53:53
3 12-15-2022 02:54:03 12-15-2022 02:54:03
4    01-09-2023 14:44 01-09-2023 14:44:00
5    03-05-2023 14:58 03-05-2023 14:58:00
6 02-18-2023 19:46:35 02-18-2023 19:46:35
7    12-10-2022 16:50 12-10-2022 16:50:00
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading