提取每组平均值随时间的变化

问题描述 投票:0回答:1

我有一个数据表,根据该数据表,我计算出平均值sales如下:

library(data.table)
DT <- fread(
"ID country year sales industry size cat4
1   NLD   2000  4   A   1   0
2   NLD   2000  4   B   1   1
3   NLD   2006  2   A   1   1
4   NLD   2002  4   A   1   0
5   NLD   2002  4   B   1   1
6   NLD   2006  2   A   1   1
7   NLD   2006  2   B   2   0
8   NLD   2006  1   A   1   4
9   GBR   2001  2   B   3   5
10  GBR   2001  1   B   2   5
11  GBR   2002  1   A   1   11
12  GBR   2006  1   A   1   2
13  GBR   2006  1   B   3   12
14  GBR   2006  1   A   1   2
15  GBR   2006  1   B   3   12",
header = TRUE)

setDT(DT)[,Mean_Sales:= mean(sales, na.rm=TRUE),  by=c("country", "industry", "size")]

但是,现在我对Mean_Sales随时间的变化感兴趣,每组:by=c("iso3c", "industry", "size")

我想取mean of the absolute differences除以​​它们分开的年份。

例如,对于A行业的NLD中规模为1的公司,其构成为ID = 1和ID = 8,我想要绝对差的平均值(|1-4|=3)除以年份(2006-2000 = 6)。导致3/6 = 0.5的平均值逐年变化。

我只是无法弄清楚如何将其纳入R代码。任何帮助将不胜感激。

所需的输出:

library(data.table)
DT <- fread(
"ID country year sales industry size cat4 delta
1   NLD   2000  4   A   1   0   0.5
2   NLD   2000  4   B   1   1   0.33
3   NLD   2006  2   A   1   1
4   NLD   2002  4   A   1   0
5   NLD   2002  4   B   1   1
6   NLD   2006  2   A   1   1
7   NLD   2006  2   B   1   0   0.33
8   NLD   2006  1   A   1   4   0.5
9   GBR   2001  2   B   3   5
10  GBR   2001  1   B   2   5
11  GBR   2002  1   A   1   11
12  GBR   2006  1   A   1   2
13  GBR   2006  1   B   3   12
14  GBR   2006  1   A   1   2
15  GBR   2006  1   B   3   12",
header = TRUE)
r mean variations
1个回答
0
投票

您可以将order乘以year并获得lastfirst之间的绝对差,然后将sales值除以year中的差。

library(data.table)

DT[order(year), delta := abs(last(sales) - first(sales))/(max(year) - min(year)), 
               .(country, industry, size)]
© www.soinside.com 2019 - 2024. All rights reserved.