矢量化stringr str_match以删除for循环
如何使用R矢量化删除此for循环矢量化stringr str_match以删除for循环,r,stringr,R,Stringr,如何使用R矢量化删除此for循环 library(stringr) url <- c("http://www.slate.fr/france/87869/mehdi-nemmouche-bruxelles", "http://www.slate.fr/story/87347/turquie-opposition-geek", "http://www.slate.fr/grand-format/paysages-debarquement-photos-1944-aujourdhui") f
library(stringr)
url <- c("http://www.slate.fr/france/87869/mehdi-nemmouche-bruxelles", "http://www.slate.fr/story/87347/turquie-opposition-geek", "http://www.slate.fr/grand-format/paysages-debarquement-photos-1944-aujourdhui")
for (i in 1:length(url)) {
a[i]<-str_match(url[i], "http://.*slate.fr/(.*?)/")[2]
}
库(stringr)
url您必须使用[,2]
而不是[2]
,因为输出是一个2列矩阵
,通过索引[2]
,您只能得到第二个元素,即”http://www.slate.fr/story/“
而不是第二列”
str_match(url, "http://.*slate.fr/(.*?)/")[,2]
#[1] "france" "story" "grand-format"
从?str_match
“字符串”上的矢量化“模式”应该是单一模式,
i、 e.长度为1的字符向量
str_match(url, "http://.*slate.fr/(.*?)/")[,2]
#[1] "france" "story" "grand-format"