I have a dataset, and the only variable that indicates time is t, being a series of numbers from 1-80, where when t=1 means Q1 1986, t=2 means Q2 1986, all the way to t=80 means Q4 2005.
I want to create another column that reads these periods as "Q1 1986" and "Q4 2005" etc.
CodePudding user response:
This can be done using modulos and integer division using some wrangling to avoid off-by-one errors because we start counting at 1.
paste0(
"Q", (q - 1) %% 4 1, " ",
1986 (q - 1) %/% 4
)
CodePudding user response:
The yearqtr class in zoo can be used to represent year/quarter objects. Internally a yearqtr object is represented by the year fraction where fraction is 0 for Q1, 1/4 for Q2, 2/4 for Q3 and 3/4 for Q4. Note that if t=1 represents 1986 Q1 and numbers proceed sequentially by quarter then t=0, the origin, is 1985 Q4.
library(zoo)
# test input
DF <- data.frame(t = c(1, 80))
transform(DF, yq = format(as.yearqtr("1985-4") t / 4, "Q%q %Y"))
## t yq
## 1 1 Q1 1986
## 2 80 Q4 2005
If the default output format, "%Y Q%q", is sufficient then it is even easier.
transform(DF, yq = as.yearqtr("1985-4") t / 4)
## t yq
## 1 1 1986 Q1
## 2 80 2005 Q4