简体   繁体   中英

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

This code seems redundant to me, but I am unsure how I would make it more concise? I heard that I could use a likelihoodCalculator class which would be assigned SpecificLikelihoodFactorXXXX objects, but I'm not sure how I would do this.

 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 
  } 

Here's one option that uses the case_when() function from the dplyr package.

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)  

Note : I interpreted this line

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

to be a typo and replaced it with likelihood <- likelihoodOfHarm . Feel free to remove this in the case_when() function if this is incorrect.

And just a reminder, there's a balance in making things concise and making things difficult to modify and change.

Edit . Made use of dplyr 's if_else() function instead of base R's ifelse()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM