简体   繁体   English

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

[英]Split Date into Year and Month in data.table

Given, 鉴于

 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

I want to split date into year and month as follows: 我想将日期分为年份和月份,如下所示:

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

How can I do this? 我怎样才能做到这一点?

Converting comment to an answer, you could simply use substr combined with the assignment by reference semantics. 将注释转换为答案,您可以简单地将substr参考语义的赋值结合使用。 You can wrap it up into as.integer if you prefer it not to return a string 如果您不希望它不返回字符串,则可以将其包装为as.integer

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

You can use this-> 您可以使用此->

 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  

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

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