I'm trying to fill coordinate gaps in a data frame based on points randomly created within a reference area.

In the original dataset, I have a column for lat and a column for long values, and the points created come from a polygon and are of class "sfc_POINT" "sfc".

To fill the gaps I'm using a loop, I think I would need to have lat and long from the dataset in a single column so if they are an NA, they can be replaced by a point.

Using

x = dataset x$coords = cbind(x$lat, x$long)

doesn't work, as it creates two columns anyway.

If I try to convert x$coords into SpatialPoints by coords_points <- SpatialPointsDataFrame(x[, c("lat", "long")], proj4string = CRS(proj4string(mex)))

I get "Error in .local(obj, ...) : NA values in coordinates".

Is it possible to create SpatialPoints with NAs, or does anyone have an idea on how I could do this?

Part of the code (for the area "Brazil" - the points I need can't be on land, so I first create an "ocean-only" polygon, and then sampled points from it):

rm(list=ls())

packages = c('ggplot2','sp','rgdal','sf','readxl','maps','dplyr', 'rnaturalearth')

package.check = lapply(packages, FUN = function(x) {
  if (!require(x, character.only = TRUE)) {
    install.packages(x, dependencies = TRUE)
    library(x, character.only = TRUE)
  }
})

sf::sf_use_s2(FALSE)

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

#Brazil
x_brazil = c(-48.65,-48.65,-32.3,-32.3)
y_brazil = c(-29,-6.2,-6.2,-29)
polygon_brazil = cbind(x_brazil, y_brazil) %>%
  st_linestring() %>%
  st_cast("POLYGON") %>%
  st_sfc(crs = 4326, check_ring_dir = TRUE) %>%
  st_sf() 
brazil_ocean = st_difference (polygon_brazil, land)

brazil_points = st_sample(brazil_ocean, 1500) #485 NAs

#Ploting all ramdonly generated points to check if they are all good
plot(st_geometry(land))
plot(st_geometry(polygon_brazil), add = TRUE)
plot(brazil_points, add = TRUE, pch=20, cex=.1, col = "turquoise")

#Filling coords gaps in the dataset (x)
x = mydatabase

x$coords = cbind(x$long, x$lat)


for(i in 1:dim(x)[1]) {
  
  x[i,"coords"] <- ifelse(is.na(x[i,"coords"]) && x[i,"area"]=="Brazil", 
sample(brazil_points,1), x[i,"coords"])
  
  
}

Any help would be greatly appreciated.

0

There are 0 answers