Group by period.apply() in xts

一笑奈何 提交于 2021-01-27 18:23:36

问题


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

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)

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

Any suggestions?


回答1:


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)


来源:https://stackoverflow.com/questions/43208443/group-by-period-apply-in-xts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!