我在下面的句子中找到了“oo”的位置:
sentence <- "It is a good book. Good for first reading.
This book explains everything in Qdetail with tons of examples and exercises for practice. Good for cracking written tests on campuses and competitive exams. It is cheap so any way one can have a copy along with other books"
pos = gregexpr("oo", sentence)
我的结果是
> pos
[[1]]
[1] 10 15 21 50 136 263
attr(,"match.length")
[1] 2 2 2 2 2 2
attr(,"useBytes")
[1] TRUE
根据结果,我想从每个位置提取10个字符(位置前5个,位置后5个)
举个例子, 我应该得到第一个位置的结果 “太棒了” 而且我想要为每个位置提取这个。 由于我是R的新手,我无法理解怎么做。 这个你能帮我吗。
如果我必须提取如下所示的字词,我该怎么办: 我应该为匹配
的第一个实例获得“一本好书”答案 0 :(得分:8)
我们可以在substring
unlist
输出后使用gregexpr
。
v1 <- unlist(gregexpr("oo", sentence))
substring(sentence, v1 - 5, v1 +5)
#[1] "s a good bo" "ood book. G" "ok. Good fo" "his book ex" "ce. Good fo" "her books"
答案 1 :(得分:5)
您也可以
mapply(
substr,
x=sentence,
start=pos[[1]]-5,
stop=pos[[1]]+5,
USE.NAMES = F
)
# [1] "s a good bo" "ood book. G" "ok. Good fo"
# [4] "his book ex" "ce. Good fo" "her books"
答案 2 :(得分:4)
如果您不介意使用stringr包
library(stringr)
ind<-str_locate_all(sentence,"oo")[[1]][ ,1]
str_sub(sentence,ind-5,ind+5)
[1] "s a good bo" "ood book. G" "ok. Good fo" "his book ex" "ce. Good fo" "her books"
答案 3 :(得分:4)
pos = gregexpr("oo", sentence)
调整位置和长度:
pos[[1]] <- pmax(pos[[1]] - 5, 0)
attr(pos[[1]], "match.length")[] <- 11
regmatches(sentence, pos)
#[[1]]
#[1] "s a good bo" "ood book. G" "ok. Good fo" "his book ex" "ce. Good fo" "her books"