[R] question about formatting Dates

David L Carlson dcarlson at tamu.edu
Wed Jun 27 16:52:16 CEST 2012


How about

> dates <- as.factor(c("1/2/2011", "1/4/2011", "1/4/2011", "1/4/2011",
"1/6/2011", "1/7/2011", "1/8/2011", "1/9/2011", "1/10/2011"))
> dates
[1] 1/2/2011  1/4/2011  1/4/2011  1/4/2011  1/6/2011  1/7/2011  1/8/2011 
[8] 1/9/2011  1/10/2011
Levels: 1/10/2011 1/2/2011 1/4/2011 1/6/2011 1/7/2011 1/8/2011 1/9/2011

> format(as.Date(dates, "%m/%d/%Y"), "%m/%d/%Y")
[1] "01/02/2011" "01/04/2011" "01/04/2011" "01/04/2011" "01/06/2011"
[6] "01/07/2011" "01/08/2011" "01/09/2011" "01/10/2011"


----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Erin Hodgess
> Sent: Tuesday, June 26, 2012 10:54 PM
> To: R help
> Subject: [R] question about formatting Dates
> 
> Dear R People:
> 
> I have dates as factors in the following:
> 
> > poudel.df$DATE
> [1] 1/2/2011  1/4/2011  1/4/2011  1/4/2011  1/6/2011  1/7/2011
> 1/8/2011
> [8] 1/9/2011  1/10/2011
> Levels: 1/10/2011 1/2/2011 1/4/2011 1/6/2011 1/7/2011 1/8/2011 1/9/2011
> >
> 
> I want them to be "regular" dates which can be sorted, etc.
> 
> But when I did this:
> 
> > as.character(poudel.df$DATE)
> [1] "1/2/2011"  "1/4/2011"  "1/4/2011"  "1/4/2011"  "1/6/2011"
> "1/7/2011"
> [7] "1/8/2011"  "1/9/2011"  "1/10/2011"
> 
> and
> > as.Date(as.character(poudel.df$DATE),"%m/%d/$Y")
> [1] NA NA NA NA NA NA NA NA NA
> 
> because the dates do not have leading zeros.
> 
> There are approximately 30 years of nearly daily data in the entire
> set.
> 
> Any suggestions would be much appreciated.
> 
> Sincerely,
> Erin
> 
> 
> --
> Erin Hodgess
> Associate Professor
> Department of Computer and Mathematical Sciences
> University of Houston - Downtown
> mailto: erinm.hodgess at gmail.com
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list