Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to convert Month-Year string to Date in R

Tags:

r

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.

enter image description here

like image 933
Nyxynyx Avatar asked Nov 06 '15 17:11

Nyxynyx


People also ask

How do I convert a string to a valid date format in R?

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.

How do you convert a character string with only month and year into date?

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.

How do you change character data to date 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.

What is POSIXct format in R?

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.


1 Answers

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"))
like image 140
Lucas Fortini Avatar answered Sep 22 '22 01:09

Lucas Fortini