简体   繁体   English

如何用R中的两个因子来汇总数值变量

[英]how to summarise a numeric variable by two factors in R

I have a data.frame with 3 variables and 1.425.558 observations. 我有一个包含3个变量和1.425.558个观测值的data.frame。 It´sa register of installed electric power from renewable energy plants. 这是来自可再生能源工厂的已安装电力的登记册。 Every row stands for one installed power plant. 每排代表一个已安装的发电厂。 There can be multiple power plants of the same type in a zipcode-area. 在邮政编码区域中可以有多个相同类型的发电厂。

ID  zipcode     Type    power
1   79280   solarpower  3
2   79280   solarpower  3
3   79283   hydroelectric   3
4   79280   biogas          55
5   79280   windpower   2
6   21459   windpower   4
7   21459   windpower   2

I would like to sum by zipcode how much solarpower/biogas/windpower is installed. 我想通过zipcode总结一下安装了多少太阳能/沼气/风能。

zipcode     Type    power
21459        windpower    6
79280        solarpower   6
79280        windpower    2
...and so on.

I already tried 我已经试过了

aggregate(myDat$power, by=list(myDat$zipcode,myDat$type), FUN=sum)

but my RAM was not sufficant. 但我的RAM不够用。

I know, my dataframe is very big. 我知道,我的数据框架非常大。 I could narrow it down a lot, because i only need the data for those zipcodes that start with "2". 我可以将它缩小很多,因为我只需要以“2”开头的那些zipcodes的数据。

Could you point me to a solution? 你能指点我一个解决方案吗? Thank you very much for helping an Beginner! 非常感谢您帮助初学者!

If I understand correctly what you need, you can express it using dplyr: 如果我正确理解了您的需求,可以使用dplyr表达它:

> data %.% group_by( zipcode, Type ) %.% summarise( power = sum(power) )
Source: local data frame [5 x 3]
Groups: zipcode

  zipcode          Type power
1   21459     windpower     6
2   79280     windpower     2
3   79280        biogas    55
4   79283 hydroelectric     3
5   79280    solarpower     6

And if you only want those zip code that start by 2 , you can filter first: 如果你只想要那些以2开头的邮政编码,你可以先filter

> data %.% filter( grepl( "^2", zipcode ) ) %.% 
     group_by( zipcode, Type ) %.% summarise( power = sum(power) )
Source: local data frame [1 x 3]
Groups: zipcode

  zipcode      Type power
1   21459 windpower     6

data.table version: data.table版本:

library(data.table)
dt = data.table(your_df)

dt[, sum(power), by = list(zipcode, Type)]

And to narrow down first: 并先缩小范围:

dt[grep("^2", zipcode), sum(power), by = list(zipcode, Type)]

Because grep is expensive, in both dplyr and data.table you're likely better off (speed-wise) summarizing first, and filtering second, ie: 因为grep很贵,所以在dplyrdata.table你可能最好先(快速)总结,然后过滤第二,即:

dt[, sum(power), by = list(zipcode, Type)][grep("^2", zipcode)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM