R中某个时间段的平均价格

问题描述

我开始为R着迷,我是时间序列概念的新手。

我有200年时间范围的面板数据,我想计算每个城市10年内的price_average,但是我找不到找到适当方法将其整形为函数的方法。

> all_cities
    month price year     town
110    10  2625 1699   Munich
111    11  2730 1699   Munich
112    12  2782 1699   Munich
113     1    34 1700 Hannover
114     1  2520 1700   Munich
115     2    34 1700 Hannover
116     2  2730 1700   Munich
117     3    33 1700 Hannover
118     3  2765 1700   Munich
119     4    36 1700 Hannover
120     4  3150 1700   Munich

我正在寻找以下形式的返回数据框:

> all_cities_10y
    s.year e.year mean_price    town
1     1690  1699    xxx         Munich
2     1700  1709    xxx         Munich
3     1700  1709    xxx         Hannover

稍后,我想在图中显示数据。但是,我希望这个问题是明确的。我感谢任何建议。
structure(list(month = c(1,1,2,3,4,5,6,7,8,9,10,11,12,4
),price = c(34,2520,34,2730,33,2765,36,3150,3097,3675,24,3360,23,2205,20,2152,21,2590,2567,2415,24),year = c(1700,1700,1701,1701),town = c("Hannover","Munich","Hannover","Hannover"
)),row.names = 113:143,class = "data.frame")

解决方法

这可能对您有用... 我使用了您问题中的数据(请参阅底部答案),但未使用所提供的示例数据,因为它仅包含1700-1709年间隔内的年份。

library( data.table )
#make it a data.table if not already
setDT( DT )
#summarise
DT[,.(mean_proce = mean(price) ),by = .(s.year = floor(year/10)*10,e.year = 9 + floor(year/10)*10,town )]

#    s.year e.year     town mean_proce
# 1:   1690   1699   Munich   2712.333
# 2:   1700   1709 Hannover     34.250
# 3:   1700   1709   Munich   2791.250

使用的样本数据

DT <- fread("    month price year     town
    10  2625 1699   Munich
    11  2730 1699   Munich
    12  2782 1699   Munich
     1    34 1700 Hannover
     1  2520 1700   Munich
     2    34 1700 Hannover
     2  2730 1700   Munich
     3    33 1700 Hannover
     3  2765 1700   Munich
     4    36 1700 Hannover
     4  3150 1700   Munich")

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...