在一列中筛选包含精确字符串的行。

huangapple go评论67阅读模式
英文:

Filter rows that contain exact strings in a column

问题

df <- df %>% filter(grepl('\\<air\\>', y))
英文:

I need to filter rows from df that contain air as a stand-alone word in a column

library(dplyr)
df &lt;- data.frame(x = c(13, 34, 5, 124, 56),
                 y = c(&#39;air transport&#39;, &#39;hairdressing&#39;, &#39;airport&#39;, &#39;repair&#39;, &#39;frontend&#39;))

This gives me rows that partially contain air

df %&gt;% filter(grepl(&#39;air&#39;,y))

    x             y
1  13 air transport
2  34  hairdressing
3   5       airport
4 124        repair

Here is my intended result

   x             y
1 13 air transport

答案1

得分: 1

使用\\b来匹配零长度的单词边界:

df %>%
  filter(grepl('\\bair\\b', y))
英文:

Use \\b to match a zero-length word boundary:

df %&gt;% 
  filter(grepl(&#39;\\bair\\b&#39;, y))

huangapple
  • 本文由 发表于 2023年3月3日 17:37:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75625389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定