我如何使这个 R 代码更简洁(使用 S4 class)?

How would I make this R code more concise (using S4 class)?

这段代码对我来说似乎是多余的,但我不确定如何让它更简洁?我听说我可以使用一个 likelihoodCalculator class,它会被分配 SpecificLikelihoodFactorXXXX 对象,但我不确定我会怎么做。

 likelihood <- (density*count)/100000000
  
  if (factorA=="Yes") {                 
    likelihood<- likelihood*.35
  } 
  
  if (factorB<30){
    likelihood <- likelihood*1.31   
  }  

  if (factorC>50){
    likelihood <- likelihood*1.9 
  } else if (factorC>25){
    likelihood <- likelihood*1.6 
  } else if (factorC>10){
    likelihood <- likelihood*1.3 
  } else if (factorC==0){
    likelihood<- likelihood
  }
  
  if (factorD=="Yes"){
    likelihood <- likelihood*1.66 
  } 

这是一个使用 case_when() function from the dplyr 包的选项。

library(dplyr)

likelihood <- (density*count)/100000000

likelihood <- if_else(factorA == "Yes", likelihood * 0.35, likelihood)
likelihood <- if_else(factorB < 30, likelihood * 1.31, likelihood)

likelihood <- case_when(
  factorC > 50 ~ likelihood * 1.9, 
  factorC > 25 ~ likelihood * 1.6, 
  factorC > 10 ~ likelihood * 1.3, 
  factorC == 0 ~ likelihoodOfHarm
)

likelihood <- if_else(factorD == "Yes", likelihood * 1.66, likelihood)  

注意:我解释了这一行

} else if (factorC==0){
    likelihoodOfHarm <- likelihoodOfHarm
}

打错了,改成likelihood <- likelihoodOfHarm。如果不正确,请随时在 case_when() 函数中将其删除。

提醒一下,在使内容简洁与使内容难以修改和更改之间存在平衡。

编辑。使用 dplyrif_else() 函数而不是基础 R 的 ifelse()