如何加速R码
下面的代码可以很好地删除myCharVector中的停止字。但是当myCharVector有大量的句子时,它需要花费太长的时间来完成。如何加速循环操作(使用apply) 谢谢如何加速R码,r,loops,tm,R,Loops,Tm,下面的代码可以很好地删除myCharVector中的停止字。但是当myCharVector有大量的句子时,它需要花费太长的时间来完成。如何加速循环操作(使用apply) 谢谢 library(tm) myCharVector <- c("This is the first sentence", "hello this is second", "and now is the third one") for(i in 1:length(myCharVector)) { for(j in
library(tm)
myCharVector <- c("This is the first sentence", "hello this is second", "and now is the third one")
for(i in 1:length(myCharVector))
{
for(j in 1:length(stopwords("en")))
{
tmp1 <- paste(stopwords("en")[j], " ", sep = "")
tmp1 <- paste(" ", tmp1, sep = "")
myCharVector[i] <- gsub(tmp1, " ", myCharVector[i])
}
}
library(tm)
myCharVector您可以尝试mgsub
library(qdap)
mgsub(sprintf(' %s ', stopwords('en')), ' ', myCharVector)
#[1] "This first sentence" "hello second" "and now third one"
您可以尝试mgsub
library(qdap)
mgsub(sprintf(' %s ', stopwords('en')), ' ', myCharVector)
#[1] "This first sentence" "hello second" "and now third one"
在这种情况下,似乎有一个问题
不过,总的来说,要努力更多地利用R的矢量化操作。例如,您可以执行以下操作,而不是分别粘贴每个单词:
stopwords = paste0(' ', stopwords('en'), ' ')
它依次用空格包围每个停止字。同样,您不需要循环使用myCharVector
,您可以直接使用gsub
最重要的是,不要在索引上循环。这是间接的、缓慢的,而且(几乎?)总是不必要的。而是直接在条目上循环:
for (word in paste0(' ', stopwords('en'), ' '))
myCharVector = gsub(word, ' ', myCharVector)
同时,这比您的解决方案更短、更清晰、更高效
(也就是说,这将产生错误的结果,无论如何,您应该真正使用预定义的函数。)在这种情况下,似乎存在一个错误
不过,总的来说,要努力更多地利用R的矢量化操作。例如,您可以执行以下操作,而不是分别粘贴每个单词:
stopwords = paste0(' ', stopwords('en'), ' ')
它依次用空格包围每个停止字。同样,您不需要循环使用myCharVector
,您可以直接使用gsub
最重要的是,不要在索引上循环。这是间接的、缓慢的,而且(几乎?)总是不必要的。而是直接在条目上循环:
for (word in paste0(' ', stopwords('en'), ' '))
myCharVector = gsub(word, ' ', myCharVector)
同时,这比您的解决方案更短、更清晰、更高效
(也就是说,这会产生错误的结果,你应该使用预定义的函数。)你试过tm\u map
和removeWords
?@Henrik我试过rm\u stopwords(myCharVector,tm::stopwords(“en”)
,但这会删除这个
,和和
,而基于循环的预期输出拥有它。@akrun感谢您指出这一点!你试过tm\u map
和removeWords
吗?@Henrik我试过rm\u stopwords(myCharVector,tm::stopwords(“en”)
,但这会删除这个
,并且和
,而基于循环的预期输出会删除它。@akrun感谢你指出这一点!