R中的列联表类似于按行分组的数据

时间:2017-05-29 10:10:25

标签: r

我想为这样的患者数据库建立一个列联表:

> data <- data.frame(Patient_nb = c("patient1", "patient1", "patient2", "patient3", "patient3"), Healthstate=c("Virus", "Alcool", "Alcool", "Virus", "Autoimmune"))

    Patient_nb   Healthstate   
 1   patient1     "Virus"
 2   patient1     "Alcool"
 3   patient2     "Alcool"
 4   patient3     "Virus"
 5   patient3     "Autoimmune"

创建一个表格,了解每个健康状况的患者数量,按患者分组;像这样的结果:

           Alcool    Virus   Autoimmune
Alcool       2         1         0
Virus        1         2         1
Autoimmune   0         1         1

至于说,第一行意味着2名患者患有&#34; Alcool&#34;健康状况,但只有一个人同时拥有&#34; Alcool&#34;和#34;病毒&#34; Healthstate。

&#34;表&#34;函数给我这个结果,所以它不是我正在寻找的。

> table(data$Patient_nb, data$Healthstate)

           Alcool   Virus   Autoimmune
patient1     1        1         0
patient2     1        0         0
patient3     0        1         1

1 个答案:

答案 0 :(得分:1)

我们需要crossprod

crossprod(table(data))