I want to combine two variables into one with a date format

后端 未结 5 957
再見小時候
再見小時候 2021-01-26 22:59

I have a data set with a character column for months (MONTH) and a numeric column indicating years (YEAR). In order to work with it as panel data, I ne

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-26 23:27

    If you wish to use a full-on Tidyverse solution, consider this combination of tidyr, and lubridate's parse_date_time:

    library(tidyverse)
    df <- tibble::tribble(
      ~STATE,      ~MONTH,      ~YEAR,   ~VALUE,
    "California",     "JAN",      2018,      800,
    "California",     "FEB",      2018,      780,
    "California",     "MAR",      2018,      600,
    "Minesota",       "JAN",      2018,      800,
    "Minesota",       "FEB",      2018,      780,
    "Minesota",       "MAR",      2018,      600)
    
    df %>%
       tidyr::unite(TIME, c(MONTH, YEAR), sep = "-") %>%
       dplyr::mutate(TIME = lubridate::parse_date_time(TIME, "my"))
    #> # A tibble: 6 x 3
    #>   STATE      TIME                VALUE
    #>                       
    #> 1 California 2018-01-01 00:00:00   800
    #> 2 California 2018-02-01 00:00:00   780
    #> 3 California 2018-03-01 00:00:00   600
    #> 4 Minesota   2018-01-01 00:00:00   800
    #> 5 Minesota   2018-02-01 00:00:00   780
    #> 6 Minesota   2018-03-01 00:00:00   600
    

    Also check out the following related question: Converting year and month ("yyyy-mm" format) to a date?

提交回复
热议问题