R – Change columns names in a spatial dataframe

Ordnance Survey have a great OpenRoads dataset, but unfortunately it contains a column called ‘primary’, which is a keyword in SQL. This makes it challenging/impossible to import the OpenRoads dataset into a SQL database (e.g. GRASS), without changing the offending column name.

Enter R! Or any other capable programming language. The following script reads a folder of shp files, changes a given column name and overwrites the original files. Note the use of the ‘@’ symbol to call a slot from the S4 class object (thanks Stack Exchange).

library(rgdal)

f = list.files("~/Downloads/OS/data", pattern="shp")

f = substr(f, 1, nchar(f) - 4)

lapply(f, function(i){

x = readOGR("/home/mspencer/Downloads/OS/data", i)

colnames(x@data)[11] = "prim"

writeOGR(x,
"/home/mspencer/Downloads/OS/data",
i,
"ESRI Shapefile",
overwrite_layer=T)

})

 

Advertisements