Home > Back-end >  R: Creating a New Column with Quarterly dates in r
R: Creating a New Column with Quarterly dates in r

Time:08-30

I have the following dataframe:

df = obs seriesA seriesB
1        50       50
2        50       50
3        50       50
4        50       50
5        50       50

I would like to create a new column called date that contains quarterly data from a given interval. e.g.:

df = obs seriesA seriesB   date
1        50       50       Q1-2000
2        50       50       Q2-2000
3        50       50       Q3-2000
4        50       50       Q4-2000
5        45       34       Q1-2001

I would like to have an easy enough method that I can extrapolate to longer data frames: e.g. from Q1-2000 to Q1-2019. Also it would have to be in date format to be able to read it as a date.

CodePudding user response:

You can create a sequence using seq, and then use zoo::as.yearqtr to format the string:

library(zoo)
seq(from = as.yearqtr("2000-01-01"), to = as.yearqtr("2019-01-01"), by = 1/4) |>
  format("Q%q-%Y")

#[1] "Q1-2000" "Q2-2000" "Q3-2000" "Q4-2000" "Q1-2001" "Q2-2001" "Q3-2001" "Q4-2001" "Q1-2002"

CodePudding user response:

You can use the levels of interaction:

levels(interaction("Q", 1:4, "-", 2000:2019, sep = ""))
#[1] "Q1-2000" "Q2-2000" "Q3-2000" "Q4-2000" "Q1-2001" "Q2-2001" "Q3-2001" "Q4-2001" "Q1-2002"...

CodePudding user response:

Or simply paste and rep:

paste(paste0("Q", 1:4), rep(2000:2020, each = 4), sep = "-")

CodePudding user response:

Another possible solution, using outer:

as.vector(outer(paste0("Q", 1:4), 2000:2019, \(x,y) paste(x, y, sep = "-")))

#>  [1] "Q1-2000" "Q2-2000" "Q3-2000" "Q4-2000" "Q1-2001" "Q2-2001" "Q3-2001"
#>  [8] "Q4-2001" "Q1-2002" "Q2-2002" "Q3-2002" "Q4-2002" "Q1-2003" "Q2-2003"
#> [15] "Q3-2003" "Q4-2003" "Q1-2004" "Q2-2004" "Q3-2004" "Q4-2004" "Q1-2005"
#> [22] "Q2-2005" "Q3-2005" "Q4-2005" "Q1-2006" "Q2-2006" "Q3-2006" "Q4-2006"
#> [29] "Q1-2007" "Q2-2007" "Q3-2007" "Q4-2007" "Q1-2008" "Q2-2008" "Q3-2008"
#> [36] "Q4-2008" "Q1-2009" "Q2-2009" "Q3-2009" "Q4-2009" "Q1-2010" "Q2-2010"
#> [43] "Q3-2010" "Q4-2010" "Q1-2011" "Q2-2011" "Q3-2011" "Q4-2011" "Q1-2012"
#> [50] "Q2-2012" "Q3-2012" "Q4-2012" "Q1-2013" "Q2-2013" "Q3-2013" "Q4-2013"
#> [57] "Q1-2014" "Q2-2014" "Q3-2014" "Q4-2014" "Q1-2015" "Q2-2015" "Q3-2015"
#> [64] "Q4-2015" "Q1-2016" "Q2-2016" "Q3-2016" "Q4-2016" "Q1-2017" "Q2-2017"
#> [71] "Q3-2017" "Q4-2017" "Q1-2018" "Q2-2018" "Q3-2018" "Q4-2018" "Q1-2019"
#> [78] "Q2-2019" "Q3-2019" "Q4-2019"
  • Related