Search code examples
rlubridate

Why i am getting error while I am looping dates?


I have created function which would get you a date of day specified

 get_specified_weekday_dates<- function(startdate, enddate= Sys.Date()-1, day_want="Fri"){
  seq_date= data.frame(Price_Date=seq(as.Date(startdate),as.Date(enddate), by=1))
  seq_date$wkdy= wday(seq_date$Price_Date, label = T)
  data.frame(Price_Date=filter(seq_date,wkdy==day_want)[1])
 }
 CalenderDates=get_specified_weekday_dates("2010-01-01")

But now when i want to loop through those dates i am getting error

for (i in Weekly_Close_Price$PRICE_DATE){
  print(i)
  print(as.Date(i))
}

Output

[1] 14610
 Error in as.Date.numeric(i) : 'origin' must be supplied

How can I loop through dates using Only for loops


Solution

  • Here are two ways :

    1. Change the date from number to date in loop.
    for (i in Weekly_Close_Price$PRICE_DATE){
      print(as.Date(i, origin = '1970-01-01'))
    }
    
    1. Loop over the index.
    for (i in seq_along(Weekly_Close_Price$PRICE_DATE)) {
      print(Weekly_Close_Price$PRICE_DATE[i])
    }