Format Date to Year-Month in R

前端 未结 3 966
执笔经年
执笔经年 2020-12-17 22:55

I would like to retain my current date column in year-month format as date. It currently gets converted to chr format. I have tried as_datetime but it coerces all values to

3条回答
  •  -上瘾入骨i
    2020-12-17 23:39

    lubridate only handle dates, and dates have days. However, as alistaire mentions, you can floor them by month of you want work monthly:

    library(tidyverse)
    
    df_month <-
      df %>%
      mutate(Date = floor_date(as_date(Date), "month"))
    

    If you e.g. want to aggregate by month, just group_by() and summarize().

    df_month %>%
      group_by(Date) %>%
      summarize(N = sum(N)) %>%
      ungroup()
    
    #> # A tibble: 4 x 2
    #>  Date           N
    #>       
    #>1 2017-01-01    59
    #>2 2018-01-01    20
    #>3 2018-02-01    33
    #>4 2018-03-01    45
    

提交回复
热议问题