2012-07-10 27 views
2

在R,我得到了数据级日期如下:如何分解R中的日期数据?

20100701 
20100702 
20100703 
20100704 

我怎么可能把它们变换为后续形式:

2010 07 01 
2010 07 02 
2010 07 03 

在3列中的年,月,日的数据。

+1

目前还不清楚如何回答你的问题。你能编辑包含'dput(myinputdatahere)'的输出,以便我们可以复制你正在使用的内容吗?这将为我们提供准确回答您的问题所需的元数据。 – 2012-07-10 06:29:00

回答

2

只是提了,这也可以做(尽管也许不太方便比包lubridate)与功能strptime和包装中的format.POSIXct

x <- c(20100701,20100702,20100703,20100704) 
strptime(x, format="%Y%m%d") -> y 
data.frame(year=format(y,format="%Y"),month=format(y,format="%m"),day=format(y,format="%d")) 
    year month day 
1 2010 07 01 
2 2010 07 02 
3 2010 07 03 
4 2010 07 04 
1

一些假数据:

dates <- c("20100701", "20100701", "20100701", "20100701") 

要获取日期:

library(lubridate) 
ymd(dates) 
Using date format %Y%m%d. 
[1] "2010-07-01 UTC" "2010-07-01 UTC" "2010-07-01 UTC" "2010-07-01 UTC" 

为了得到一个数据帧,只是分割字符串:

library(stringr) 
data.frame(year=str_sub(dates, 1, 4), month=str_sub(dates, 5, 6), day=str_sub(dates, 7, 8)) 
    year month day 
1 2010 07 01 
2 2010 07 01 
3 2010 07 01 
4 2010 07 01 
+0

通过将'str_sub'更改为'substr',您可以轻松摆脱stringr的依赖关系 – Dason 2012-10-05 16:33:07

3

这是很直接如果您使用包装lubridate

library(lubridate) 
x <- ymd(dates) 
data.frame(y=year(x), m=month(x), d=day(x)) 
    y m d 
1 2010 7 1 
2 2010 7 2 
3 2010 7 3 
4 2010 7 4 

lubridate提供一种堆叠的便利函数与日期工作。在本例中:

  • ymd()将字符串转换为日期,猜测格式是什么。
  • year() extractst年
  • month()提取一个月
  • day()提取一天