从两个变量中创建数字以查找共病



对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])

您可能想尝试使用dbplyr包中的case_when()函数和dplyr包中的mutate()函数。

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))的意思是,对于diabetes的值为Y, Heart_Failure的值为N的行,将Comorbidity的值设置为1。

最新更新