0

I have several tables that run frequencies and percentages of my data:

tableAge1 <- table(data$Age)
tableAge2 <- round(prop.table(tableAge1) * 100, 2)
tableGender1 <- table(data$Gender)
tableGender2 <- round(prop.table(tableGender1) * 100, 2)

results:

18-24 25-29 30-34 35-39
    2     1     1     2

18-24 25-29 30-34 35-39
15.38  7.69  7.69 15.38

Male Female Not_Answer
   3      8          1

Male Female Not_Answer
23.08  69.23      7.69

I want to connect these tables together like so:

18-24 25-29 30-34 35-39 18-24 25-29 30-34 35-39 Male Female Not_Answer
    2     1     1     2 15.38  7.69  7.69 15.38    3      8          1

Is there a way to do this?

bind_rows() comes close but adds the data for each categorical variable in a separate line:

> bind_rows(tableAge1, tableAge2, tableGender1)
# A tibble: 3 x 10
  `18-24` `25-29` `30-34` `35-39` `40-44` `50-54` `65-69` Female  Male    `Prefer not to answer`
  <table> <table> <table> <table> <table> <table> <table> <table> <table> <table>               
1  2.00   1.00    1.00     2.00    2.00    4.00   1.00    NA      NA      NA                    
2 15.38   7.69    7.69    15.38   15.38   30.77   7.69    NA      NA      NA                    
3    NA     NA      NA       NA      NA      NA     NA     9       3       1 
DrPaulVella
  • 391
  • 8
  • 22

1 Answers1

0

solution was found here: using-dplyr-to-create-summary-proportion-table

rather than try to merge tables, I used group_by on the original datasource to bring together the categorical variables and then run the stats:

table <- data %>%
  gather(variable, value, Age, Gender, Income) %>%
  group_by(variable, value) %>%
  summarise (n = n()) %>%
  mutate(freq = (n / sum(n)) * 100)

> table
# A tibble: 16 x 4
# Groups:   variable [3]
   variable value                      n  freq
   <chr>    <chr>                  <int> <dbl>
 1 Age      "18-24"                    2 15.4 
 2 Age      "25-29"                    1  7.69
 3 Age      "30-34"                    1  7.69
 4 Age      "35-39"                    2 15.4 
 5 Age      "40-44"                    2 15.4 
 6 Age      "50-54"                    4 30.8 
 7 Age      "65-69"                    1  7.69
 8 Gender   "Female"                   9 69.2 
 9 Gender   "Male"                     3 23.1 
10 Gender   "Prefer not to answer"     1  7.69
11 Income   ""                         3 23.1 
12 Income   "$125-$150k"               1  7.69
13 Income   "$150-$175k"               2 15.4 
14 Income   "$200-$225k"               2 15.4 
15 Income   "$250k+"                   2 15.4 
16 Income   "$75-$100k"                3 23.1 
> 
DrPaulVella
  • 391
  • 8
  • 22