有人可以解释为什么 %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/