Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent R from coercing this vector of Dates to numeric?

Tags:

r

When combining a date vector with an NA, R will coerce the whole vector to numeric if NA appears first. If NA does not appear first it will coerce to Date.

x <- Sys.Date()
c(NA, x)
# [1]    NA 16248
c(x, NA)
# [1] "2014-06-27" NA

How can I make it coerce to Date always, regardless of the order the NAs appear? Secondly, what if I do not know the type of x, how can I still be certain that it coerces to the class of the vector x and not numeric?

like image 998
andrew Avatar asked Jun 27 '14 20:06

andrew


People also ask

How do you prevent coercion in R?

One way to deal with this warning message is to simply suppress it by using the suppressWarnings() function when converting the character vector to a numeric vector: What is this? R successfully converts the character vector to a numeric vector without displaying any warning messages.

What does it mean when values get coerced in R?

When you call a function with an argument of the wrong type, R will try to coerce values to a different type so that the function will work. There are two types of coercion that occur automatically in R: coercion with formal objects and coercion with built-in types.

How do I change date format to numeric in R?

Method 1: Use as.numeric() as. This will return the number of seconds that have passed between your date object and 1/1/1970.

How do I change the 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.


1 Answers

This is the result of S3 method dispatch acting on the first argument NA and hence the default method is used which coerces everything up to numerics. The solution is to be explicit about the method to call, in this case c.Date():

x <- Sys.Date()
xx <- c.Date(c.Date(NA, x))
xx
class(xx)

> xx
[1] NA           "2014-06-27"
> class(xx)
[1] "Date"
like image 161
Gavin Simpson Avatar answered Oct 16 '22 12:10

Gavin Simpson