Filter lines without knowing the column name in R

Asked

Viewed 80 times

2

Hello, how can I select a row from a data frame that contains an expression but I don’t know which column that expression will be in?

  • You can make a loop by passing by column, and saving on which column and row is, with grepl.

1 answer

5


Use the function which. 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 roll

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 to 7, column 2. So just rotate

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

that the desired result is obtained.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.