 # Conditional count ("Countif") across multiple columns

Hey,
I'm struggling to group values of multiple columns in different categories, i.e. I want to count the number of rows with values > x for multiple columns. In Excel I would use the COUNTIF function but I'm not sure how to do that in R.

For one column I would use

``````sum(df[,1]<=0.05)
or
length(which(df[,1]<= 0.05))
``````

For multiple columns (column 2 to 25) like this but that's not working...

``````  count <- df %>%
dplyr::summarise(across(2:25, sum(.<= 0.05))))
``````

What am I doing wrong?
Can you help me with an alternative for that using dplyr? And maybe also an option to count based on multiple conditions in one step? So for example all values <= 0.05 in one row and all values >= 0.05 & < 0.1 in the next row and so on?

Thanks!
Nele

Does this help ?

``````
mtcars
nrow(mtcars)

mtcars %>%
summarise(across(c(disp,hp),
~.x>110))

mtcars %>%
summarise(across(c(disp,hp),
~as.numeric(.x>110)))

mtcars %>%
summarise(across(c(disp,hp),
~sum(as.numeric(.x>110))))

mtcars %>%
summarise(across(c(disp,hp),
~sum(as.numeric(.x>110)))) %>%
rowSums()``````

Thanks for the quick reply!

The third option is working:

``````count  <- df %>%
dplyr::summarise(across(c(2:25), ~sum(as.numeric(.x<0.05))))
``````
``````(list_of_groups_of_vars_to_summarise <-
list(c("disp","hp"),
c("disp","hp","cyl")))
(list_of_evaluations <-
list( function(x) sum(as.numeric(x>110)),
function(x) sum(as.numeric(x>140))
))

purrr::map2(.x = list_of_groups_of_vars_to_summarise,
.y = list_of_evaluations ,~{
summarise(mtcars,across(.x,.y))
})
# or
purrr::map2_dfr(.x = list_of_groups_of_vars_to_summarise,
.y = list_of_evaluations ,~{
summarise(mtcars,across(.x,.y))
})``````

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.