Reputation: 7061
Suppose I have a count table such like:
library(tidyverse)
set.seed(123)
df<-data.frame(x=letters[1:3],
y=sample(1:10, 3),
z=sample(3:20, 3))%>%
mutate(tot=rowSums(select(., -1)))
df
x y z tot
1 a 3 20 23
2 b 10 13 23
3 c 2 7 9
How to quickly generate a proportion table like
x y z tot
1 a 13.04 86.96 100
2 b 43.48 56.52 100
3 c 22.22 77.78 100
Upvotes: 1
Views: 126
Reputation: 16121
You can use:
df %>% mutate_if(is.numeric, ~./tot*100)
# x y z tot
# 1 a 13.04348 86.95652 100
# 2 b 43.47826 56.52174 100
# 3 c 22.22222 77.77778 100
which will update only your numeric variables, wherever they exist in your database.
Upvotes: 1
Reputation: 953
Is this what you want?
library(tidyverse)
set.seed(123)
df<-data.frame(x=letters[1:3],
y=sample(1:10, 3),
z=sample(3:20, 3))%>%
mutate(tot=rowSums(select(., -1)))
df
x y z tot
1 a 3 20 23
2 b 10 13 23
3 c 2 7 9
proportion_df<-cbind(x=df$x,df[,-1] / df$tot * 100)
proportion_df
x y z tot
1 a 13.04348 86.95652 100
2 b 43.47826 56.52174 100
3 c 22.22222 77.77778 100
Upvotes: 0