Check if lat/lon in polygon (R) - r

I have a lat/lon combination and want to check whether the point is inside a polygon (sp::Polygon class)
Consider this example:
UKJ32 <- sp::Polygon(cbind(c(-1.477037449999955, -1.366895449999959, -1.365159449999965, -1.477037449999955),
c(50.923958250000027, 50.94686525000003, 50.880069750000018, 50.923958250000027))) %>%
list() %>%
sp::Polygons(ID="UKJ32 - Southampton")
I would now like to test whether the points in df are in this polygon (and if so, return the Polygon ID).
tibble(lon = c(-1.4, 10), lat = c(50.9, 10))
Can someone tell me how I get to the result
tibble(lon = c(-1.4, 10), lat = c(50.9, 10), polyg_ID = 'UKJ32')

If you wish to stick to sp, there is a point.in.polygon() function in sp package:
UKJ32 <- sp::Polygon(cbind(c(-1.477037449999955, -1.366895449999959, -1.365159449999965, -1.477037449999955),
c(50.923958250000027, 50.94686525000003, 50.880069750000018, 50.923958250000027))) |>
list() |>
sp::Polygons(ID="UKJ32 - Southampton")
a <- tibble::tibble(lon = c(-1.4, 10), lat = c(50.9, 10))
sp::point.in.polygon(a$lon, a$lat, UKJ32#Polygons[[1]]#coords[,1], UKJ32#Polygons[[1]]#coords[,2])
#> [1] 1 0
Created on 2022-10-16 with reprex v2.0.2

The {sp} package is by now somewhat dated - after having lived a long & fruitful life - and most of current action happens in context of its successor, the {sf} package.
Assigning some kind of a polygon feature - either an id or a metric - to a points dataset is a frequent use case. It at present often done via a sf::st_join() call. For an example in action consider this earlier answer https://stackoverflow.com/a/64704624/7756889
I suggest that you try to move your workflow to the more current {sf} package; you will find it easier to keep up with recent development.
And even if this were not possible for whatever reason - use sp::Polygons() with utmost caution. I carries no information about coordinate reference system - which is a fancy way of saying it has no way of interpreting the coordinate numbers. Are they decimal degrees, or meters? Could be feet or fathoms for all that I know.
Strictly speaking you should not be allowed to proceed with a point-in-polygon operation calculation without this information.

Related

R: Applying a function to two different tables based on a condition (Spatial Join)

I suspect that this is fairly trivial, but I'm also fairly new to R and have not found a solution to this so far.
I have two tables of events, A and B, each containing points with spatial information (latitude and longitude) and dates. Both are sf objects. Table A has fewer events than table B.
The data in both tables looks like this:
ID
date
lat
lon
1
2020/01/01
44.62
34.88
For every point from A, I want to find the nearest neighbor from B - but only for events on that day. And then add its ID and the distance to a new column. The function to perform the spatial join is st_join from the nngeo package and works great.
In other words, I'd want the program to take an event in table A, then take every event on the same day in table B and then apply the st_join function. It should iterate through every event in A and repeat the same procedure.
I think that this would require a for...if...else statement, but I can't wrap my head around what it would look like, especially since there are two different tables involved. Like I said, I'm new to R.
My idea so far looks something like this:
for (row in AW_sf){
if (AW_sf$date == OIR_sf$date){
SpacialJoin <- st_join(AW_sf, OIR_sf, join = st_nn, k = 1)
}
else {
print ("Done")
}
}
This does not work, and it also seems wrong. Accordingly, it results in 12 warnings like so:
In `==.default`(AW_sf$date, OIR_sf$date) :
longer object length is not a multiple of shorter object length
2: In if (AW_sf$date == OIR_sf$date) { ... :
the condition has length > 1 and only the first element will be used
I hope I expressed myself somewhat clearly and I'm sorry if something remains unclear. I would be incredibly thankful for any ideas or help!
I figured it out, it's not the most elegant or fast solution I suppose, but it's much simpler than I thought it would have to be and it does the trick, using the function r2evans suggested.
EventPairs <- A %>% geo_join(B, by=c("longitude", "latitude"), unit =
c("km"), max_dist = 20, distance_col = "distance") %>% filter(date.x
== date.y)

Why does dput()/dput2() not work with Polygons / SpatialPolygons

I would like to ask another question, which includes SpatialPolygons. In order to make it reproducible I wanted to use dput() for the SpatialPolygons object, but its not outputting a reproducible structure.
Why can I use dput() with SpatialPoints, but not with Lines/SpatialLines, Polygons/SpatialPolygons?
Is the only workaround, to export the coordinates and recreate the SpatialPolygons in the example?
Test Data:
library(sp)
df = data.frame(lon=runif(10, 15,19), lat=runif(10,40,45))
dput(SpatialPoints(coordinates(df)))
dput(Lines(list(Line(coordinates(df))), 1))
dput(SpatialLines(list(Lines(list(Line(coordinates(df))), 1))))
dput(Polygons(list(Polygon(df)), 1))
dput(SpatialPolygons(list(Polygons(list(Polygon(df)), 1))))
dput(SpatialPolygons(list(Polygons(list(Polygon(df)), 1))), control="all")
The dupt2() method from this answer works for Lines/SpatialLines but not for Polygons/SpatialPolygons, where this error occurs:
Error in validityMethod(object) : object 'Polygons_validate_c' not
found
So how to make a SpatialPolygons-object reproducible?
A workaround would be to convert the objects to simple features and then use dput(). They can obviously be deparsed.
Example using LINESTRING and POLYGON:
library(sp)
library(sf)
df = data.frame(lon=runif(10, 15,19), lat=runif(10,40,45))
SLi = SpatialLines(list(Lines(list(Line(coordinates(df))), 1)))
SPo = SpatialPolygons(list(Polygons(list(Polygon(df)), 1)))
dput(st_as_sf(SLi))
dput(st_as_sf(SPo))
After running the code I mentioned in the comments, I decided I would offer a tentative solution and see if you a) have the same results on your system, and b) whether it addressed the issues you were having.
newSpPa <- dput(SpatialPolygons(list(Polygons(list(Polygon(df)), 1))), control="all")
oldSpPa <- SpatialPolygons(list(Polygons(list(Polygon(df)), 1)))
identical(oldSpPa, newSpPa)
#[1] TRUE
It wasn't clear from my reading your question whether the return of a call to new("SpatialPolygons", ...) was deemed to be unsatisfactory. I think the assignment step that I did was different than your code and it's possible that my assignment would only succeed in the setting of previously defined objects being in the workspace at the time of creation. If that's the case then I think the typical suggestion would be to do this in the setting of package-creation.

