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

后端 未结 7 952
自闭症患者
自闭症患者 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:18

    I think @ben-rollert's solution is a good solution.

    You just have to be careful if you want to use this solution in a function inside a new package.

    When developping packages, it's recommended to use the syntaxe packagename::function_name() (see http://kbroman.org/pkg_primer/pages/depends.html).

    In this case, you have to use the version of as.Date() defined by the zoo library.

    Here is an example :

    > devtools::session_info()
    Session info ----------------------------------------------------------------------------------------------------------------------------------------------------
     setting  value                       
     version  R version 3.3.1 (2016-06-21)
     system   x86_64, linux-gnu           
     ui       RStudio (1.0.35)            
     language (EN)                        
     collate  C                           
     tz                               
     date     2016-11-09                  
    
    Packages --------------------------------------------------------------------------------------------------------------------------------------------------------
    
     package  * version date       source        
     devtools   1.12.0  2016-06-24 CRAN (R 3.3.1)
     digest     0.6.10  2016-08-02 CRAN (R 3.2.3)
     memoise    1.0.0   2016-01-29 CRAN (R 3.2.3)
     withr      1.0.2   2016-06-20 CRAN (R 3.2.3)
    
    > as.Date(zoo::as.yearmon("1989-10", "%Y-%m")) 
    Error in as.Date.default(zoo::as.yearmon("1989-10", "%Y-%m")) : 
      do not know how to convert 'zoo::as.yearmon("1989-10", "%Y-%m")' to class “Date”
    
    > zoo::as.Date(zoo::as.yearmon("1989-10", "%Y-%m"))
    [1] "1989-10-01"
    

    So if you're developping a package, the good practice is to use :

    zoo::as.Date(zoo::as.yearmon("1989-10", "%Y-%m"))
    

提交回复
热议问题