【问题标题】:Change strings with 'YYYYMMDD' to 'MMM YYYY' using R stringr使用 R stringr 将带有 'YYYYMMDD' 的字符串更改为 'MMM YYYY'
【发布时间】:2017-03-03 02:28:46
【问题描述】:

我有一个字符串字符向量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)

但这似乎很笨重。这里必须有一个更简单的方法,对吧?像我的第一次尝试?

【问题讨论】:

    标签: r regex date stringr


    【解决方案1】:

    我们可以通过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" 
    

    【讨论】:

      【解决方案2】:

      基础 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"    
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-05
        • 1970-01-01
        相关资源
        最近更新 更多