我有一个数据集 DS。我想按照如下模式替换模式将包含的语句替换为其他语句:
我使用了以下功能:
from_distincts_to_origins <- function(patternST, replacementST,originalFile){
#---------------------------------------
patternST<-paste0('\\b',patternST,'\\b')
#---------------------------------------
# we have to point back to the original data set
file_origin_DF <- as.data.frame(originalFile)
file_output <- file_origin_DF
for(i in 1:length(patternST)) {
where <- file_output[[1]]#vector
file_output <- apply(file_output,
2,
function(x) sub(patternST[i],
replacementST[i],
where,
#ignored.case=FALSE,
perl=FALSE,
fixed=FALSE, useBytes=FALSE)
)
file_output <- as.data.frame(file_output, stringsAsFactors =F) # in order to work
}
return(file_output)
}
将会发生的是,R 将开始用“足球”代替所有“我喜欢足球”。当它传递到第二行时,它会寻找“I like football,W Lazio”,但它只会找到“ football,W Lazio ”,因此这些行不会被“Lazio”替换。
一种可能的解决方案是对 Pattern 进行排序,使其顶部有最长的字符串,但这只会减少替换缺失。
R中有另一种方法可以做到这一点吗?
