Converting From CSV to SHP in R.
As I was going through a tutorial on doing geospatial data analysis in R, I came across a situation where I had collected my own data, and I needed to convert the CSV file into a SHP file. In this brief post, I share the solution I found.
First install the needed libraries if they are not yet on your system.
install.packages(c("tidyverse", "sf"))
Next, load the libraries.
library(tidyverse)
library(sf)
Now read in the CSV file into a dataframe.
geodata <- read_csv("data/geodata.csv")
Next, examine it to see what it looks like.
geodata
To convert the dataframe, use the Simple Features library
geodata_sf <- st_as_sf(geodata, coords = c("longitude", "latitude"), crs = 4326)
The arguments used are:
geodata - the dataframe in question
coords - the names of the columns with the latitude and longitude values
crs - the coordinate reference system to be assigned to the output
Examine the data to see what it now looks like.
geodata_sf
The two columns latitude
and longitude
have been combined into a single geometry
column that has points.
Finally, write this spatial dataframe to an R data object file.
write_rds(geodata_sf, "data/geodata.rds")
In future, we can now just read in this file as needed.
new_geodata <- read_rds("data/geodata.rds")
new_geodata
And that's how you convert a CSV file into a SHP file in R.
The code and data file are in my Code Snippets repo.