## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
has_rf <- requireNamespace("randomForest", quietly = TRUE)
has_seriation <- has_rf && requireNamespace("seriation", quietly = TRUE)
has_igraph <- has_rf && requireNamespace("igraph", quietly = TRUE)

## ----eval = has_rf------------------------------------------------------------
library(Proximum)

set.seed(1)
rf <- randomForest::randomForest(
  Species ~ ., data = iris, ntree = 200, keep.inbag = TRUE
)

px <- as_proximity(rf, newdata = iris)
px

## ----eval = has_rf, error = TRUE----------------------------------------------
try({
rf_stored <- randomForest::randomForest(
  Species ~ ., data = iris, ntree = 50, proximity = TRUE
)
as_proximity(rf_stored) # asks for in-bag; the forest has out-of-bag
})

## ----eval = has_rf------------------------------------------------------------
summary(px)

## ----eval = has_rf------------------------------------------------------------
px_oob <- as_proximity(rf, newdata = iris, type = "oob")
px_oob

## ----eval = has_rf------------------------------------------------------------
cor(px[upper.tri(px)], px_oob[upper.tri(px_oob)])

## ----eval = has_rf------------------------------------------------------------
set.seed(1)
small <- randomForest::randomForest(
  Species ~ ., data = iris, ntree = 3, keep.inbag = TRUE
)
sum(is.na(as_proximity(small, newdata = iris, type = "oob")))

## ----eval = has_rf------------------------------------------------------------
c(
  inbag = min(eigen(unclass(px), symmetric = TRUE, only.values = TRUE)$values),
  oob   = min(eigen(unclass(px_oob), symmetric = TRUE, only.values = TRUE)$values)
)

## ----eval = has_rf------------------------------------------------------------
summary(px)$euclidean
summary(px_oob)$euclidean

## ----eval = has_rf------------------------------------------------------------
repaired <- make_psd(px_oob, method = "clip")
repaired
summary(repaired)$euclidean

## ----eval = requireNamespace("ranger", quietly = TRUE)------------------------
set.seed(1)
rg <- ranger::ranger(Species ~ ., data = iris, num.trees = 200, keep.inbag = TRUE)
as_proximity(rg, newdata = iris)

## ----eval = has_seriation, fig.width = 5, fig.height = 4.2--------------------
autoplot(px, type = "heatmap")

## ----eval = has_rf, fig.width = 6, fig.height = 4.2---------------------------
autoplot(px, type = "mds", colour = iris$Species)

## ----eval = has_igraph, fig.width = 6, fig.height = 4.6-----------------------
autoplot(px, type = "network", threshold = 0.3)

