Abraham Mathew
2013-Nov-05 16:00 UTC
[R] Convert date column with two different structures
Let's say I have the following data frame and the date column has two different ways in which date is presented. How can I use as.Date or the lubridate package to have one date structure for the entire colum df = data.frame(Date=c("5/1/13","8/1/13","9/1/13","Apr-10", "Apr-11","Apr-12","Apr-13")) It's "month/date/year" and "month-year". An alternative approach would be to perform some conditional statements where if the date is "Apr-11", then populate it with "04/01/2011". [[alternative HTML version deleted]]
Hello, Try the following. idx <- grep("[[:alpha:]]", df$Date) Date <- as.Date(df$Date, "%m/%d/%y") Date[idx] <- as.Date(paste("01", df$Date[idx]), "%d %b-%y") Hope this helps, Rui Barradas Em 05-11-2013 16:00, Abraham Mathew escreveu:> Let's say I have the following data frame and the date column has two > different ways in which date is presented. How can I use as.Date or the > lubridate package to have one date structure for the entire colum > > df = data.frame(Date=c("5/1/13","8/1/13","9/1/13","Apr-10", > > "Apr-11","Apr-12","Apr-13")) > It's "month/date/year" and "month-year". > > An alternative approach would be to perform some conditional statements > where if the date is "Apr-11", then populate it with "04/01/2011". > > [[alternative HTML version deleted]] > > ______________________________________________ > 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. >
HI, You could try: library(lubridate) Date1 <- mdy(as.character(df[,1])) ?Date1[is.na(Date1)] <- parse_date_time(paste(1,as.character(df[,1][is.na(Date1)]),sep="-"),"%d-%b-%y") A.K. On Tuesday, November 5, 2013 12:38 PM, Abraham Mathew <abmathewks at gmail.com> wrote: Let's say I have the following data frame and the date column has two different ways in which date is presented. How can I use as.Date or the lubridate package to have one date structure for the entire colum df = data.frame(Date=c("5/1/13","8/1/13","9/1/13","Apr-10", ? ? ? ? ? ? ? "Apr-11","Apr-12","Apr-13")) It's "month/date/year" and "month-year". An alternative approach would be to perform some conditional statements where if the date is "Apr-11", then populate it with "04/01/2011". ??? [[alternative HTML version deleted]] ______________________________________________ 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.