Search code examples
rdatefor-loopseq

For loop to get a range of dates R


Hope you can help me out! For all of my dates in a column, I would like to get a range for each date - 14 days. So for example, if the first date in my column is 29-04-2021, I would like to get the dates from 15-04-2021 until 29-04-2021. I found the function seq that does this but to do this for all the values in my column I need to put the seq function in a for loop. This is what I tried but the output is only the last row and the date format changed. This is my code (test_IIVAC$'Vacdate 1' is my column with the dates):

df <- data.frame()
 
for(i in 1:length(test_IIVAC$`Vacdate  1`)){
    te  <- as.Date(seq(test_IIVAC$`Vacdate  1`[i]-14, test_IIVAC$`Vacdate  1`[i], by = "day"))
    df1 <- rbind(df, te)
}

Can anyone help me out in getting the ranges of all the dates in the column and place them in one dataframe with the Date format? The desired output would be:

Output

Thanks a bunch!


Solution

  • You can use any of apply command to generate a sequence of date values and add it as a new column in the original dataframe.

    test_IIVAC$dates <- lapply(df$a, function(x) seq(x-14, x, by = 'day'))