Reputation: 67
I have a data frame in R with the following sample data:
choice Wealth
1 10
2 5
3 8
3 10
2 10
3 5
1 8
2 5
2 5
I am trying to create a summary table that shows the %choice by wealth level (i.e. of those with wealth x, how many chose 1 or 2 or 3):
Wealth %choice1 %choice2 %choice3
5 0% 75% 25%
8 50% 0% 50%
10 33% 33% 33%
I've tried a number of different methods but can't seem to get this correct (table, dplyr, etc.). As I am a novice in R, any ideas or help would be very much appreciated.
Upvotes: 0
Views: 157
Reputation: 67000
Here's a way with the tabyl
function from the janitor
package:
library(janitor); library(dplyr)
df %>%
tabyl(Wealth, choice) %>%
adorn_percentages("row")
# Wealth 1 2 3
# 5 0.0000000 0.7500000 0.2500000
# 8 0.5000000 0.0000000 0.5000000
# 10 0.3333333 0.3333333 0.3333333
Upvotes: 2
Reputation: 323396
Check with rowSums
with table
tb=table(df$Wealth,df$choice)
tb/rowSums(tb)
1 2 3
5 0.0000000 0.7500000 0.2500000
8 0.5000000 0.0000000 0.5000000
10 0.3333333 0.3333333 0.3333333
Upvotes: 1