How to avoid R converting dates to numeric in a for loop? This is related to this question that shows the same behavior for mapply disabling mapply automatically converting Dates to numeric
date <- c('2008-02-20','2009-10-05')
date <- as.Date(date, format = '%Y-%m-%d')
date
[1] "2008-02-20" "2009-10-05"
for (i in date) print(i)
[1] 13929
[1] 14522
disabling mapply automatically converting Dates to numeric
I have reopened this question since the duplicate Looping over a datetime object results in a numeric iterator asks why R loops convert date and datetime objects to numeric, this question asks how to avoid that behavior. And the answer is to the point solving the problem, unlike the accepted and other answers in the duplicate, that correctly answer that other question.
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.
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.
Date objects in RDate objects are stored in R as integer values, allowing for dates to be compared and manipulated as you would a numeric vector. Logical comparisons are a simple. When referring to dates, earlier dates are “less than” later dates.
You can use the as. Date( ) function to convert character data to dates. The format is as. Date(x, "format"), where x is the character data and format gives the appropriate format.
The for
loop coerces the sequence to vector, unless it is vector, list, or some other things. date
is not a vector, and there is no such thing as vector of dates. So you need as.list
to protect it from coercion to vector:
for (d in as.list(date)) print(d)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With