Home > Software design >  How to get a column to display percentages in R
How to get a column to display percentages in R

Time:11-04

I have produced a table which shows the number of different people in each income group form a data table, I would like to produce a column which shows this as a percentage.

This is my current code that produces a table with a column with the number of people in each income group

ind_and_countries %>%
  group_by(Income_Group)%>%
  summarise(Number = n())%>%
  arrange(desc(Number))

I have tried using mutate(Percentage = Number/colSums(Number)*100) I think the issue is when I need to divide by the total number and can't seem to get this to work.

CodePudding user response:

The formattable package used here is only affecting the appearance. You could use Number/sum(Number) alone.

ind_and_countries %>%
  group_by(Income_Group)%>%
  summarise(Number = n())%>%
  mutate(Percentage = formattable::percent(Number / sum(Number))) %>% 
  arrange(desc(Number))

CodePudding user response:

Just add mutate(Percentage = Number / sum(Number) * 100)

  •  Tags:  
  • r
  • Related