我正在使用两个表table1和table2。第一个表(table1)包含称为“代码”的列,该列包含与放置在路径上的一组点相对应的唯一标识符(代码)。第二个表(table2)包含这些点之间的距离,如下所示:
code1| code2| distance
252| 252| 1000|
我想将连续点之间的距离(第2行中的点与第1行的点,第3行中的点与第2行中的点等)添加到表1中,如下(构成距离):
codes distance
251 0
252 1000
253 20000
样本数据:
table1<-structure(list(codes = c("251", "253", "259", "261")), row.names = c(NA,
-4L), class = "data.frame")
table2<-structure(list(dist = c(43733.8720639044, 50226.4427668293, 13373.4575031321,
57107.3295670365, 68610.7672078486, 68974.0419745275, 63599.9002699614,
47370.0886728576, 40298.4023452974, 48089.0718267054, 74934.8997999821,
81332.8498247429, 34715.6143235733, 38149.8130708784, 50016.5254783694,
15510.828443256, 11677.4399553228, 39174.1270562218, 26845.8279732768,
33243.7779980375), code1 = c(253L, 253L, 261L, 261L, 261L, 261L,
261L, 261L, 261L, 261L, 261L, 261L, 259L, 259L, 259L, 259L, 259L,
259L, 259L, 259L), code2 = c(252L, 251L, 253L, 252L, 260L, 258L,
251L, 256L, 257L, 259L, 254L, 255L, 253L, 252L, 258L, 251L, 256L,
257L, 254L, 255L)), row.names = c(NA, -20L), class = "data.frame")
答案 0 :(得分:1)
library(dplyr)
table1 %>%
mutate(codes2 = lag(codes)) %>%
mutate_all(list(as.integer)) %>%
left_join(., table2, by=c("codes"="code1", "codes2"="code2")) %>%
select(-codes2)
#> codes dist
#> 1 251 NA
#> 2 253 50226.44
#> 3 259 34715.61
#> 4 261 48089.07