Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reorder sf object by column

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Do you need this?

library(dplyr)

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

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

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading