仅从r中的日期中提取四分之一 [英] Extract only quarter from a date in r
问题描述
我只想从日期中提取四分之一,例如,从日期 2003-02-08中获取整数1。我一直在尝试沿着这条线
I would like to extract ONLY the quarter from a date, e.g., to get an integer 1 from the date "2003-02-08". I have been trying something along this line
library(mondate)
as.yearqtr(dat$DATE)
2003 Q1
"2003 Q1"
as.character(as.yearqtr(dat$DATE))[1]
2003 Q1
"2003 Q1"
一直没有给我想要的结果。当然,我可以这样写条件
which hasn't been giving my desired result. Of course I can write conditions as follows
library(data.table)
data$DATE = as.Date(data$DATE, format='%d%b%Y')
data$month=month(data$DATE)
setDT(data)[month==1, quarter:=1]
...
这会起作用,但一点都不优雅。
This will work, but is not elegant at all. Is there a more beautiful way of doing this?
谢谢lmo和user2100721!我真的希望我能接受所有答案!
Thank you lmo and user2100721! I really wish I could accept all of the answers!
推荐答案
我会这样做:
# example data
DT = data.table(id = 1:10, d = as.IDate("2003-02-08") + seq(100, by=50, length.out=10))
DT[, qtr := quarter(d)]
id d qtr
1: 1 2003-05-19 2
2: 2 2003-07-08 3
3: 3 2003-08-27 3
4: 4 2003-10-16 4
5: 5 2003-12-05 4
6: 6 2004-01-24 1
7: 7 2004-03-14 1
8: 8 2004-05-03 2
9: 9 2004-06-22 2
10: 10 2004-08-11 3
季度
函数由data.table提供,可在 Date
和 IDate
向量上使用。 ( IDate
使用整数存储。)
The quarter
function is provided by data.table and works on both Date
and IDate
vectors. (IDate
uses integer storage.)
这篇关于仅从r中的日期中提取四分之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!