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?
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.
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.
Method 1: Use as.numeric() as. This will return the number of seconds that have passed between your date object and 1/1/1970.
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.
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"
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