使用 R stringr 将 'YYYYMMDD' 的字符串更改为 'MMM YYYY'

Change strings with 'YYYYMMDD' to 'MMM YYYY' using R stringr

我有一个字符串字符向量 my_strings,其中一些元素包含 YYYYMMDD 格式的单个日期。我想用 MMM YYYY 日期替换 YYYYMMDD 日期。例如,

my_strings <- c('apple','2000 20150101 bar', '20160228')

会变成 c('apple', '2000 Jan 2015 bar', 'Feb 2016')。在 R(尤其是 stringr)中执行此操作的最佳方法是什么?

我认为以下方法可行:

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"))

但我想我不能对捕获的项目做任何事情?我确实发现这行得通:

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)

但这看起来很笨拙。这里必须有一个更简单的方法,对吧?有点像我的第一次尝试?

我们可以用 gsubfn

library(gsubfn)
gsubfn("([0-9]{8})", ~format(as.Date(x, "%Y%m%d"), "%b %Y"), my_strings)
#[1] "apple"             "2000 Jan 2015 bar" "Feb 2016" 

基础 R 解决方案:

my_strings <- c('apple','2000 20150101 bar', '20160228')

unlist( lapply(strsplit(my_strings, '\ '), function( x ) {
  b1 <- format(as.Date(x, "%Y%m%d"), "%b %Y")
  x[which(!is.na(b1) )] <- na.omit( b1 )
  paste( x, collapse = '  ' )
})
)

# [1] "apple"               "2000  Jan 2015  bar" "Feb 2016"