Extract raster values of particular polygons of a SpatialPolygonsDataFrame (indexation) - r

I have a SpatialPolygonsDataFrame with 120 Polygons and some associated data. Now I’d like to extract the mean of the values on a raster within each polygon separately. I succeded in plotting individual polygons with:
plot(SpatialPolygons(SPdataframe#polygons)[i])
But it did not work to extract the values in the same manner:
extract(raster, SpatialPolygons(SPdataframe#polygons)[i],fun="mean",na.rm=TRUE,method="simple")
Can anyone explain the difference between the use of the same indexation in this two cases? What is the official way to choose particular polygons of a SpatialPolygonsDataFrame with indices?
Thank you a lot for your help in advance!

The correct indexation for single polygons of a SpatialPolygonsDataFrame is: SPdataframe[i,]
(Merci to R-sig_geos user Rafael Wüest)

Related

Is there a way to randomly create points (geo-referenced) in a raster within the area defined by a shapefile? Rstudio

Ok so, this might actually be very straightforward and I apologize in advance.
I am using R for a geospatial analysis. I want to create a series of geo-referenced points which are randomly (but uniformly) generated across the area delimited by the limits of a shapefile.
Let's say that I Have a raster of the american continent and the shapefiles of the major lakes (just an example). I would like to create points for one species inside lake 1, then for another inside lake 2.
Is this at all possible? Using shapefiles to limit the geographical extent and then randomly sampling a pre-determined (and equidistanced) number of points?
Thank you very much in advance for any help and insight.
I have yet to try anything because I have actually no idea where to start in terms of randomly generating the points but according to the specificity of them being equidistant
Looking into this question using ggmap to plot points randomly distributed within boundaries of shape file that was suggested by stack overflow, part of my question is answered. However, how would I go to get, let's say, a point every km in a type of grid inside the shape?
Cheers
Francisco
Here is an example showing how you can get 10 regularly distributed points for each of the second level subdivisions of Luxembourg.
library(terra)
v <- vect(system.file("ex/lux.shp", package="terra"))
set.seed(12)
s <- spatSample(v, 10, "regular", strata="NAME_2")
plot(v)
points(s, col="red")

How to extract data points from rasterstack to a shapefile?

I need to extract daily weather data points from a raster stack and place it over a shapefile of various sewer sheds in my state. My boss wants me to use the writeRaster and extract function to do this. He said this would create a GeoTiff. I am new to R and unsure how to do something like this. Anything that can point me in the right direction would be appreciated.

Extract values in a Spatial Polygon dataframe

I'm currently trying to find out a value of a certain polygon in my Spatial Polygon dataframe. I need to know what "ID" was assigned to each "FSA" level. Below is the picture of how my data is set up. The dataset is called "FSA2015EditedFINAL2". I tried this:
FSA2015EditedFINAL2#polygons[[1]]#ID
But that just tells me the first polygons ID, and I don't know what FSA that corresponds to...
I'm hoping to be able to type in the FSA I need and pull out what ID it got.
Any help would be amazing!!!!
Thanks!

writeRaster function in R is automatically setting (unwanted) maximum value, can I set the max value to null?

I am running into a problem with the "writeRaster" function in the raster package in R. I am importing a raster (TIF) that I made in ArcGIS (a distance to feature raster).
My goal was to resample the distance raster to the correct resolution and extent, then "mask" it with the appropriate raster to crop it to the shape I require. When I check the results of the mask with the basic plot function, everything looks great and I can see that each pixel in the new masked raster has a distance value.
However, when I write this raster to a file using the writeRaster function, the resulting raster looks like "swiss cheese" and has missing values for any distance over 35km. After much reading, I cannot find any documentation to suggest that there is a way to modify the maximum value set by writeRaster---or that it should even be setting a max value. I have included my code and the basic plots below. A big thank you to anyone who attempts to help me with this!
#Read in distance to fresh water raster
distFW <- raster("D:/Academia/Arc Data/Grackle/NicaCR_90mlayers/dist_FW.tif")
[plot(distFW)][1]
#Resample this layer to the desired resolution and template
NiCR_DistFW<-as.integer(resample(distFW,NiCRrast.tmpl,method="ngb"))
#essentially the same as the first plot
[plot(NiCR_DistFW)][2]
#Mask the resampled raster to the desired shape
NiCR.DistFW.mask.utm <- mask(NiCR_DistFW,NiCR_Mask) #with CA countries cut out.
[plot(NiCR.DistFW.mask.utm)][3]
#write raster to file (this is where things get weird)
writeRaster(x=NiCR.DistFW.mask.utm, filename='DistFWmask2.tif', format='GTiff', datatype='INT2S') #a way to ensure INT2S
#read the newly written raster file in to R so we can review it
dFW <-raster("DistFWMask2.tif")
[plot(dFW)_writeRaster_result][4]
[1]: https://i.stack.imgur.com/v9RkK.jpg
[2]: https://i.stack.imgur.com/v2DG3.jpg
[3]: https://i.stack.imgur.com/cCwJe.jpg
[4]: https://i.stack.imgur.com/MjWj7.jpg
As you can see from plot 4, an undesirable max value has been set. I was the raster I write to file to look like the one in plot 3, not plot 4.
Thanks in advance for any advice.
Well friends, after taking an hour to detail my question I managed to figure out the answer myself. It had to do with setting the datatype.
INT2S has a maximum value of 32,767
by switching it to INT4S, I capture the full range of values in my raster.
Problem solved!

Reattach attribute table to Spatial Polygon to make Spatial Polygon Dataframe

I have built a web app using Shiny and Leaflet, but it renders very slowly because the Spatial Polygon DataFrame (merge.proj) that is being added to the map is 20,000 polygons. I may try to allow the user to view only certain neighborhoods at a time as a fix, but first I thought I'd simplify polygons to see how much that sped up the process.
My understanding is that simplifying polygons reduces # of vertices etc and gives you a Spatial Polygon, which loses the attribute table. I was hoping to then reattach the attribute table and re-create a Spatial Polygon Dataframe that is hopefully reduced in size.
However, the code is erroring and all the help I can find online just shows how to do this when making the Spatial Polygon and dataframe from scratch, and I'm having trouble applying what they did to my data (see here). The error says that my polygon IDs and row.names don't match, but they both originally came from the same Spatial Polygon Dataframe so I'm confused. And I'm not sure how to manually manipulate things so they match.
I am pasting below the error and the code I currently have. Any suggestions would be greatly appreciated!
# For faster plotting, simplify polygons
merge.simplify <- gSimplify(merge.proj,0.1,topologyPreserve = T)
# Create a dataframe
merge.df <- data.frame(merge.proj#data)
# Do coercion to SPDF
merge.spdf <- SpatialPolygonsDataFrame(merge.simplify, merge.df)
ERROR: Error in SpatialPolygonsDataFrame(merge.simplify, merge.df) :
row.names of data and Polygons IDs do not match

Resources