Find nearest features using sf in R

I'm wanting to find the nearest polygons in a simple features data frame in R to a set of points in another simple features data frame using the sf package in R. I've been using 'st_is_within_distance' in 'st_join' statements, but this returns everything within a given distance, not simply the closest features.
Previously I used 'gDistance' from the 'rgeos' package with 'sp' features like this:
m = gDistance(a, b, byid = TRUE)
row = apply(m, 2, function(x) which(x == min(x)))
labels = unlist(b#data[row, ]$NAME)
a$NAME <- labels
I'm wanting to translate this approach of finding nearest features for a set of points using rgeos and sp to using sf. Any advice or suggestions greatly appreciated.
It looks like the solution to my question was already posted -- https://gis.stackexchange.com/questions/243994/how-to-calculate-distance-from-point-to-linestring-in-r-using-sf-library-and-g -- this approach gets just what I need given an sf point feature 'a' and sf polygon feature 'b':
closest <- list()
for(i in seq_len(nrow(a))){
closest[[i]] <- b[which.min(
st_distance(b, a[i,])),]
}

R function to count coordinates

Trying to get it done via mapply or something like this without iterations - I have a spatial dataframe in R and would like to subset all more complicated shapes - ie shapes with 10 or more coordinates. The shapefile is substantial (10k shapes) and the method that is fine for a small sample is very slow for a big one. The iterative method is
Street$cc <-0
i <- 1
while(i <= nrow(Street)){
Street$cc[i] <-length(coordinates(Street)[[i]][[1]])/2
i<-i+1
}
How can i get the same effect in any array way? I have a problem with accessing few levels down from the top (Shapefile/lines/Lines/coords)
I tried:
Street$cc <- lapply(slot(Street, "lines"),
function(x) lapply(slot(x, "Lines"),
function(y) length(slot(y, "coords"))/2))
/division by 2 as each coordinate is a pair of 2 values/
but is still returns a list with number of items per row, not the integer telling me how many items are there. How can i get the number of coordinates per each shape in a spatial dataframe? Sorry I do not have a reproducible example but you can check on any spatial file - it is more about accessing low level property rather than a very specific issue.
EDIT:
I resolved the issue - using function
tail()
Here is a reproducible example. Slightly different to yours, because you did not provide data, but the principle is the same. The 'principle' when drilling down into complex S4 structures is to pay attention to whether each level is a list or a slot, using [[]] to access lists, and # for slots.
First lets get a spatial ploygon. I'll use the US state boundaries;
library(maps)
local.map = map(database = "state", fill = TRUE, plot = FALSE)
IDs = sapply(strsplit(local.map$names, ":"), function(x) x[1])
states = map2SpatialPolygons(map = local.map, ID = IDs)
Now we can subset the polygons with fewer than 200 vertices like this:
# Note: next line assumes that only interested in one Polygon per top level polygon.
# I.e. assumes that we have only single part polygons
# If you need to extend this to work with multipart polygons, it will be
# necessary to also loop over values of lower level Polygons
lengths = sapply(1:length(states), function(i)
NROW(states#polygons[[i]]#Polygons[[1]]#coords))
simple.states = states[which(lengths < 200)]
plot(simple.states)

Include polygon ID when extracting raster values to polygons in R

I followed How do I extract raster values from polygon data then join into spatial data frame? (which was helpful) to create a matrix (then data frame) of mean raster values to a polygon. The problem now is that I want to know which polygon is which. My SpatialPolygonsDataFrame has an ID value in p$Block_ID. Is there a way to bring that over in the extract() code?
Alternatively, does the extract() function report output in the order it was input (that would make sense)? i.e. the order of p$Block_ID will be preserved in the output? I looked through the documentation and it was not clear one way or the other. If so it is easy enough to add an ID column to the extract() output.
Here is my generalized code for reference. NOTE note reproducible because I don't think it really needs to be at this point. Where r is a raster and p in the polygons
extract(r, p, small = TRUE, fun = mean, na.rm = TRUE, df = TRUE, nl = 1)
Thoughts?
The values are returned in order, as one would expect in R, and as stated in the manual (?extract): The order of the returned values corresponds to the order of object y
Thus you can do (reproducible example from ?extract)
e <- extract(r, p)
ee <- data.frame(ID=p$Block_ID, e)
I could not get R. Hijmans answer working for me. I found that this works.
e = extract(r, p)
e$ID = as.factor(e$ID)
levels(e$ID) = levels(p$Block_ID)

Resources