每行创建多边形并保留列

Create polygon per row and retain columns

早上好、下午好还是晚上好

我已将一些位置数据分组到 1 小时的 bin 中。

对于每个我都提取了最小的纬度和经度。

看起来像这样:

df <- "ID    time_bin count      lat       lon    maxlat   minlat    maxlon    minlon
1 2018-10-07 22:00:00    47 51.21723 -5.021828  51.22082 51.21457 -5.019105 -5.024372
2 2018-10-07 23:00:00    61 51.21797 -4.907367  51.23592 51.21224 -4.743538 -5.018899
3 2018-10-08 00:00:00    65 51.27263 -4.612118  51.32474 51.23751 -4.576005 -4.734378
4 2018-10-08 01:00:00   107 51.42989 -4.563178  51.52467 51.32735 -4.553063 -4.575208
5 2018-10-08 02:00:00    65 51.59331 -4.565254  51.64160 51.52571 -4.550257 -4.598212
6 2018-10-08 03:00:00    84 51.59082 -4.637655  51.63241 51.57906 -4.600483 -4.674987"
    
df <- read.table(text=df, header = TRUE)

我希望使用最小和最大纬度和对数为每一行创建一个多边形。我知道我可以通过使用 orcs 包中的 coords2Polygons 函数来做到这一点。

例如,如果我取第一行并手动输入它们,as in the example:

library(sp)
library(Orcs)
library(mapview)

test <- cbind(c(51.21457, 51.22082, 51.22082, 51.21457),
              c(-5.024372, -5.024372, -5.019105, -5.019105))


spy1 <- coords2Polygons(test, ID = "A")
plot(spy1, col = 34)

这是使用最小和最大纬度/经度的组合创建的,以确定四个角。

我想每行创建一个多边形。保留所有其他信息并绘制在 leaflet.

我已经尝试了几次,但一切都开始变得有点混乱。

一种方法是使用来自这个优秀答案 sf 包。使用 leaflet:

在您的数据上实施
library(sf)
library(leaflet)
lst <- lapply(1:nrow(df), function(x){
  res <- matrix(c(df[x, 'maxlat'], df[x, 'maxlon'],
                  df[x, 'maxlat'], df[x, 'minlon'],
                  df[x, 'minlat'], df[x, 'minlon'],
                  df[x, 'minlat'], df[x, 'maxlon'],
                  df[x, 'maxlat'], df[x, 'maxlon'])  
                , ncol =2, byrow = T
  )
  st_polygon(list(res))
  
})
df$geomtry <- st_sfc(lst)
str(df)
sfdf <- st_sf(df)
leaflet() %>%
  addTiles() %>%
  addPolygons(data = sfdf)