Reputation: 49
OK, apply is my nemesis, but I'm pretty sure it's involved with the answer here.
I have poverty data with three levels, state (name_1), county(name_2), and township(name_3). I need to do a naive downscale, where I assume that the average state income (income = e2004MeanY) is equal to 1) each county income and 2) each township income.
> 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
I've aggregated the data, so I have the means for each state:
> 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
I have dataframes, vnm2 and vnm3, which are aggregated the same way as vnm1, except by name_2 and name_3, respectively:
vnm2 <- aggregate(da[,-c(1:3)], da[,2, drop=F], mean, na.rm=TRUE)
vnm3 <- na.omit(da[,-c(1:2)])
How do I get the vnm1$e2004MeanY values into vnm2 and vnm3?
Upvotes: 2
Views: 738
Reputation: 12411
I think that this code will work (even if it is not optimized) :
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 : It has been tested with a simple example.
Upvotes: 1