0

Is there any possibility to declare the data type of the attribute columns when importing, for example, a ESRI Shapefile with the readOGR command?

For example, I would like to keep the leading zeros in my key column (id_code):

example<- readOGR(example.shp", example")
str(example@data) 
#'data.frame': 7149 obs. of  22 variables:
# $ id_code: num  101 102 103 104 105 106 107 108 109 110 ...

The result should something be like this:

str(example@data) 
#'data.frame': 7149 obs. of  22 variables:
# $ id_code: char  "0101" "0102" "0103" "0104" "0105" "0106"...

I am looking for something similar as colClasses in the read.csv() function

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bushroot
  • 259
  • 1
  • 13

1 Answers1

0

Yes, you can declare the data type when importing by specifying the encoding, ogrDrivers and use_iconv options in readOGR.

Please see ?readOGR.

From the documentation for the encoding option:

default NULL, if set to a character string, and the driver is “ESRI Shapefile”, and use_iconv is FALSE, it is passed to the CPL Option “SHAPE_ENCODING” immediately before reading the DBF of a shapefile. If use_iconv is TRUE, and encoding is not NULL, it will be used to convert input strings from the given value to the native encoding for the system/platform.

You may also want to look into ogrInfo.

Hack-R
  • 22,422
  • 14
  • 75
  • 131
  • 1
    I had read `?readOGR`, but still could not figure out to do it correctly. The [vignette](https://cran.r-project.org/web/packages/rgdal/vignettes/OGR_shape_encoding.pdf) did not help either. Could you give an example? – Bushroot Oct 05 '16 at 07:29