(This article was first published on R – scottishsnow, and kindly contributed to R-bloggers)
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([email protected])[11] = "prim" writeOGR(x, "/home/mspencer/Downloads/OS/data", i, "ESRI Shapefile", overwrite_layer=T) })
To leave a comment for the author, please follow the link and comment on their blog: R – scottishsnow.
R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...