vectorize stringr str_match删除for循环

时间:2014-11-18 09:33:28

标签: 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")

for (i in 1:length(url)) {
a[i]<-str_match(url[i], "http://.*slate.fr/(.*?)/")[2]
}

这不起作用:

a<-str_match(url, "http://.*slate.fr/(.*?)/")[2]

1 个答案:

答案 0 :(得分:1)

您必须使用[,2]代替[2],因为输出是2列matrix,并且通过索引[2],您只获得第2个元素,即{{} 1}}而不是"http://www.slate.fr/story/"列`。

2nd

来自str_match(url, "http://.*slate.fr/(.*?)/")[,2] #[1] "france" "story" "grand-format"

的说明
  

在'string'上进行矢量化。 'pattern'应该是一个单一的模式,        即长度为1的字符向量。