Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 用第二个向量中指定的单词替换一个向量中单词的所有实例_R - Fatal编程技术网

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"