根据字符串条件过滤行,dplyr filter,包含
Filter row based on a string condition, dplyr filter, contains
我想使用 dplyr contains() 和过滤器过滤数据框。一定很简单吧?我见过的示例使用 base R grepl 来破坏对象。这是一个简单的数据框:
site_type <- c('Urban','Rural','Rural Background','Urban Background','Roadside','Kerbside')
df <- data.frame(row_id, site_type)
df <- as.tibble(df)
df
现在我想按 site.type 包含字符串背景的所有行过滤数据框。
如果我知道 site_type:
的唯一值,我可以直接找到字符串
filtered_df <- filter(df, site_type == 'Urban Background')
但我想做类似的事情:
filtered_df <- filter(df, site_type(contains('background', match_case = False)))
知道怎么做吗? dplyr helper contains
只能用于列而不是行吗?
dplyr 中的 contains
函数是一个 select 助手。它的目的是在使用 select
函数时提供帮助,而 select
函数专注于 selecting 列而不是行。请参阅文档 here。
filter
是 selecting 行的预期机制。您可能正在寻找的函数是 grepl
,它对文本进行模式匹配。
所以您正在寻找的解决方案可能是:
filtered_df <- filter(df, grepl("background", site_type, ignore.case = TRUE))
我怀疑 contains
主要是将 grepl
应用于列名的包装器。所以逻辑很相似。
参考文献:
- grep R documentation
- high rated question applying exactly this technique
我想使用 dplyr contains() 和过滤器过滤数据框。一定很简单吧?我见过的示例使用 base R grepl 来破坏对象。这是一个简单的数据框:
site_type <- c('Urban','Rural','Rural Background','Urban Background','Roadside','Kerbside')
df <- data.frame(row_id, site_type)
df <- as.tibble(df)
df
现在我想按 site.type 包含字符串背景的所有行过滤数据框。 如果我知道 site_type:
的唯一值,我可以直接找到字符串filtered_df <- filter(df, site_type == 'Urban Background')
但我想做类似的事情:
filtered_df <- filter(df, site_type(contains('background', match_case = False)))
知道怎么做吗? dplyr helper contains
只能用于列而不是行吗?
dplyr 中的 contains
函数是一个 select 助手。它的目的是在使用 select
函数时提供帮助,而 select
函数专注于 selecting 列而不是行。请参阅文档 here。
filter
是 selecting 行的预期机制。您可能正在寻找的函数是 grepl
,它对文本进行模式匹配。
所以您正在寻找的解决方案可能是:
filtered_df <- filter(df, grepl("background", site_type, ignore.case = TRUE))
我怀疑 contains
主要是将 grepl
应用于列名的包装器。所以逻辑很相似。
参考文献:
- grep R documentation
- high rated question applying exactly this technique