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

## ----setup, eval = has_rf-----------------------------------------------------
library(Proximum)
library(randomForest)

set.seed(1)
rows <- sample(nrow(iris), 60)
df <- iris[rows, ]

set.seed(2)
rf_shallow <- randomForest(Species ~ ., data = df, ntree = 300, maxnodes = 4,
                           keep.inbag = TRUE)
set.seed(3)
rf_deep <- randomForest(Species ~ ., data = df, ntree = 300, keep.inbag = TRUE)

px1 <- as_proximity(rf_shallow, newdata = df)
px2 <- as_proximity(rf_deep, newdata = df)
px1

## ----mantel, eval = has_rf----------------------------------------------------
mantel_test(px1, px2, n_perm = 999)

## ----oob, eval = has_rf-------------------------------------------------------
oob <- as_proximity(rf_deep, newdata = df, type = "oob")
mantel_test(px1, oob, n_perm = 999)$parameter

## ----cka, eval = has_rf-------------------------------------------------------
cka(px1, px2)
rv_coefficient(px1, px2)

## ----refuse, error = TRUE, eval = has_rf--------------------------------------
try({
cka(oob, oob)
})

## ----repair, eval = has_rf----------------------------------------------------
cka(make_psd(px2), make_psd(oob))

## ----protest, eval = has_rf---------------------------------------------------
protest(px1, px2, n_perm = 999)

## ----protest_k, eval = has_rf-------------------------------------------------
vapply(c(2, 4, 6), function(k) unname(protest(px1, px2, k = k, n_perm = 99)$statistic),
       numeric(1))

## ----permanova, eval = has_rf-------------------------------------------------
permanova(px2, ~ Species + Sepal.Width, data = df, n_perm = 999)

## ----refuse_undefined, error = TRUE, eval = has_rf----------------------------
try({
small <- randomForest(Species ~ ., data = df, ntree = 15, keep.inbag = TRUE)
permanova(as_proximity(small, newdata = df, type = "oob"), ~ Species, data = df)
})

