Home > Back-end >  Reorder sf object by column
Reorder sf object by column

Time:09-06

I'm getting more familiar with sf objects for spatial data in R, but cannot figure out this simple aspect -- how do I reorder my sf object by a column with values that I specify. Take this example

library(sf)

points <- data.frame(long = c(-50, -50, 50, 50, -50,
                              -100, -100, 100, 100, -100),
                     lat = c(-50, 50, 50, -50, -50,
                             -100, 100, 100, -100, -100),
                     ID = c(rep(1, 5), rep(2, 5)))

hulls <- points %>%
  st_as_sf(coords = c("long", "lat")) %>%
  group_by(ID) %>%
  summarize(geometry = st_union(geometry)) %>%
  st_convex_hull()

plot(hulls, col=c("red", "blue"))

hulls

Simple feature collection with 2 features and 1 field
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: -100 ymin: -100 xmax: 100 ymax: 100
CRS:           NA
# A tibble: 2 × 2
     ID                                              geometry
* <dbl>                                             <POLYGON>
1     1           ((-50 -50, -50 50, 50 50, 50 -50, -50 -50))
2     2 ((-100 -100, -100 100, 100 100, 100 -100, -100 -100))

We cannot see the red object because it is behind the blue one. So, if I want to reorder the plotting order I want to manipulate the ID column, but sf objects seem to behave differently to other R objects. I want to be able to do something like hulls[hulls$ID==c(2, 1)], but this not only doesn't work, but also subtracts the ID column for some reason.

Any help appreciated

CodePudding user response:

Do you need this?

library(dplyr)

hulls_red <- hulls %>% 
  arrange(-ID)

plot(hulls_red, col=c("red", "blue"))

enter image description here

  •  Tags:  
  • r sf
  • Related