Home > Net >  R: Obtain Row Number of a Tibble Using dplyr Package
R: Obtain Row Number of a Tibble Using dplyr Package

Time:03-28

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

CodePudding user response:

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.

CodePudding user response:

We could use filter with across or if_all

library(dplyr)
tbl %>% 
    mutate(rn = row_number()) %>% 
    filter(across(p:q, `==`, 1)) %>% 
    pull(rn)
[1] 5

Or using

tbl %>% 
  summarise(rn = which(if_all(p:q, `==`, 1)))
# A tibble: 1 × 1
     rn
  <int>
1     5

Or using base R with rowSums on a logical matrix

 which(rowSums(tbl == 1) == 3)
[1] 5

CodePudding user response:

Another possible solution:

library(dplyr)

tbl %>% 
  rowid_to_column %>% 
  filter(p == 1 & d == 1 & q == 1) %>% 
  pull(rowid)

#> [1] 5
  • Related