根据多种条件计算SUM并创建新的数据帧

时间:2018-12-03 14:05:56

标签: r dataframe sum

这是我的数据框df的摘录(完整数据框中有更多的国家和地区)

   country.x    year     emissions      etsemit
   Austria      2005     16194772.5     16539659
   Austria      2005     15039192.4     15275065
   Austria      2005     13757090.8     14124646
   Austria      2005     13582006.8     14572511
   Austria      2009     12526267.6     12767555
   Austria      2010     13852187.5     15506112
   Austria      2011     13666544.9     15131551
   Austria      2012     12256272.5     13121434
   Austria      2012     11224625.0      8074514
   Austria      2012      9499543.9      6426135
   Austria      2015     10623549.8      7514263
   Austria      2016     10448925.8      7142937
   Belgium      2005     29246990.2     25460856
   Belgium      2006     28136794.9     24099282
   Belgium      2007     27435552.7     23706084
   Belgium      2009     25344134.8     23166180
   Belgium      2009     25744709.0     21185552
   Belgium      2009     26341043.0     22073616
   Belgium      2011     22921875.0     18950876
   Belgium      2012     22809482.4     17463388
   Belgium      2013     21242431.6     16728267
   Belgium      2013     20375966.8     15230243
   Belgium      2013     21091058.6     16053800
   Belgium      2016     19792162.1     15027777

我想获取每个emissionscountry.x的{​​{1}}之和。结果应该输入到一个新的数据框中,如下所示:

year

我正在努力根据 country.x year emissions Austria 2005 value of calculation SUM Austria 2009 value of calculation SUM Austria 2010 value of calculation SUM Austria 2011 value of calculation SUM Austria 2012 value of calculation SUM Austria 2015 value of calculation SUM Austria 2016 value of calculation SUM Belgium 2005 value of calculation SUM Belgium 2006 value of calculation SUM Belgium 2007 value of calculation SUM Belgium 2009 value of calculation SUM Belgium 2011 value of calculation SUM Belgium 2012 value of calculation SUM Belgium 2013 value of calculation SUM Belgium 2016 value of calculation SUM 和`year创建总和。我想这很简单,但是请问我一个问题。

感谢任何类型的帮助。

Nordsee

1 个答案:

答案 0 :(得分:2)

基本R:

aggregate(emissions~country.x + year , df, sum)

dplyr:

#install.packages("dplyr")
library(dplyr)

df %>% group_by(country.x, year) %>% summarise(emissions_sum = sum(emissions))