Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through vector of dates in R drops class info

Tags:

date

loops

r

vector

Here is my example.

my_df <- data.frame(col_1 = c(1,2), 
col_2 = c(as.Date('2018-11-11'), as.Date('2016-01-01')))
dates_list <- my_df$col_2
for(el in dates_list){
  print(el)
}

It generates:

17846
16801

How do I output dates instead? I can do it with explicit index, but would like to have simpler solution

like image 999
user1700890 Avatar asked Oct 16 '25 08:10

user1700890


1 Answers

1) Use as.list:

for(el in as.list(dates_list)) {
  print(el)
}

giving:

[1] "2018-11-11"
[1] "2016-01-01"

2) or not quite as nice but one can iterate over the indexes:

for(i in seq_along(dates_list)) {
  print(dates_list[i])
}
like image 91
G. Grothendieck Avatar answered Oct 18 '25 07:10

G. Grothendieck