user13874
user13874

Reputation: 377

dplyr - ratio of column

Apologies if this is a repeat question. Can someone show me how to calculate the proportion in each column using dplyr? I listed input and output data below.

INPUT DATA

>sample_data
am     n
<dbl> <int>
 0    19
 1    13

DESIRED OUTPUT

>sample_data
am     n
<dbl> <int>
 0    0.59375
 1    0.40625

You can generate input data from the below code

sample_data <- mtcars %>% group_by(am) %>% tally()  

Thanks in advance!

Upvotes: 0

Views: 49

Answers (1)

NelsonGon
NelsonGon

Reputation: 13319

We can get it as follows:

   sample_data %>% 
 mutate(Prop=n/sum(n)) %>% 
   select(-n)
# A tibble: 2 x 2
     am  Prop
  <dbl> <dbl>
1     0 0.594
2     1 0.406

Upvotes: 1

Related Questions