1

I have been struggling to solve this apparently easy problem, I have a data frame with the following column names:

  names <-  c("2013-1", "2013-10", "2013-11", "2013-12", "2013-2", 
"2013-3", "2013-4", "2013-5", "2013-6", "2013-7", "2013-8", "2013-9", 
"2014-1", "2014-2", "2014-3")

As you can see, the column names are dates (recognized by R as character) and I need to reorder the columns so each column corresponds to the month that comes after the previous one, eg. 2013-1, 2013-2, 2013-3... but since R sees the column names as words and not dates it is ordering it differently, with 2013-10 before 2013-2 for example.

I tried to convert the column names to date using:

as.Date(names, format="%Y-%m")

But R apparently does not recognize this date format and I get NA's. I am still stuck with this ordering no matter what I try so any help would be very appreciated.

Thank you

2 Answers 2

2

You may also have a look at as.yearmon in zoo package. From the help text: "yearmon is a class for representing monthly data."

library(zoo)
x <- as.yearmon(names, format = "%Y-%m")
x

# sort and format output according to taste, e.g.
format(sort(x), "%Y-%m")
# [1] "2013-01" "2013-02" "2013-03" "2013-04" "2013-05" "2013-06" "2013-07" "2013-08" "2013-09"
# [10] "2013-10" "2013-11" "2013-12" "2014-01" "2014-02" "2014-03"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, chose it as answer because solves my problem faster and in a cleaner way.
2

Try

as.Date(paste(names, "-01", sep=""), format="%Y-%m-%d")

and R should see it as a date.

EDIT: If you want to keep your original format, but insert a zero between 1 and 9, you can use strftime:

strftime(as.Date(paste(names, "-01", sep=""), "%Y-%m-%d"), "%Y-%m")

1 Comment

It works, but not exactly as I wanted. Adding manually the day means there is no way that R understands yyyy-mm date format? If possible I would prefer to keep the original format.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.