Determine is a point falls within a json - r

I'm trying to determine if a point falls within a JSON sf. There were several postings that indicated the "over" function in the "sp" package would work, but I'm getting an error.
northamerica <- geojsonsf::geojson_sf("data/custom.geo.json") #source: https://geojson-maps.ash.ms/ - Regions - north america
northamerica <- sf::st_transform(northamerica,crs=4326)
pts <- data.frame(click=1,lat=37.43997, lng=277.9102)
pts <- sf::st_as_sf(x = pts,coords = c("lng", "lat"),
crs = 4326)
sp::over(pts,northamerica)
I get the following error when I run the above code:
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘over’ for signature ‘"sf", "sf"’
Any ideas why I'm getting this error or suggestions on an alternative method?

I realized that with sf objects that I needed to us "sf_within" instead of "over" from the sp package. Still learning spatial data in R.

Related

Resample and matching raster stack using loop in R

I aim to combine biodiversity data with land cover information (rasters and vectors).
However, I need to match the resolution, extent, CRS, and dimensions of each raster (predictor variables) with my biodiversity data (answer variables). I had succeed to do it individually but there are six rasters.
Although, when I try a loop for the raster stack. I got some errors.
 
library(terra)
library(raster)
#Create a raster stack with land cover predictors:
CDI_stack<-raster::stack(list.files(path = dir_Proj1, pattern='.tif', full.names=T))
#Convert to cylindrical equal area projection
equalareaproj<-"+proj=cea +lon_0=0 +lat_ts=30 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"
crs(CDI_stack, warn=FALSE)<-equalareaproj
#Raster with standard dimension, resolution, extention and CRS
standard<-terra::subset(study_area, 2)
#Loop for the raster stack
for(i in 1:length(CDI_stack#layers)){
#Creating a single raster with each layer to maintain values
CDI_layer<-terra::rast(terra::subset(CDI_stack, i))
#Matching a raster extention individually
CDI_layer<-ext(standard)
#Cropping it with standard raster to reduce matching error
raster::crop(CDI_layer[i],standard)
#Resample resolution
terra::resample(CDI_layer[i], standard, method= "near", threads= T)
#Write the raster:
return(writeRaster(Resampled_layer,
filename=paste0("~/Land use/Chronic_Anthropogenic_Disturbance_Surface/", CDI_layer[i]),
format="GTiff", overwrite=TRUE))
}
I found these errors:
Error in h(simpleError(msg, call)) :
error evaluating argument 'x' in method selection for function 'crop': 'this S4 class is not subsettable
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘crop’ for signature ‘"numeric"’
I would like to know if there's any complication to use raster stack or whether I am doing any code step wrongly. I expect to found the correction on the code or of the use of class object.
Please, I hope for your support. Thank you!
G.
Thank you for your advice, Mr. Hijimans.
I found too many errors.
When we do it directly with the raster stack the R returns that the method for the function 'resample' does not work on RasterStack class (see below).
As a stack can have multiple layers, the loop simplified the process rather to work on each one of them.
I preferred to work with a list from the raster stack than the stack, it worked better in the loop.
Also, I used a vector to crop the raster, it preserved raster values (avoiding return NA).
rc <- terra::resample(CDI_stack, standard, method= "bilinear", threads= T)
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘resample’ for signature ‘"RasterStack", "SpatRaster"’
#Create a list from the stack with land cover predictors:
CDI_list<-terra::as.list(CDI_stack)
rm(study_area,CDI_stack)
#Create a list to store the results
results <- list()
#Loop for each SpatRaster from the list
for(i in 1:length(CDI_list)) {
r<-rast(CDI_list[[i]]) # create a raster for each layer
ext(r) <-ext(standard) # redefine extension for each layer
#Crop rasters using the vector to avoid 'NA' values
rc <- terra::crop(r, standard_vec)
#Resample rasters following standard parameters
rc <- terra::resample(rc, standard, method= "bilinear", threads= T)
#Rewrite the list layers with the result
results[[i]] <- rc
}
#Check the values
results[[4]]
#Rasterize the list to save it as a data frame
resampled<-rast(results)
df<-as.data.frame(resampled)
summary(df)
#Save the data frame in the project directory
data.table::fwrite(df, "~/Land use/DATASETS/resampled.csv")
It should be easy enough to find out what is going wrong when you run the code line by line; including inside the for-loop (set i to 1 or whatever the valye is when the error occurs).
You will see that this fails:
CDI_layer <- ext(standard)
raster::crop(CDI_layer[i],standard)
Because CDI_layer[i] is a single number.
There are other things that are awkward. Especially, just use "terra", do not also use "raster" at the same time to avoid confusion.
Seeing your answer it would seem that you can do all of this in two lines
CDI_stack <- terra::rast(files)
rc <- terra::resample(CDI_stack, standard, method= "bilinear", threads= T)
df <- as.data.frame(rc)

How to calculate the distance of a centroid to a polygon in a shape file? R

I have this, and I am trying to use gDistance to calculate the distance between each centroid and the city of Baghdad. I am trying to do it like this:
gDistance(districts_centroids, districts#data$ADM3NAME %in% c("Baghdad"), byid=TRUE)
Where district_centroids are Formal Class SpatialPoints, and the districts#data... is basically the city of Baghdad in the shp file.
I get an error saying the following:
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘is.projected’ for signature ‘"logical"’
In addition: Warning message:
In RGEOSDistanceFunc(spgeom1, spgeom2, byid, "rgeos_distance") :
Spatial object 1 is not projected; GEOS expects planar coordinates
I am completely new to R and I don't really know what's going on.
Any help would be appreciated
Thank you!
This is a great question. After taking a look at things, it was decided the best way to answer this question was using simple feature objects rather than spatial objects.
The map in question looks familiar. I used the IRQ_2_sf.rds map which is probably the same map used and shown above. There are other alternative ways to achieve the solution to this question. Jupyter Lab is the IDE used.
Using the Google API and the geocode function, the coordinates for Baghdad were retrieved.
baghdad <- geocode("Baghdad, Iraq", source = c("google") )
A tibble: 1 × 2
lon lat
<dbl> <dbl>
44.36607 33.31524
Then sf functions were used to create the sf column object.
baghdad.sfg <- st_point(c(lon, lat), dim = "XY")
baghdad.sfc <- st_sfc(baghdad.sfg, crs = 4326)
Then, using the sf map named iraq, the centroids were created.
Note: warning message - st_centroid does not give correct centroids for longitude/latitude data. For this answer, the centroids will be close
enough.
iraq.c <- st_centroid(iraq)
The distance from each centroid to Baghdad gets determined in kilometers.
head(dist <- data.frame(c(st_distance(iraq.c$geom[], baghdad.sfc)/1000)))
Units: [m]
[1] 28.63250 59.61553 215.43354 323.06418 259.14509 113.55356
And then create a date frame that includes the names, the centroid geometry and the distance values. Requires some cleaning and binding.
distance <- c(dist$c.st_distance.iraq.c.geom....baghdad.sfc..1000.)
x <- distance[]
d_Bdad_Km <- as.numeric(str_extract(x, "[0-9]*.[0-9]."))
iraq2 <- iraq[-c(5, 8,9,10,11,12,13)]
df_dist <- cbind(iraq2, d_Bdad_Km) # df as desired
And then the outputs gets plotted.
plot(iraq$geom)
plot(iraq.c$geom, add = TRUE, col = "red")
plot(baghdad.sfc, add = TRUE, pch = 19, col = "blue")
Please ask if there are any follow-up questions. The plot can be viewed at this link:

Extract WORLDCLIM data using R for a single country

I want to extract world climate data for minimum and maximum temperature for only one country India using R and save it as a data set (to use with my own data-set that contains crop yields at the district level).
I have gone through several posts and can see that this can be done easily in R, however the posts that I have tried to follow are a bit different in terms of the commands or sequences and I am getting confused.
(https://gis.stackexchange.com/questions/259478/worldclim-data-na-for-my-coordinates, https://gis.stackexchange.com/questions/227585/using-r-to-extract-data-from-worldclim
What I have tried to use is as follows.
library(raster)
library(sp)
r<- getData('CMIP5', var='tmin', res=10, rcp=45, model='HE', year=70)
r <- r[[c(1,12)]]
values <- extract(r,points)
df <- cbind.data.frame(coordinates(points),values)
head(df)
However, I can run only the first two lines and the line values
<- extract(r,points) gives the error Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘extract’ for signature ‘"RasterStack", "function"’
Any suggestions?
Here is the solution for it
library(raster)
library(sp)
library(rgeos)
library(rgdal)
library(sf)
r<- getData('CMIP5', var='tmin', res=10, rcp=45, model='HE', year=70)
#Using Zonal statistics
poly <- shapefile("Provide_your_drive_name" e.g. "F:\\Kriging in R\\India Shape files\\2011_Dist.shp")
plot(poly)
#This will take considerable time
ex <- extract(r, poly, fun='mean', na.rm=TRUE, df=TRUE, weights = TRUE)
write.csv(cbind(poly$DISTRICT,ex),"Worldclim.csv", row.names = F)
# using centroids
nc <- st_read(dsn="Provide_your_drive_name" e.g. "F:\\Kriging in R\\India Shape files", layer="2011_Dist")
# just view the attributes & first 6 attribute values of the data
head(nc)
sp_cent <- gCentroid(as(nc, "Spatial"), byid = TRUE)
values <- extract(r,sp_cent)
write.csv(cbind(as.data.frame(nc$DISTRICT),as.data.frame(values)),"Worldclim_centroids.csv", row.names = F)

R - Crop for JPEG Impages

I'm trying to plot a image (a flag) on a map using raster layers and
# Load packages
library(maptools)
library(raster)
library(jpeg)
# Read in a jpeg and convert to raster
usa.flag <- as.raster(readJPEG(".../usa.jpg"))
# Get spacial image of map
data("wrld_simpl")
usa.map <- subset(wrld_simpl, NAME == "United States")
When I try to crop, I get an error:
usa.sub <- crop(usa.flag, extent(usa.map))
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘crop’ for signature ‘"raster"’
But I can't figure out what I'm missing about the use of crop().

What does the following error mean: TopologyException: found non-nonded intersection between LINESTRING

I'm trying to fortify a shape file that I loaded into R with rgdal, but I get the following error:
"Error: TopologyException: found non-noded intersection between LINESTRING
(34.7279 1.59723, 34.7278 1.59729) and LINESTRING
(34.7278 1.59723, 34.7278 1.59729) at 34.727793021883102 1.5972887049072426"
I am using a shape file for the continent of Africa from maplibrary.org. It is available from my dropbox here: https://www.dropbox.com/s/etqdw3nky52czv4/Africa%20map.zip
I am using the following code:
library(rgdal)
library(ggplot2)
africa = readOGR("Africa_SHP", layer = "Africa")
africa.map = fortify(africa, region="COUNTRY")
And I get the error I mentioned before. I take it that R has some problems with the polygon - is there a way around this?
As you can see from the comments mdsumner and agstudy were able to answer why this is happening, though agstudy was unable to recreate it with the dataset available. I did find a work-around for this problem.
library(rgdal)
library(rgeos)
library(ggplot2)
#LOADING IN DATA
africa = readOGR("directory", layer="filename")
#FIXING THE NON-NODED INTERSECTS#
africa = gBuffer(africa, width=0, byid=TRUE)
africa.map = fortify(africa, region="ID")

Resources