'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 1:[1]
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.
Solution 2:[2]
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
Solution 3:[3]
Another possible solution:
library(dplyr)
tbl %>%
rowid_to_column %>%
filter(p == 1 & d == 1 & q == 1) %>%
pull(rowid)
#> [1] 5
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quinten |
| Solution 2 | |
| Solution 3 | PaulS |
