2020-10-07

Filter rows containing a certain string in R

Title

Problem

We want to filter rows containing a certain string in R. In our example, rows containing the string 'foo'.

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

   Company    Metric
1 company1  7.590178
2      foo  9.711493
3     test 10.862799
4     food  9.337434

Solution

  • dplyr
  • Using the grepl function inside filter.

    library(dplyr)
    filter(foo, grepl("foo", Company))
    

      Company   Metric
    1     foo 9.711493
    2    food 9.337434
    
  • data.table
  • Another options is the function like from data.table with a similar syntax to SQL.

    library(data.table)
    DT <- data.table(foo)
    DT[Company %like% 'foo']
    
       Company   Metric
    1:     foo 9.711493
    2:    food 9.337434
    

    References

    No hay comentarios:

    Publicar un comentario

    Nube de datos