Search code examples
rraster

How to create SpatialPixelsDataFrame object in R (compatible with adehabitat package)


My problem is simple. I have found very good package called adehabitat in R. To use it I need to transform my data into specificaly structured object containing raster map data and coordinates of an animal. To see it please type:

# example data in adahabitat package
data(bauges)
bauges
str(bauges)

How do I convert my data (bellow) into such structure? I figured out how to convert $locs into SpatialPoints, but I don't know how to convert map (in my example are raster values categorical codes of individual types of habitat -i.e. not continuous variable).

# My example data:
library(raster)
library(adehabitatHS)

# map
habitat_type_temp <- matrix(c(1,1,1,1,1,1,1,1,2,2,
                              1,1,2,2,1,1,1,2,2,2,
                              1,2,2,2,3,3,3,2,2,2,
                              2,2,2,1,1,1,3,2,2,1,
                              2,2,1,1,1,1,3,2,1,1,
                              2,1,1,1,1,1,3,3,1,1,
                              2,1,1,1,1,3,3,3,3,1,
                              1,1,1,1,1,1,1,3,3,3), 10)
habitat_type <- t(habitat_type_temp)

# coordinates
animal_coords <- data.frame(x = c(2,4,5,5,6,9),
                            y = c(2,8,3,2,4,3))


# see the situation
plot(raster(habitat_type, xmn=1, xmx=10, ymn=1, ymx=8))
points(animal_coords$x, animal_coords$y)


# creating object which could be manipulated in adehabitat package
my.hab <- list()
my.hab$map <- SpatialPixelsDataFrame(...)
my.hab$locs <- SpatialPoints(animal_coords)

Is it even possible to insert such manually fabricated data into such specific type of object, or I need some original tiff with specific CRS?


Solution

  • You could just drop the location somewhere to produce the SpatialPixelsDataFrame, I think this is roughly Iowa:

    x <- 93+rep(1:8,each=10)/100
    y <- rep(seq(42.01,42.1,by=0.01), 8)
    z <- c(1,1,1,1,1,1,1,1,2,2,
      1,1,2,2,1,1,1,2,2,2,
      1,2,2,2,3,3,3,2,2,2,
      2,2,2,1,1,1,3,2,2,1,
      2,2,1,1,1,1,3,2,1,1,
      2,1,1,1,1,1,3,3,1,1,
      2,1,1,1,1,3,3,3,3,1,
      1,1,1,1,1,1,1,3,3,3)
    xy.df <- data.frame(x,y)
    xy.coords <- SpatialPixels(SpatialPoints(xy.df))
    llCRS <- CRS("+proj=utm +zone=15 +ellps=WGS84")
    xy.sp <- SpatialPoints(xy.coords, proj4string = llCRS)
    xyz <- as.data.frame(cbind(x,y,z))
    xyz.spdf <- SpatialPixelsDataFrame(xy.coords, xyz)
    plot(xyz.spdf)
    

    Your spatialpoints would have to be changed similarly.