I've looked all over and can't seem to get a clear idea of how to do this; I have ts data with quarterly frequencies. I simply want to add a dummy variable only for the data corresponding to Q4 but I can't seem to make this work. I thought subset may be correct however I get an error that datasets are of different length when I try and regress data~trend+subset. I ran into a similar problem when trying to use the as.factor approach. I'm a newbie to R so any help would be appreciated.

  • 1
    $\begingroup$ The answers here could be of help to you: stackoverflow.com/questions/11952706/generate-a-dummy-variable-in-r. $\endgroup$
    – Dr_Be
    Jan 11, 2016 at 13:52
  • $\begingroup$ post the first 10 lines of your data set. Do you have a date column? If yes, then one can extract the month (look for the function .. e.g. the Date objects, timeDate and so forth) $\endgroup$
    – Richi W
    Mar 13, 2016 at 10:15
  • $\begingroup$ This most probably already has an answer on stats.stackexchange ... or it gets a good one there ... in any case Sergeys answer could be helpful too. $\endgroup$
    – Richi W
    Jul 11, 2016 at 6:28

2 Answers 2


Time series of 4 years of quarterly data with 1 for 4th quarter:

ts(rep(c(0,0,0,1),4), f=4)
  Qtr1 Qtr2 Qtr3 Qtr4
1    0    0    0    1
2    0    0    0    1
3    0    0    0    1
4    0    0    0    1

Is this what you want?

That was a dummy series of ts class. Actually, depending on your needs simple rep(c(0,0,0,1),4) may suffice, e.g. for ARIMA regression as exog dummy (w/o coercion to ts)


Here's one solution.

For this example I will use the ausres data set.

df <- data.frame(time=time(austres), Value = as.matrix(austres))
df$Quarter <- ifelse(df$time - floor(df$time) == 0, 'Q1',
          ifelse(df$time - floor(df$time) == 0.25, 'Q2',
          ifelse(df$time - floor(df$time) == 0.5, 'Q3',
          ifelse(df$time - floor(df$time) == 0.75, 'Q4',''))))

df$NewData <- ifelse(df$Quarter == 'Q4', df$Value*1.15, df$Value)

First line, convert your time series to a data frame. Then associate each ts to corresponding quarter. Last line you'll want to transform Q4 based on whatever you want to do. In this case I am increasing Q4 by 15%. If you need to transform the data frame back to a time series you can always do that since the first column is preserved.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.