这是一个选项,data.table
在执行连接之前将其转换为长格式:
#convert into long format i.e. unlist the nbs column
nm <- c("FIPS","STATE","value", "weight")
DT_long <- DT[, .(nbs=unlist(nbs)), nm]
#look for neighbours in same STATE and FIPS
DT_long[, neighbor_sum_in_the_same_state :=
.SD[.SD, on=.(FIPS=nbs, STATE), sum(x.value[1L] * x.weight[1L]), by=.EACHI]$V1]
#look for all in same FIPS but exclude those with same STATE
DT_long[, neighbor_sum_in_other_states :=
.SD[.SD, on=.(FIPS=nbs), sum(x.value[x.STATE!=i.STATE][1L] * x.weight[x.STATE!=i.STATE][1L]), by=.EACHI]$V1]
#produce desired output
DT_long[, lapply(.SD, sum, na.rm=TRUE), nm,
.SDcols=c("neighbor_sum_in_the_same_state", "neighbor_sum_in_other_states")]
输出:
FIPS STATE value weight neighbor_sum_in_the_same_state neighbor_sum_in_other_states
1: 1 A 1 2 14 21
2: 2 B 2 3 11 12
3: 3 A 3 4 0 17
4: 4 B 1 5 5 14
5: 5 A 2 6 16 0
6: 6 B 3 7 26 12
7: 7 A 1 2 14 5
8: 8 B 2 3 27 2
9: 9 A 3 4 2 42
10: 10 B 1 5 6 14
11: 11 A 2 6 12 26
12: 12 B 3 7 11 2
13: 13 A 1 2 12 11
14: 14 B 2 3 5 24
15: 15 A 3 4 12 26
16: 16 B 1 5 21 24
17: 17 A 2 6 4 5
18: 18 B 3 7 6 14
19: 19 A 1 2 14 5
20: 20 B 2 3 11 12
21: 21 A 3 4 12 27
FIPS STATE value weight neighbor_sum_in_the_same_state neighbor_sum_in_other_states