Search code examples
rdateconverters

Converting date in R


I want to convert those dates as this format "1995-01", "1995-02", etc.

Here is some of my data

              Date     Change
1     January-1995 0.01417476
2    February-1995 0.01427050
3       March-1995 0.01556348
4       April-1995 0.01644737
5         May-1995 0.01603727
6        June-1995 0.01627500
7        July-1995 0.01557800
8      August-1995 0.01429773
9   September-1995 0.01344300
10    October-1995 0.01334667
11   November-1995 0.01328429
12   December-1995 0.01345368
13    January-1996 0.01293091
14   February-1996 0.01301762
15      March-1996 0.01289048
16      April-1996 0.01268476
17        May-1996 0.01287364
18       June-1996 0.01253400
19       July-1996 0.01254591
20     August-1996 0.01271238
21  September-1996 0.01245700
22    October-1996 0.01201636
23   November-1996 0.01191300
24   December-1996 0.01195600

I tried this :

date <- as.Date(Data$Date,format="%B/%Y")

and this

date <- as.Date(paste0("01/", Data$Date),format = "%m/%Y")

But it juste return me

[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

I'm stuck!


Solution

  • The last option can be modified to include the %d for day when we are pasteing the day. Also, in format, specify the correct delimiter and %B- (Full month name) where as %m- month as decimal number)

    as.Date(paste0("01/", Data$Date),format = "%d/%B-%Y")
    

    Or use lubridate

    library(lubridate)
    my(Data$Date)
    my("January-1995")
    [1] "1995-01-01"