【问题标题】:How to convert numeric year month to year-month-day date format in xts?如何在xts中将数字年月转换为年月日日期格式?
【发布时间】:2013-08-27 21:03:09
【问题描述】:

我想用年月末日期索引(即 1989-12-31)将 df 转换为 xts。我在网上搜索但没有答案。感谢并感谢您的帮助。

df <- read.table(textConnection("
date    a     b      c     d 
198912 29.46 13.47 32.52 22.06 
199001 36.35 17.30 38.14 24.98 
199002 33.72 15.57 38.14 23.61 
199003 30.76 14.01 34.74 21.73 
"),header=T)

【问题讨论】:

    标签: r xts


    【解决方案1】:

    使用yearmon 类,然后使用as.Date.yearmon 引用help('yearmon')

    as.Date.yearmon 和 as.yearmon.yearqtr 每个都有一个可选的第二个参数“frac”,它是一个介于 0 和 1 之间的数字(包括 0 和 1),表示结果所代表的时间段的分数。默认为 0,表示周期的开始。

    as.Date(as.yearmon(as.character(df$date), format = '%Y%m'), frac=1)
    ## [1] "1989-12-31" "1990-01-31" "1990-02-28" "1990-03-31"
    

    【讨论】:

      【解决方案2】:

      为了笑,这里有一个基本的 R 方法,它确实很丑:

      Reduce(c,
       lapply(
        as.Date(paste0("1-",as.character(df$date)),format="%d-%Y%m"),
        function(x) seq.Date(x,length=2,by="1 month")[2] - 1
       )
      )
      
      [1] "1989-12-31" "1990-01-31" "1990-02-28" "1990-03-31"
      

      【讨论】:

        猜你喜欢
        • 2015-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多