在data.table中将日期分为年和月

时间:2015-06-25 10:12:05

标签: r date data.table

鉴于,

 set.seed(1234)
 library(data.table)
 dt <- data.table(date=c(201405, 201406, 201501, 201503), x = rnorm(4, 0, 1))

返回,

     date          x
1: 201405 -1.2070657
2: 201406  0.2774292
3: 201501  1.0844412
4: 201503 -2.3456977

我想将日期分为年和月,如下所示:

   year month          x
1: 2014     5 -1.2070657
2: 2014     6  0.2774292
3: 2015     1  1.0844412
4: 2015     3 -2.3456977

我该怎么做?

2 个答案:

答案 0 :(得分:0)

Converting comment to an answer, you could simply use substr combined with the assignment by reference semantics. You can wrap it up into as.integer if you prefer it not to return a string

dt[, `:=`(year = substr(date, 1L, 4L), month = substr(date, 5L, 6L))]

答案 1 :(得分:-1)

您可以使用此 - &gt;

 dt$month=as.integer(substr(dt$date,5,6))  
 dt$year=substr(dt$date,1,4)    
 dt  
 date               x month year  
 1: 201405 -1.2070657     5 2014  
 2: 201406  0.2774292     6 2014  
 3: 201501  1.0844412     1 2015  
 4: 201503 -2.3456977     3 2015