我想计算数据集中每行中两组英国国家网格坐标之间的距离(即本例中每行的AreaA和AreaB之间的距离),以公里为单位。
library("sf")
BBox <- st_bbox(c(xmin = -10000, xmax = 15000, ymax = 20000, ymin = -5000), crs = st_crs(27700)) %>% st_as_sfc()
P1 <- st_sample(BBox, 50, exact = TRUE)
P2 <- st_sample(BBox, 50, exact = TRUE)
Points <- data.frame(AreaA=sample(110:190,50,replace=FALSE),AreaB=sample(10:90,50,replace=FALSE))
Points$AreaA_X <- data.frame(st_coordinates(P1))[,1]
Points$AreaA_Y <- data.frame(st_coordinates(P1))[,2]
Points$AreaB_X <- data.frame(st_coordinates(P2))[,1]
Points$AreaB_Y <- data.frame(st_coordinates(P2))[,2]
答案 0 :(得分:0)
我在提问时碰到了答案。但是,我认为我仍然会发布问题和答案,以防将来对其他人有帮助。
Points_sf <- st_as_sf(Points, coords = c("AreaA_X","AreaA_Y"),crs=27700)
Points_sf$geometry2 <- st_as_sf(Points[,c("AreaB_X","AreaB_Y")], coords = c("AreaB_X","AreaB_Y"),crs=27700)
Points_sf$Distance_M <- st_distance(Points_sf$geometry, Points_sf$geometry2, by_element = TRUE)