---
title: "Reference Based Chimera Detection"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Reference Based Chimera Detection}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
library(rchime)
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

## Overview

The `rchime()` function allows you to detect and remove chimeras from your dataset using a referenced based approach. `rchime()` can be used with [strollur objects](https://mothur.org/strollur/reference/strollur.html) or data.frames as inputs. Let's look at examples of both data types using sequence data from [mothur's](https://mothur.org) [MiSeq_SOP](https://mothur.org/wiki/miseq_sop/) example analysis, and the `silva_gold()` reference sequences. *rchime* is designed to be flexible and you can use any reference you choose. 

### Creating *[strollur](https://mothur.org/strollur/)* objects

Let's create a [strollur object](https://mothur.org/strollur/reference/strollur.html) containing the MiSeq_SOP sequences.

```{r}
fasta_data <- readRDS(rchime_example("miseq_fasta.rds"))
abundance_data <- readRDS(rchime_example("miseq_abundance.rds"))

strollur <- strollur::new_dataset("rchime reference example")

strollur::add(strollur, table = fasta_data, type = "sequence")
strollur::assign(strollur, table = abundance_data, type = "sequence_abundance")

strollur
```

### Loading data.frames

```{r}
data_df <- readRDS(rchime_example("miseq_data_frame.rds"))

str(data_df)
```

## Removing chimeras

When removing chimeras using a reference, the potential parents are chosen from the set of reference sequences. Let's use the reference to remove the chimeras.

```{r}
reference <- silva_gold()
str(reference)

rchime(strollur, reference = reference)
strollur

data <- rchime(data_df, reference = reference)
data
```

## Results

The `rchime()` function returns a [strollur object](https://mothur.org/strollur/reference/strollur.html). Let's take a closer look at the `chimera_report` generated by `rchime()`. The [chimera_report](https://mothur.org/rchime/articles/chimera_report.html) is a data.frame with a row for each sequence in your dataset. Let's take a look at the first 5 chimeric sequences in the report:

```{r}
chimera_report <- strollur::report(data, type = "chimera_report")

chimera_report[chimera_report$Chimeric_Status == "Y", ] |> head(n = 5)
```

