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

Tags: #<Tag:0x00007f57f6245d88> #<Tag:0x00007f57f6245c20>


This stems from a user question here:

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

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:

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) & !$longitude)]
  index <- index[(points$latitude[index] < 90) & (points$latitude[index] > -90) & !$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

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)