Clipping of raster as a shapefile in r - r

I want to clip a raster using shapefile in r as a shape of shapefile. I used crop function but it clipping as extents not as a shape. Please help me

Crop, as stated in the manual pages, crops to the extent of the object,
for your purposes you may use raster::mask(), with the same syntaxis of crop
mask function "Creates a new Raster* object that has the same values as x, except for the cells that are NA (or other maskvalue) in a ’mask’."
You may pass inverse=T so you get those values out of the spatialPolygon.

Related

Spatial extents of raster data and shapefile do not overlap, how to fix without sp transform?

Using a raster data set and a shapefile to find landscape metrics within buffers of raster. Sometimes the extents overlay and sometimes they do not overlap (using the same code). The extents are not the same despite using the spTransform function. How do I solve this? in Arc they do overlap.
library(raster)
library(rgdal)
CDL2020 <- raster("CDL_2020_38.tif")
Buffer_10 <- readOGR("LAND_ANALYSIS_3.0/10km_Buffer_2020.shp")
#Set to same projection
Buffer_10 <- spTransform(Buffer_10,proj4string(CDL2020))
Using this code I imported and set to the same projections, however they are still different extents.

R: Clip a shapefile boundary out of a generated image

I generated an image of ordinary kriged predictions. I have a shapefile of a boundary line and I'd like to crop the ordinary kriged predictions in the shape of that shapefile.
This is the code I use to generate the image:
image(OK.pred,loc=grid,axes=F,useRaster=TRUE). I just want to clip an object out of the image -- when I plot them, they overlay perfectly.
It's almost identical to the issue here, https://gis.stackexchange.com/questions/167170/is-it-possible-to-clip-a-shapefile-to-an-image-in-r, but I'm relatively new to R and got totally lost with the netcdf file part.
I found a bunch of code on how to clip rasters, but I just can't figure out how to even save an image into a variable let alone transform it to a raster in order to clip it. Any help would be much appreciated!
OK.pred<-krige.conv(gambling.geo,coords = gambling.geo$coords, data=gambling.geo$data, locations=grid,krige=krige.control(obj.model=gambling.vario.wls))
ordinarykrig = image(OK.pred,loc=grid,axes=F,useRaster=TRUE)
Macau <- readOGR("MAC_adm0.shp")
x <- crop(?...)
Taken from http://leg.ufpr.br/geoR/tutorials/kc2sp.R:
You need to convert the kriging output to a Spatial object before you can pass it to mask(). The following should do it:
OK.pred<-krige.conv(gambling.geo,coords = gambling.geo$coords, data=gambling.geo$data, locations=grid,krige=krige.control(obj.model=gambling.vario.wls))
GT.s <- points2grid(SpatialPoints(as.matrix(grid)))
reorder <- as.vector(matrix(1:nrow(grid), nc=slot(GT.s, "cells.dim")[2])[,slot(GT.s, "cells.dim")[2]:1])
SGDF.s <- SpatialGridDataFrame(grid=GT.s, data=as.data.frame(OK.pred[1:2])[reorder,])
r<-raster(SGDF.s)
x<-mask(r, Macau)

Changing the extent and resolution of raster layers in R for successful stacking

I am trying to create a species distribution model in R. I have created raster layers in ArcMap and have imported them into R. They cannot be stacked unless the extents are exactly the same and they all have the same number of rows and columns.
However, when I alter these factors to successfully stack them they lose all their values and my stacked data frame is just filled with NAs.
Does anyone know how I can alter the extent and resolution of my raster layers so they can be successfully stacked -- so I can then attach environmental info to presence points.
Cheers
One way to do this is to choose a raster that has the projection and extent that you want and use that as a template for the others
For example, if you have rasterA and rasterB. You can use projectRaster() to make a new version of rasterA with the same extent and resolution as rasterB. You should then be able to stack new.rasterA & rasterB.
new.rasterA <- projectRaster(rasterB, rasterA) # define the projection and extent
r.stack <- stack(new.rasterA, rasterB) # add them to a raster stack object
I had the same issue and I solved this in arcgis by snapping each raster to a mask of my study area.
This can be done by clicking geoprocessing -> environments -> processing extent - then select a layer you want to snap to in the snap raster box. I did this before I extracted (clipped) each layer and it worked perfectly. You can check the extent in properties when you are done for each layer you do to double check before you upload them into R.

OSM autoplot automatically alters coordinates

I have noticed that the autoplot function in OpenStreetMaps seems to change the x,y axis scale in a strange way. Contrast the map produced through ggmap:
test1=get_map(location=c(31.00302,-4.27480,41.84012,4.291),source="osm")
ggmap(test1)
and the map created by OpenStreetMap's ggplot2 compatible plotting function:
UL=c(4.29100,31.00302)
LR=c(-4.27480,41.84012)
test2=openmap(UL,LR,type="osm")
autoplot(test2)
These two should be the same, but the map produced by autoplot has longitude and latitude coordinates multiplied by 100,000. How do I make it so that autoplot does not multiply everything by 100,000?
(Just renaming everything is not sufficient. I need the underlying coordinate system to reflect the numbers used above.)
Thank You.
I needed to change the projection to a long/lat projection. This was accomplished by:
test2=openproj(test2, projection = "+proj=longlat")

R clip raster with multiple bands

I want to create a subset of an image with four bands. Therefore I am using the crop function in R.
A<-raster("L8_stacked.tif")
subset<-extent(c(639451, 660104, 5469254, 5489566))
B<-crop(A,subset)
As a result I get a raster with only one band in the .tif file. Do I have to define other options to get a subset image with 4 bands?
As the others already pointed out in the comments, the raster() function returns a (single) RasterLayer object. If you want a multilayer raster object you need to use the stack() or brick() function load the image into R. I.e.:
A <- stack("L8_stacked.tif")
If you then apply your extent with the crop() function, the result should be a raster stack containing all the bands from the original image.
To learn more on the raster package, read this document.

Resources