How do I add percentage sign to this table?
table(sample.1$Department)/50*100
Click here for the pic of my code output
I want to add the percentage sign to the numbers here. E.g. 28%, 46%, 8%, etc.
CodePudding user response:
Recreating data
I didnt see a reproducible dataset, so I created one for now:
# Create rows and columns:
names <- c("Boston Fire Department",
"Boston Police Department",
"Boston Public Library",
"BPS Facility Management",
"BPS Special Education")
counts <- c(28,46,8,10,8)
# Turn into data frame:
df <- data.frame(names,
counts)
Get proportions/percentages:
From there you will just need to create a new column for the percentages, here thus called "props":
df$prop <- paste(df$counts, "%", sep = "")
df
Which will print this:
names counts prop
1 Boston Fire Department 28 28%
2 Boston Police Department 46 46%
3 Boston Public Library 8 8%
4 BPS Facility Management 10 10%
5 BPS Special Education 8 8%
Or if you just wanna change the counts to percentages, you can save over the column already there:
df$counts <- paste(df$counts, "%", sep = "")
df
Which gives you this:
names counts
1 Boston Fire Department 28%
2 Boston Police Department 46%
3 Boston Public Library 8%
4 BPS Facility Management 10%
5 BPS Special Education 8%
CodePudding user response:
You might want to use proportions(table(.)) instead of calculating the percentages manually which is prone to mistakes. Try one of those:
with(sample.1, as.data.frame.table(proportions(table(Department))*100)) |>
transform(Freq=paste0(Freq, '%'))
# Department Freq
# 1 Facility 10%
# 2 Fire 28%
# 3 Police 46%
# 4 Public 8%
# 5 Special 8%
with(sample.1, proportions(table(Department))*100) |>
{\(.) setNames(paste0(., '%'), unlist(attr(., 'dimnames')))}()
# Facility Fire Police Public Special
# "10%" "28%" "46%" "8%" "8%"
Note: R >= 4.1 used.
Data:
sample.1 <- data.frame(Department=unlist(Map(rep, c('Fire', 'Police','Public', 'Facility', 'Special'),
c(14, 23, 4, 5, 4))))
CodePudding user response:
The object class from table() is a bit obnoxious to work with, unfortunately.
Here is an example using the data from the package palmerpenguins:
library(palmerpenguins)
t <- table(penguins$species)/50*100
> t
Adelie Chinstrap Gentoo
304 136 248
t2 <- sub("$", "%", t)
names(t2) <- names(t)
> t2
Adelie Chinstrap Gentoo
"304%" "136%" "248%"
What sub() does here is to match the regex for the end of the element in the table (i.e., $) and to add "%" at the end. Unfortunately, this doesn't keep the header of the table, but it transforms it into a vector with the same order, so we can just overwrite it using names()
