1
$\begingroup$

Can we draw time series plot with only month and year in R? I don't have date variable in my dataset.

Dataset looks like this-

month  year     percentage
1      2012      34%
2      2012      55%
.
.
.
.
1     2013      15%
$\endgroup$

1 Answer 1

1
$\begingroup$

I would convert it to a date column using paste and as.Date setting it to the first of the month.

> df <- data.frame('month'=c(1,2,3,1,2), year=c(2012, 2012, 2012, 2013, 2013))

> df
  month year
1     1 2012
2     2 2012
3     3 2012
4     1 2013
5     2 2013

> df[, 'date_col'] <- as.Date(paste(1, df$month, df$year), '%d %m %Y')

> df
  month year   date_col
1     1 2012 2012-01-01
2     2 2012 2012-02-01
3     3 2012 2012-03-01
4     1 2013 2013-01-01
5     2 2013 2013-02-01

EDIT: If you don't want first of the month as a place holder, you can use as.yearmon from the zoo package

> as.yearmon(paste(df$month, df$year), '%m %Y')
[1] "Jan 2012" "Feb 2012" "Mar 2012" "Jan 2013" "Feb 2013"
$\endgroup$
2
  • $\begingroup$ Thank you for the reply. So you are taking date as 1 for each month. But for the present data, its said that there are 4 services .first service started somewhere in Jan, second service somewhere in May and so on..Then I cannot take 1st as date. Can we just include month and year? $\endgroup$
    – pinky
    Mar 18, 2016 at 16:58
  • $\begingroup$ I would highly recommend setting the day as a place holder even if its not exact, but if you use the zoo package you can use as.yearmon. Here is an example. stackoverflow.com/questions/10446833/… $\endgroup$
    – dmb
    Mar 18, 2016 at 17:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.