EAG
EAG

Reputation: 59

How can I add months to a date in a for loop and append the result to a list or dataframe?

The goal is to get a dataframe with two columns: the first column would be the month and the second column would be the year. I'd like the for loop to take me to two years from now. I left the for loop empty given that I was nowhere near finding the solution.

D <- data.frame(month(Sys.Date()), year(Sys.Date()))
D <- rename(D, Month = month.Sys.Date..., Year = year.Sys.Date...)

for (x in 1:24) {
     D1 <- return() 
}

Upvotes: 1

Views: 142

Answers (1)

akrun
akrun

Reputation: 887118

We don't need a loop. An option is to paste the 'Year', 'Month' together, convert to yearmon class (from zoo) and add a sequence of months

library(zoo)
 as.yearmon(paste0(D$Year, "-", D$Month)) + 0:24/12

Upvotes: 1

Related Questions