Reputation: 1
The R code below had worked on an earlier version of R and sf but is not working on a different laptop in which I recently downloaded R, RStudio, and necessary packages. Using the "st_crop" function for a world map (sf object) results in a map in which there are only horizontal lines up towards the north pole. I was only able to crop by the object by first converting it to a "SpatialPolygonsDataFrame" and the cropping it using the "crop" function in the sp package. Is there a bug, or am I doing something wrong here?
R 4.1.0 sf 1.0.3 rnaturalearth 0.1.0 dplyr 1.0.7
library(sp)
library(sf)
library(dplyr)
library(rnaturalearth)
library(raster)
library(ggplot2)
# World map (sf object)
world_sf <- ne_countries(scale = 10, type = "countries", returnclass = "sf") %>%
filter(!(admin == "Antarctica"))
#This code does NOT work
ext_world1 <- c(xmin = -165, xmax = 175, ymin= -59.47275, ymax = 83.6341)
world_sf1 <- st_crop(world_sf, ext_world1)
ggplot() + geom_sf(data = world_sf1, color="gray20", fill = "gray85", lwd = 0.3)
# This code produces the expected result
ext_world2 <- as(raster::extent(-165, 175, -59.47275, 83.6341), "SpatialPolygons")
world_sp <- crop(as_Spatial(world_sf), ext_world2)
world_sf2 <- st_as_sf(world_sp)
ggplot() + geom_sf(data = world_sf2, color="gray20", fill = "gray85", lwd = 0.3)
Upvotes: 0
Views: 858
Reputation: 416
st_crop()
is working, but you need to make sure you are using the right coordinate reference system. Try this...
world_sf_4326 <- ne_countries(type = "countries", returnclass = "sf") %>%
filter(!(admin == "Antarctica")) %>%
st_transform(crs = 4326)
st_crs(world_sf_4326)
Upvotes: 1