I'm using as.Date
to convert a string like Aug-2002
to a dates object representing just the month of Aug of 2002, or if a day must be specified, Aug 1, 2002.
However
> as.Date(c('07-2002'), "%M-%Y")
[1] "2002-11-06"
> as.Date(c('Aug-2002'), "%b-%Y")
[1] NA
Why does the first line of code convert it to a different month and day? And the second one is NA
?
I referred to this table for the formatting symbols.
The as. Date() function will convert a string into date format, and the format of the output will always be in yyyy-mm-dd format in R (ISO 8601). The format argument in the as. Date() function is to specify the date format of the string input.
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.
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.
POSIXct stores date and time in seconds with the number of seconds beginning at 1 January 1970. Negative numbers are used to store dates prior to 1970. Thus, the POSIXct format stores each date and time a single value in units of seconds. Storing the data this way, optimizes use in data.
The problem you are having is that the dates you have do not have a day value. Without the day value the format="%m-%Y"
will not work in as.Date
. These options below will solve them:
as.Date(paste0('01-', c('07-2002')), format="%d-%m-%Y")
library(zoo) #this is a little more forgiving:
as.yearmon(c('07-2002'), "%m-%Y")
as.yearmon(c('Aug-2002'), "%b-%Y")
as.Date(as.yearmon(c('07-2002'), "%m-%Y"))
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