简体   繁体   English

日期在R中不起作用

[英]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. 因此, "Sep 20, 2010", "Mar 5, 2011", "Mar 9, 2011"等等。 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. 我也尝试了sort(date),但是它按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. 您需要的是as.Date()函数中的format=参数。 So if date is a vector defined as in your post, you can do 因此,如果date是您帖子中定义的向量,则可以

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

%b is the abbreviated month name, eg Mar %b是缩写的月份名称,例如Mar

%d is the numeric day of the month %d是月份中的数字天

%Y is the year %Y是年份

Using the sort() function should then correctly sort the vector ascending by calendar date. 然后,使用sort()函数应按日历日期对升序的向量进行正确排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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