0

Suppose I have the following table:

_                    Male Female    Total
Pay_with_cash         55     15      70
Use_a_credit_card     60     40     100
Total                115     55     170

How can I convert this to a dataset with 55 rows for males that pay with cash, 15 rows for females that pay with cash, etc? I want there to be only two variables: gender and payment type. Is this possible in R? Although this is not showing up as a table in this interface, please imagine a contingency table.

Jaap
  • 81,064
  • 34
  • 182
  • 193
  • 1
    Could you provide the `dput()` of your contingency table in order to make this a more [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? – MrFlick Oct 13 '15 at 14:57
  • Likely a dup of: http://stackoverflow.com/questions/30481496/is-there-a-general-inverse-of-the-table-function (assuming you used `table()` to create your contingency table) – MrFlick Oct 13 '15 at 15:03

1 Answers1

1

You can do this with reshaping then dplyr do.

library(dplyr)
library(tidyr)
library(magrittr)

your_table = 
  c(55, 60, 115, 15, 40, 55, 70, 100, 170) %>%
  matrix(3) %>%
  set_rownames(c("Pay_with_cash",
                 "Use_a_credit_card",
                 "Total")) %>%
  set_colnames(c("Male", "Female", "Total"))


your_table %>%
  as.data.frame %>%
  select(-Total) %>%
  mutate(payment_type = rownames(.)) %>%
  filter(payment_type != "Total") %>%
  gather(gender, frequency, Male, Female) %>%
  group_by(payment_type, gender) %>%
  do(data_frame(ones = rep(1, .$frequency))) %>%
  select(-ones)
bramtayl
  • 4,004
  • 2
  • 11
  • 18