3

I am trying to use a for loop to extract dates from an SQL query in R. Currently I have:

StartDate<-"2017-07-01"
EndDate<- "2017-07-05"
dates<-seq(as.POSIXct(StartDate, format="%Y-%m-%d"), as.POSIXct(EndDate, format="%Y-%m-%d"), by='days')

for (f in dates){
. 
. Code here that is inside for loop
.
}

My issue is that does not come out in a date format as in Dates. How do I get f in the same format as StartDate and EndDate?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Fiona
  • 477
  • 1
  • 9
  • 18

2 Answers2

7

Let's try as.list() wrapper so that 'Date' format is preserved in for loop

for (f in as.list(dates)){
 print(str(f))
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Prem
  • 11,775
  • 1
  • 19
  • 33
  • This works better than what I was doing but for some reason it skips half of my code out in the loop? Unsure as to why...Maybe it's my code? Is there a limit to what can go into a for loop? – Fiona Dec 28 '17 at 14:39
  • I don't think that `for` loop has any iteration limit. – Prem Dec 28 '17 at 17:11
0
StartDate<-"2017-07-01"
EndDate<- "2017-07-05"
dates<-seq(as.POSIXct(StartDate, format="%Y-%m-%d"), as.POSIXct(EndDate, format="%Y-%m-%d"), by='days')

for (f in dates){
print(as.POSIXct(f,origin = "1970-01-01"))
}   
Nimantha
  • 6,405
  • 6
  • 28
  • 69
SDaymier
  • 51
  • 4
  • Why is the origin "1960-01-01"? – Fiona Dec 28 '17 at 14:36
  • You can change it but usually we use a default date which is : 1970-01-01 ( i made a mistake). You can see : https://stackoverflow.com/questions/37690722/how-to-get-origin-from-posixct-object – SDaymier Dec 28 '17 at 14:38