export khrud object from kernelUD to raster

570 Views Asked by At

In R, how can I export a khrud object from function kernelUD in package adehabitat to a raster file (geoTiff)?

I tried following this thread (R: how to create raster layer from an estUDm object) using the code here:

writeRaster(raster(as(udbis1,"SpatialPixelsDataFrame")), "udbis1.tif")

where udbis1 is a khrud object, but I get "Error in as(udbis1, "SpatialPixelsDataFrame") : no method or default for coercing “khrud” to “SpatialPixelsDataFrame." I think the issue may be that the old thread was before an update to the adehabitat package changed the data format from estUD to khrud. Maybe?

2

There are 2 best solutions below

0
On

AdehabitatHR solutions work well for data that are in the required format or when using multiple animals. Though when wanting to create KDE with data organized differently or for only one source, it can be frustrating. For some reason, @johaness' answer doesn't work for my case so here is an alternative solution that avoids the headaches of going into adehabitatHR's innards.

library(adehabitatHR)
library(raster)
# Recreating an example for only one animal
# with a basic xy dataset like one would get from tracking
loc<-puechabonsp$relocs
loc<-as.data.frame(loc)
loc<-loc[loc$Name=="Brock",]
coordinates(loc)<-~X+Y

ud<-kernelUD(loc)

# Extract the UD values and coordinates into a data frame
udval<-data.frame("value" = ud$ud, "lon" = ud@coords[,1], "lat" = ud@coords[,2])
coordinates(udval)<-~lon+lat
# coerce to SpatialPixelsDataFrame
gridded(udval) <- TRUE

# coerce to raster
udr <- raster(udval)

plot(udr)
0
On

You do not provide a reproducible example. The following works for me:

library(adehabitatHR)
library(raster)

data(puechabonsp)
loc <- puechabonsp$relocs

ud <- kernelUD(loc[, 1])

r <- raster(as(ud[[1]], "SpatialPixelsDataFrame"))
writeRaster(r, filename = file.path(tempdir(), "ud1.tif"))