Extract Month and Year From Date in R

前端 未结 4 418
[愿得一人]
[愿得一人] 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:29

    This will add a new column to your data.frame with the specified format.

    df$Month_Yr <- format(as.Date(df$Date), "%Y-%m")
    
    df
    #>   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
    
    # your data sample
      df <- data.frame( ID=1:3,Date = c("2004-02-06" , "2006-03-14" , "2007-07-16") )
    

    a simple example:

    dates <- "2004-02-06"
    
    format(as.Date(dates), "%Y-%m")
    > "2004-02"
    

    side note: the data.table approach can be quite faster in case you're working with a big dataset.

    library(data.table)
    setDT(df)[, Month_Yr := format(as.Date(Date), "%Y-%m") ]
    

提交回复
热议问题