How to get contour lines around the grids in R-raster? - r

Having a raster in R, how can I draw a contour line around the grids (not joining the centers or anything else, really following the boundaries of the grids) having some value (or identified by some mask)?
The following example shows how to get the contour lines around areas with value 0.6: how to do the same but with the lines following the borders of the grids?
The function should return an object to add to a plot (as a SpatialLinesDataFrame for rasterToContour), and adjacent grids should be included in one single contour line (i.e., only the outer boundaries of a polygon should be drawn). I couldn't find the solution with rasterToPolygons (see here for a visual aspect, but it didn't help me here).
set.seed(2)
r <- raster(nrow=10, ncol=10)
r[] <- runif(ncell(r))
r[r>0.6] <- 0.6
rc <- rasterToContour(r, levels=c(0.6))
plot(r)
plot(rc, add=TRUE)

I'd use a combination of clump() and rasterToPolygons():
library(raster)
library(rgeos) ## For dissolve = TRUE in rasterToPolygons()
## Recreate your data
set.seed(2)
r <- raster(nrow = 10, ncol = 10)
r[] <- runif(ncell(r))
plot(r)
## Compute and then plot polygons surrounding cells with values greater than 0.6
SP <- rasterToPolygons(clump(r > 0.6), dissolve = TRUE)
plot(SP, add = TRUE)

Related

Line density function in R equivalent to Line density tool in ArcMap (arcpy)

I need to calculate the magnitude-per-unit area of polylines that fall within a radius around each cell. Essentially I need to calculate a km/km2 road density within a 500m pixel search radius. ArcMap has a quick and easy tool that handles this, but I need a pure R solution.
Here is a link on how line density works: http://desktop.arcgis.com/en/arcmap/10.3/tools/spatial-analyst-toolbox/how-line-density-works.htm
And this is how to use it in a python (arcpy) script: http://desktop.arcgis.com/en/arcmap/10.3/tools/spatial-analyst-toolbox/line-density.htm
I currently execute a backwards approach using raster::focal function, calculating a density of burned in road features. I then convert the km2/km2 output to km/km2.
#Import libraries
library(raster)
library(rgdal)
library(gdalUtils)
#Read-in an already created raster mask (cells are all set to 0)
mask <- raster("x://path to raster mask...")
#Make a copy of the mask to burn features in, keeping the original untouched
roads_mask <- file.copy(mask, "x://output path ...//roads.tif")
#Read-in road features (shapefile format)
roads_sldf <- readOGR("x://path to shapefile" , "roads")
#Rasterize spatial lines data frame ie. burn road features into mask
#Where road features get a value of 1, mask extent gets a value of 0
roads_raster <- gdalUtils::gdal_rasterize(src_datasource = roads_sldf,
dst_filename = "x://output path ...//roads.tif", b = 1,
burn = 1, l = "roads", output_Raster = TRUE)
#Run a 1km circular radius density function (be mindful of edge effects)
weight <- raster::focalWeight(roads_raster,1000,type = "circle")
1km_rdDensity <- raster::focal(roads_raster, weight, fun=sum, filename = '',
na.rm=TRUE, pad=TRUE, NAonly=FALSE, overwrite=TRUE)
#Convert km2/km2 road density to km/km2
#Set up the moving window
weight <- raster::focalWeight(roads_raster,1000,type = "circle")
#Count how many records in each column of the moving window are > 0
columnCount <- apply(weight,2,function(x) sum(x > 0))
#Get the sum of the column count
number_of_cells <- sum(columnCount)
#multiply km2/km2 density by number of cells in the moving window
step1 <- roads_raster * number_of_cells
#Rescale step1 output with respect to cell size(30m) and radius of a circle
final_rdDensity <- (step1*0.03)/3.14159265
#Write out final km/km2 road density raster
writeRaster(final_rdDensity,"X://path to output...", datatype = 'FLT4S', overwrite = TRUE)
After some more research I think I may be able to use a kernel function, however I don't want to apply the smoothing algorithm... As well the output is an 'im' object which I would need to write to as a 'tif'
#Import libraries
library(spatstat)
library(rgdal)
#Read-in road features (shapefile format)
roads_sldf <- readOGR("x://path to shapefile" , "roads")
#Convert roads spatial lines data frame to psp object
psp_roads <- as.psp(roads_sldf)
#Apply kernel density, however this is where I am unsure of the arguments
road_density <- spatstat::density.psp(psp_roads, sigma = 0.01, eps = 500)
Cheers.
See this question https://gis.stackexchange.com/questions/138861/calculating-road-density-in-r-using-kernel-density
Tried to mark as a duplicate but doesn't work because the other Q is on gis stack exchange
Short answer is use spatstat.geom::pixellate()
I also needed spatstat.geom::as.psp(sf::st_geometry(x)) to convert an sf lines object to the correct format and maptools::as.im.RasterLayer(r) to convert a raster. I was able to convert the result to RasterLayer with raster::raster(pix_res)
Perhaps you can use terra::rasterizeGeom which is available in the development version that you can install with install.packages('terra', repos='https://rspatial.r-universe.dev')
Example data
library(terra)
f <- system.file("ex/lux.shp", package="terra")
v <- vect(f) |> as.lines()
r <- rast(v, res=.1)
Solution
x <- rasterizeGeom(v, r, fun="length", "km")
And then use focal sum, but you would not have a perfect circle.
What you could do instead, if your dataset is not too large, is create a circle for each grid cell and use intersect. Something like this:
p <- xyFromCell(r, 1:ncell(r)) |> vect(crs="+proj=longlat")
p$id <- 1:ncell(r)
b <- buffer(p, 10000)
values(v) <- NULL
i <- intersect(v, b)
x <- aggregate(perim(i), list(id=i$id), sum)
r[x$id] <- x[,2]

