dplyr filter()与类似SQL的%wildcard% [英] dplyr filter() with SQL-like %wildcard%

查看:66
本文介绍了dplyr filter()与类似SQL的%wildcard%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下数据:

foo <- data.frame(Company = c("company1", "foo", "test", "food"), Metric = rnorm(4, 10))

> foo
   Company    Metric
1 company1 10.539970
2      foo  9.487823
3     test  9.663994
4     food  9.499327

以下代码为什么返回0结果(而不是第二行和第四行)?

Why does the following code return 0 results (instead of the second and fourth rows)?

library(dplyr)
library(data.table)

foo %>% dplyr::filter(Company %like% "%foo%")

我正在尝试在特定输入字符串上使用与SQL等效的通配符来过滤 dplyr :: filter ,使用 data.table 中的%like%运算符包。

I'm trying to use the SQL-equivalent wildcard filter on a particular input string to dplyr::filter, using the %like% operator from the data.table package.

我在做什么错了?

推荐答案

您可以与库(stringr)一起使用

You can use with library(stringr)

library(dplyr)
library(stringr)
foo <- data.frame(Company = c("company1", "foo", "test", "food"), Metric = rnorm(4, 10))

foo %>% filter(str_detect(Company,"foo"))

正则表达式

foo %>% filter(str_detect(Company,"^f")) 

这篇关于dplyr filter()与类似SQL的%wildcard%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