how do i count the number of rows in a column by group that meets a specific criteria in r?

Try this tidyverse approach. You can reshape data to long using pivot_longer() keeping school variable. After that create a variable to check if value reaches the desired condition. Finally, summarise() allows computing the expected values which are formated to percents as you want using paste0(). Just a reminder that columns are of type character. Here the code:

library(tidyverse)
#Code
mydata %>% pivot_longer(-school) %>%
  group_by(school,name) %>%
  mutate(Var=ifelse(value>=50,1,0)) %>%
  summarise(Perc=paste0(100*round(mean(Var),3),'%')) %>%
  pivot_wider(names_from = name,values_from=Perc)

Output:

# A tibble: 3 x 4
# Groups:   school [3]
  school point rime  sound
  <fct>  <chr> <chr> <chr>
1 es     100%  66.7% 66.7%
2 hs     50%   0%    100% 
3 ms     66.7% 66.7% 66.7%

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top