Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

## Motivation for this blog

I have seen several packages and frameworks used for the development of decision analytic models for cost effectiveness analysis in R. Some can be hard to understand and are often paywalled behind some sort of training that is associated with using package. Even after attending some sort of training, some run into more issues with debugging this type of code.

After struggling with some of these packages for some time, I thought to myself why not try coding my own solution. I decided to start simple beginning with defining functions needed for decision tree modelling.

## The Main Code

For coding a decision tree model in R we require two unique functions:
1) A function defining a chance node.
2) A function defining net monetary benefit.

The code for each of these functions are given below:

#Net Benefits
NB<-function(Threshold,Costs,Effects){
Threshold*Effects-Costs
}

#chance node
c_node<-function(p,x,y){ if(p>1|p<0){
print('p must be a value on the interval [0,1]')
}else{
p*x+(1-p)*y
}}

These two functions will simplify much of the modelling process as we will be building decision tree models by each branch.

## Coding a Decision Tree Model

We will consider the following decision tree model of vaccination. In this case we have an individual who is making a decision to vaccinate or to not vaccinate. A special note about this model is that with vaccination there is a risk of experience side effects due to the vaccine.

The way we will code up this model will be seen in the block below:

#Threshold Value
L<-5000
#Costs
SickCost<-2500
InjuryCost<-1000
VaxCost<-50

#Utilities
Sick<-0.5
SickAE<-0.4
Well<-1
WellAE<-0.9

#Payoffs
SickNoVax<-NB(L,SickCost,Sick)
WellNoVax<-NB(L,0,Well)
SickVaxAE<-NB(L,VaxCost+InjuryCost,Sick)
WellVaxAE<-NB(L,VaxCost+InjuryCost,WellAE)
SickVaxNoAE<-NB(L,VaxCost,Sick)
WellVaxNoAE<-NB(L,VaxCost,Well)

#ChanceNodes
NoVax_SWRisk<-c_node(0.6,SickNoVax,WellNoVax)
VaxAE_SWRisk<-c_node(0.6,SickVaxAE,WellVaxAE)
VaxNoAE_SWRisk<-c_node(0.6,SickVaxNoAE,WellVaxNoAE)

#Decisions
Vax<-c_node(0.5,VaxAE_SWRisk,VaxNoAE_SWRisk)
NoVax<-NoVax_SWRisk

#Organizing as a DataFrame
data1<-c("Vaccinate","Dont Vaccinate")
data2<-c(Vax, NoVax)
DecisionTree<-data.frame(Decisions=data1,Scores=data2)

#Optimal Choice
DecisionTree\$Decisions[which.max(DecisionTree\$Scores)]

## Notes

• We define our Threshold, Costs, Utilities and Payoffs before building out the branches of our decision trees using the c_node() function. Better practice would be to define probabilities used in this function before as well.
• The decisions you are considering should be organized in a data frame.
• which.max() is essential to defining optimal treatment. In our context we read our code as “Define the decision which provides the maximum net benefits score”.