Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the rules involved in coercing dates with the c() function

Tags:

date

r

coercion

As I understand when the objects being concatenated with the c(...) function are of different types they are coerced into a single type which is the type of the output object

According the the R documentation

The output type is determined from the highest type of the components in the hierarchy NULL < raw < logical < integer < double < complex < character < list < expression.

Dates have a data type of double so if paired with a character should result in a character, if paired with an integer should result in a double, as we can see here

> a<-as.Date("2019-01-01")
> c("a",a)
[1] "a"     "17901"
> c(1L,a)
[1]     1 17901
> typeof(c(1L,a))
[1] "double"

However if the date is first the function tries to convert the other values to class Date. This does not seem to match the behaviour from the documentation

> c(a,1)
[1] "2019-01-05" "1970-01-02"
> c(a,"a")
[1] "2019-01-05" NA
Warning message: In as.POSIXlt.Date(x) : NAs introduced by coercion

What additional rules are being applied here? Or alternatively what have I misunderstood about the situation?

like image 751
Iain Paterson Avatar asked Oct 10 '19 15:10

Iain Paterson


People also ask

What class are dates in R?

R has developed a special representation for dates and times. Dates are represented by the Date class and times are represented by the POSIXct or the POSIXlt class.

What is the use of date and time function in R?

time() and Sys. timezone() Function. date() function in R Language is used to return the current date and time.

Which function we use to create date time from the text representation in R?

strftime() function in R Language is used to convert the given date and time objects to their string representation.

How does R handle dates?

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.


1 Answers

Functions can be "overloaded" in R based on the data type of the first parameter. You can see there is a special c.Date function that is run when you call c with Date object as the first parameter. You can see all the "special" c() functions with methods("c"). These functions can (and do) define different rules than the base c() function. But since overloading only happens based on the data type of the first parameter, the order in which the values appear makes a big difference.

like image 182
MrFlick Avatar answered Sep 28 '22 21:09

MrFlick