Search code examples
rrasterspatialdata-extractionspatstat

How to convert "im" pixel image to raster?


I am trying to convert an "im" pixel image I've produced into a raster image. The "im" was created with the following code:

library(sf)
library(spatstat)
library(rgeos)
library(raster)

# read ebird data 
ebd_species <- ("ebd_hooded.txt") %>%
  read_ebd()

# extracting coordinates 
latitude_species <- ebd_species$latitude
longitude_species <- ebd_species$longitude

#convert to spatial object
coordinates1 <- data.frame(x = longitude_species, y = latitude_species) %>% st_as_sf(coords = c("x", "y"))

# converting to point pattern data
coordinates <- as.ppp(coordinates1)

# density image
a <- density(coordinates,2)
plot(a)

This is the plot I get: plot

What I want to do is convert this into a raster. I wanna then use the coordinates of the ebird data to extract the values of density from the raster.


Solution

  • Looks like you are using geographic coordinates (longitude, latitude) directly in spatstat. Are you sure this is OK in your context? For regions away from the equator this can be quite misleading. Consider projecting to planar coordinates using sf::st_transform() (see other of my answers on this site for code to do this). Also, in newer versions of sf you can convert directly from sf to spatstat format with e.g. as.ppp().

    If you want a kernel density estimate of the intensity at the data points you can use the option at = "points" in density.ppp():

    a <- density(coordinates, 2, at = "points")
    

    Then a is simply a vector with length equal to the number of points containing the intensity estimate for each data point. This uses "leave-one-out" estimation by default to minimize bias (see the help file for density.ppp).