I need to write a line of code that will find coordinates out of bounds, and change them back into bounds. I'm trying to use mapply() with an ifelse(), but I keep getting errors. Example below.
I have a list of spatial points (x,y coords) and particles moving through that space. When particles move too far from any points, I need to reel them back in. For now, I'm trying to take particles that are further from the nearest point than that point is to its nearest neighbor, and pull them back to the nearest point.
install.packages("rgeos")
library(rgeos)
first set of points (subset of many)
points <- data.frame(matrix(nrow=19,ncol=2))
colnames(points) <- c("X","Y")
points$X <- c(5136, 5293, 5393, 5381, 5299, 5310, 4984, 5112,
5213, 5111, 5317, 5264,5075, 5313, 5228, 5237, 5071, 5120, 5067)
points$Y <- c( 5427, 5399, 5381, 5371, 5370, 5364, 5321, 5317,
5321, 5295, 5297, 5284,5226, 5273, 5273, 5264, 5251, 5219, 5212)
particles at current spot
particles <- data.frame(matrix(nrow=19,ncol=3))
colnames(particles) <- c("name","X","Y")
particles$name <- c("a","b","c","d","e","f","g","h","i","j",
"k","l","m","n","o","p","q","r","s")
particles$X <- c(5139, 5289, 5398, 5377, 5298, 5312, 4983, 5113,
5211, 5113, 5317, 5263,
5073, 5309, 5230, 5234, 5065, 5120, 5067)
particles$Y <- c(5427, 5399, 5381, 5372, 5369, 5364, 5321,
5318,5321, 5295, 5297, 5285, 5226, 5273,5273, 5264, 5251, 5219,
5212)
distance from particle to nearest point
particletopoint <-as.vector(apply(gDistance(SpatialPoints(points),SpatialPoints(particles[,2:3]),byid=TRUE),1,min))
distance from point to its nearest neighbor (these are made up since I'm not using all possible points here, but will come out as vector of 19 anyway)
pointtoneighbor <- c(4,4,5,4,2,3,3,4,4,3,2,1,4,3,3,2,5,1,1)
so I need to edit the "particles" df to change the coordinates of those that are too far from their closest point back to the coordinates of the closest point. This is where I start getting errors.
Using just
pointtoneighbor>= particletopoint
[1] TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE FALSE TRUE TRUE
I can see that 5 of the particle coordinates need to be changed, but I'm not so sure how to use apply() to do this.
particles[2:3] <- mapply(function(x) if (pointtoneighbor >= particletopoint) x else points,particles[2:3])
I think the problem has to do with not telling the code which element in points[] to use, but I don't know how to fix it.
I also tried
particles[,2:3] <- mapply(function(x)ifelse(pointtoneighbor>=particletopoint,x,points),particles[,2:3])
But that gave me a different error.
By the way, I want to do this with an apply function rather than a for loop for efficiency. It will be on a large dataset.
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire