0

假设我有下表:

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

如何将其转换为一个数据集,其中男性用现金支付 55 行,女性用现金支付 15 行,等等?我希望只有两个变量:性别和付款类型。这在R中可能吗?虽然这没有在此界面中显示为表格,但请想象一个列联表。

4

1 回答 1

1

你可以通过重塑然后 dplyr 来做到这一点。

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)
于 2015-10-13T15:23:29.007 回答