Search code examples
rdplyrtibble

R: Obtain Row Number of a Tibble Using dplyr Package


I want to obtain the row number of any row that satisfies certain conditions.

In my tibble formation bellow, I want to obtain only the row number in which (p = 1, d = 1 q = 1)

tbl <- tibble::tibble(p = c(0, 0, 0, 0, 1, 0, 2, 2, 2, 2), d = c(1, 1, 1, 1, 1, 1, 1, 0, 0, 0), q = c(1, 1, 1, 1, 1, 1, 1, 0, 0, 0))

tbl

A tibble: 10 x 3

p d p
1 0 1 1
2 0 1 1
3 0 1 1
4 0 1 1
5 1 1 1
6 0 1 1
7 0 1 1
8 2 0 0
9 2 0 0
10 2 0 0
tbl |>  dplyr::filter(p == 1, d == 1, q == 1) |> 
  dplyr::row_number()

# p d q 
# 1 2 3 

What I Want

I just want a function that will print the row number that has the desired quality such that I can make the function that produce it an object with a name the use it in another function


Solution

  • You can use the following code:

    library(dplyr)
    tbl %>%
      with(which(p == 1 & d == 1 & q == 1))
    

    Output:

    [1] 5
    

    Which means it was the 5th row of your data.