我有一组需要重新格式化的英国邮政编码。它们由一个 incode 和一个 outcode 组成,其中 incode 的形式是“数字字母字母”,例如2DB 和 outcode 是 2 到 4 个字母和数字的组合,例如NW1 或 SW10 或 EC1A
目前 incode 和 outcode 之间有一个空格,但我需要重新格式化这些,以便完整的邮政编码为 7 个字符,例如:('-' 代表空格)
- NW1-2DB -> NW1-2DB(outcode 和 incode 之间有 1 个空格)
- SW10-9NH -> SW109NH(0 个空格)
- E1-6QL -> E1--6QL(2 个空格)
数据:
df <- data.frame("postcode"=c("NW1 2DB","SW10 9NH","E1 6QL"))
df
# postcode
# 1 NW1 2DB
# 2 SW10 9NH
# 3 E1 6QL
我已经编写了一个正则表达式字符串来分隔 outcode 和 incode,但找不到在它们之间添加可变数量空格的方法(此示例只是在 outcode 和 incode 之间创建两个空格)。
require(dplyr)
df <- df %>% mutate(postcode_2sp = gsub('?(\\S+)\\s*?(\\d\\w{2})$','\\1 \\2', postcode)
为了解决这个问题,我尝试使用 mutate()
, nchar()
和 rep()
:
df<-df %>%
mutate(outcode=gsub('?(\\S+)\\s*\\d\\w{2}$','\\1',postcode),
incode=gsub('\\S+\\s*?(\\d\\w{2})$','\\1',postcode)) %>%
mutate(out_length=nchar(outcode))%>%
mutate(postcode7=paste0(outcode,
paste0(rep(" ",4-out_length),collapse=""),
incode))
但得到这个错误:
Error: invalid 'times' argument
没有创建 postcode7 的最后一步,df 如下所示:
df
# postcode outcode incode out_length
# 1 NW1 2DB NW1 2DB 3
# 2 SW10 9NH SW10 9NH 4
# 3 E1 6QL E1 6QL 2
如果我将 rep 'times' 参数设置为常量,代码会按预期运行(但不会执行我需要它执行的操作!)
df<-df %>%
mutate(outcode=gsub('?(\\S+)\\s*\\d\\w{2}$','\\1',postcode),
incode=gsub('\\S+\\s*?(\\d\\w{2})$','\\1',postcode)) %>%
mutate(out_length=nchar(outcode))%>%
mutate(postcode7=paste0(outcode,
paste0(rep(" ",4),collapse=""),
incode))
df
# postcode outcode incode out_length postcode7
# 1 NW1 2DB NW1 2DB 3 NW1 2DB
# 2 SW10 9NH SW10 9NH 4 SW10 9NH
# 3 E1 6QL E1 6QL 2 E1 6QL
有没有办法制作rep()
接受一个列作为 mutate 中的 times 参数?还是我应该寻找一种完全不同的方法?
编辑:我刚刚意识到我可以使用 if
输出代码中的 2 个字符、3 个字符或 4 个字符的每种情况的语句,但感觉不是很优雅。
最佳答案
查看 stringr
包中的 str_pad
方法,该方法适合您的情况:
library(stringr)
df<-df %>%
mutate(outcode=gsub('?(\\S+)\\s*\\d\\w{2}$','\\1',postcode),
incode=gsub('\\S+\\s*?(\\d\\w{2})$','\\1',postcode)) %>%
mutate(out_length=nchar(outcode)) %>%
mutate(postcode7 = paste(outcode, str_pad(incode, 7-out_length), sep = ""))
df
# postcode outcode incode out_length postcode7
# 1 NW1 2DB NW1 2DB 3 NW1 2DB
# 2 SW10 9NH SW10 9NH 4 SW109NH
# 3 E1 6QL E1 6QL 2 E1 6QL
关于regex - R - 将可变数量的空格插入邮政编码字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38105528/