rdata-representation

Filter a data frame by part of name in column


Here's my example below.

Name <- c("HU-5-A", "HU-6-C", "CE-5-A", "LE-3-C", "LE-4-A", "CE-9-B")
x <- c(rnorm(6))
y <- c(rnorm(6))
df <- data.frame(cbind(Name, x, y))

I'd like to filter my df but by only common part in the Name column so the result will be

Name         x         y
LE-3-C 0.6087576 2.3199352
LE-4-A 0.4040382 0.1556805

Thank's for the help.


Solution

  • stringr can help solve this too if you want to stick in the tidyverse world.

    library(tidyverse)
    df %>% 
       filter(str_detect(Name,'LE'))
    
        Name                  x                 y
    1 LE-3-C  0.632601346894576 0.573187971758856
    2 LE-4-A -0.818879986489542 0.284050547258268