我在数据帧(df)中有一堆文本,通常在1列中包含三行地址,我的目标是提取区域(文本的中心部分),例如:
73 Greenhill Gardens, Wandsworth, London
22 Acacia Heights, Lambeth, London
Run Code Online (Sandbox Code Playgroud)
幸运的是,在95%的情况下,输入数据的人使用逗号分隔我想要的文本,其中100%的时间结束",伦敦"(即逗号空间伦敦).为了清楚地说明事情,我的目标是在",伦敦"和之前的逗号之后提取文本
我想要的输出是:
Wandsworth
Lambeth
Run Code Online (Sandbox Code Playgroud)
我之前可以设法提取部分:
df$extraction <- sub('.*,\\s*','',address)
Run Code Online (Sandbox Code Playgroud)
之后
df$extraction <- sub('.*,\\s*','',address)
Run Code Online (Sandbox Code Playgroud)
但不是我需要的中间部分.有人可以帮忙吗?
非常感谢!
您可以省去正则表达式的头痛并将矢量视为CSV,使用文件读取功能来提取相关部分.我们可以利用可用于删除列read.csv()的事实colClasses.
address <- c(
"73 Greenhill Gardens, Wandsworth, London",
"22 Acacia Heights, Lambeth, London"
)
read.csv(text = address, colClasses = c("NULL", "character", "NULL"),
header = FALSE, strip.white = TRUE)[[1L]]
# [1] "Wandsworth" "Lambeth"
Run Code Online (Sandbox Code Playgroud)
或者我们可以使用fread().它的select论点很好,它会自动剥离空白区域.
data.table::fread(paste(address, collapse = "\n"),
select = 2, header = FALSE)[[1L]]
# [1] "Wandsworth" "Lambeth"
Run Code Online (Sandbox Code Playgroud)
以下是几种方法:
# target ", London" and the start of the string
# up until the first comma followed by a space,
# and replace with ""
gsub("^.+?, |, London", "", address)
#[1] "Wandsworth" "Lambeth"
Run Code Online (Sandbox Code Playgroud)
要么
# target the whole string, but use a capture group
# for the text before ", London" and after the first comma.
# replace the string with the captured group.
sub(".+, (.*), London", "\\1", address)
#[1] "Wandsworth" "Lambeth"
Run Code Online (Sandbox Code Playgroud)