I would like to run a logical operation (multiple conditions) across many columns. I have written a query which is working fine. However, I want to shorten my code as I have to write several queries.
I have tried shortening the query using "any" and "brackets". However, the second query is running fine but giving me a different answer. Does "any" function work on multiple columns?
Here are my conditions -
- any of the column (B2 to B5) has 1 & B1 <=2, then "Noissue"
- any of the column (B2 to B5) has -99 & B1 <=2, then "Noissue"
- B1 ==3, then "Noissue"
- Rest is all issue
| Participate | B1 | B2 | B3 | B4 | B5 | Query1 | Query2 |
|---|---|---|---|---|---|---|---|
| 3 | -1 | -1 | -1 | -1 | -1 | Noissue | Noissue |
| 1 | -1 | 1 | -1 | -1 | 1 | Noissue | Noissue |
| 1 | -1 | -1 | -1 | -1 | -1 | Issue | Noissue |
| 2 | -1 | 1 | 1 | -1 | 1 | Noissue | Noissue |
| 2 | 1 | 1 | 1 | 1 | -1 | Noissue | Noissue |
| 1 | -99 | -99 | -99 | -99 | -99 | Noissue | Noissue |
I appreciate if anyone help me on reducing the code lines using different functions.
mutate(Batch_v1,
case_when (
((Batch_v1$B1 == 1 | Batch_v1$B2 == 1 | Batch_v1$B3 == 1 | Batch_v1$B4 == 1 | Batch_v1$B5 == 1| Batch_v1$B6 == 1| Batch_v1$B7 == 1|Batch_v1$B8 == 1|Batch_v1$B9 == 1|Batch_v1$B10 == 1|Batch_v1$BOth == 1) &
Batch_v1$Participate %in% c(1,2,-99))~"Noissue",
((Batch_v1$B1 == -99 | Batch_v1$B2 == -99 | Batch_v1$B3 == -99|Batch_v1$B4 == -99 |Batch_v1$B5 == -99|Batch_v1$B6 == -99|Batch_v1$B7 == -99|Batch_v1$B8 == 1|Batch_v1$B9 == -99|Batch_v1$B10 == -99|Batch_v1$BOth == -99) &
Batch_v1$Participate %in% c(1,2,-99))~"Noissue",
Batch_v1$Participate ==3 ~ "Noissue",
TRUE ~ "Issue"))
mutate(Batch_v1,
case_when (
((any(Batch_v1[,2:6] == 1)) & Batch_v1$Participate %in% c(1,2,-99))~ "Noissue",
((any(Batch_v1[,2:6] == -99)) & Batch_v1$Participate %in% c(1,2,-99))~ "Noissue",
Batch_v1$Participate ==3 ~ "Noissue",
TRUE ~ "Issue"))