Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a mm-yy string "Jan-01" into date format [duplicate]

Tags:

date

r

The date in my original Excel file represents the monthly data in the format of "Jan-01". Of course, I can manually convert them to something more useful in the Excel first and then input that into R.

How can I convert such adate into a Date class in R?

like image 484
Fred Avatar asked May 18 '12 03:05

Fred


People also ask

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.


2 Answers

If you want a date class, use as.Date:

x <- "Jan-01"
as.Date(paste("01-", x, sep = ""), format = "%d-%b-%y")

If you want a POSIXct class, consider using lubridate:

library(lubridate)
x <- "Jan-01"
dmy(paste("01-", x , sep =""))

If you want to just rely on base:

x <- "Jan-01"
as.POSIXct(paste("01-", x, sep = ""), format = "%d-%b-%y")
like image 50
R J Avatar answered Oct 22 '22 03:10

R J


Edit:

The easiest way is to use the yearmon class in zoo:

 require(zoo)
 as.yearmon(x, "%b-%y")
#[1] "Jan 2001"

Somewhat longer method:

 x="Jan-01"
 xs<-strsplit(x, "-")
 xd <- as.Date( xs[[1]][2], paste( xs[[1]][1], "01",  sep="-"), format="%y-%b-%d")
 xd
#[1] "2001-01-01"

If you want to process a string of dates, then you may need to use sapply if picking the second method to make a vector of years and a vector of months

like image 25
IRTFM Avatar answered Oct 22 '22 02:10

IRTFM