Format Date to Year-Month in R

前端 未结 3 993
执笔经年
执笔经年 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条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 23:54

    You can solve this with zoo::as.yearmon() function. Follows the solution:

    library(tidyquant)
    library(magrittr) 
    library(dplyr)
    
    df <- data.frame(Date=c("2017-01-01","2017-01-02","2017-01-03","2017-01-04",
                      "2018-01-01","2018-01-02","2018-02-01","2018-03-02"),
               N=c(24,10,13,12,10,10,33,45))
    df %<>% mutate(Date = zoo::as.yearmon(Date))
    

提交回复
热议问题