gpt4 book ai didi

R Leaflet map - 为每一行数据框画线

转载 作者:行者123 更新时间:2023-12-03 23:57:37 25 4
gpt4 key购买 nike

我正在尝试使用 Leaflet 在 map 上创建线条纬度/经度点之间。这是一个示例输入数据:

  segment_id latitude1 longitude1 latitude2 longitude2      len
1 1 48.15387 17.07388 48.15396 17.07387 10.98065
2 1 48.15396 17.07387 48.15404 17.07377 11.31327
3 1 48.15404 17.07377 48.15410 17.07364 11.74550
4 1 48.15410 17.07364 48.15412 17.07349 11.48138
5 1 48.15412 17.07349 48.15412 17.07334 11.63625
6 2 48.15424 17.07307 48.15432 17.07299 10.79304

这样做的结果应该是 6 行 lat1,lng1 -> lat2,lng2 .我很难与 addPolylines 一起工作,它正在创建额外的不需要的线条,我不知道为什么。

enter image description here

这就是它的样子,没有多余的线条堆叠在一起:D

到目前为止,这是我的代码,但它是垃圾:
  drawEdges <- function(x) {
d <- cbind(x$latitude1,x$latitude2)
s <- rep(1:nrow(x), each = 2) + (0:1) * nrow(x)
latitudeOut <- d[s]
e <- cbind(x$longitude1,x$longitude2)
t <- rep(1:nrow(x), each = 2) + (0:1) * nrow(x)
longitudeOut <- e[t]
mymap <<- addPolylines(map = mymap,data = x, lng = ~longitudeOut, lat = ~latitudeOut)
}

if (!is.null(edges)){
segments <- split( edges , f = edges$segment_id )
segments
sapply(segments, drawEdges)
}

感谢您的帮助

最佳答案

为了使线按顺序连接,您需要将数据重新整理成长格式,并按顺序排列点。

并且要在不使用任何空间对象(例如来自 library(sp) )的情况下执行此操作,您需要使用循环添加行。

library(leaflet)

### --- reshaping the data ----
## keep the order - but because we're going to split the data, only use odd numbers
## and we'll combine the even's on later
df$myOrder <- seq(from = 1, to = ((nrow(df) * 2) - 1), by = 2)

## put the data in long form by splitting into two sets and then rbinding them
## I'm renaming the columns using setNames, as we need to `rbind` them
## together later
df1 <- setNames(df[, c("segment_id","latitude1","longitude1", "myOrder")],
c("segment_id", "lat","lon", "myOrder"))

df2 <- setNames(df[, c("segment_id","latitude2","longitude2", "myOrder")],
c("segment_id", "lat","lon", "myOrder"))

## make df2's order even
df2$myOrder <- (df2$myOrder + 1)

df <- rbind(df1, df2)

## can now sort the dataframe
df <- df[with(df, order(myOrder)), ]

## and de-dupelicate it
df <- unique(df[, c("segment_id", "lat","lon")])
### -----------------------------


## ----- plotting ---------------
map <- leaflet(data = df) %>%
addTiles() %>%
addCircles()

## without using any spatial objects, you add different lines in a loop
for(i in unique(df$segment_id)){
map <- addPolylines(map, data = df[df$segment_id == i,],
lat = ~lat, lng = ~lon, group = ~segment_id)
}
map

enter image description here

关于R Leaflet map - 为每一行数据框画线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41202642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com