在 xts 中按 period.apply() 分组 [英] Group by period.apply() in xts

查看:26
本文介绍了在 xts 中按 period.apply() 分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 4 个变量(2 个 id 变量和 2 个度量)的 xts 对象:

Hi i have an xts object with 4 variables (2 id vars and 2 measures):

> head(mi_xts)

                     squareId country     smsIN     smsOUT
2013-12-01 00:00:00     9999      39 0.4953734 0.93504713
2013-12-01 00:10:00     9999      39 0.1879042 0.50057622
2013-12-01 00:20:00     9996      39 0.5272736 0.25643745
2013-12-01 00:30:00     9996      39 0.0965593 0.25249854
2013-12-01 00:40:00     9999      39 1.2104980 0.49123277
2013-12-01 00:50:00     9999      39 0.4756599 0.09913715

我想使用一个 period.apply,它每天按 squareId(我不关心国家/地区)返回 smsIN 和 smsOUT 组的平均值.我刚刚写了这段代码:

i'd like to use a period.apply that returns the mean of smsIN and smsOUT group by squareId (i don't care about country) per days. I just wrote this code:

days <- endpoints(mi_xts, on = "days")
mi_xts.1d<- period.apply(mi_xts, INDEX = days, FUN = mean)

但显然我只得到 1 行结果:

but obviously i get only 1 row result:

                    squareId country     smsIN    smsOUT
2013-12-01 23:50:00   9995.5      39 0.8418086 0.6644908

有什么建议吗?

推荐答案

您需要通过 "squareId" split,使用 apply.daily 聚合code>,然后 rbind 将所有内容重新组合在一起.

You need to split by "squareId", aggregate using apply.daily, then rbind everything back together.

s <- split(mi_xts, mi_xts$squareId)
a <- lapply(s, function(x) apply.daily(x, mean))
r <- do.call(rbind, a)

这篇关于在 xts 中按 period.apply() 分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