简体   繁体   English

将日期列从年月日转换为仅年月

[英]Transforming date column from year-month-day to just year-month

I have a dataset with a date column. 我有一个带有日期列的数据集。 I am trying to take that date column and transform it to one that only has month and year, as a Posix date. 我正在尝试将该日期列转换为只有Posix日期的只有月份和年份的日期列。 The reason I need to be able to do this is to be able to use a bin that is a month wide in ggplot2 and scale_x_date. 我需要执行此操作的原因是能够使用ggplot2和scale_x_date中一个月宽的bin。 Here is a test dataset: 这是一个测试数据集:

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))

Basically, I want to turn the date column into one that is just year-month. 基本上,我想将date列变成只有year-month的列。

Any quick, eloquent ways to do such a thing? 有什么快速,雄辩的方法可以做到这一点?

EDIT: I created another thread that has more of the end goal of what I'm looking for. 编辑:我创建了另一个线程,它具有我正在寻找的更多最终目标。 It is located here: Creating month-sized bins with ggplot2 in r 它位于这里: 在R中使用ggplot2创建月大小的垃圾箱

From the manual: 从手册中:

"The "yearmon" class is used to represent monthly data. Internally it holds the data as year plus 0 for January, 1/12 for February, 2/12 for March and so on in order that its internal representa- tion is the same as ts class with frequency = 12." ““ yearmon”类用于表示月度数据。在内部,它保存数据为年份加1月的0、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

Is this what you really want, a yearmon which is a fraction of a year? 这是您真正想要的吗,一整年的一整年? If this works for you see 如果这对您有用,请参阅

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM