Extract Month and Year From Date in R

前端 未结 4 423
[愿得一人]
[愿得一人] 2020-11-27 15:31

I have tried a number of methods to no avail. I have data in terms of a date (YYYY-MM-DD) and am trying to get in terms of just the month and year, such as: MM-YYYY or YYYY-

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 16:15

    Here's another solution using a package solely dedicated to working with dates and times in R:

    library(tidyverse)
    library(lubridate)
    
    (df <- tibble(ID = 1:3, Date = c("2004-02-06" , "2006-03-14", "2007-07-16")))
    #> # A tibble: 3 x 2
    #>      ID Date      
    #>         
    #> 1     1 2004-02-06
    #> 2     2 2006-03-14
    #> 3     3 2007-07-16
    
    df %>%
      mutate(
        Date = ymd(Date),
        Month_Yr = format_ISO8601(Date, precision = "ym")
      )
    #> # A tibble: 3 x 3
    #>      ID Date       Month_Yr
    #>            
    #> 1     1 2004-02-06 2004-02 
    #> 2     2 2006-03-14 2006-03 
    #> 3     3 2007-07-16 2007-07
    

    Created on 2020-09-01 by the reprex package (v0.3.0)

提交回复
热议问题