Forum Discussion
Anonymous
7 years agoNot applicable
regmatches woes in R/Query Editor
Hi all I'm trying to do some pattern matching in the query editor. The intention being that I can then merge a reformatted postcode to an enormous table, which I do not want to upload in it's ent...
- Anonymous7 years ago
Fixed it! The regex could be more comprehensive and it's very step by step, but this R script converts UK postcodes matching the regex pattern to an 8 character format in the query editor.
# 'dataset' holds the input data for this script # returns string w/o leading or trailing whitespace trim <- function (x) gsub("\\s+|\\s+", "", x) ws <- function(x){ if(x>0){strrep(" ",x)} else {""} } pattern <- "^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?)))) ?[0-9][A-Za-z]{2}" match <- function(x) {gregexpr(pattern , as.character(x), perl=TRUE)} part <- function(x) {c(regmatches(x, match(x)))} pCodeList <- part(dataset$post_code) pCodeVector <- as.character(pCodeList) for(i in 1:length(pCodeVector)) { pCodeVector[i] <- trim(pCodeVector[i]) pCodeLength <- nchar(pCodeVector[i]) pCodeRight <- toupper(substr(pCodeVector[i], pCodeLength - 2, pCodeLength)) pCodeLeft <- toupper(substr(pCodeVector[i],1, pCodeLength -3)) pCodeVector[i] <- paste(pCodeLeft, ws((8 - nchar(pCodeLeft)) - nchar(pCodeRight)), pCodeRight, sep='') } PCDS <- within(dataset, {PCDS = (pCodeVector)})Development discussion warmly welcomed.
Beth
x