Skip to content

Instantly share code, notes, and snippets.

@josecarlosgonz
Created May 6, 2014 18:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josecarlosgonz/be3cfcd698a66f92ee94 to your computer and use it in GitHub Desktop.
Save josecarlosgonz/be3cfcd698a66f92ee94 to your computer and use it in GitHub Desktop.
Merge a shapefile with a csv and save it using UTF-8
### Load a shape file and merge it with a csv
### Author: Jose Gonzalez
### www.jose-gonzalez.org
# This script shows how to load a shapefile, merge it with a csv and save it with the proper
# encoding
### Load rgdal
require(rgdal)
# Load csv
data <- read.csv("myData.csv", fileEncoding="utf8", stringsAsFactors=F)
# Load shapefile using "UTF-8". Notice the "." is the directory and the shapefile name
# has no extention
shp <- readOGR(".", "myShapefile", stringsAsFactors=FALSE, encoding="UTF-8")
# Explore with a quick plot
plot(shp, axes=TRUE, border="gray")
# Merge shapefile and csv
temp <- merge(shp, data, by.x="id", by.y="Code")
# The shapefile behaves as a data.frame. Explore a bit
head(temp)
# Check your locale and set shapefile encoding to UTF-8
Sys.getlocale("LC_CTYPE")
getCPLConfigOption("SHAPE_ENCODING")
setCPLConfigOption("SHAPE_ENCODING", "UTF-8")
# Write merged shapefile using UTF-8
writeOGR(test, ".", "shp-merged", driver="ESRI Shapefile", layer_options= c(encoding= "UTF-8"),
overwrite_layer=T)
@ikashnitsky
Copy link

ikashnitsky commented Jul 25, 2017

Thanks a lot Jose!
...it was so painful before I found you script
I was struggling with saving in UTF-8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment