Looping through vector of dates in R drops class i

2020-04-14 09:07发布

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

3条回答
在下西门庆
2楼-- · 2020-04-14 09:30

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])
}
查看更多
霸刀☆藐视天下
3楼-- · 2020-04-14 09:31

You can also use as_date function from lubridate.

library(lubridate)

for(i in dates_list){
   print(as_date(i))
}

[1] "2018-11-11"
[1] "2016-01-01"
查看更多
倾城 Initia
4楼-- · 2020-04-14 09:35

The cause of the problem could be that dates_list <- my_df$col_2 coerces the column to a date vector:

dates_list <- my_df$col_2
class(dates_list)
> [1] "Date"

so another solution would be to resolve this, as follows:

dates_list <- my_df["col_2"]
class(dates_list)
[1] "data.frame"

for(el in dates_list){
    print(el)
}
[1] "2018-11-11" "2016-01-01"
查看更多
登录 后发表回答