I have been trying to obtain a column of weighted averages which excludes some rows for each row using data.table.
In the following example, FIPS is ID variable and STATE is group variable. I want to calculate weighted average of value excluding neighboring counties in a same state. as well as in other states.
I know how to implement it but I guess there is a more efficient way. I am not familiar with rowwise manipulation using data.table. Any ideas? Thank you in advance.
library(data.table)
rm(list=ls())
set.seed(920410)
DT <- data.table(FIPS =1:21, STATE = LETTERS[1:2], value=1:3, weight=2:7); DT
DT[, nbs := list(list(sample(1:21, 3))), by= names(DT)]
for(i in 1:nrow(DT)){
DT$neighbor_sum_in_the_same_state[i] <- sum(DT[FIPS %in% unlist(DT$nbs[i]) & STATE == DT$STATE[i], value*weight])
DT$neighbor_sum_in_other_states[i] <- sum(DT[FIPS %in% unlist(DT$nbs[i]) & STATE != DT$STATE[i], value*weight])
}