# Using For loop to identify the right mtry for model (this took around 4 minutes for me. Get yourself a drink :-)

accuracy_list =c()
for (i in 3:8) {
print(i)
model_optimal <- randomForest(INCOME ~ ., data = TrainSet, ntree = 500, mtry = i, importance = TRUE)
predValid <- predict(model_optimal, ValidSet, type = "class")
accuracy_list[i-2] = mean(predValid == ValidSet$INCOME)
}

accuracy_list

#[Output]: 
#[1] 0.6333333 0.6408333 0.6425000 0.6454167 0.6450000
#[6] 0.6454167

#We can also plot the result:
plot(3:8,accuracy_list)