rrasterrasterize

Creating raster with circles from dataframe in R


How can I create a raster layer with filled circles centered in "c(df$lat,cd$lon)" and radius "df$radius" from a dataframe?

df <- data.frame(lat=c(40.4,42.4,42.4,42.4,42.3), 
                 lon=c(-0.3,1,1.5,2.7,2.1), 
                 radius=c(4.4,8.4,11.4,5.4,10.3))

df
#   lat  lon radius
#  40.4 -0.3    4.4
#  42.4  1.0    8.4
#  42.4  1.5   11.4
#  42.4  2.7    5.4
#  42.3  2.1   10.3

Solution

  • library(dismo)
    df <- data.frame(lat=c(40.4,42.4,42.4,42.4,42.3), 
                     lon=c(-0.3,1,1.5,2.7,2.1), 
                     radius=c(4.4,8.4,11.4,5.4,10.3))
    

    Note the use of lon/lat, not lat/lon

    p <- df[,2:1]
    

    The radius is in meters so your numbers are very small. I'll change them

    rad <- df[,3]*2500
    

    Compute circles

    cc <- circles(p, rad, lonlat=TRUE, dissolve=FALSE)
    plot(cc)
    points(p)
    

    Get the polygons

    pls <- polygons(cc)
    

    To get a RasterLayer you can either use predict(cc, ) or rasterize(pls, )

    r <- raster(extent(pls), res=.01)
    pr <- predict(cc, r)
    

    (if you do not want the overlaps to be counted, use dissolve=TRUE in the circles function)