使用逻辑运算符缩短可变代码

时间:2019-03-29 13:28:14

标签: r logical-operators operator-precedence

我正在尝试用5个标准肥胖(3个可能的二元结果),胰岛素抵抗(3个可能的二元结果),血脂异常TGC(3个可能的二元结果),血脂异常HDL(2个可能的二元结果)和高血压(4个可能的二进制结果)。如果受试者在这5个标准中的任何3个中均为阳性,则将其视为代谢综合征阳性。

考虑到任何对4或5个标准呈阳性的受试者都将由代理覆盖,我尝试将它们合并到C5,3中。但是我尝试覆盖任何可能的组合时,我的代码太大了。是否可以使用运算符优先级来使代码更小以使其更紧凑?

METSYN <- array (NA,dim = dim(BancoTOTAL)[1] )
for (i in 1:791){  
  METSYN[i] <- ifelse ( #OID1 OID2
    BancoTOTAL$sexo.x[i] == 0 && BancoTOTAL$cintura.x[i] > 90 
                       && BancoTOTAL$Glic[i] >= 100 
                       && BancoTOTAL$TRIG[i] > 150 
                       |BancoTOTAL$sexo.x[i] == 1 && BancoTOTAL$cintura.x[i] > 80 
                       && BancoTOTAL$Glic[i] >= 100 
                       && BancoTOTAL$TRIG[i] > 150 
                       |BancoTOTAL$IMC[i] > 30
                       && BancoTOTAL$Glic[i] >= 100 
                       && BancoTOTAL$TRIG[i] > 150

and soon
, 1, 0)
}

这是我使用中间分类变量重做的代码

METSYN <- array(NA, dim = dim(BancoTOTAL)[1])
    for (i in 1:(dim(BancoTOTAL)[1])){
      METSYN[i] <- ifelse(
        #OID1
        BancoTOTAL$obesity[i] == 1
        && BancoTOTAL$insulinR[i] == 1
        && BancoTOTAL$dyslipidemiaTGC[i] == 1
        #OID2
        |BancoTOTAL$obesity[i] == 1
        && BancoTOTAL$insulinR[i] == 1
        && BancoTOTAL$dyslipidemiaHDL[i] == 1
        #OIH
        |BancoTOTAL$obesity[i] == 1
        && BancoTOTAL$insulinR[i] == 1
        && BancoTOTAL$HBP[i] == 1
        #OD1D2
        |BancoTOTAL$obesity[i] == 1
        && BancoTOTAL$dyslipidemiaTGC[i] == 1
        && BancoTOTAL$dyslipidemiaHDL[i] == 1
        #OD1H
        |BancoTOTAL$obesity[i] == 1
        && BancoTOTAL$dyslipidemiaTGC[i] == 1
        && BancoTOTAL$HBP[i] == 1
        #OD2H
        |BancoTOTAL$obesity[i] == 1
        && BancoTOTAL$dyslipidemiaHDL[i] == 1
        && BancoTOTAL$HBP[i] == 1
        #ID1D2
        |BancoTOTAL$obesity[i] == 1
        && BancoTOTAL$dyslipidemiaTGC[i] == 1
        && BancoTOTAL$dyslipidemiaHDL[i] == 1
        #ID1H
        |BancoTOTAL$insulinR[i] == 1
        && BancoTOTAL$dyslipidemiaTGC[i] == 1
        && BancoTOTAL$HBP[i] == 1
        #ID2H
        |BancoTOTAL$insulinR[i] == 1
        && BancoTOTAL$dyslipidemiaHDL[i] == 1
        && BancoTOTAL$HBP[i] == 1
        #D1D2H
        |BancoTOTAL$dyslipidemiaTGC[i] == 1
        && BancoTOTAL$dyslipidemiaHDL[i] == 1
        && BancoTOTAL$HBP[i] == 1
        , 1, 0 )
    }

1 个答案:

答案 0 :(得分:0)

这对您有用吗? (使用您的中间类别变量)

METSYN <- unlist(lapply(1:dim(BancoTOTAL)[1], function (x){
  (BancoTOTAL$obesity[x]+BancoTOTAL$insulinR[x]+BancoTOTAL$dyslipidemiaTGC[x]+BancoTOTAL$dyslipidemiaHDL[x]+BancoTOTAL$HBP[x])>=3
}))