r - 如何计算R中 bool 数据的组合数

标签 r

确定因素或基于许多 bool 字段创建新类别字段的最佳方法是什么?在此示例中,我需要计算药物的唯一组合数。

   > MultPsychMeds
       ID OLANZAPINE HALOPERIDOL QUETIAPINE RISPERIDONE
    1   A          1           1          0           0
    2   B          1           0          1           0
    3   C          1           0          1           0
    4   D          1           0          1           0
    5   E          1           0          0           1
    6   F          1           0          0           1
    7   G          1           0          0           1
    8   H          1           0          0           1
    9   I          0           1          1           0
    10  J          0           1          1           0

也许另一种表达方式是我需要对或对列表进行交叉或交叉制表。最终结果应类似于:
Combination            Count
OLANZAPINE/HALOPERIDOL     1
OLANZAPINE/QUETIAPINE      3
OLANZAPINE/RISPERIDONE     4
HALOPERIDOL/QUETIAPINE     2

可以使用以下命令在R中复制此数据帧:
MultPsychMeds <- structure(list(ID = structure(1:10, .Label = c("A", "B", "C", 
"D", "E", "F", "G", "H", "I", "J"), class = "factor"), OLANZAPINE = c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L), HALOPERIDOL = c(1L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L), QUETIAPINE = c(0L, 1L, 1L, 1L, 
0L, 0L, 0L, 0L, 1L, 1L), RISPERIDONE = c(0L, 0L, 0L, 0L, 1L, 
1L, 1L, 1L, 0L, 0L)), .Names = c("ID", "OLANZAPINE", "HALOPERIDOL", 
"QUETIAPINE", "RISPERIDONE"), class = "data.frame", row.names = c(NA, 
-10L))

最佳答案

这是使用reshapeplyr包的一种方法:

library(reshape)
library(plyr)

#Melt into long format
dat.m <- melt(MultPsychMeds, id.vars = "ID")
#Group at the ID level and paste the drugs together with "/"
out <- ddply(dat.m, "ID", summarize, combos = paste(variable[value == 1], collapse = "/"))

#Calculate a table
with(out, count(combos))

                       x freq
1 HALOPERIDOL/QUETIAPINE    2
2 OLANZAPINE/HALOPERIDOL    1
3  OLANZAPINE/QUETIAPINE    3
4 OLANZAPINE/RISPERIDONE    4

关于r - 如何计算R中 bool 数据的组合数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7184950/

相关文章:

r - 按行应用 if-else 函数

r - 对空集/NA 的 NA 集而不是 0 求和?

r - ggplot2条形图按一组值排序

r - 在 R 包中保存和检索临时文件

r - 斐波那契函数

r - 使用 curve() 绘制 survreg 的生存和风险函数

r - Bootstrap 标准错误位于引导类中的什么位置?

r - 在 R 中,从 df 中采样 n 行,其中某个列具有非 NA 值(有条件地采样)

r - 如何用 NAs - R 简单地计算行数

R - read.table 和 write.table 中的列名称以数字开头并包含空格