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

发布于 2025-01-20 14:22:48 字数 499 浏览 0 评论 0原文

我有这样的列:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墨小沫ゞ 2025-01-27 14:22:48

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

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))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文