4

目标:RR. 在当前的任务中,我想替换一些出现在 a 中的单词,corpus同时保持corpus.

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")

修改后的 Gsub

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)
    }
}
}

代码执行

gsub2(pattern1,replacement1,corpus,fixed=TRUE)

但是,实际语料库中不会产生任何变化。我认为这是因为所有更改都在函数内进行,因此仅限于函数内。然后我尝试返回语料库但R无法识别语料库对象。

有人可以指出我正确的方向吗?谢谢。

4

2 回答 2

3

尝试使用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
于 2013-06-11T10:49:33.183 回答
2

如果你,正如你已经建议的那样,返回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)
}

接着

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

这不是你想要的吗?

于 2013-06-11T10:51:18.230 回答