我正在寻找一种快速方法来根据另一个表中的索引列表获取表中列的总和。
这是一个可重现的简单示例:首先创建一个边缘表
fake_edges <- st_sf(data.frame(id=c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'),
weight=c(102.1,98.3,201.0,152.3,176.4,108.6,151.4,186.3,191.2),
soc=c(-0.1,0.7,1.1,0.2,0.5,-0.2,0.4,0.3,0.8),
geometry=st_sfc(st_linestring(rbind(c(1,1), c(1,2))),
st_linestring(rbind(c(1,2), c(2,2))),
st_linestring(rbind(c(2,2), c(2,3))),
st_linestring(rbind(c(1,1), c(2,1))),
st_linestring(rbind(c(2,1), c(2,2))),
st_linestring(rbind(c(2,2), c(3,2))),
st_linestring(rbind(c(1,1), c(1,0))),
st_linestring(rbind(c(1,0), c(0,0))),
st_linestring(rbind(c(0,0), c(0,1)))
)))
tm_shape(fake_edges, ext = 1.3) +
tm_lines(lwd = 2) +
tm_shape(st_cast(fake_edges, "POINT")) +
tm_dots(size = 0.3) +
tm_graticules(lines = FALSE)
然后从表中创建一个网络,并找到从第一个节点到所有节点的成本最低的路径。
fake_net <- as_sfnetwork(fake_edges)
fake_paths <- st_network_paths(fake_net,
from=V(fake_net)[1],
to=V(fake_net),
weights='weight', type='shortest')
现在,我要改进的是为该fake_paths
表的每一行查找的过程
- 路径中
id
最后一条边的 soc
路径所有边的总和
我所做的是以下(这里有 9 行很快,但在大型网络上需要很长时间):
# Transforming to data.tables makes things a bit faster
fake_p <- as.data.table(fake_paths)
fake_e <- as.data.table(fake_edges)
# ID of the last edge on the path
fake_p$id <- apply(fake_p, 1, function(df) unlist(fake_e[df$edge_paths %>% last(), 'id'], use.names=F))
# Sum of soc
fake_p$result <- to_vec(for (edge in 1:nrow(fake_p)) fake_e[unlist(fake_p[edge, 'edge_paths']), soc] %>% sum())
最终,我想要的是soc
我要求result
加入的总和支持原版fake_edges
fake_e = left_join(fake_e,
fake_p %>% select(id, result) %>% drop_na(id) %>% mutate(id=as.character(id), result=as.numeric(result)),
by='id')
fake_edges$result <- fake_e$result
fake_edges
Simple feature collection with 9 features and 4 fields
Geometry type: LINESTRING
Dimension: XY
Bounding box: xmin: 0 ymin: 0 xmax: 3 ymax: 3
CRS: NA
ID | 重量 | 社会 | 几何学 | 结果 |
---|---|---|---|---|
一种 | 102.1 | -0.1 | 线串 (1 1, 1 2) | -0.1 |
b | 98.3 | 0.7 | 线串 (1 2, 2 2) | 0.6 |
C | 201.0 | 1.1 | 线串 (2 2, 2 3) | 1.7 |
d | 152.3 | 0.2 | 线串 (1 1, 2 1) | 0.2 |
e | 176.4 | 0.5 | 线串 (2 1, 2 2) | 不适用 |
F | 108.6 | -0.2 | 线串 (2 2, 3 2) | 0.4 |
G | 151.4 | 0.4 | 线串 (1 1, 1 0) | 0.4 |
H | 186.3 | 0.3 | 线串 (1 0, 0 0) | 0.7 |
一世 | 191.2 | 0.8 | 线串 (0 0, 0 1) | 1.5 |