简体   繁体   中英

as.Date not working in R

I have a data set that has dates in the following format. There are some repeated dates too. I need to sort the data according to the dates in calendar order. So "Sep 20, 2010", "Mar 5, 2011", "Mar 9, 2011" and so on. I tried the following but it gives me an error.

as.Date(date)
Error in charToDate(x) : 
  character string is not in a standard unambiguous format

I also tried sort(date) but it sorts the date alphabetically by Month. How can I sort this type of dates in calendar order ?

date<-c("Mar  9, 2011", "Sep 30, 2011", "Sep 20, 2010", "Mar  5, 2012", "Jul 11, 2012", 
        "Jul 11, 2012","Mar 26, 2013", "Sep 23, 2013", "Apr  7, 2011", "Apr 22,  2013", 
        "Apr 26, 2012")

What you need is the format= argument in the as.Date() function. So if date is a vector defined as in your post, you can do

date <- sort(as.Date(date, format="%b %d, %Y"))

%b is the abbreviated month name, eg Mar

%d is the numeric day of the month

%Y is the year

Using the sort() function should then correctly sort the vector ascending by calendar date.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM