8

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?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Fred
  • 579
  • 2
  • 4
  • 13
  • As mentioned clearly in the title, it's month and year, not month and date. strptime("Jan-01","%b-%d") [1] "2012-01-01" > strptime("Jan-01","%b-%y") [1] NA – Fred May 18 '12 at 04:52
  • 1
    Add a 1 to the front to represent the first day of the month: `datevar <- "Jan-01"; as.Date(paste("01",datevar,sep="-"),"%d-%b-%y");` – thelatemail May 18 '12 at 05:06

3 Answers3

15

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")
RJ-
  • 2,919
  • 3
  • 28
  • 35
5

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

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Please refer to the title, it's month and year, not month and date. > xd <- as.Date(paste(xs[[1]][1], xs[[1]][2], sep="-"), format="%b-%y") > xd [1] NA > xd <- as.Date(paste(xs[[1]][1], xs[[1]][2], sep="-"), format="%b-%Y") > xd [1] NA > xd <- as.Date(paste(xs[[1]][1], xs[[1]][2], sep="-"), format="d%-%b-%Y") > xd [1] NA – Fred May 18 '12 at 05:08
  • 1
    OK, easy to fix. The format spec for two digit year is %y rather than %Y – IRTFM May 18 '12 at 13:26
0

If you forcibly specify the first day of the month you can convert the dates as so:

datevar <- c("Jan-01","Feb-01","Mar-12")
as.Date(paste("01",datevar,sep="-"),"%d-%b-%y")

It should be noted that this is essentially the same answer as DWin has below, just manually specifying the day instead of the year.

thelatemail
  • 91,185
  • 12
  • 128
  • 188