【问题标题】:Transforming date column from year-month-day to just year-month将日期列从年月日转换为年月
【发布时间】:2014-04-09 01:49:23
【问题描述】:

我有一个包含日期列的数据集。我正在尝试将该日期列转换为只有月份和年份的日期列,作为 Posix 日期。我需要能够做到这一点的原因是能够在 ggplot2 和 scale_x_date 中使用一个月宽的 bin。这是一个测试数据集:

testset <- data.table(date=as.Date(c("2013-07-02","2013-08-03","2013-09-04","2013-10-05","2013-11-06","2013-07-03","2013-08-04","2013-09-05","2013-10-06","2013-11-07")), plant = LETTERS[1:5], PlantID = c(1,2,3,4,5,1,2,3,6,7), product = as.factor(letters[26:22]), rating = runif(30))

基本上,我想将日期列转换为仅是年月的列。

有什么快速、有说服力的方法来做这样的事情吗?

编辑:我创建了另一个线程,该线程具有更多我正在寻找的最终目标。它位于这里:Creating month-sized bins with ggplot2 in r

【问题讨论】:

  • lubridate::floor_date(testset$date, "month")
  • Base R 将是:as.Date(paste(format(testset$date,"%Y-%m"),"01",sep="-")),这相当简单。
  • 或者zoo,你可以试试as.yearmon。 (testset[, YM := as.yearmon(date)])
  • @hadley,仅将日期显示为本月的第一天。我想完全摆脱白天的条目。 (%y %m)
  • 您无法摆脱 POSIX 日期中的这一天。 @AnandaMahto 建议的as.yearmon 会允许这样做,尽管我认为。

标签: r date datetime ggplot2 data.table


【解决方案1】:

来自手册:

""yearmon" 类用于表示月数据。在内部它保存数据为年加 0 代表 1 月,1/12 代表 2 月,2/12 代表 3 月,依此类推,以使其内部表示 化与频率 = 12 的 ts 类相同。”

> require(zoo)
> as.yearmon("2007-03-01")
[1] "Mar 2007"
> as.numeric(as.yearmon("2007-03-01"))
[1] 2007.167

这真的是你想要的吗,一年的一小部分?如果这对您有用,请查看

http://cran.r-project.org/web/packages/zoo/zoo.pdf

【讨论】:

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