Conditional count over rows

Hello,

I am trying to count the number of occurrences of a condition over a large set of columns. The following works, but at the cost of either having to replicate all the columns or destroy the information. I am looking for a way to combine the two statements inside mutate so I can do other counts.

suppressMessages(library(tidyverse))

test <- tribble(
  ~x1, ~b7_1, ~b7_2,
  1, NA_real_, 95,
  2, 3, 55,
  3, NA_real_, NA_real_,
  4, 100, 200,
  5, 12, NA_real_
)

test %>%
  mutate(
    across(starts_with("b7_"), ~(.x < 60)),
    sum = rowSums(across(starts_with("b7_")), na.rm = TRUE)
  )
#> # A tibble: 5 × 4
#>      x1 b7_1  b7_2    sum
#>   <dbl> <lgl> <lgl> <dbl>
#> 1     1 NA    FALSE     0
#> 2     2 TRUE  TRUE      2
#> 3     3 NA    NA        0
#> 4     4 FALSE FALSE     0
#> 5     5 TRUE  NA        1

Created on 2022-12-14 with reprex v2.0.2

Any ideas would be greatly appreciated.

Claus

test %>%
  mutate(
    myb7sum= rowSums(across(starts_with("b7_"),
                         .fns = ~.x< 60), na.rm = TRUE))
  )
# A tibble: 5 × 4
     x1  b7_1  b7_2 myb7sum
  <dbl> <dbl> <dbl>   <dbl>
1     1    NA    95       0
2     2     3    55       2
3     3    NA    NA       0
4     4   100   200       0
5     5    12    NA       1
1 Like

Thank you so much @nirgrahamuk ! So across does the transformation to logical on the fly for the b7_* columns. Not sure why I could not see that given that I use across to do the transformation :man_shrugging:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.