[R] Determine if a set of x and y-latitude points are inside of a polygon using R
David L Carlson
dcarlson at tamu.edu
Thu Apr 28 15:38:03 CEST 2016
Give us reproducible data using dput(). There are easier ways to accomplish what you want in R. The overwriting problem stems from the fact that you have a double loop so each iteration of the outer loop overwrites the data produced in the inner loop.
Also your if/else specification should be producing the following error message:
Error: unexpected 'else' in "else"
Since else needs to be on the same line as the closing curly brace for if:
if (M>1) {
Bounds$T[i] = M
} else
{
Bounds$T[i] = M
}
And why use if/else at all since you execute Bounds$T[i] = M either way?
-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352
-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Shawn Adderly
Sent: Wednesday, April 27, 2016 3:08 AM
To: r-help at r-project.org
Subject: [R] Determine if a set of x and y-latitude points are inside of a polygon using R
Objective: Determine if a set of x and y-latitude points are inside of
a polygon using R.
Lets say I have 9 polygons. Where I have labeled the polygons to be
checked from 1-9. The problem I’m running into is running the
point.in.polygon to check if those points are in one of several
polygons, as my code overwrites the result.
To accomplish this I am using the R-built in function called
point.in.polygon. Point.in.polygon takes the x, and y lat/lon points,
and the polygon boundaries.
Here is the code I've written thus far:
require("SDMTools")
require("sp")
#b is the polygon that I'm referring
for (b in 1:9)
{
D <- subset(Bounds, Polygon == b)
for (i in 1:length(Bounds$latitude))
{
M = point.in.polygon(Bounds$latitude[i], Bounds$longitude[i], D$PY,D$PX)
if (M>1) {
Bounds$T[i] = M
}
else
{
Bounds$T[i] = M
}
}
}
Minimal Dataset:
Latitude Longitude Polygon Latitude Polygon Longitude Polygon
38.65485 -121.4965 38.43768 -121.4018 1
38.562 -121.4768 38.56559 -121.4018 1
38.7011 -121.3018 38.57065 -121.5141 1
38.62568 -121.3198 38.56559 -121.5141 1
38.60253 -121.2899 38.563459 -121.5141 2
38.28272 -121.2969 38.56359 -121.5141 2
38.64286 -121.2204 38.54065 -121.515 2
38.67442 -121.5105 38.57065 -121.515
______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list