Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

r - How to filter a sf object by latitude?

Data

I have a shapefile for Ontario province boundary that I read as follows:

library(sf)
library(here)
ontario <- sf::st_read(here::here("data", "messy_data", "Ontario.shp"), quiet = TRUE) %>%
  st_transform(4326)

It can be plotted as follows:

enter image description here

Question

I want to keep the ontario data only for latitude < 51. But since it is a sf object, dplyr::filter(latitude < 51) doesn't work. I know that I can extract the coordinates with st_coordinates(), but how can I join them back to the data to filter out the higher altitude?
Alternatively, is there any function in sf that I could use to do the filter? I looked into the help but couldn't find anything relevant so far.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let's get Canada from the GADM data:

library(raster)
library(sf)
cdn = getData("GADM",country="can",level=1)

this should be Ontario:

ont = cdn[9,]
ont$NAME_1

convert to an sf object:

ont = st_as_sf(ont)

Now to business - crop to 51 degrees north:

ont_south = st_crop(ont, xmin=-180, xmax=180, ymin=-90, ymax=51)
plot(ont_south$geometry)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...