I need a quarter-year formatted variable in R to use in ggplot2 and I just can't get it right. In Stata this is straightforward (and I guess it is in R as well when you know the code).
This is an incredibly basic question but I've been working on it for some time. Hopefully someone here has a solution. I've tried following several solutions given in stackoverflow and here to no avail.
I have 5 years of panel data for 6 regional units. I want a quarter-date formatted variable to use in ggplot2.
Here is a overview over my date data from different tries in R for 3 years (sorry about the horrible excel-format):
The "quarter" variable here ranging from 208 onwards is the Stata-formatted quarter-year variable after import to R using "haven" . I've tried solving this format problem by different versions of "as.yearqtr()" in the "zoo" package, but I can't find the correct specification.
I later want to use the quarter variable in ggplot2 as an x-axis and to add a grey-shaded area by:
The lubridate functions year and semester have what you're looking for, but I'm going to have to assume that your source data is convertible to a datetime object, such as ("2014-02-16") or you can wrangle it to one.
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#>
#> date
library(stringr)
library(magrittr)
obs <- "2016-02-16"
paste(year(obs), "Q", semester(obs)) %>% str_replace("Q\\s", "Q")
#> [1] "2016 Q1"
The lubridate library includes a quarter function and if you look at this SO answer it'll help you include the year in the semester value (3rd answer down)
What exactly is your problem? In any case you might also want to check out my package dint that i developed specifically for dealing with year quarter dates.
you can just make a year-quarter column in your data.frame with df$yq <- dint::date_yq(year, quarter). and then use scale_x_date_yq() with ggplot.
Thanks for all the helpful feedback! I have some more work to do on dates in R. I wound up making a ISO8601-formatted date variable in Stata, and got the correct year-quarter format with
zoo uses a format where it stores the quarters as fractions of the year, so 2015.0 is the first quarter, 2015.25 the second quarter and so forth. if you have a date like 2015.1 where .1 means first quarter, you can just use some simple arithmetic to convert the two
x <- c(2014.1, 2014.2, 2014.3, 2014.4)
year <- x %/% 1 # integer divions
quarter <- (x %% 1) * 10 # reminder
print(year)
print(quarter)
quarter_zoo <- (quarter - 1L) / 4
zooyq <- year + quarter_zoo
print(zooyq)
zoo::as.yearqtr(zooyq)