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

后端 未结 5 892
再見小時候
再見小時候 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:18

    You could simplify the below, but it makes it easier to see what's going on:

    library(lubridate)
    library(tidyverse)
    
    df2 <- df %>% 
      mutate(TIME = parse_date_time(paste0(MONTH, YEAR), orders = "%b%Y"),
             TIME = as.character(substr(TIME, 6, 7)),
             TIME = paste0(TIME, "-", YEAR))
    

    This is using lubridate - the easiest way to parse dates in R IMO, dplyr from tidyverse and substr from base R.

    If you want to keep the date column then just pipe in another mutate and call the new column something different.

提交回复
热议问题