Check if row has particular value in R

Viewed 217

Inside a case_when, I am currently using:

rowSums(select(., starts_with('type')), na.rm = TRUE) > 0

to check whether those rows starting with 'type' are all NA or not.

Is there a way to check if there are any '1's present in that row instead? Returns true if there is at least one 1 in that row, and false if there doesn't exist any 1s.

Thanks!

1 Answers

We can change the select subset of data to a logical matrix with ==, then apply the rowSums on the matrix, and check if the row wise sum is greater than 0

library(dplyr)
...
rowSums(select(., starts_with('type')) ==1, na.rm = TRUE) > 0

In addition to the above, it can be done using if_any

...
if_any(starts_with('type'), ~. == 1)
Related