---
title: "Matching sample names with identifix"
author: "Matthias Pucher (<matthias.pucher@ecosight.at>)"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Matching sample names with identifix}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

<img src="logo.png" alt="identifix logo" style="float: right; height: 139px; border: none; padding: 0; margin: 0 0 1em 1em;" />

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

```{r setup}
library(identifix)
```

Two lists of sample names often describe the same samples, e.g. the names in a
lab report and in a field protocol, but they are written differently and in a
different order. identifix finds the matching pairs and tells you which names
could not be matched safely.

## The data

The package contains 99 name pairs with typical differences. In the file, the
names of a row belong together (apart from a few that are different on
purpose); we shuffle the second column to make it realistic.

```{r}
ex <- read.csv(system.file("extdata", "sample_names.csv", package = "identifix"),
               stringsAsFactors = FALSE, fileEncoding = "UTF-8")
set.seed(1)
lab <- ex$n1
field <- sample(ex$n2)
head(data.frame(lab, field), 10)
```

## Matching

```{r}
m <- idfix_match(lab, field)
m
```

The result is an integer vector: for each name of `lab` the position of the
matching name in `field`, or `NA`. So `field[m]` is aligned with `lab`:

```{r}
head(data.frame(lab, field = field[m]), 12)
```

## Checking the result

`idfix_report()` shows which step found each pair. For names without a match,
it explains why and suggests the most similar unmatched name of the other set.
`suggestion_check` warns if numbers or dates of the suggestion differ.

```{r}
rep <- idfix_report(m)
head(rep[!is.na(rep$n2_index), c("n1", "n2", "step")], 15)
idfix_report(m, unmatched_only = TRUE)[, c("n1", "n2", "note", "suggestion_name",
                                          "suggestion_check")]
```

Some names were not matched on purpose:

* `Buffer_Tris_pH7` and `Buffer_Tris_7.0`: the numbers differ (`7` vs. `7.0`).
* `Incubation_37C` and `Incubation_37_Deg`: `C` and `Deg` are different words.
* `Exp_2026-11-12_FR` and `12/11/2026_Exp`: the other names in `field` that
  use `/` are written month first (`05/22/2026`), so `12/11/2026` is read as
  11 December.
* `Centrifuge_Run_1` and `Centrifuge_1`: a word is missing. This is only
  matched by the optional `"subset"` step.

## Choosing steps

`idfix_steps()` lists all steps in the order in which they run:

```{r}
idfix_steps()
```

Pass the steps you want to `steps`. For example, add the optional `"subset"`
step:

```{r}
steps <- c(idfix_steps()$step[idfix_steps()$default], "subset")
m2 <- idfix_match(lab, field, steps = steps)
m2
```

Or switch off typo correction:

```{r}
m3 <- idfix_match(lab, field, steps = setdiff(steps, c("typo", "subset")))
sum(!is.na(m3))
```

Switching off `"case"`, `"punctuation"`, `"zeros"` or `"dates"` also removes
these normalisations from the later steps. Use this if, in your data,
`S_01` and `S_1` really are different samples.

## Dates

`idfix_extradat()` shows how dates in names are understood:

```{r}
idfix_extradat(c("Exp_2026-09-01", "2026Setember01", "1er septembre 2026",
                 "Trial_Sept_2026", "S_04/03/2026", "Probe 03.04."))
```

Numeric dates like `04/03/2026` are ambiguous. With `date_order = "auto"` the
order is taken from unambiguous dates in the same set with the same
separator. Without such evidence, dates with dots are read day-first, and
other dates keep both readings: they are only matched if exactly one reading
fits a name in the other set. Use `date_order = "dmy"` or `"mdy"` if you know
the convention.

## Correcting by hand

You can correct or add matches by assignment. `idfix_report()` marks them as
`"manual"` and warns if a position is used twice.

```{r}
i <- which(lab == "Centrifuge_Run_1")
m[i] <- which(field == "Centrifuge_1")
idfix_report(m)[i, c("n1", "n2", "step")]
```

To get a plain integer vector, use `as.vector(m)`.

## Checking pairs

`idfix_review()` shows the pairs one by one: in a window (RStudio viewer or
browser) if the shiny package is installed, otherwise in the console.
Differences between the names are highlighted, each pair is confirmed or
rejected with one key, and for names without a match the most similar names
are offered. Pairs you leave undecided keep their match.

```{r, eval = FALSE}
m <- idfix_review(m)
```

Every step and every pair has a confidence level (see `idfix_steps()`):
`high` (only whitespace, case, punctuation or leading zeros differ), `medium`
(dates, word order, additional words next to a date) and `low` (typos,
abbreviations, missing words, ambiguous dates). Pairs confirmed earlier or set
by hand are `known`. By default all pairs are shown; choose levels to check
only the uncertain ones:

```{r, eval = FALSE}
m <- idfix_review(m, confidence = c("low", "unmatched"))
```

```{r}
table(idfix_report(m)$confidence)
```

## Remembering decisions

`idfix_known()` collects all decisions, from the review and from corrections
by hand, as a table. Save it and pass it to `idfix_match()` as `known` next
time: confirmed pairs are matched first (step `"known"`) and are shown as
confirmed, with the date of the confirmation; rejected pairs are never matched
or suggested again. In `idfix_review()` such pairs are already marked as
confirmed, so only new names have to be checked; reject a pair to revoke an
earlier confirmation. Decisions accumulate over the runs.

```{r}
m[which(lab == "Buffer_Tris_pH7")] <- which(field == "Buffer_Tris_7.0")
known <- idfix_known(m)
known
```

```{r, eval = FALSE}
write.csv(known, "known.csv", row.names = FALSE)
# next time
known <- read.csv("known.csv")
```

```{r}
m_next <- idfix_match(lab, field, known = known)
idfix_report(m_next)[lab %in% c("Centrifuge_Run_1", "Buffer_Tris_pH7"),
                     c("n1", "n2", "step", "confidence", "review", "note")]
```

## Renaming

When the matching is right, `idfix_rename()` brings names into the spelling
of the other set:

```{r}
head(idfix_rename(m))               # lab names in field spelling
head(idfix_rename(m, to = "n1"))    # field names in lab spelling
```

It also renames directly in objects. It finds by itself where the names are
(names of a vector or list, a column, row or column names); use `where` if
several places fit.

```{r}
# a named vector with values per lab sample
conc <- setNames(round(runif(3), 2), lab[1:3])
idfix_rename(m, conc)

# field results in long format, renamed into lab spelling
res <- data.frame(sample = rep(field[1:2], each = 2), value = 1:4)
idfix_rename(m, res, to = "n1")
```

Names without match are kept (`unmatched = "keep"`) or set to `NA`
(`unmatched = "na"`).

## More than two sets

`idfix_multi()` matches several sets into one table with one row per sample.
Each further set is matched against the rows found so far, so samples that
are missing in the first set can still be aligned between the others.

```{r}
plate <- c("SAMPLE_ALPHA_01", "Protein Extract B", "dna_sample_001",
           "Std_20ng", "Extra_Site_1")
t <- idfix_multi(lab = lab, field = field, plate = plate)
t[!is.na(t$plate), ]
```

Check single matchings with `idfix_report()` and rename one set into the
spelling of another with `idfix_rename()`:

```{r}
r <- idfix_report(attr(t, "matches")$plate)
r[!is.na(r$n2), c("n1", "n2", "step", "note")]
idfix_rename(t, from = "plate")
idfix_rename(t, from = "plate", to = "field")
```

`idfix_rename()` uses the table itself, so rows you remove or correct by hand
are taken into account.
