【问题标题】:Why does %in% return false when matching string?为什么 %in% 匹配字符串时返回 false?
【发布时间】:2018-05-05 09:10:06
【问题描述】:

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

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

【问题讨论】:

  • %in% 匹配 R 对象,而不是字符串中的单词。也许你想要grepl

标签: r substring


【解决方案1】:

%in% 检查前一个元素是否与后者中的任何元素匹配。在这种情况下,x 只有 元素 "hahahaha &lt;sentiment&gt;too much&lt;/sentiment&gt; &lt;feature&gt;doge&lt;/feature&gt;.",没有 "&lt;sentiment&gt;",所以 "&lt;sentiment&gt;" %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

如果要检查"&lt;sentiment&gt;" 是否是x子字符串,请使用grepl

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

或者使用str_detect from stringr:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 2014-10-10
      相关资源
      最近更新 更多