Salvador
Salvador

Reputation: 1549

Subsetting a shapefile

I have a shapefile here: https://login.filesanywhere.com/fs/v.aspx?v=8c6c63865a6574bcaa69 I have a shapefile of California red legged frog that I am overlaying on top of California, however, the range of these frogs extends outside of California and going into Mexico. I only want the frog data from California, how can I trim data extending into Mexico? I tried to use subset to separate the 'ORIGIN' but it doesn't seem to have any effect. Thanks for any help beforehand..

enter image description here

library(rgdal)
library(tidyverse)

ranas <- readOGR(dsn = ".", layer = "data_0")
names(ranas)

# Coerce into a dataframe 
ranas4 <- fortify(ranas) 
head(ranas4) 

cali_map <- map_data("state",region="california") 
counties <- map_data("county",region="California")
 head(counties)
 
windows(w=9)
ggplot(cali_map, aes(x = long, y = lat, group = group)) +
geom_polygon() +
geom_polygon(data = ranas4, fill = "green")  

ggplot(cali_map, aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "cornsilk4", col = "cornsilk") +
geom_polygon(data=counties,color="black",fill="lightgoldenrod") +
geom_polygon(data = ranas4, fill = "green", alpha = 0.5) +
theme_void() +
theme(panel.background = element_rect(fill = "cornsilk"))  +
coord_map("albers",lat=90,lat1=80)

# Tried to trim data outside California (Mexico data) with no success.
#I tried: 
ranas2 <- subset(ranas,ORIGIN !=1)
but it doesn't have any effect or subsets anything. 

Upvotes: 1

Views: 59

Answers (1)

user18309711
user18309711

Reputation:

Subsetting your spatial dataframe won't be of much use, because neither of its features (rows) is entirely within California:

## plot features by origin:
library(ggplot2)
library(sf)

my_shp <- read_sf(dsn = "path_to_shp_directory")

my_shp %>% 
  ggplot() +
  geom_sf() + 
  facet_wrap(~ ORIGIN)

You can still crop (clip) a feature with California's boundaries ...:

## make sure both geometries have the same CRS,
## if necessary, by st_transform(your_epsg_code)
my_shp_cropped <- st_crop(my_shp, cali_map)

... but note that won't recalculate the underlying frog data (e.g. frog count in California only).

Upvotes: 1

Related Questions