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"
関数は結果を取得しますが、mail
getmail(pattern,word) を実行した後、名前空間にグローバル変数がない方が良いと思います。どうすれば修正できますか? mail
sapply 関数を削除しないでください。名前空間を入れないように、私のやり方で行ってください。
もっと簡単な方法で結果を取得できることはわかっていますが、関数についてもっと学びたいと思っています。
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"