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

标签 r substring

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

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

最佳答案

%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

关于r - 为什么 %in% 匹配字符串时返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47420980/

相关文章:

返回对应于 R 中唯一元素的重复元素的索引

r - 使用 kable 或 DT 将标题固定在顶部

json - 数据帧 R 中的子串

c# - 获取特定值作为字符串 c#

r - 无法使用 Monetdb.R 连接到本地数据库

r - 如何更改 Jupyter 中 R 图的大小?

r - ggplot2:为条形图的构面布局中的行指定不同的比例

c# - 如何从 lineX 读取到 lineY C#

mysql - 非英语语言的子字符串

algorithm - "Manacher' s 算法中索引 i 处的初始回文长度如何等于 R - i”?