Calculate percentage by group in one column using dplyr, ignoring blanks

Viewed 62

I want to calculate the percentage in the column 'Color', ignoring blanks.

Example:

Df

Color
green

green
blue
blue
blue

blue

Code

  Df %>%
    group_by(color) %>%
    summarise(n = n()) %>%
    mutate(per = n/sum(n, na.rm = TRUE))

Desired output:

Color  n   per
green  2   0.33
blue   4   0.67

What is the code missing? I know this is a simple question, and would really appreciate insights you could offer!

1 Answers

I tried your code, and it seems to work except that the output includes a row for NA values, which I assume is the issue you're having. I would fix it like this:

df %>% filter(!is.na(color)) %>%
   count(color) %>%
   mutate(per = n/sum(n))

or, if you need something that runs even faster on large data sets:

df <- df[!is.na(df$color),] %>% count(color)
df$per <- df$n/sum(df$n)
Related