R sample a raster with square polygons

I would like to sample a big raster by creating In small raster 100x100 cells.
I don't know how to do that so any ideas are welcome
My actual lead :
library(raster)
library(spatstat)
library(polyCub)
r <- raster(ncol=1000,nrow=1000) # create empty raster
r[] <- 1:(1000*1000) # Raster for testing
e <- extent(r) # get extend
# coerce to a SpatialPolygons object
p <- as(e, 'SpatialPolygons')
nc <- as.owin.SpatialPolygons(p) #polyCub
pts <- rpoint(50, win = nc)
plot(pts)
Now I need to generate 100x100 cell square around my 50 points and I would like to crop r using those square and stack each small raster individually ...
The answer by #adrian-baddeley basically has the ingredients to do what
you want. If you simply want a list of small im objects that contain
the 100x100 box you simply subset im objects by owin objects to
extract the relevant region. Here is an example (with fewer points to
avoid overplotting)
library(raster)
library(spatstat)
library(maptools)
r <- raster(ncol=1000,nrow=1000) # create empty raster
r[] <- 1:(1000*1000) # Raster for testing
e <- extent(r) # get extend
# coerce to a SpatialPolygons object
p <- as(e, 'SpatialPolygons')
nc <- as.owin.SpatialPolygons(p)
set.seed(42)
pts <- rpoint(7, win = nc)
rim <- as.im.RasterLayer(r)
Box <- owin(c(-50,50) * rim$xstep, c(-50,50) * rim$ystep)
The following is a list of im objects of size 100x100
imlist <- solapply(seq_len(npoints(pts)),
function(i) rim[shift(Box, pts[i])])
Here is a plot of the im objects in the region and the points on top
plot(pts)
for(i in imlist) plot(i, add = TRUE)
plot(pts, pch = 19, add = TRUE)
You can convert to a list of raster layers with
rasterList <- lapply(imlist, as, Class = "RasterLayer")
PS: The following is a list of im objects of the original size with
NA outside the 100x100 box if you need that format instead
imlist <- solapply(seq_len(npoints(pts)),
function(i) rim[shift(Box, pts[i]), drop = FALSE])
If you want to use spatstat then you need to convert the raster object r into an object of class im supported by spatstat. You can do this conversion in the maptools package. Call this image object rim. Then you can do as follows
Box <- owin(c(-50,50) * rim$xstep, c(-50,50) * rim$ystep)
BoxesUnion <- MinkowskiSum(pts, Box)
W <- intersect.owin(as.mask(rim), BoxesUnion)
This would give you the subset of the raster that is covered by the squares.
If you want to keep the squares separate, do something like
M <- as.mask(rim)
BoxList <- solapply(seq_len(npoints(pts)),
function(i) intersect.owin(M, shift(Box, pts[i])))
Then BoxList is a list of the individual sub-rasters.

