How to merge a shapefile and set the encoding with R
[This article was first published on Jose Gonzalez » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### 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) |
I’ve struggled all morning on how to set shapefile encodings in R. Finally I got this solution to handle both French and Spanish characters.
Happy coding!
The post How to merge a shapefile and set the encoding with R appeared first on Jose Gonzalez.
To leave a comment for the author, please follow the link and comment on their blog: Jose Gonzalez » R.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.