好的,申请是我的克星,但我很确定这里有答案。
我有三个级别的贫困数据,州(name_1),县(name_2)和乡镇(name_3)。我需要做一个天真的缩减,我假设平均州收入(收入= e2004MeanY)等于1)每个县的收入和2)每个乡镇的收入。
> head(da)
name_1 name_2 name_3 e2004MeanY acc_500k
0 Vung Dong Bac Lao Cai Xi Mai Ca 637 539.67810
1 Vung Dong Bac Bac Kan Bac Kan Township 2199 378.90057
2 Vung Dong Bac Bac Kan Ba Be 1075 549.34222
3 Vung Dong Bang Song Cuu Long Long An Can Duoc 2284 74.61940
4 Vung Dong Bang Song Cuu Long Long An Can Giuoc 2256 96.18077
5 Vung Dong Bang Song Cuu Long Can Tho Vi Thanh Township 2136 262.74435
我汇总了数据,因此我可以为每个州提供资源:
> vnm1 <- aggregate(da[,-c(1:3)], da[,1, drop=F], mean, na.rm=TRUE)
> head(vnm1)
name_1 e2004MeanY acc_500k alt cost cropland
1 Vung Bac trung Bo 1680.296 497.8453 162.023675 375.4979 98.78586
2 Vung Dong Bac 1574.306 355.9818 327.662351 423.0005 98.66135
3 Vung Dong Bang Song Cuu Long 2031.346 269.4059 4.733111 186.6358 98.41601
4 Vung Dong bang song Hong 2416.989 118.4019 11.128992 150.1016 98.40423
5 Vung Dong Nam Bo 3350.440 205.7134 171.782189 233.0148 99.15330
6 Vung Duyen Hai Nam Trung Bo 1855.655 793.1942 235.375168 427.0307 97.12402
我有数据帧,vnm2和vnm3,它们与vnm1的聚合方式相同,除了分别是name_2和name_3:
vnm2 <- aggregate(da[,-c(1:3)], da[,2, drop=F], mean, na.rm=TRUE)
vnm3 <- na.omit(da[,-c(1:2)])
如何将vnm1 $ e2004MeanY值输入vnm2和vnm3?
答案 0 :(得分:1)
我认为此代码可以正常工作(即使它未经过优化):
f2 <- function(i) {vnm1[which(vnm1[,1] ==da[min(which( da[,2] == vnm2[i,1])),1]),2]}
data.frame(cbind(vnm2,e2004MeanY=sapply(FUN=f2,1:length(vnm2[,1]))))
f3 <- function(i) {vnm1[which(vnm1[,1] ==da[min(which( da[,3] == vnm3[i,1])),1]),2]}
data.frame(cbind(vnm2,e2004MeanY=sapply(FUN=f3,1:length(vnm3[,1]))))
PS:它已经通过一个简单的例子进行了测试。