Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through date in R loses format

This has been frustrating me. Even with lubridate I can't get dates to maintain their type when I loop over them. For example:

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 loop through years (creating a separate plot for each year in my data set): I lose the formatting of the year, and would have to re-cast the data

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

If I loop though specifying indices, I get date objects back:

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 the indexed option, without using foreach, or is that the only way?

like image 358
beroe Avatar asked Apr 29 '15 23:04

beroe


People also ask

How are dates formatted in R?

To format the dates in R, use the format() function. The format() method accepts an R object and the format in which we want the output. The format() method provides you with formatting an R object for pretty printing. The Dates in R are expressed as the number of days since 1970-01-01.

How do I change date format in R?

To format = , provide a character string (in quotes) that represents the current date format using the special “strptime” abbreviations below. For example, if your character dates are currently in the format “DD/MM/YYYY”, like “24/04/1968”, then you would use format = "%d/%m/%Y" to convert the values into dates.

What is the default date format in R?

Note that the default date format is YYYY-MM-DD; therefore, if your string is of different format you must incorporate the format argument. There are multiple formats that dates can be in; for a complete list of formatting code options in R type ? strftime in your console.


2 Answers

Try this

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

I think for (yr in yearrange) coerces yearrange into a vector and POSIXct is not one of the supported types that vector coerces into.

like image 181
cryo111 Avatar answered Nov 05 '22 00:11

cryo111


lapply doesn't seem to have the same problem, e.g.:

for (x in yearrange) plot(1, main=x)
#Main title = 1420070400
lapply( yearrange, function(x) plot(1, main=x) )
#Main title = 2015-01-01
like image 41
thelatemail Avatar answered Nov 05 '22 00:11

thelatemail