我的数据看起来像这样:
population <- c(101:110)
coverage <- c(91:100)
area <- c("Cambridge", "Cambridge","Cambridge", "Cambridge","Cambridge", "Oxford", "Oxford","Oxford", "Oxford","Oxford")
all <- data.frame(population,coverage,area)
然后,我想要一个简洁的R代码来计算具有移动覆盖范围的区域内的人口百分比。我知道它是这样的(但不是这个):
coverage <- population x (coverage/100) / (aggregate(population, by=area, FUN=sum))
如何计算面积总和,用作所有行百分比计算的分母?通常我会使用聚合来按区域获取总体,然后将其合并回数据框以用作分母,但这根本不是很优雅。我希望数据最终看起来像这样:
population <- c(101:110)
coverage <- c(91:100)
area <- c("Cambridge", "Cambridge","Cambridge", "Cambridge","Cambridge", "Oxford", "Oxford","Oxford", "Oxford","Oxford")
percentage <- c(18, 18, 18, 18, 18, 19, 19, 19, 19, 19)
all <- data.frame(population,coverage,area, percentage)
非常感谢帮助。
答案 0 :(得分:0)
您可以dplyr
使用area
对计算进行分组:
library(dplyr)
all %>% group_by(area) %>% mutate(percentage=population*(coverage/100)/sum(population))
##Source: local data frame [10 x 4]
##Groups: area [2]
##
## population coverage area percentage
## <int> <int> <fctr> <dbl>
##1 101 91 Cambridge 0.1784660
##2 102 92 Cambridge 0.1822136
##3 103 93 Cambridge 0.1860000
##4 104 94 Cambridge 0.1898252
##5 105 95 Cambridge 0.1936893
##6 106 96 Oxford 0.1884444
##7 107 97 Oxford 0.1922037
##8 108 98 Oxford 0.1960000
##9 109 99 Oxford 0.1998333
##10 110 100 Oxford 0.2037037
答案 1 :(得分:0)
我想你想要dplyr总结一下。
这实现了你想要的吗?
库(dplyr) 所有%&gt;%group_by(区域)%&gt;%汇总(coveragePct = sum(coverage)/ sum(population))
答案 2 :(得分:0)
您可以使用dplyr执行此操作:
all.summary <- all %>%
group_by(area) %>%
mutate(percentage = population/sum(population)*(coverage/100))
all.summary
population coverage area percentage
<int> <int> <fctr> <dbl>
1 101 91 Cambridge 0.1784660
2 102 92 Cambridge 0.1822136
3 103 93 Cambridge 0.1860000
4 104 94 Cambridge 0.1898252
5 105 95 Cambridge 0.1936893
6 106 96 Oxford 0.1884444
7 107 97 Oxford 0.1922037
8 108 98 Oxford 0.1960000
9 109 99 Oxford 0.1998333
10 110 100 Oxford 0.2037037