R 用第二个向量中指定的单词替换一个向量中单词的所有实例
我试图找到一种有效的方法来删除输入列表中一组单词的所有实例以及删除列表中的单词R 用第二个向量中指定的单词替换一个向量中单词的所有实例,r,R,我试图找到一种有效的方法来删除输入列表中一组单词的所有实例以及删除列表中的单词 vectorOfWordsToRemove <- c('cat', 'monkey', 'wolf', 'mouses') vectorOfPhrases <- c('the cat and the monkey walked around the block', 'the wolf and the mouses ate lunch with the monkey', 'this should rem
vectorOfWordsToRemove <- c('cat', 'monkey', 'wolf', 'mouses')
vectorOfPhrases <- c('the cat and the monkey walked around the block', 'the wolf and the mouses ate lunch with the monkey', 'this should remain unmodified')
remove_strings <- function(a, b) { stringr::str_replace_all(a,b, '')}
remove_strings(vectorOfPhrases, vectorOfWordsToRemove)
vectorOfWordsToRemove首先,我创建一个空字符串向量,替换为:
vectorOfNothing <- rep('', 4)
vectorOfNothing首先,我创建一个空字符串向量,替换为:
vectorOfNothing <- rep('', 4)
vectorofthing您可以使用gsubfn()
:
库(gsubfn)
replaceStrings您可以使用gsubfn()
:
库(gsubfn)
替换字符串
library(qdap)
vectorOfPhrases <- qdap::mgsub(vectorOfWordsToRemove,
vectorOfNothing,
vectorOfPhrases)
> vectorOfPhrases
[1] "the and the walked around the block" "the and the ate lunch with the"
[3] "this should remain unmodified"
library(gsubfn)
replaceStrings <- as.list(rep("", 4))
newPhrases <- gsubfn("\\S+", setNames(replaceStrings, vectorOfWordsToRemove), vectorOfPhrases)
> newPhrases
[1] "the and the walked around the block" "the and the ate lunch with the"
[3] "this should remain unmodified"