How to fill data gaps with random coordinates from a polygon?

88 Views Asked by At

I have a data set of whale sightings with some coordinate gaps but associated with areas of reference, of which I have coordinate limits. I've used these limits to create a polygon restricted to the marine environment (using library ‘sf’) for each of the areas. Now I would like to fill the coordinate gaps by randomly selecting latitudes and longitudes from the polygons.

My piece of code (example for the area 'Angola'):

#Creating a ocean-only polygon for the Southern Hemisphere (my study area)

x_coord = c(180, 180, -180, -180) y_coord = c(0, -90, -90, 0)

polygonSH = cbind(x_coord, y_coord) %>%

st_linestring() %>% st_cast("POLYGON") %>%

st_sfc(crs = 4326, check_ring_dir = TRUE) %>%

st_sf()

land = rnaturalearth::ne_countries(returnclass = "sf") %>%

st_union()

ocean = st_difference(polygonSH, land)

plot(st_geometry(land)) plot(st_geometry(polygonSH), add = TRUE) plot(st_geometry(ocean), add = TRUE, col = "blue")

#Creating ocean-only polygons for each of the different areas to then use them in the arguments to run ramdon coords

#Angola

x_angola = c(11.72,11.72,13.58,13.58) #longitude limits of Angola area

y_angola = c(-12.34,-16.6,-16.6,-12.34) #latitude limits of Angola area

polygon_angola = cbind(x_angola, y_angola) %>%

st_linestring() %>% st_cast("POLYGON") %>%

st_sfc(crs = 4326, check_ring_dir = TRUE) %>%

st_sf()

plot(st_geometry(land))

plot(st_geometry(polygon_angola), add = TRUE)

angola_ocean = st_difference (polygon_angola, land) plot(st_geometry(angola_ocean), add = TRUE, col = "pink")

...

Before having the polygons restricted to the marine environment, I've used the code below to randonmly generate the coordinates, and ideally I would like to use something similar, but adjusted to working with spatial data:

for(i in 1:dim(x)[1]) {

x[i,"lat"] <- ifelse(is.na(x[i,"lat"]) && x[i,"area"]=="Angola", runif(1,-16.6,-12.34), x[i,"lat"])

x[i,"long"] <- ifelse(is.na(x[i,"long"]) && x[i,"area"]=="Angola", runif(1, 11.72,13.58), x[i,"long"])

}

I would really appreciate having folk's input on this issue.

1

There are 1 best solutions below

2
On

I can't get your code to work due to issues (invalid spherical geometry) not directly related to the subject of the question.

So please allow me to illustrate a possible approach using the well known & much loved North Carolina shapefile that ships with the {sf}.

library(sf)
library(dplyr)


# included with sf package
shape <- st_read(system.file("shape/nc.shp", package="sf")) %>% 
  summarise() # a single polygon 

# now the action! 50 random points over North Carolina
random_points <- shape %>% 
  st_sample(50)

# check results...
plot(shape)
plot(random_points, col = "red", pch = 4, add = T)

enter image description here