Julio1000MX
Julio1000MX

Reputation: 11

Assign a percentage for a string

I have universities that have won Nobel prizes listed. There are two columns, one for the university, and the other one for the type of prize (physics, literature,..) If a university has more than one prize, it will appear as many times followed by the category of that won prize.

uni_data <- nobel %>% 
  group_by(name_of_university) %>%
  summarise(category)
  

How can I compute the distribution of prizes as a percentage? For example, if Duck University has won 4 prizes. 3 in literature and 1 in physics, how could I compute in a separate column the distribution of it? In this case, it would be 75% for literature and 25% for physics.

I want to do this with all universities.

I have tried group the list by uni; but after it i have not found a funtion to assing as a percentage.

Upvotes: 1

Views: 30

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145985

You can count to get the numbers, and then divide by the total to get a percentage:

library(dplyr)
nobel %>%
  count(name_of_university, category) %>%
  group_by(name_of_university) %>%
  mutate(proportion = n / sum(n)) %>%
  ungroup()

Upvotes: 1

Related Questions