if (!require("randomForest")) install.packages("randomForest")
library(randomForest)
if (!require("ranger")) install.packages("ranger")
library(ranger)

rf_comp <- function(train){
  rf<-randomForest(as.factor(train$class) ~ .,data=train, ntree=5000,
                   importance=T) 
  print(rf)  # error
  detach("package:ranger", unload=TRUE)
  rf_imp<-data.frame(rf_score=importance(rf, type=1)) # Cannot do if ranger is loaded
  #dplyr::arrange(rf_imp,-MeanDecreaseAccuracy) 
  #print(dplyr::slice_max(rf_imp,order_by=MeanDecreaseAccuracy, n=20))
  
  library(ranger)
  rf2<-ranger(as.factor(train$class) ~ ., data=train, num.trees=5000,
              importance="permutation") 
  print(rf2)  # error
  rf2_imp<-data.frame(rf_score=rf2$variable.importance)
  #dplyr::arrange(rf_imp,-MeanDecreaseAccuracy) 
  #print(dplyr::slice_max(rf2_imp,order_by=rf_score, n=20))
  
  #rftest <- predict(rf, newdata=test, type="class")
  #confusionMatrix(table(rftest,test$class))  
  
  return(list(rf_imp=rf_imp, rf2_imp=rf2_imp))
}
