My date data is in the format "yyyymm", specifically 20071 / 20074 / 20077 / 200710.
I want to convert this to quarters.
Also, in another dataset I have monthly data that I want to aggregate to quarters. Is there a function?
In base R, you could append a temporary date and extract year and quarter from it.
x <- as.character(c(20071, 20074, 20077, 200710))
temp <- as.Date(paste(x, "01"), "%Y%m %d")
paste(format(temp, "%Y"), quarters(temp))
#[1] "2007 Q1" "2007 Q2" "2007 Q3" "2007 Q4"
If you want quarter as numbers, we can use lubridate::quarter
paste(format(temp, "%Y"), lubridate::quarter(temp))
#[1] "2007 1" "2007 2" "2007 3" "2007 4"
The yearqtr
class repesents a year and quarter internally as a year plus a fraction (0 for Q1, 1/4 for Q2, 2/4 for Q3 and 3/4 for Q4) and displays as shown:
library(zoo)
ym <- c(20071, 20074, 20077, 200710) # test data
yq <- as.yearqtr(as.character(ym), "%Y%m")
yq
## [1] "2007 Q1" "2007 Q2" "2007 Q3" "2007 Q4"
It is probably preferable to leave it as yearqtr
since you can perform many operations on it (eg yq + 1/4
is the next quarter) but if you want it as pure character strings use format(yq)
or as.character(yq)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.