---
title: "Using outqrf"
author: "lucian xu"
date: "`r Sys.Date()`"
bibliography: "biblio.bib"
link-citations: true
vignette: >
  %\VignetteIndexEntry{Using 'outqrf'}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
output: html_document
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  warning = FALSE,
  message = FALSE,
  fig.width = 6, 
  fig.height = 4,
  fig.align = "center"
)
```

## Overview

{outqrf} is an R package used for outlier detection. Each numeric variable is regressed onto all other variables using a quantile random forest [@Meinshausen]. We use {ranger} package [@wright] to perform the fitting and prediction of quantile regression forests. Next, we will compute the rank of the observed values in the predicted results' quantiles. If the rank of the observed value exceeds the threshold, the observed value is considered an outlier.

Since the same predicted value might be distributed across multiple quantiles in the predicted quantile results, this affects our location finding for the observed value. Therefore, we also used a method similar to the outForest package to compare the observed value with the 50% quantile value again to determine the final quantile result.

## Installation

```{r install,eval=FALSE}
# Development version
devtools::install_github("flystar233/outqrf")
```

## Usage

```{r usage, echo=TRUE}
library(outqrf)
#Generate data with outliers in numeric columns
irisWithOutliers <- generateOutliers(iris, p = 0.05,seed =2024)
# Find outliers by quantile random forest regressions
out <- outqrf(irisWithOutliers,quantiles_type=400)
out$outliers
```

## Evaluation on diamonds (Small Dataset)

```{r Evaluation1, echo=TRUE}
library(outqrf)
irisWithOutliers <- generateOutliers(iris, p = 0.05,seed =2024)
qrf <- outqrf(irisWithOutliers,quantiles_type=400)

evaluateOutliers(iris,irisWithOutliers,qrf$outliers)
```



```{r Evaluation1_1, eval=FALSE}
plot(qrf)
```

```{r Evaluation1_2, echo=FALSE}
library(outqrf)
irisWithOutliers <- generateOutliers(iris, p = 0.05,seed =2024)
qrf <- outqrf(irisWithOutliers,quantiles_type=400)
plot(qrf)
```

## Evaluation on diamonds (Big Dataset)

```{r Evaluation2, echo=TRUE}
library(outqrf)
library(ggplot2)
library(dplyr)
data <- diamonds|>select(price,carat,cut,color,clarity)
data2 <- outqrf::generateOutliers(data, p = 0.001,seed =2024)
# 108
qrf <- outqrf(data2,num.threads=8,quantiles_type=400)
#The process can be slow because it needs to predict the value at 400|1000 quantiles for each observation. 
evaluateOutliers(data,data2,qrf$outliers)
```

## References
