[R] Combining month and year into a single variable

Sam Albers tonightsthenight at gmail.com
Wed Feb 1 23:26:00 CET 2012


Hello all,

## I am trying to convert some year and month data into a single
variable that has a date format so I can plot a proper x axis.
## I've made a few tries at this and search around but I haven't found
anything. I am looking for something of the format "%Y-%m"

## A data.frame
df <- data.frame(x=rnorm(36, 1, 10), month=rep(1:12, each = 3),
year=c(2000,2001,2002))

## One option. I'm not totally sure why this doesn't work
df$Date <- as.Date(paste(df$year, df$month,sep="-"), "%Y-%m")

## This adds the monthly total to the day rather than the MOnday and this option
## is messy anyway as I am adding a day to the variable
or = format(ISOdate(df$year-1, 12, 31), "%Y-%m-%d")
df$Date2 = as.Date(or) + df$month

## Just a plot to illustrate this.
plot(x~Date2, data=df)

## Any thoughts on how I can combine the year and the month into a
form that is useful for plotting?

Thanks in advance!

Sam



More information about the R-help mailing list