rdataframedplyrtime-seriestsibble

How to convert monthly data as.date type variable in R?


I have monthly data and want to convert period columns as.date in r. In addition, rows are not ordered according to time in data frame

df <- data.frame (period  = c("March 2019", "February 2019", "January 2019", "May 2019","April 2019","August 2019","June 2019","July 2019","November 2019","September 2019","October 2019","December 2019"),sales  = rnorm(12))

           period        sales
1      March 2019  1.841711557
2   February 2019  0.403043685
3    January 2019  0.524417978
4        May 2019  0.236378511
5      April 2019 -0.099441313
6     August 2019  0.001731664
7       June 2019  0.792067260
8       July 2019 -0.352379347
9   November 2019  1.174681909
10 September 2019  0.075480279
11   October 2019 -0.258695621
12  December 2019 -1.775315927

Solution

  • Using as.Date with appropriate format on pasted 1 to period, then order.

    transform(dat, period=as.Date(paste(1, period), '%d %b %Y')) |>
      {\(.) .[order(.$period), ]}()
    #        period      sales
    # 1  2019-01-01 0.25542882
    # 5  2019-02-01 0.11748736
    # 10 2019-03-01 0.98889173
    # 6  2019-04-01 0.47499708
    # 2  2019-05-01 0.46229282
    # 8  2019-06-01 0.90403139
    # 12 2019-07-01 0.08243756
    # 7  2019-08-01 0.56033275
    # 4  2019-09-01 0.97822643
    # 9  2019-10-01 0.13871017
    # 11 2019-11-01 0.94666823
    # 3  2019-12-01 0.94001452
    

    Data:

    set.seed(42)
    dat <- data.frame(period=sample(paste(month.name, 2019)), 
                      sales=runif(12))