---
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)

strollur_results <- rchime(strollur, reference = reference)

strollur

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

## Results

The `rchime()` function returns a list containing the results of the function. When you are running the command with a strollur object, the chimera_report is  added, and chimeras are removed for you automatically. Let's take a closer look at the results returned. 

### Chimera Report

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}
strollur_results$chimera_report[
  strollur_results$chimera_report$Chimeric_Status == "Y",
] |> head(n = 5)
```

### Chimeras

Results also contains a list of the names of the chimeric sequences. Let's get the names of the first 10 chimeras.

```{r}
strollur_results$chimeras |> head(n = 10)
```
