【发布时间】:2017-07-27 07:19:30
【问题描述】:
我在 R 中有一个数据框,其中每一行是一个个体,每一列是一个疾病代码。每个单元格包含 1 或 0,以指示个体是否患有疾病。对于每个疾病代码 X,我想将患有疾病 X 的个体与未患有疾病 X 的个体区分开来。然后我想计算患有疾病 X 的患者同时患有疾病 Y 或疾病 Z 的相对风险。这是样本数据和我的方法:
# generate reproducible dataframe with disease diagnoses
set.seed(2)
ID = c(0:19)
disease0 = c(rbinom(10, 1, 0.0), rbinom(10, 1, 1.0))
disease1 = c(rbinom(10, 1, 0.1), rbinom(10, 1, 0.9))
disease2 = c(rbinom(10, 1, 0.5), rbinom(10, 1, 0.5))
disease3 = c(rbinom(10, 1, 0.9), rbinom(10, 1, 0.1))
disease4 = c(rbinom(10, 1, 1.0), rbinom(10, 1, 0.0))
(disease.df = data.frame(cbind(ID, disease0, disease1, disease2, disease3, disease4)))
row.names(disease.df) = disease.df[ ,1]
disease.df[ ,1] = NULL
disease.df
disease0 disease1 disease2 disease3 disease4
0 0 0 1 0 1
1 0 0 0 1 1
2 0 0 1 1 1
3 0 0 0 1 1
4 0 1 0 0 1
5 0 1 0 1 1
6 0 0 0 0 1
7 0 0 0 1 1
8 0 0 1 1 1
9 0 0 0 1 1
10 1 1 0 0 0
11 1 1 0 0 0
12 1 1 1 0 0
13 1 1 1 1 0
14 1 1 1 0 0
15 1 1 1 0 0
16 1 0 1 0 0
17 1 1 0 1 0
18 1 1 1 0 0
19 1 1 0 0 0
我可以使用以下代码来计算患有疾病 0 的个体同时患有疾病 1 到 4 的相对风险。
colMeans(filter(disease.df, disease0 == 1))/colMeans(filter(disease.df, disease0 != 1))
disease0 disease1 disease2 disease3 disease4
Inf 4.5000000 2.0000000 0.2857143 0.0000000
我的问题是,有没有一种方法可以使用矢量化操作或应用函数来针对所有 5 种疾病执行此操作,同时避免 for 循环。理想情况下,它会生成这样的表格:
disease0 disease1 disease2 disease3 disease4
diease0 Inf 4.5000000 2.0000000 0.2857143 0.0000000
diease1 7.3636364 Inf 1.0227273 0.4090909 0.2045455
diease2 1.8333333 1.0185185 Inf 0.6111111 0.5238095
diease3 0.3055556 0.4583333 0.6111111 Inf 2.8518519
diease4 0.0000000 0.2222222 0.5000000 3.5000000 Inf
【问题讨论】:
-
在看到来自 Ronak 的以下评论之前,我保存了上述编辑。很抱歉有任何混淆。
标签: r statistics vectorization