Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string on first number only

Tags:

regex

r

strsplit

So i have a dataset with street adresses, they are formatted very differently. For example:

d <- c("street1234", "Street 423", "Long Street 12-14", "Road 18A", "Road 12 - 15", "Road 1/2")

From this I want to create two columns. 1. X: with the street address and 2. Y: with the number + everything that follows. Like this:

X           Y
Street      1234
Street      423
Long Street 12-14
Road        18A
Road        12 - 15
Road        1/2

Until now I have tried strsplit and followed some similar questions here , for example: strsplit(d, split = "(?<=[a-zA-Z])(?=[0-9])", perl = T)). I just can't seem to find the correct regular expression.

Any help is highly appreciated. Thank you in advance!

like image 435
Jesse Avatar asked Feb 09 '17 10:02

Jesse


2 Answers

There may be whitespace between the letter and a digit, so add \s* (zero or more whitespace symbols) between the lookarounds:

> strsplit(d, split = "(?<=[a-zA-Z])\\s*(?=[0-9])", perl = TRUE)
[[1]]
[1] "street" "1234"  

[[2]]
[1] "Street" "423"   

[[3]]
[1] "Long Street" "12-14"      

[[4]]
[1] "Road" "18A" 

[[5]]
[1] "Road"    "12 - 15"

[[6]]
[1] "Road" "1/2" 

And if you want to create columns based on that, you might leverage the separate from tidyr package :

> library(tidyr)
> separate(data.frame(A = d), col = "A" , into = c("X", "Y"), sep = "(?<=[a-zA-Z])\\s*(?=[0-9])")
            X       Y
1      street    1234
2      Street     423
3 Long Street   12-14
4        Road     18A
5        Road 12 - 15
6        Road     1/2
like image 132
Wiktor Stribiżew Avatar answered Sep 18 '22 17:09

Wiktor Stribiżew


This will also work:

do.call(rbind,strsplit(sub('([[:alpha:]]+)\\s*([[:digit:]]+)', '\\1$\\2', d), split='\\$'))
#     [,1]          [,2]     
#[1,] "street"      "1234"   
#[2,] "Street"      "423"    
#[3,] "Long Street" "12-14"  
#[4,] "Road"        "18A"    
#[5,] "Road"        "12 - 15"
#[6,] "Road"        "1/2"    
like image 32
Sandipan Dey Avatar answered Sep 19 '22 17:09

Sandipan Dey