How to modify Json file and save it?

Dear All,
I would like to combine the coordinates of Western Sahara to Morocco

dt <- tibble::tribble(~from, ~to,
                      "Western Sahara", "Morocco")
dataset <- geojsonR::FROM_GeoJson(url_file_string = "")

for (i in 1:nrow(dt)){
  vars <- dataset %>% 
    .[["features"]] %>% 
  dataset$features[[which(vars== dt$to[i])]]$geometry$coordinates <- 
  list(dataset$features[[which(vars== dt$to[i])]]$geometry$coordinates, 
       dataset$features[[which(vars== dt$from[i])]]$geometry$coordinates) %>%, .)
  dataset$features[[which(vars %in% dt$from[i])]] <- NULL

# Check
dataset %>% 
  .[["features"]] %>% 
  purrr::map_chr(~.x$properties$ADMIN) %>% 
  .[. %in% dt$from]

my question how to write the the final database to json file?

If it's about merging 2 polygons, I'd rather go with sf package (and sfheaders for convenient hole removal -- those 2 polygons have gaps between them).

Here I'm selecting 2 polygons, creating an union of those and removing holes. Resulting union will replace one of the original geometries; the other is excluded when writing a geojson.


countries <- read_sf("")
countries$geometry[countries$ADMIN == "Morocco"] <-
  countries$geometry[countries$ADMIN %in% c("Morocco", "Western Sahara")] |> 
  st_union() |> 
  st_collection_extract("POLYGON") |>

write_sf(countries[countries$ADMIN != "Western Sahara",], "countries.geojson")

Hi.. Thanks for sharing your code, i tested the new countries.geojson by viewing it on mapbox to check the new coordinates

Before Editing

after merging "Morocco", and "Western Sahara"

There is some part in Western Sahara is not added Morocco.
Please advise.

I'm sorry, but I can't reproduce this.
Besides, your "Before Editing" image does not match with the shapes I get from provided link. To me it looks like you have only loaded the original countries.json to Mapbox, perhaps with a different name but still with the original content.

#> Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE

orig <- read_sf("")
orig[orig$ADMIN == "Morocco",] |> mapview()

orig[orig$ADMIN == "Western Sahara",] |> mapview()

# after merging:
merged <- read_sf("countries.geojson") 
merged[merged$ADMIN == "Morocco",] |> mapview()

I did a mistake when i edited your code the first time.
Now it works fine and thanks for showing how to view the map in R.
Really appreciated

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.