Home > Back-end >  How to set data type of column in data frame
How to set data type of column in data frame

Time:04-10

I have columns like these:

year       period     period2        Sales
2015       201504     April 2015     10000
2015       201505     May 2015       11000
2018       201803     March 2018     12000

I want to change the type of period or period2 column as a date, to use later in time series analysis

Data:

tibble::tibble(
  year = c(2015,2015,2018),
  period  = c(201504, 201505,201803 ),
  period2  =  c("April 2015", "May 2015", "March 2018"),
  Sales = c(10000,11000,12000)
)

CodePudding user response:

Using lubridate package you can transform them into date variables:

   df <- tibble::tibble(
      year = c(2015,2015,2018),
      period  = c(201504, 201505,201803 ),
      period2  =  c("April 2015", "May 2015", "March 2018"),
      Sales = c(10000,11000,12000)
    )
    
    library(dplyr)
    df %>% 
      mutate(period = lubridate::ym(period),
             period2 = lubridate::my(period2))
  • Related