首页 > 解决方案 > 使用 groupby 中的 yearmonth 列创建时间序列 R

问题描述

df有列:yearmonth, store, item, sales.

group1:键商店、商品和年月的聚合 df 并计算每个商店、商品和年月组合的 total_sales。

预期输出:使用 group1 yearmonth 将此 groupby 输出转换为时间序列,列中没有任何 NAN 值。

groupby 前 3 行:groupby 对象的名称:group1

[IN]group1
[out]
 store  item yearmonth total_sales
   <int> <int> <chr>           <int>
 1     1     1 2013-01           328
 2     1     1 2013-02           322
 3     1     1 2013-03           477  and so on

#Converting yearmonth to datetime before converting group1 to time series
group1$yearmonth = as.Date(as.yearmon(as.character(group1$yearmonth),"%Y-%m"), frac = 0)

尝试将 groupby 输出转换为时间序列:

      > as.ts(group1)
Time Series:Start = 1 End = 30000 Frequency = 1 
      store item yearmonth total_sales
    1     1    1        NA         328
    2     1    1        NA         322
    3     1    1        NA         531 and so on...

如何在不获取这些 NAN 值的情况下使用 groupby yearmonth 作为键并创建时间序列对象?

标签: r

解决方案


我们可以删除该yearmonth列并将其添加为xts对象中的索引。

ts_group <- xts::xts(group1[setdiff(names(group1), 'yearmonth')],
                as.Date(paste0(group1$yearmonth, "-01")))

#           store item total_sales
#2013-01-01     1    1         328
#2013-02-01     1    1         322
#2013-03-01     1    1         477

或者使用zoo图书馆。

library(zoo)
ts_group <- zoo(group1[setdiff(names(group1), 'yearmonth')], 
                       as.yearmon(group1$yearmonth))

推荐阅读