How to get polygons of a shapefile containing centroids of polygons from another shapefile in R?

I'm working with two shapefiles in R and I'm trying to select the polygons of one of them which contains the centroids of another shp.
I've been able to get the centroids of each file separately (attached image), but I can't find a way to accomplish the task described above. In the example, let's say I want to get only polygons (shp1) with blue centroids (from shp2) inside of them.
example
Thanks!
You could use gCentroid() and gContains() from the rgeos package:
library(raster) ## For data and functions used to make example SpatialPolygons objects
library(rgeos) ## For topological operations on geometries
## Make a couple of example SpatialPolygons objects, p1 & p2
p1 <- shapefile(system.file("external/lux.shp", package="raster"))
r <- raster(extent(p1))
r[] <- 1:10
p2 <- rasterToPolygons(r, dissolve=TRUE)
## Find centroids of p2
cc <- gCentroid(p2, byid=TRUE)
## Select Polygons in p1 that contain at least one of centroids from p2
p3 <- p1[apply(gContains(p1, cc, byid=TRUE), 2, any),]
## Plot to check that that worked
ared <- adjustcolor("red", alpha=0.6)
plot(p1)
plot(p3, add=TRUE, col="wheat")
plot(p2, add=TRUE, border=ared)
points(cc, pch=16, col=ared)

error in mask a raster by a spatialpolygon

