Stefan Musch Stefan Musch - 28 days ago 11
R Question

Fill a data frame with increasing date objects in R

I can't seem to figure the following out.

I have a data frame with 398 rows and 16 variables. I want to add a date variable. I know that for each row the date increases by a week and starts with 2010-01-01. I've tried the following:

date <- ymd("2010-01-01")
df <- as.data.frame(c(1:nrow(data), 1))
for (i in 1:nrow(data)){
date <- date + 7
df[i,] <- as.Date(date)
}


I then want to bind it to my data-frame. However, the values inside df are non-dates. If I perform the date +7 calculation it works (e.g. once it goes to 2010-01-08), but if I assign it to the df it turns into weird numerical values.

Appreciate any help.

Answer Source

Try the following:

library(lubridate)
date <- ymd("2010-01-01")

df <- data.frame(ind = 1:5)
df$dates <- seq.Date(from = date, length.out = nrow(df), by = 7) 
# note that `by = "1 week"` would also work, if you prefer more readable code.
df
  ind      dates
1   1 2010-01-01
2   2 2010-01-08
3   3 2010-01-15
4   4 2010-01-22
5   5 2010-01-29