R 矢量化Gsub的一个问题

R 矢量化Gsub的一个问题,r,function,for-loop,text-mining,gsub,R,Function,For Loop,Text Mining,Gsub,目标: 我是R的新手,但我正在努力熟悉R中的编程。在当前任务中,我想替换语料库中出现的大量单词,同时保持语料库的结构 Gsub不允许将向量用于模式和相应的替换,因此我决定编写一个修改的Gsub函数。(我知道Gsubfn函数,但我也想培养一些编程技能。) 数据生成 a<- c("this is a testOne","this is testTwo","this is testThree","this is testFour") corpus<- Corpus(VectorSource

目标: 我是
R
的新手,但我正在努力熟悉
R
中的编程。在当前任务中,我想替换
语料库中出现的大量单词,同时保持
语料库的结构

Gsub
不允许将向量用于模式和相应的替换,因此我决定编写一个修改的
Gsub
函数。(我知道
Gsubfn
函数,但我也想培养一些编程技能。)

数据生成

a<- c("this is a testOne","this is testTwo","this is testThree","this is testFour")
corpus<- Corpus(VectorSource(a))
pattern1<- c("testOne","testTwo","testThree")
replacement1<- c("gameOne","gameTwo","gameThree")
gsub2(pattern1,replacement1,corpus,fixed=TRUE)
然而,在实际语料库中没有产生任何变化。我认为这是因为所有的变化都是在职能范围内进行的,因此,仅限于职能范围内。然后我尝试返回语料库,但是
R
无法识别语料库对象

有人能给我指一下正确的方向吗?
谢谢。

尝试使用
mapply

# original data
corpus <- c("this is a testOne","this is testTwo","this is testThree","this is testFour")
# make a copy to gsub into
corpus2 <- corpus

# set pattern/replacement
pattern1<- c("testOne","testTwo","testThree")
replacement1<- c("gameOne","gameTwo","gameThree")

corpus2 # before gsub
# run gsub on all of the patterns/replacements
x <- mapply(FUN= function(...) {
     corpus2 <<- gsub(...,x=corpus2)},
     pattern=pattern1, replacement=replacement1)
rm(x) # discard x; it's empty
corpus2 # after gsub
#原始数据

语料库如果您如前所述返回
corpus
对象,该怎么办

gsub2<- function(myPattern, myReplacement, myCorpus, fixed=FALSE,ignore.case=FALSE){
  for (i in 1:length(myCorpus)){
    for (j in 1:length(myPattern)){
      myCorpus[[i]]<- gsub(myPattern[j],myReplacement[j], myCorpus[[i]], fixed=TRUE)
    }
  }
  return(myCorpus)
}

gsub2In R术语在两个循环完成后,函数需要返回
myCorpus
,然后需要将函数的结果分配给对象。请参阅
stringr
包中的
str\u replace\u all
,以查看上述方法的替代方法。当我运行代码并返回语料库对象并调用
gsub2
时,我会得到一个包含4个文本文档的
语料库。你说的“R无法识别语料库对象”是什么意思?啊,是的!我提到的错误消息是一个意外的符号,正如我现在所想的,这是因为我使用了错误类型的括号返回myCorpus。这很尴尬。。。但是谢谢你的更正!这是一个好的、简单的替代方法。我知道这在计算上比我的函数要便宜。谢谢
gsub2<- function(myPattern, myReplacement, myCorpus, fixed=FALSE,ignore.case=FALSE){
  for (i in 1:length(myCorpus)){
    for (j in 1:length(myPattern)){
      myCorpus[[i]]<- gsub(myPattern[j],myReplacement[j], myCorpus[[i]], fixed=TRUE)
    }
  }
  return(myCorpus)
}
a <- gsub2(pattern1,replacement1,corpus,fixed=TRUE)

 > class(a)
[1] "VCorpus" "Corpus"  "list"   


> for (i in 1:length(a)){print(a[[i]])}
this is a gameOne
this is gameTwo
this is gameThree
this is testFour