Home > Software design >  How to count str_detect() across a selection of columns?
How to count str_detect() across a selection of columns?

Time:11-04

I have a db like this:

tibble(Q1 = c("0","A"),
       Q2 = c("A","A"),
       Q3 = c("0","A"),
       C1 = c("A","0")
) -> DB

I aim to add a new column which is a count of how many "0" are detected in the row when the column starts with "Q".

In this case, this column would be like

DB %>%
mutate(S = c(2,0))

CodePudding user response:

DB %>%
  rowwise() %>%
  mutate(S = sum(c_across(starts_with("Q")) == "0")) %>%
  ungroup()
# # A tibble: 2 x 5
#   Q1    Q2    Q3    C1        S
#   <chr> <chr> <chr> <chr> <int>
# 1 0     A     0     A         2
# 2 A     A     A     0         0

CodePudding user response:

One possible solution:

DB %>%
  mutate(S = rowSums(.[startsWith(names(.), "Q")]=="0"))

# A tibble: 2 x 5
  Q1    Q2    Q3    C1        S
  <chr> <chr> <chr> <chr> <dbl>
1 0     A     0     A         2
2 A     A     A     0         0
  • Related