I am using gDistance function from rgeos package to calculate the nearest distance from points to a polygon. Originally I used for loop to calculate the distance for each row in my points data set, however, the speed is extremely slow, especially when I have a large data set. So I tried to use 'apply'. My codes look like:
Invasive_dist <- apply(sp_invasive_pixels, 1, function(x) gDistance(x, sp_tumor))
whereas sp_invasive_pixels is my SpatialPoint object, and sp_tumor is the SpatialPolygons object. My code does not work, the error message is:
Error in apply(sp_invasive_pixels, 1, function(x) gDistance(x, sp_tumor)) : dim(X) must have a positive length
What do I need to change?
test_poly <- data.frame(matrix(nrow = 4, ncol = 2)) test_pts <- data.frame(matrix(nrow = 4, ncol = 2)) test_poly$X1 <- c(1, 1, 2, 2) test_poly$X2 <- c(1, 2, 1, 2) test_pts$X1 <- c(4, 5, 6, 7) test_pts$X2 <- c(5, 6, 7, 8) sp_pts <- SpatialPoints(test_pts) sp_poly <- SpatialPolygons(list(Polygons(list(Polygon(test_poly)),1)))