Catbutt
Catbutt

Reputation: 1

How do I create percentage from total amount in r studio

First I get a total amount for each category.

table <- my_data %>% 
  group_by(Category) %>% 
  summarise(Total = sum(count))
table

my result -

  Category      Total
   <chr>         <dbl>
 1 Date Range        5
 2 None             87
 3 Product           1
 4 Reset             2

what I want to do next is get a percentage of each category compared to the total.

I try like this.

irisNew <- table %>% group_by(Total) %>% 
  summarize(count = n()) %>% 
  mutate(pct = count/sum(count))  # find percent of total
irisNew

but it gives me

 Total count   pct
  <dbl> <int> <dbl>
1     1     3   0.3
2     2     1   0.1
3     3     1   0.1
4     5     1   0.1

I want something that gets percentage of each category compared to total amount

  Category      Total        Percent
   <chr>         <dbl>
 1 Date Range        5           %
 2 None             87           %
 3 Product           1           %
 4 Reset             2           %

Upvotes: 0

Views: 37

Answers (1)

akrun
akrun

Reputation: 886978

From the table, we can divide the sum of 'Total' after ungrouping

library(dplyr)
table %>%
  ungroup %>%
  mutate(Percent = 100 * Total/sum(Total))

-output

#   Category Total   Percent
#1 Date Range     5  5.263158
#2       None    87 91.578947
#3    Product     1  1.052632
#4      Reset     2  2.105263

NOTE: table is a function name. It is better to avoid naming objects with function names

data

table <- structure(list(Category = c("Date Range", "None", "Product", 
"Reset"), Total = c(5L, 87L, 1L, 2L)), class = "data.frame", 
row.names = c("1", 
"2", "3", "4"))

Upvotes: 3

Related Questions