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

Split Date into Year and Month in data.table

给定,

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

return,

     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

我该怎么做?

你可以用这个->

 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  

将评论转换为答案,您可以简单地使用 substr 结合 引用赋值 语义。如果你不喜欢 return 一个字符串

,你可以把它包装成 as.integer
dt[, `:=`(year = substr(date, 1L, 4L), month = substr(date, 5L, 6L))]