r - 从两个变量创建数字以查找合并症
问题描述
在这里对 R 来说是全新的。我目前正试图弄清楚有多少患者患有心力衰竭 (HF) 和糖尿病 (DM)。我已经弄清楚有多少人有其中之一,但现在我需要弄清楚如何找到合并症。有没有办法为仅 DM (1)、仅 HFpEF (2) 和 DM+HFpEF(3) 和两者都创建数值 (0)
这是我为单独查找两者的发生率所做的代码。0 1 和 2 指治疗组。由于我已经定义了变量,我可以将它们加在一起以获得 DM+HFpEF 吗?
DM_HFpEF_together$hfpef_1 <- ifelse (DM_HFpEF_together$ea_2> 1.5, 1, 0)
table(DM_HFpEF_together$hfpef_1 [DM_HFpEF_together$grp == 0])
table(DM_HFpEF_together$hfpef_1 [DM_HFpEF_together$grp == 1])
table(DM_HFpEF_together$hfpef_1 [DM_HFpEF_together$grp == 2])
DM_HFpEF_together$dmstatus_1 <- ifelse (DM_HFpEF_together$dmstatus_1 == 'Y', 1, 0)
table(DM_HFpEF_together$dmstatus_1 [DM_HFpEF_together$grp == 0])
table(DM_HFpEF_together$dmstatus_1 [DM_HFpEF_together$grp == 1])
table(DM_HFpEF_together$dmstatus_1 [DM_HFpEF_together$grp == 2])
解决方案
您可能想尝试使用包中的函数以及包中case_when()
的函数。dbplyr
mutate()
dplyr
library(dbplyr) #for the case when function
library(dplyr) # for the mutate function
set.seed(25) #for reproducibility
pt<-paste("S", seq(1:10), sep="") #Fake patients
DM<-sample(c("Y", "N"), 10, replace=TRUE) #Random diabetes diagnoses
set.seed(68) #New seed to get a different random draw
HF<-sample(c("Y", "N"), 10, replace=TRUE) #Random Heart Failure diagnoses
DF<-data.frame(Patient=pt, Diabetes=DM, Heart_Failure=HF)#Create a dataframe of fake data
DF_Final<-DF %>%
mutate(Comorbidity=case_when(Diabetes =="Y" & Heart_Failure=="N" ~ 1,
Diabetes =="N" & Heart_Failure == "Y" ~ 2,
Diabetes =="Y" & Heart_Failure=="Y" ~ 3,
Diabetes =="N" & Heart_Failure=="N" ~ 0))
这里使用%>%
或“管道”将数据帧发送到mutate()
函数的第一个参数中。该mutate()
函数在数据框中创建一个新列。该case_when()
函数允许您根据其他变量的条件有条件地重新分类变量。语法mutate(CoMorbidity = case_when(Diabetes=="Y" & Heart_Failure=="N" ~ 1))
意味着对于糖尿病值为 Y 且 Heart_Failure 值为 N 的行,将 Comorbidity 的值设置为 1。
推荐阅读
- python - 使用嵌套列表索引列表
- mongodb - Meteor Mongo 更新($set 对象;$push 数组)
- html - 在中心 CSS 中对齐单个列表项
- c++ - 查找 .txt 文件中的项目数
- postgresql - 如何以其他用户身份连接到数据库?
- angular - Angular `ng update @angular/...` 返回 `401 Unauthorized`
- c# - Akka.net .net 标准到 .net 核心思想 接待员
- amazon-web-services - aws 私有子网访问
- vb.net - 表单之间的启动画面
- python - 没有名为“glob2”的模块