Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading shape file with sf::st_read fails to capture encoding UTF8

I want to read a shape file which is encoded in UTF8. It works fine when I read it using rgdal::readOGR but sf::st_read fails to get the correct Encode. Any suggestions on how to solve this?

For a reproducible example, the shape file I'm trying to read can be downloaded here.

Reading with rgdal::readOGR

shp <- rgdal::readOGR(shp_file, encoding = "UTF-8")
head(shp@data)

>   ID CD_GEOCODM      NM_MUNICIP
> 0 53    1200013      ACRELÂNDIA
> 1 54    1200054    ASSIS BRASIL
> 2 55    1200104       BRASILÉIA
> 3 56    1200138          BUJARI
> 4 57    1200179        CAPIXABA
> 5 58    1200203 CRUZEIRO DO SUL

Reading with sf::st_read

  sf <- sf::st_read(shp_file, stringsAsFactors=F, options = "ENCODING=UTF8")
  head(sf)


>   ID CD_GEOCODM      NM_MUNICIP                       geometry
> 1 53    1200013   ACREL<c2>NDIA POLYGON ((-67.14117 -9.6833...
> 2 54    1200054    ASSIS BRASIL POLYGON ((-69.79978 -10.506...
> 3 55    1200104    BRASIL<c9>IA POLYGON ((-69.58835 -10.643...
> 4 56    1200138          BUJARI POLYGON ((-68.31643 -9.2954...
> 5 57    1200179        CAPIXABA POLYGON ((-67.84667 -10.287...
> 6 58    1200203 CRUZEIRO DO SUL POLYGON ((-72.89221 -7.4995...


# I have also tried manually adding the encoding but it still doesn't work.

sf <- sf::st_read(shp_file, stringsAsFactors=F, options = "ENCODING=UTF8")
Encoding(sf$NM_MUNICIP) <- "UTF-8"
sf$NM_MUNICIP

> [1] "ACREL\xc2NDIA"        "ASSIS BRASIL"         "BRASIL\xc9IA"         "BUJARI"              
> [5] "CAPIXABA"             "CRUZEIRO DO SUL"      "EPITACIOL\xc2NDIA"    "FEIJ\xd3"            
> [9] "JORD\xc3O"            "M\xc2NCIO LIMA"       "MANOEL URBANO"        "MARECHAL THAUMATURGO"
> [13] "PL\xc1CIDO DE CASTRO" "PORTO WALTER"         "RIO BRANCO"           "RODRIGUES ALVES"     
> [17] "SANTA ROSA DO PURUS"  "SENADOR GUIOMARD"     "SENA MADUREIRA"       "TARAUAC\xc1"         
> [21] "XAPURI"               "PORTO ACRE"          


The same problem occurs with other shape files, like this other one, so I don't think this is a problem of the file itself.

like image 402
rafa.pereira Avatar asked Jun 13 '19 01:06

rafa.pereira


1 Answers

It worked for me when tried to read it with sf::st_read using encoding as WINDOWS-1252 instead of UTF8. I hope it helps!

sf <- sf::st_read("ac_municipios/12MUE250GC_SIR.shp", options = "ENCODING=WINDOWS-1252")
like image 64
lgelape Avatar answered Sep 22 '22 07:09

lgelape