Filter lines without knowing the name of the column in R

2
Hello, how can I select a line from a date frame that contains an expression but I do not know which column this expression will be in?

    
asked by anonymous 17.09.2018 / 23:30

1 answer

4

Use the which function. See the data set below:

library(ggplot2)
mpg
# A tibble: 234 x 11
   manufacturer model     displ  year   cyl trans    drv     cty   hwy fl    class 
   <chr>        <chr>     <dbl> <int> <int> <chr>    <chr> <int> <int> <chr> <chr> 
 1 audi         a4          1.8  1999     4 auto(l5) f        18    29 p     compa…
 2 audi         a4          1.8  1999     4 manual(… f        21    29 p     compa…
 3 audi         a4          2    2008     4 manual(… f        20    31 p     compa…
 4 audi         a4          2    2008     4 auto(av) f        21    30 p     compa…
 5 audi         a4          2.8  1999     6 auto(l5) f        16    26 p     compa…
 6 audi         a4          2.8  1999     6 manual(… f        18    26 p     compa…
 7 audi         a4          3.1  2008     6 auto(av) f        18    27 p     compa…
 8 audi         a4 quatt…   1.8  1999     4 manual(… 4        18    26 p     compa…
 9 audi         a4 quatt…   1.8  1999     4 auto(l5) 4        16    25 p     compa…
10 audi         a4 quatt…   2    2008     4 manual(… 4        20    28 p     compa…
# ... with 224 more rows

If I run

which(mpg == "a4", arr.ind = TRUE)

The result is

which(mpg == "a4", arr.ind = TRUE)
     row col
[1,]   1   2
[2,]   2   2
[3,]   3   2
[4,]   4   2
[5,]   5   2
[6,]   6   2
[7,]   7   2

That is, the string a4 is in rows 1 through 7, column 2. Therefore, just run

mpg[which(mpg == "a4", arr.ind = TRUE)[, 1], ]
# A tibble: 7 x 11
  manufacturer model displ  year   cyl trans      drv     cty   hwy fl    class  
  <chr>        <chr> <dbl> <int> <int> <chr>      <chr> <int> <int> <chr> <chr>  
1 audi         a4      1.8  1999     4 auto(l5)   f        18    29 p     compact
2 audi         a4      1.8  1999     4 manual(m5) f        21    29 p     compact
3 audi         a4      2    2008     4 manual(m6) f        20    31 p     compact
4 audi         a4      2    2008     4 auto(av)   f        21    30 p     compact
5 audi         a4      2.8  1999     6 auto(l5)   f        16    26 p     compact
6 audi         a4      2.8  1999     6 manual(m5) f        18    26 p     compact
7 audi         a4      3.1  2008     6 auto(av)   f        18    27 p     compact

you get the result you want.

    
17.09.2018 / 23:43