目标:我是R
的新手,但我正在努力熟悉R
编程。在当前任务中,我想替换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
无法识别语料库对象。
请问有人可以指出我正确的方向吗?谢谢。
尝试使用 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)
}
然后
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
这不是你想要的吗?