1

I need to create 12 variables starting from a certain date t1, increasing each one by 3 months.

Here's an example:

 t1           t2           t3     
01-01-2000  01-04-2000   01-07-2000

I've tried something like this (with package lubridate):

for (i in 1:12) {
     month(AAA$t(i+1)) <- month(AAA$t(i)) + 3 }

But I'm obtaining:

Error in as.POSIXlt(x) : attempt to apply non-function

sm925
  • 2,648
  • 1
  • 16
  • 28
jeff
  • 323
  • 1
  • 7
  • 3
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Is that sample supposed to be `AAA` and is that a data.frame? It only has three columns but you want it to have 12? – MrFlick Jun 28 '19 at 15:10
  • AAA is a dataframe. There's a column t1 (class date) and i need to have 12 columns starting from t1 to t12. If the first record of t1 is 01-01-2000, first record of t2 should be 01-04-2000, t3 01-07-2000 and so on – jeff Jun 28 '19 at 15:15
  • Instead of `month(AAA$t(i+1))`, try `month(AAA[paste("t",i+1,sep="")])`. – Argon Jun 28 '19 at 15:30

1 Answers1

1

If you want to create a dataframe with t1 through t12 containing a range of dates:

t = seq(mdy("01/01/2000"), by = "3 months", length.out = 12) #this replaces the loop
names(t) <- paste0("t", c(1:12)) #this names your vector
data.frame(as.list(t)) #this creates the df
yfa
  • 101
  • 5
  • @Sabrina, this is a great example of "how to think" in R; it's a vectorized language, so many things you would do in a for loop in other languages are instead simply done on the vector. For loops are rarely (but still sometimes) needed. – Aaron left Stack Overflow Jun 28 '19 at 15:51
  • Thanks yfa. What if I need to use a certain variable instead of (for example) "01/01/2000" ? – jeff Jul 01 '19 at 12:18