首页 文章

从zoo :: yearmon对象中提取月份和年份

提问于
浏览
112

我有一个 yearmon 对象:

require(zoo)
date1 <- as.yearmon("Mar 2012", "%b %Y")
class(date1)
# [1] "yearmon"

如何从中提取月份和年份?

month1 <- fn(date1)
year1 <- fn(date1)

我应该使用什么功能代替 fn()

6 回答

  • 12

    "yearmon" 类的对象使用 format() 方法 . 这是您的示例日期(正确创建!)

    date1 <- as.yearmon("Mar 2012", "%b %Y")
    

    然后我们可以根据需要提取日期部分:

    > format(date1, "%b") ## Month, char, abbreviated
    [1] "Mar"
    > format(date1, "%Y") ## Year with century
    [1] "2012"
    > format(date1, "%m") ## numeric month
    [1] "03"
    

    这些作为字符返回 . 在适当的情况下,如果您希望将年份或数字月份作为数字变量,请包装 as.numeric() ,例如

    > as.numeric(format(date1, "%m"))
    [1] 3
    > as.numeric(format(date1, "%Y"))
    [1] 2012
    

    有关详细信息,请参阅 ?yearmon?strftime - 后者说明了您可以使用的占位符字符 .

  • 5

    lubridate package对于这种事情是惊人的:

    > require(lubridate)
    > month(date1)
    [1] 3
    > year(date1)
    [1] 2012
    
  • 15

    我知道OP在这里使用的是 zoo ,但是我发现这个线程在搜索同一问题的标准 ts 解决方案 . 所以我想我也会为 ts 添加一个 zoo 的免费答案 .

    # create an example Date 
    date_1 <- as.Date("1990-01-01")
    # extract year
    as.numeric(format(date_1, "%Y"))
    # extract month
    as.numeric(format(date_1, "%m"))
    
  • 142

    你可以使用 format

    library(zoo)
    x <- as.yearmon(Sys.time())
    format(x,"%b")
    [1] "Mar"
    format(x,"%Y")
    [1] "2012"
    
  • 0

    对于大型载体:

    y = as.POSIXlt(date1)$year + 1900    # x$year : years since 1900
    m = as.POSIXlt(date1)$mon + 1        # x$mon : 0–11
    
  • 99

    这个问题没有准确说明预期的输出是什么,但假设月份你想要月份数(1月= 1)和你想要数字4位数年份的那一年假设我们刚刚运行了问题中的代码:

    cycle(date1)
    ## [1] 3
    as.integer(date1)
    ## [1] 2012
    

相关问题