I have a character vector of strings my_strings
where some elements include a single date in YYYYMMDD
format. I'd like to replace the YYYYMMDD
dates with MMM YYYY
dates. For example,
my_strings <- c('apple','2000 20150101 bar', '20160228')
would become c('apple', '2000 Jan 2015 bar', 'Feb 2016')
. What's the best way to do this in R (esp., stringr)?
I thought the following would work:
library(stringr)
pattern <- '([0-9]{4})([0-9]{2})[0-9]{2}'
str_replace(my_strings, pattern, str_c(month.abb[as.integer("\\2")], " \\1"))
But I guess I can't do anything with the captured items? I did find that this works:
library(stringr)
library(dplyr)
library(lubridate)
pattern <- '[0-9]{8}'
my_strings %>%
str_match(pattern) %>%
ymd() %>%
format('%b %Y') %>%
str_replace_na() ->
replacement_vals
str_replace(my_strings, pattern, replacement_vals)
But this seems clunky. There has to be a simpler approach here, right? Something like my first attempt?