I have raster of the following features:
library(raster)
library(rgeos)
test <- raster(nrow=225, ncols=478, xmn=-15.8, xmx=32, ymn=-9.4, ymx=13.1)
I want to mask in this raster the cells that are within a given distance of a point.
I create the spatial points as followed:
p2=readWKT("POINT(31.55 -1.05)")
Then I create a spatial polygon object by adding a 0.5 buffer:
p2_Buffered <- gBuffer(p2, width = 0.5)
mask(test, mask=p2_Buffered,inverse=T)
When I mask my raster given this spatial object, I have the following error message:
Error in .polygonsToRaster(x, y, field = field, fun = fun, background
= background, : number of items to replace is not a multiple of replacement length
I do not understand because this is script I have been running many many times with different point and different buffer width without any problem.
What is strange is that when I change the width of the buffer, it works fine:
p2_Buffered <- gBuffer(p2, width = 0.4)
mask(test, mask=p2_Buffered,inverse=T)
This is also true for a different focal point:
p2=readWKT("POINT(32.55 -1)")
p2_Buffered <- gBuffer(p2, width = 0.5)
mask(test, mask=p2_Buffered,inverse=T)
I would like to identify the specific problem I have for that point because this is a script I should run in a routine (I have been doing it without any problem so far).
Thanks a lot
This is indeed a bug with polygons that go over the edge of a raster. It has been fixed in version 2.3-40 (now on CRAN), so it should go away if you update the raster package.
Here is a workaround (removing the part of the polygon that goes over the edge).
library(raster)
library(rgeos)
r <- raster(nrow=225, ncols=478, xmn=-15.8, xmx=32, ymn=-9.4, ymx=13.1)
e <- as(extent(r), 'SpatialPolygons')
p <- readWKT("POINT(31.55 -1.05)")
pb <- gBuffer(p, width = 0.5)
pbe <- intersect(pb, e)
values(r)
x <- mask(r, mask=pbe, inverse=TRUE)
You usually need to set some values to the raster layer. For a mask layer its always best to set values to 1.
library(raster)
library(rgeos)
# make sample raster
test <- raster(nrow=225, ncols=478, xmn=-15.8, xmx=32, ymn=-9.4, ymx=13.1)
# set values of raster for mask
test <- setValues(test, 1)
# make point buffer
p2=readWKT("POINT(15 5)")
p2_Buffered <- gBuffer(p2, width = 1.5)
# name projection of buffer (assume its the same as raster)
projection(p2_Buffered) <- projection(test)
# visual check
plot(test); plot(p2_Buffered, add=T)
If you want to trim down your raster layer to the just the single polygon then try this workflow.
step1 <- crop(test, p2_Buffered) # crop to same extent
step2 <- rasterize(p2_Buffered, step1) # rasterize polygon
final <- step1*step2 # make your final product
plot(final)
If you just want to poke a hole in your raster layer then use the mask function
# rasterize your polygon
p2_Buffered <- rasterize(p2_Buffered, test, fun='sum')
# now mask it
my_mask <- mask(test, mask=p2_Buffered,inverse=T) # try changing the inverse argument
plot(my_mask)

Cut polygons using contour line beneath the polygon layers

I would like to cut a polygon layer, according to the elevation, into two parts (upper and lower part). The polygon might convex or concave, and the position to cut might vary from each other. The contour line has an interval of 5m, which means I might need to generate a contour with much condensed contour lines, e.g, 1m interval. Any idea on how to do it, better in ArcGIS, or in R?
Below is the running example for the Q:
library(sp)
library(raster)
r<-raster(ncol=100,nrow=100)
values(r)<-rep(1:100,100)
plot(r) ### I have no idea why half of the value is negative...
p1<-cbind(c(-100,-90,-50,-100),c(60,70,30,30,60))
p2<-cbind(c(0,50,100,0),c(0,-25,10,0))
p1p<-Polygons(list(Polygon(p1,hole=T)),"p1")
p2p<-Polygons(list(Polygon(p2,hole=T)),"p2")
p<-SpatialPolygons(list(p1p,p2p),1:2)
plot(p,add=T)
segments(-90,80,-90,20) ##where the polygon could be devided
segments(50,20,50,-30) ##
Thanks in advance~
Marco
If I understand correctly, you can use the rgeos package and related Spatial tools in R.
I took the trick to buffer an intersected line and then generate the "difference" polygon from this site:
http://www.chopshopgeo.com/blog/?p=89
Generate example raster, and an overlying polygon.
vdata <- list(x = 1:nrow(volcano), y = 1:ncol(volcano), z = volcano)
## raw polygon data created using image(vdata); xy <- locator()
xy <- structure(list(x = c(43.4965355534823, 41.7658494766076, 36.2591210501883,
25.560334393145, 13.7602020508178, 18.7949251835441, 29.179041644792,
40.6645037913237, 44.2832110429707, 47.272577903027, 47.5872480988224
), y = c(30.0641086410103, 34.1278207016757, 37.6989616034726,
40.900674136118, 32.7732500147872, 27.4781100569505, 22.5523984682652,
22.7986840476995, 24.5226831037393, 29.3252519027075, 33.8815351222414
)), .Names = c("x", "y"))
## close the polygon
coords <- cbind(xy$x, xy$y)
coords <- rbind(coords, coords[1,])
library(sp)
## create a Spatial polygons object
poly <- SpatialPolygons(list(Polygons(list(Polygon(coords, hole = FALSE)), "1")))
## create a contour line that cuts the polygon at height 171
cl <- contourLines(vdata, levels = 171)
## for ContourLines2SLDF
library(maptools)
clines <- ContourLines2SLDF(cl)
Now, intersect the polygon with the line, then buffer the line slightly and difference that again with the polygon to give a multipart poly.
library(rgeos)
lpi <- gIntersection(poly, clines)
blpi <- gBuffer(lpi, width = 0.000001)
dpi <- gDifference(poly, blpi)
Plot the original data, and the polygon halves extracted manually from the Spatial object.
par(mfrow = c(2,1))
image(vdata)
plot(poly, add = TRUE)
plot(SpatialPolygons(list(Polygons(list(dpi#polygons[[1]]#Polygons[[1]]), "1"))),
add = TRUE, col = "lightblue")
image(vdata)
plot(poly, add = TRUE)
cl <- contourLines(vdata, levels = 171)
plot(SpatialPolygons(list(Polygons(list(dpi#polygons[[1]]#Polygons[[2]]), "2"))),
add = TRUE, col = "lightgreen")
That works for this fairly simple case, it might be useful for your scenario.

Resources