percentage count by group using dplyr

后端 未结 1 1722
萌比男神i
萌比男神i 2021-01-14 06:30

with a data frame df like below

df <- data.frame(colors = c(\"red\", \"blue\", \"green\", \"red\", \"red\" , \"blue\"))

I c

相关标签:
1条回答
  • You can either pipe this to a mutate( prop = count / sum(count) ) or directly within summarise with nrow(.). Something like this:

    df %>%
      group_by(colors) %>%
      summarise(count = n() / nrow(.) )
    

    or

    df %>%
      group_by(colors) %>%
      summarise(count = n() ) %>%
      mutate( prop = count / sum(count) )
    
    0 讨论(0)
提交回复
热议问题