如何在数据框中设置列的数据类型

How to set data type of column in data frame

我有这样的专栏:

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

我想将 periodperiod2 列的类型更改为日期,以便稍后在时间序列分析中使用

数据:

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)
)

使用 lubridate 包,您可以将它们转换为日期变量:

   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))