0
word <- c('abc noboby@stat.berkeley.edu','text with no email','first me@mything.com also you@yourspace.com')
pattern <- '[-A-Za-z0-9_.%]+@[-A-Za-z0-9_.%]+\\.[A-Za-z]+'


getmail<-function(pattern,word){
mail<<-c()
sapply(word,function(x){
out<-gregexpr(pattern,x)
for (i in 1:length(out[[1]])){
if (out[[1]][i]>0)
mail<<-union(mail,substr(x,start=out[[1]][i],stop=out[[1]][i]+attr(out[[1]],"match.length")[i]-1))
}})
return(mail)
}

getmail(pattern,word)

[1] "noboby@stat.berkeley.edu" "me@mything.com"           "you@yourspace.com"       
ls()
[1] "getmail" "mail"    "pattern" "word"     

関数は結果を取得しますが、mailgetmail(pattern,word) を実行した後、名前空間にグローバル変数がない方が良いと思います。どうすれば修正できますか? mailsapply 関数を削除しないでください。名前空間を入れないように、私のやり方で行ってください。

もっと簡単な方法で結果を取得できることはわかっていますが、関数についてもっと学びたいと思っています。

mail<-c()
out<-gregexpr(pattern,word)
for (i in 1:length(out)){
  for (j in 1:length(out[[i]])){
    if (out[[i]][j]>0)
    mail<-union(mail,substr(word[i],start=out[[i]][j],stop=out[[i]][j]+attr(out[[i]],"match.length")[j]-1))}}
mail
[1] "noboby@stat.berkeley.edu" "me@mything.com"           "you@yourspace.com"       
4

1 に答える 1

0

おそらくベクトル化を利用して、ほとんどのループをスキップします。

> m <- gregexpr(pattern,word)
> lapply(seq_along(word),
         function(i){substring(word[i],m[[i]],m[[i]] + attr(m[[i]],"match.length"))})
[[1]]
[1] "noboby@stat.berkeley.edu"

[[2]]
[1] ""

[[3]]
[1] "me@mything.com "   "you@yourspace.com"

これにより、基本的に 2 行だけでそこまでたどり着くことができます。はい、空の文字列を除外し、空白を削除する必要がありますが、これはややクリーンだと思います。

于 2012-10-05T14:09:44.127 に答える