dplyr 过滤器功能无法在 R 中过滤我的数据框

问题描述 投票:0回答:1

我在 R 中有一个包含两列的数据框。第一列的数据类型/类是“字符”。然而,其中嵌入了数字......但我认为这些仍然是技术上的字符,因为当我运行函数类(column_name)时它返回“字符”。

我正在尝试使用 dplyr 过滤器功能过滤数据框。我希望过滤器函数返回相同的数据框,但没有“doc_id”列末尾包含“(2).txt”的行。

我一直在尝试很多事情,但没有一个奏效。

我试过:

constitutions <- constitutions %>% filter(!str_detect(doc_id, "(2).txt"))

constitutions <- constitutions[constitutions$doc_id %in% "(2).txt == FALSE]

constitutions %>% filter(!str_detect(doc_id, "(2).txt"))

*注意:这个^似乎只摆脱了其中的一些,但并没有接近全部。

constitutions <- subset(constitutions, !"(2).txt" %in% doc_id)

constitutions <- subset(constitutions, !("(2).txt" %in% consitutions$doc_id))

还有更多的迭代......我错过了什么?

附言我试图从宪法数据框中删除的 doc_id 列值的示例是:

Brazil_1988_rev_2017 (2).txt

在上述功能之一中使用正则表达式是否可行?我迷路了,想法用完了。 任何帮助将不胜感激。

r dataframe dplyr filter subset
1个回答
0
投票

这样转义括号和句号能解决问题吗?

constitutions <- constitutions %>% filter(!str_detect(doc_id, "\\(2\\)\\.txt"))

括号和句点(以及其他一堆符号)都是正则表达式中的特殊符号。要查找文字括号或句点,您必须使用反斜杠进行转义。例如:

这有效:

> "document(2).txt" %>% str_detect("\\(2\\)\\.txt")
[1] TRUE

这不是:

> "document(2).txt" %>% str_detect("(2).txt")
[1] FALSE

这里是更多关于正则表达式的链接。整章都很有用,但这里是关于转义的部分:https://r4ds.hadley.nz/regexps.html#sec-regexp-escaping

© www.soinside.com 2019 - 2024. All rights reserved.