Quoting by date in R loses format

It disappointed me. Even with lubridate I cannot get dates to support their type when I go through them. For instance:

 require(lubridate) yearrange = ymd(20110101) + years(seq(4)) yearrange #[1] "2012-01-01 UTC" "2013-01-01 UTC" "2014-01-01 UTC" "2015-01-01 UTC" class(yearrange) #[1] "POSIXct" "POSIXt" 

However, if I try to go through the years (creating a separate schedule for each year in my data set): I lose the formatting of the year and will have to redisplay the data

 for (yr in yearrange) { show(yr) } #[1] 1325376000 #[1] 1356998400 #[1] 1388534400 #[1] 1420070400 

If I loop through with indexes, I return date objects:

 for (i in seq(length(yearrange))) { show(yearrange[i]) } #[1] "2012-01-01 UTC" #[1] "2013-01-01 UTC" #[1] "2014-01-01 UTC" #[1] "2015-01-01 UTC" 

Is there an easy way to avoid indexing without using foreach , or is this the only way?

+6
source share
2 answers

try it

 for (yr in as.list(yearrange)) { show(yr) } 

I think that for (yr in yearrange) forces the yearrange to the vector and POSIXct does not apply to the supported types that the vector enters.

+7
source

lapply doesn't seem to have the same problem, for example:

 for (x in yearrange) plot(1, main=x) #Main title = 1420070400 lapply( yearrange, function(x) plot(1, main=x) ) #Main title = 2015-01-01 
+2
source

Source: https://habr.com/ru/post/986258/


All Articles