如何根据R中另一列的类别多次求和一列的值

  • 本文关键字:一列 求和 何根 r loops sum longitudinal
  • 更新时间 :
  • 英文 :


我想我的问题有点奇怪,让我试着解释一下。我需要为一个关于粮食供应和国际商业的纵向数据库(连续29年(求解一个简单的方程:(importations-exportations)/(production+importations-exportations)*100(粮农组织的粮食依赖系数方程(。最大的问题是,我的数据库中的食品及其利益价值(生产、进口和出口(不一致,所以我需要找到一种方法,将该方程应用于每年的利益价值总和,这样我就可以得到每年所需的系数。

我的数据帧如下:

element      product   year   value (metric tons)
Production   Wheat     1990   16
Importation  Wheat     1990   2
Exportation  Wheat     1990   1
Production   Apples    1990   80
Importation  Apples    1990   0
Exportation  Apples    1990   72
Production   Wheat     1991   12
Importation  Wheat     1991   20
Exportation  Wheat     1991   0

我想这个解决方案很简单,但我在R方面不够好,无法独自解决这个问题。每一个帮助都是非常受欢迎的。

谢谢!

这是我的R会话的图片

require(data.table)
# dummy table. Use setDT(df) if yours isn't a data table already
df <- data.table(element = (rep(c('p', 'i', 'e'), 3))
, product = (rep(c('w', 'a', 'w'), each=3))
, year = rep(c(1990, 1991), c(6,3))
, value = c(16,2,1,80,0,72,12,20,0)
); df
element product year value
1:       p       w 1990    16
2:       i       w 1990     2
3:       e       w 1990     1
4:       p       a 1990    80
5:       i       a 1990     0
6:       e       a 1990    72
7:       p       w 1991    12
8:       i       w 1991    20
9:       e       w 1991     0

# long to wide
df_1 <- dcast(df
, product + year ~ element
, value.var = 'value'
); df_1
# apply calculation
df_1[, food_depend_coef := (i-e) / (p+i-e)*100][]
product year  e  i  p food_depend_coef
1:       a 1990 72  0 80      -900.000000
2:       w 1990  1  2 16         5.882353
3:       w 1991  0 20 12        62.500000

最新更新