I'm trying to create a vector of dates (formatted as character strings not as dates) using a for loop. I've reviewed a few other SO questions such as (How to create a vector of character strings using a loop?), but they weren't helpful. I've created the following for loop:
start_dates <- c("1993-12-01")
j <- 1
start_dates <- for(i in 1994:as.numeric(format(Sys.Date(), "%Y"))){
date <- sprintf("%s-01-01", i)
j <- j + 1
start_dates[j] <- date
}
However, it returns a NULL (empty) vector start_dates. When I increment the i index manually it works. For example:
> years <- 1994:as.numeric(format(Sys.Date(), "%Y"))
> start_dates <- c("1993-12-01")
> j <- 1
> i <- years[1]
> date <- sprintf("%s-01-01", i)
> j <- j + 1
> start_dates[j] <- date
> start_dates
[1] "1993-12-01" "1994-01-01"
> i <- years[2]
> date <- sprintf("%s-01-01", i)
> j <- j + 1
> start_dates[j] <- date
> start_dates
[1] "1993-12-01" "1994-01-01" "1995-01-01"
It must have something to do with the construction of my for() statement, but I can't figure it out. I'm sure it's super simple. Thanks in advance.