Converting year and month (“yyyy-mm” format) to a date?

后端 未结 7 1164
自闭症患者
自闭症患者 2020-11-21 04:55

I have a dataset that looks like this:

Month    count
2009-01  12
2009-02  310
2009-03  2379
2009-04  234
2009-05  14
2009-08  1
2009-09  34
2009-10  2386
         


        
7条回答
  •  耶瑟儿~
    2020-11-21 05:17

    Try this. (Here we use text=Lines to keep the example self contained but in reality we would replace it with the file name.)

    Lines <- "2009-01  12
    2009-02  310
    2009-03  2379
    2009-04  234
    2009-05  14
    2009-08  1
    2009-09  34
    2009-10  2386"
    
    library(zoo)
    z <- read.zoo(text = Lines, FUN = as.yearmon)
    plot(z)
    

    The X axis is not so pretty with this data but if you have more data in reality it might be ok or you can use the code for a fancy X axis shown in the examples section of ?plot.zoo .

    The zoo series, z, that is created above has a "yearmon" time index and looks like this:

    > z
    Jan 2009 Feb 2009 Mar 2009 Apr 2009 May 2009 Aug 2009 Sep 2009 Oct 2009 
          12      310     2379      234       14        1       34     2386 
    

    "yearmon" can be used alone as well:

    > as.yearmon("2000-03")
    [1] "Mar 2000"
    

    Note:

    1. "yearmon" class objects sort in calendar order.

    2. This will plot the monthly points at equally spaced intervals which is likely what is wanted; however, if it were desired to plot the points at unequally spaced intervals spaced in proportion to the number of days in each month then convert the index of z to "Date" class: time(z) <- as.Date(time(z)) .

提交回复
热议问题