首页 > 解决方案 > 从两个变量创建数字以查找合并症

问题描述

在这里对 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])

标签: r

解决方案


您可能想尝试使用包中的函数以及包中case_when()的函数。dbplyrmutate()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。


推荐阅读