问题
I am new to R and I have a simple problem (by my opinion) but I haven't found a solution so far. I have a (long) set of 2D (x,y) coordinates - just points in 2D space, like this:
ID x y
1 1758.56 1179.26
2 775.67 1197.14
3 296.99 1211.13
4 774.72 1223.66
5 805.41 1235.51
6 440.67 1247.59
7 1302.02 1247.93
8 1450.4 1259.13
9 664.99 1265.9
10 2781.05 1291.12
etc.....
How do I filter points (rows in the table) that are in certain area (of any shape!)? How to filter dots that are within a subset of specified coordinates. How do I specify the wanted/unwanted area subsets? And how to put it in R? :) Thx a lot in advance!
回答1:
To check if points are inside a shape of any kind use the inpip
function of the splancs
package.
library(splancs)
set.seed(123)
my.shape <- matrix(runif(10), 5)
my.points <- data.frame(x=runif(500), y=runif(500))
my.points$in.shape <- 1:500 %in% inpip(my.points, my.shape)
plot(my.points[1:2], col=1 + my.points$in.shape)
polygon(my.shape)
To test for multiple shapes, put them in a list and use lapply
:
set.seed(127)
multi.shapes <- lapply(1:3, function(...) matrix(runif(6), 3))
my.points$in.multi.shapes <- 1:500 %in%
unlist(lapply(multi.shapes, function(p) inpip(my.points, p)))
plot(my.points[1:2], col=1 + my.points$in.multi.shapes)
for(p in multi.shapes) polygon(p)
来源:https://stackoverflow.com/questions/17571602/r-filter-coordinates