Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
775 views
in Technique[技术] by (71.8m points)

r - dplyr filter() with SQL-like %wildcard%

Suppose I have the following data:

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

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%")

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.

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use:

filter(foo, grepl("foo", Company, fixed = TRUE))

Output:

  Company    Metric
1     foo  9.906805
2    food 10.464493

As Dhawal Kapil pointed out I think %like% is from data.table:

library(data.table)
DT <- data.table(foo)
DT[Company %like% 'foo']

Output:

   Company    Metric
1:     foo  9.906805
2:    food 10.464493

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...