!str_detect(col,pattern)从data.frame中删除的行多于str_detect(col,pattern)

时间:2018-04-25 09:28:55

标签: r filter dplyr

我有一个包含多个字符列的大型data.frame / tibble,我正在清理那里的数据。一列包含城市名称。有时一行不包含城市名称(即城市是“”或城市也可能是NA)。有时城市会标有度数符号(即“°”或“\ u00B0”)。

使用tidyverse / dplyr和stringr的示例情况:

nrow(df) #5000
df.degree <- df %>% filter(str_detect(city, '\u00B0')) 
nrow(df.degree) #30
df.withoutdegree <- df %>% filter(!str_detect(city, '\u00B0'))
nrow(df.withoutdegree) #4500

我的目标是只移除包含城市列中度数符号的30行。如果我查找这些行,我会使用filter和str_detect来获取它们。否定str_detect会删除更多行而不仅仅是那些行。

这似乎是我错过了一些我需要设置的明显文档或参数或我缺少的不同方法的情况。但是,我似乎无法找到它。你能指出我正确的方向吗?

任何有关使这个更优雅的代码示例的提示(也许使用“contains()”?)也非常感激。

谢谢! :)

PS:以下工作正常btw:

df.withoutdegree <- df %>% filter(!(grepl('\u00B0', city, ignore.case = TRUE)))
nrow(df.withoutdegree) #4970

但是,我发现代码更难以阅读,我通常有兴趣了解为什么在这种情况下否定str_detect不起作用。

2 个答案:

答案 0 :(得分:1)

城市包含NA个值,因此请确保不要将其过滤掉

df <- df %>% filter( is.na(city) | !str_detect(city, '\u00B0'))

答案 1 :(得分:0)

如果目标是删除值\u00B0,那么这应该有效:

df <- df %>% filter(!str_detect(city, '\\\u00B0'))