Search code examples
rleafletgispolygonr-sp

Create polygon per row and retain columns


Good morning, afternoon or evening

I have grouped some positional data into 1 hour bins.

For each I have extract the minimum lat and lon.

It looks like this:

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)

Using the min and max lats and logs I wish to create a polygon for each row. I know I can do this by using the coords2Polygons function from the orcs package.

For example, if I take the first row and enter them manually, 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)

This is created using a combination of min and max lats / longs to determine the four corners.

I want to create a polygon each row. Retain all the other info and plot in leaflet.

I have had a few attempts but it all starts to get a bit messy.


Solution

  • One approach would be to use sf package from this excellent answer here. Implementing on your data with 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)
    

    enter image description here