Convert spocc::occ() output to a sp spatial class

,

This stems from a user question here: What happened to functions occ_to_sp and occ2sp? · Issue #186 · ropensci/spocc · GitHub

At one point in the spocc package we had a function occ_to_sp which helped you convert data.frame output of the main function spocc::occ() into an sp package spatial class that you could then use downstream.

(parenthetically: we had a duplicate of occ_to_sp called occ2sp that was removed, see occ2sp and occ_to_sp · Issue #97 · ropensci/spocc · GitHub)

We decided to remove remove occ_to_sp function in this commit back in June 2015 because we wanted to reduce dependencies in the package since it’s already a “heavy package” (that is, lots of other packages are needed for this package to work).

You can still achieve the same thing occ_to_sp did relatively easily. Here’s an example:

library(sp)
library(maptools)
library(spocc)
occ_to_sp <- function(x, coord_string = "+proj=longlat +datum=WGS84", just_coords = FALSE){
  points <- occ2df(x)
  # remove NA rows
  points <- points[complete.cases(points),]

  # check valid coords
  index <- 1:dim(points)[1]
  index <- index[(points$longitude < 180) & (points$longitude > -180) & !is.na(points$longitude)]
  index <- index[(points$latitude[index] < 90) & (points$latitude[index] > -90) & !is.na(points$latitude[index])]

  spobj <- sp::SpatialPoints(as.matrix(points[index,c('longitude','latitude')]), proj4string = sp::CRS(coord_string))

  sp_df <- sp::SpatialPointsDataFrame(spobj, data = data.frame(points[index,c('name',"prov")]))
  if (just_coords) spobj else sp_df
}


data(wrld_simpl)
plot(wrld_simpl[wrld_simpl$NAME == "United States", ],xlim=c(-70,-60))
out <- occ(query = "Accipiter striatus", from = "gbif")
sp_points <- occ_to_sp(out, just_coords=TRUE)
points(sp_points, col = 2)

1 Like