【问题标题】:How to extract month from a Year-Month (2017-10) type object in R?如何从 R 中的年月(2017-10)类型对象中提取月份?
【发布时间】:2018-05-15 19:13:37
【问题描述】:

这个对象是字符格式的,我想避免通过基于字符串的函数提取 10 个,因为它非常麻烦。如果有办法通过 as.Date() 和某种特定格式,我很乐意使用它

【问题讨论】:

  • 这可能会有所帮助:stackoverflow.com/questions/6242955/…
  • 因为 6,7 不是通用的。月份可以是 5 也可以是 12
  • 最不麻烦的可能只是一个捕获从“-”到结尾的所有数字的正则表达式。
  • 库(stringr); str_extract("2010-10", pattern = "[0-1]?[0-9]$")

标签: r date format


【解决方案1】:

我最近真的很喜欢anytime 包中的anydate

试试这个:

library(anytime)
format(anydate("2017-10"), "%m")

【讨论】:

    【解决方案2】:

    我相信这个问题之前已经在 SO 上提出过。

    作为anytime 包的替代方案,您可以使用lubridate

    library(lubridate)
    format(ymd("2017-10", truncated = 1L), "%m")
    

    或以 R 为基数

    format(as.Date(paste0("2017-10", "-01")), "%m")
    

    【讨论】:

      【解决方案3】:

      这会将其转换为 yearmon 对象(表示没有日期的年份和月份),然后提取月份。请参阅?yearmon 了解更多信息。

      library(zoo)
      
      cycle(as.yearmon("2017-10"))
      ## [1] 10
      

      【讨论】:

        猜你喜欢
        • 2023-04-05
        • 1970-01-01
        • 2021-10-02
        • 1970-01-01
        • 2014-06-14
        • 2020-11-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多