r - 使用 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 作为键并创建时间序列对象?
解决方案
我们可以删除该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))
推荐阅读
- python - 我如何在 Pyramid 中的 .ini 文件上使用环境变量?
- string - 使用 InStr 方法检查文件名中是否存在字符串
- apache - 如何在 Apache Web 服务器上调试 SSL 客户端身份验证
- css - 无法在容器中成功地将按钮居中
- java - 将同一列表上的嵌套 for 循环移植到 Java 流
- c - 为什么我的程序会跳过 gets() 函数?
- proxy - 如何确定由 IE 外部的 wpad.dat 确定的正在使用的特定代理
- php - 通过引用传递数组并更改其值
- php - 使用 PhpSpreadsheet 写入 Excel 文件
- html - Flexbox - div内的响应右对齐UL?