Search code examples
rmapboxgeojsongeojsonio

How to add multiple lat longs when converting to csv to gejson format in R


I have lat/longs of a particular area. How do I insert multiple lat/lons corresponding to a single area in CSV file? I am just using random numbers right now in my CSV file. I have attached a screenshot to show my CSV file. I don't want single latitude and longitude but multiple corresponding to a single area. I have to plot them later on map box

This is the code I am using to convert my csv file to geojson file

library(geojsonio)
library(rgdal)
file_to_geojson(input = "FINAL DATA ENTRY.csv",method ="web" ) 

geojson file when created gives coordinates as this. If you see red highlighted area in my geojson output file I converted from a csv file, What I want is geometry should be polygon or multipolygon and it should include 100 coordinates not single one. How do I provide those 100+ coordinates to csv file? Ill be more clear if someone is not able to understand me. Let me know. Ignore my bad English, please.enter image description here

Added My csv file.


Solution

  • Try this:

    Using the sf-package which allows to combine points of a group (such as a state) to MULTIPOINT or POLYGON. In your file, some states only have one point so I just can convert it to MULTIPOINT.

    And then save the sf-class as geojson.

    
    library(geojsonio)
    library(sf)
    library(tidyverse)
    
    data<- data[,c("State", "lat", "lon")]
    
    sf_data <- st_as_sf(data, coords = c("lon", "lat"))
    
    sf_data  %>%
      group_by(State) %>%
      summarise(geometry = st_combine(geometry)) %>%
      st_cast("POLYGON") -> res_sfdata
    
    
    geojson_write(res_sfdata, file = "yourpath/res_sfdata.geojson")
    
    

    You'll have to remove the other columns however. Because you have different information in them on each point you want to aggregate.

    EDIT: In case you want to group by more columns:

    
    data<- data[,c("State", "PC_Name", "lat", "lon")]
    
    sf_data <- st_as_sf(data, coords = c("lon", "lat"))
    
    sf_data  %>%
      group_by(State, PC_Name) %>%
      summarise(geometry = st_combine(geometry)) %>%
      st_cast("POLYGON") %>%
      group_by(State) %>%
      summarise(geometry = st_combine(geometry)) 
      st_cast("MULTIPOLYGON") -> res_sfdata