For Loop to Populate Dates

I have written some .R script to create a table and a new column in my DF to allow for a date column to create some time series analysis. I want to fill the empty column with dates starting at 2020-03-07 and +1 for every row below. However my for loop isn't working. Wondering what I might be missing here

#Create Empty date colummn
CFR_Table$Date <- NA

#Fill Date Column With Dates Starting @ 2020-03-07
for (i in CFR_Table$Date) {
  as.Date("2020-03-07") + 1
}

I initially thought that I needed to set perimeters of where to start and end however I tried this and was not successful

for (i in results$Date) {
  as.Date("2020-03-07:2020-06-26") + 1
}

First, I would not use a for loop at all. Here is an example of filling a column with dates using the seq.Date function.

DF <- data.frame(X = 1:100)
DF$Date <- seq.Date(from = as.Date("2020-03-07"), length.out = nrow(DF), by = 1)
summary(DF)
#>        X               Date           
#>  Min.   :  1.00   Min.   :2020-03-07  
#>  1st Qu.: 25.75   1st Qu.:2020-03-31  
#>  Median : 50.50   Median :2020-04-25  
#>  Mean   : 50.50   Mean   :2020-04-25  
#>  3rd Qu.: 75.25   3rd Qu.:2020-05-20  
#>  Max.   :100.00   Max.   :2020-06-14

Created on 2020-06-26 by the reprex package (v0.3.0)

The problem with your for loop is that it produces the same value every iteration and it does not assign the calculated value to the data frame; it merely calculates the value.

Yes your for loop is doing these things wrong

  1. Not incrementing by a variable that increases by 1 in each pass. So please do Date + j and increment j by j <- j + 1.
  2. You can declare an empty tribble and then tribble.add_row() function within the loop to keep adding dates into it.
  3. Once you are out of the loop, print your table to see if you have the dates or not ..

Hope it helps

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.