R统计中的多个关键字搜索
multiple keyword search in R stats
我有三个句子
1)冰箱坏了一个月。
2)冰箱被分成三部分。
3) 冰箱坏了也没用
如何在 R 中使用 str_match 以便我可以使用逻辑 AND 运算符。这样它会在返回结果之前同时搜索 fridge 和 broken 作为关键字。
我使用的代码
x<- which(!is.na(str_match(data1$TWEET_TEXT,"fridge & broken")))
data9<- data1[x,]
但它不起作用。
你能帮忙吗,因为我是 R 编码的新手。
您可以创建一个需要检测的单词向量 ("v1"),使用 lapply
循环向量,检查单词是否存在于 "TWEET_TEXT" 列中 ( grepl(x,..)
),使用 Reduce
和 &
。如果列表中相应的元素都是 TRUE,则 &
将 return "TRUE" 否则 "FALSE"。使用它作为索引,可以对 "data1" 进行子集化。
v1 <- c('broken', 'fridge')
x1 <- Reduce(`&`, lapply(c('broken', 'fridge'),
function(x) grepl(x, data1$TWEET_TEXT)))
data1[x1,, drop=FALSE]
# TWEET_TEXT
#1 The fridge is broken for a month.
#2 The fridge is broken in 3 parts
#3 A broken fridge is of no use
另一种选择是使用 stringr
中的 str_detect
或 stringi
中的 stri_detect
。如果只有两个单词,下面的代码也应该可以工作
library(stringr)
x2 <- with(data1, str_detect(TWEET_TEXT, 'broken') &
str_detect(TWEET_TEXT, 'fridge'))
data1[x2,, drop=FALSE]
数据
data1 <- structure(list(TWEET_TEXT = c("The fridge is broken for a month.",
"The fridge is broken in 3 parts", "A broken fridge is of no use",
"No use of fridge")), .Names = "TWEET_TEXT", row.names = c(NA,
-4L), class = "data.frame")
我有三个句子 1)冰箱坏了一个月。 2)冰箱被分成三部分。 3) 冰箱坏了也没用
如何在 R 中使用 str_match 以便我可以使用逻辑 AND 运算符。这样它会在返回结果之前同时搜索 fridge 和 broken 作为关键字。
我使用的代码
x<- which(!is.na(str_match(data1$TWEET_TEXT,"fridge & broken")))
data9<- data1[x,]
但它不起作用。 你能帮忙吗,因为我是 R 编码的新手。
您可以创建一个需要检测的单词向量 ("v1"),使用 lapply
循环向量,检查单词是否存在于 "TWEET_TEXT" 列中 ( grepl(x,..)
),使用 Reduce
和 &
。如果列表中相应的元素都是 TRUE,则 &
将 return "TRUE" 否则 "FALSE"。使用它作为索引,可以对 "data1" 进行子集化。
v1 <- c('broken', 'fridge')
x1 <- Reduce(`&`, lapply(c('broken', 'fridge'),
function(x) grepl(x, data1$TWEET_TEXT)))
data1[x1,, drop=FALSE]
# TWEET_TEXT
#1 The fridge is broken for a month.
#2 The fridge is broken in 3 parts
#3 A broken fridge is of no use
另一种选择是使用 stringr
中的 str_detect
或 stringi
中的 stri_detect
。如果只有两个单词,下面的代码也应该可以工作
library(stringr)
x2 <- with(data1, str_detect(TWEET_TEXT, 'broken') &
str_detect(TWEET_TEXT, 'fridge'))
data1[x2,, drop=FALSE]
数据
data1 <- structure(list(TWEET_TEXT = c("The fridge is broken for a month.",
"The fridge is broken in 3 parts", "A broken fridge is of no use",
"No use of fridge")), .Names = "TWEET_TEXT", row.names = c(NA,
-4L), class = "data.frame")