为什么%in%在匹配字符串时返回false?

时间:2017-11-21 19:17:39

标签: r substring

有人可以解释为什么%in%在这种情况下返回false吗?字符串<sentiment>存在于较大的字符串中。

> x<-"hahahaha <sentiment>too much</sentiment> <feature>doge</feature>."
> "<sentiment>" %in% x
[1] FALSE

2 个答案:

答案 0 :(得分:4)

%in%检查前一个元素是否与后者中的任何元素匹配。在这种情况下,x只有元素 "hahahaha <sentiment>too much</sentiment> <feature>doge</feature>.",而不是"<sentiment>",因此"<sentiment>" %in% x会返回FALSE。例如,以下内容返回TRUE

y = c(x, "<sentiment>")
# > y
# [1] "hahahaha <sentiment>too much</sentiment> <feature>doge</feature>."
# [2] "<sentiment>" 

"<sentiment>" %in% y
# [1] TRUE

如果您想检查"<sentiment>"x子字符串,请使用grepl

grepl("<sentiment>", x, fixed = TRUE)
# [1] TRUE

或使用str_detect中的stringr

stringr::str_detect(x, fixed("<sentiment>"))
# [1] TRUE

答案 1 :(得分:1)

%in%match运算符,相当于match function。它在向量(或类似)中搜索对象,而不是字符串中的子字符串。

要在字符串中查找,请使用pattern matching functions之一,例如grep或类似内容。

相关问题