Reputation: 333
I have a dataframe like this, listing out the counts by Day.
**Color** **Monday** **Tuesday** **Wednesday**
Green 2 3 1
Orange 3 5 5
Blue 1 3 2
Red 4 5 1
What I want to get to is something like this. Where the columns are percents.
**Color** **Monday** **Tuesday** **Wednesday**
Green 20% 20% 10%
Orange 30% 30% 60%
Blue 10% 20% 20%
Red 40% 30% 10%
Any ideas on how to do this without manually converting once column at a time?
Thanks!
Upvotes: 0
Views: 336
Reputation: 24178
You can use mutate_if()
in combination with a custom function, such as:
percent_mean <- function(x){
m <- round(x/sum(x),2)*100
return(paste0(m, sep = "%"))
}
library(dplyr)
df %>% mutate_if(is.numeric, funs(percent_mean))
# Color Monday Tuesday Wednesday
#1 Green 20% 19% 11%
#2 Orange 30% 31% 56%
#3 Blue 10% 19% 22%
#4 Red 40% 31% 11%
Upvotes: 1