Consider the following example data:
d <- tibble(V1 = c(5, 3, 8, 7),
V2 = c(4, 0, 2, 6),
V3 = c(0, 1, 0, 3),
V4 = c(0, 0, 0, 2))
# A tibble: 4 × 4
V1 V2 V3 V4
<dbl> <dbl> <dbl> <dbl>
1 5 4 0 0
2 3 0 1 0
3 8 2 0 0
4 7 6 3 2
I want to find the column name with the first 0 for each row. If there are no zeros, then I want to get the last column name.
The result should look like this:
# A tibble: 4 × 5
V1 V2 V3 V4 firstZero
<dbl> <dbl> <dbl> <dbl> <chr>
1 5 4 0 0 V3
2 3 0 1 0 V2
3 8 2 0 0 V3
4 7 6 3 2 V4
CodePudding user response:
max.col
from base R
is fast
d$firstZero <- ifelse(!rowSums(d == 0), names(d)[ncol(d)],
names(d)[max.col(d == 0, 'first')])
using dplyr
library(dplyr)
d %>%
rowwise %>%
mutate(firstZero = names(.)[match(0, c_across(everything()),
nomatch = ncol(.))]) %>%
ungroup
-output
# A tibble: 4 × 5
V1 V2 V3 V4 firstZero
<dbl> <dbl> <dbl> <dbl> <chr>
1 5 4 0 0 V3
2 3 0 1 0 V2
3 8 2 0 0 V3
4 7 6 3 2 V4
Or using case_when
with max.col
d %>%
mutate(firstZero = names(.)[case_when(!rowSums(across(c(V1, V2, V3)) == 0) ~
ncol(.), TRUE ~ max.col(!across(c(V1, V2, V3)) != 0, "first"))])