Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid R converting dates to numeric automatically?

Tags:

r

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

Edit

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.

like image 328
dleal Avatar asked Dec 13 '16 05:12

dleal


People also ask

How do you keep date format 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.

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.

Are dates numeric in R?

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.

How do I change date type in R?

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.


1 Answers

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)
like image 180
user31264 Avatar answered Oct 20 '22 20:10

user31264