中的R%使用%从字符向量移除停止词(R remove stopwords from a charac

2019-07-21 03:01发布

我有,我想从去除停止词串的数据帧。 我试图避免使用tm包,因为它是一个大的数据集和tm似乎在慢慢跑了一下。 我使用的是tm stopword字典。

library(plyr)
library(tm)

stopWords <- stopwords("en")
class(stopWords)

df1 <- data.frame(id = seq(1,5,1), string1 = NA)
head(df1)
df1$string1[1] <- "This string is a string."
df1$string1[2] <- "This string is a slightly longer string."
df1$string1[3] <- "This string is an even longer string."
df1$string1[4] <- "This string is a slightly shorter string."
df1$string1[5] <- "This string is the longest string of all the other strings."

head(df1)
df1$string1 <- tolower(df1$string1)
str1 <-  strsplit(df1$string1[5], " ")

> !(str1 %in% stopWords)
[1] TRUE

这不是我要找的答案。 我想在拿到词的载体或字符串不是stopWords向量。

我究竟做错了什么?

Answer 1:

你是不是正确的访问列表,你不从的结果获得的元素后面%in% (其中给出的TRUE / FALSE的逻辑向量)。 你应该做这样的事情:

unlist(str1)[!(unlist(str1) %in% stopWords)]

(要么)

str1[[1]][!(str1[[1]] %in% stopWords)]

对于整个data.frame DF1,你可以这样做:

'%nin%' <- Negate('%in%')
lapply(df1[,2], function(x) {
    t <- unlist(strsplit(x, " "))
    t[t %nin% stopWords]
})

# [[1]]
# [1] "string"  "string."
# 
# [[2]]
# [1] "string"   "slightly" "string." 
# 
# [[3]]
# [1] "string"  "string."
# 
# [[4]]
# [1] "string"   "slightly" "shorter"  "string." 
# 
# [[5]]
# [1] "string"   "string"   "strings."


Answer 2:

第一。 你应该选择不公开str1或使用lapply如果str1是矢量:

!(unlist(str1) %in% words)
#>  [1]  TRUE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE  TRUE

第二。 复杂的解决方案:

string <- c("This string is a string.",
            "This string is a slightly longer string.",
            "This string is an even longer string.",
            "This string is a slightly shorter string.",
            "This string is the longest string of all the other strings.")
rm_words <- function(string, words) {
    stopifnot(is.character(string), is.character(words))
    spltted <- strsplit(string, " ", fixed = TRUE) # fixed = TRUE for speedup
    vapply(spltted, function(x) paste(x[!tolower(x) %in% words], collapse = " "), character(1))
}
rm_words(string, tm::stopwords("en"))
#> [1] "string string."                  "string slightly longer string."  "string even longer string."     
#> [4] "string slightly shorter string." "string longest string strings."


文章来源: R remove stopwords from a character vector using %in%