user1700890
user1700890

Reputation: 7742

looping through list of dates in R

Here is my example:

test_list <- c(as.Date('2017-03-08','2017-03-08' ))

    for(el in test_list){
      print(el)
    }

It generates: 17641

This is date representation. I am curious why R behaves this way.

Upvotes: 0

Views: 213

Answers (2)

jhvdz
jhvdz

Reputation: 186

What exactly do you want to get back? One time '2017-03-08' or two times as in the code below?

test_list <- as.Date(c('2017-03-08','2017-03-08'))

for(el in test_list){
   print(as.Date(el, origin = "1970-01-01"))
}

Upvotes: 2

Punintended
Punintended

Reputation: 737

Pierre Lapointe is correct that calling multiple arguments with in as.Date is part of your issue.

The number 17641 has to do with how R stores dates. Calling test_list yields "2018-04-20", which I would guess means it's added those two dates.

The origin date in R is 1970-01-01. If you add 17641 to that, you get 2018-04-20. So R is returning the integer corresponding to your date, which can be verified by calling class(el), which makes sense because in a loop your are referring to elements in test_list by their ordinality (ordinance?)

The following worked fine for me. I'm not exactly sure why, but if it ain't broke, don't fix it!

for (el in 1:length(test_list)){
  print(test_list[el])
}

Upvotes: 1

Related Questions