我有一份地址清单,其中包括(1)门牌和(2)建筑物名称。我希望将字符串分成两列。棘手的部分是一些门牌包含字符,例如"221B贝克街“。
示例如下:
add <- c("5 Ark Royal House" ,
"22A Blington Garden Lincoln Street",
"Flat 19 PICTON HOUSE" ,
"2-3 Royal Albert Court" ,
"Room 1 Grand Hall",
"No 17 The Dell Alpha House")理想的结果如下所示:
aim <- data.frame("No"=as.character(c("5", "22A", "Flat 19", "2-3", "Room 1", "No 17")),
"Building" = as.character(c("Ark Royal House",
"Blington Garden Lincoln Street" ,
"PICTON HOUSE",
"Royal Albert Court" ,
"Grand Hall" ,
"The Dell Alpha House")))发布于 2019-02-19 18:22:10
使用stringr
library(stringr)
lst <- str_match_all(add, "^(\\D*\\d[-\\w]*)\\s+(.+)")
(aim <- setNames(as.data.frame(do.call(rbind, lst)),
c("all", "No", "Building")))或者在香草R中:
pattern <- "^(\\D*\\d[-\\w]*)\\s+(.+)"
lst <- regmatches(add, regexec(pattern, add, perl = T))
(aim <- setNames(as.data.frame(do.call(rbind, lst)),
c("all", "No", "Building")))
两者都会让步
all No Building
1 5 Ark Royal House 5 Ark Royal House
2 22A Blington Garden Lincoln Street 22A Blington Garden Lincoln Street
3 Flat 19 PICTON HOUSE Flat 19 PICTON HOUSE
4 2-3 Royal Albert Court 2-3 Royal Albert Court
5 Room 1 Grand Hall Room 1 Grand Hall
6 No 17 The Dell Alpha House No 17 The Dell Alpha House请参阅a demo for the expressionregex101.com上的。
https://stackoverflow.com/questions/54763216
复制相似问题