0

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

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Amit
  • 763
  • 1
  • 5
  • 14

3 Answers3

1

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])
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

You need to specify what date your timestamp is relative to (probably 01.01.1970)

Try

for (i in Weekly_Close_Price$PRICE_DATE){
  print(i)
  print(as.Date(i, origin = "1970-01-01"))
}

(and check if the dates make sense!)

Tschösi
  • 491
  • 3
  • 13
-1

I think this works

for (i in as.character(Weekly_Close_Price$PRICE_DATE)){
  print(as.Date(i))   
 }
Amit
  • 763
  • 1
  • 5
  • 14