1

I have data of date and I want to extract the month's name and its year:

>head(merged.tables$Date)

 2015-07-31
 2013-01-12
 2014-01-03
 2014-12-03
 2013-11-13
 2013-10-27

In other word I need to get the result arranged in ascending order like this:

January_2013
 October_2013
 November_2013
 January_2014
 December_2014
 July_2015

So I tried to use this code to convert first as shown in the code above.

merged.tables$Date <-paste(months(as.Date(merged.tables$Date)),year(as.Date(merged.tables$Date)),sep="_")

But It show me this error:

Error in charToDate(x) : character string is not in a standard unambiguous format

I tried to adapt this solution character string is not in a standard unambiguous format. But I can't resolve it!

Thank you for your help

Terru_theTerror
  • 4,918
  • 2
  • 20
  • 39
user8810618
  • 115
  • 11

2 Answers2

0

Try this (passing your date to character):

merged.tables$Date <-paste(months(as.Date(as.character(merged.tables$Date))),year(as.Date(as.character(merged.tables$Date))),sep="_")

If you build your data.frame like this, you don't have that error:

merged.tables<-data.frame(Date=c("2015-07-31","2013-01-12",
"2014-01-03",
"2014-12-03",
"2013-11-13",
"2013-10-27"))

I suppose that the problem is related to the class of your data.

Ordering:

merged.tables$Date2 <-paste(months(as.Date(as.character(merged.tables$Date))),year(as.Date(as.character(merged.tables$Date))),sep="_")

merged.tables[order(merged.tables$Date),]
        Date         Date2
2 2013-01-12  gennaio_2013
6 2013-10-27  ottobre_2013
5 2013-11-13 novembre_2013
3 2014-01-03  gennaio_2014
4 2014-12-03 dicembre_2014
1 2015-07-31   luglio_2015
Terru_theTerror
  • 4,918
  • 2
  • 20
  • 39
0

You can use order on the original dates to get the correct order.
First, read in your data example.

Date <- scan(what = character(), text = '
2015-07-31
 2013-01-12
 2014-01-03
 2014-12-03
 2013-11-13
 2013-10-27')
Date <- as.Date(Date)

Now, reformat and order them.

inx <- order(Date)
newDate <- format(Date, format = "%B_%Y")[inx]
newDate
#[1] "January_2013"  "October_2013"  "November_2013" "January_2014" 
#[5] "December_2014" "July_2015"

Note that this assumes that the dates are of class Date.

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66