---
title: "Getting started with wrMisc"
author: Wolfgang Raffelsberger
date: '`r Sys.Date()`'
encoding: UTF-8  
output:
  knitr:::html_vignette:
    toc: true
    fig_caption: yes
  pdf_document:
    highlight: null
    number_sections: no  
vignette: >
  %\VignetteIndexEntry{wrMiscVignette1}
  %\VignetteEngine{knitr::rmarkdown}
---


## Introduction

This package contains a collection of various (low-level) tools which may be of general interest, in particular in the context of working with 'omics'-data. 
These functions were accumulated over a number of years of data-wrangling when treating high-throughput data from biomedical applications.
Besides, these functions are further used/integrated in more specialized functions dedicated to specific applications in the packages [wrProteo](https://CRAN.R-project.org/package=wrProteo), [wrGraph](https://CRAN.R-project.org/package=wrGraph) or [wrTopDownFrag](https://CRAN.R-project.org/package=wrTopDownFrag). 
All these packages are available on [CRAN](https://cran.r-project.org/).

If you are not familiar with [R](https://www.r-project.org/) you may find many introductory documents on the official R-site 
in [contributed documents](https://cran.r-project.org/other-docs.html) or under [Documentation/Manuals](https://cran.r-project.org/manuals.html).
Of course, numerous other documents/videos/sites with tutorials and courses exist, too.


### Dependencies and Compilation
One of the aims was to write a package easy to install, with low system requirements and few obligatory dependencies.  
All code is written in pure R and does not need any special compilers.
The number of obligatory dependencies was kept to a minumum.

Most of additional packages used in some of the functions were declared as 'suggested' (ie not obligatory), to allow installation of _wrMisc_ even if some these additional packages can't be installed/compiled at the user's side.
When a feature/function of one of the 'suggested' packages is about to be used, its presence/installation will be checked and,
only if found as missing, the user will be prompted a message inviting to install specific package(s) before using these specific functions.


### Installation And Loading
To get started, we need to install (if not yet installed) and load the package "[wrMisc](https://CRAN.R-project.org/package=wrMisc)" available from [CRAN](https://cran.r-project.org/).


```{r setup0, include=FALSE, echo=FALSE, messages=FALSE, warnings=FALSE}
suppressPackageStartupMessages({
    library(wrMisc)
})
```

```{r install, echo=TRUE, eval=FALSE}
## If not already installed, you'll have to install the package first.
## This is the basic installation commande in R
install.packages("wrMisc")
```

Since the functions illustrated in this vignette require a number of the _suggested_ packages,
let's check if they are installed and add them (via a small function), if not yet installed.
```{r install2, echo=TRUE, eval=FALSE}
packages <- c("knitr", "rmarkdown", "BiocManager", "kableExtra", "boot", "data.tree", "data.table", 
  "fdrtool", "RColorBrewer", "Rcpp", "wrMisc", "wrGraph", "wrProteo")
checkInstallPkg <- function(pkg) {       # install function
  if(!requireNamespace(pkg, quietly=TRUE)) install.packages(pkg) }

## install if not yet present
sapply(packages, checkInstallPkg)
```

Finally, this package also uses the Bioconductor package [limma](https://bioconductor.org/packages/release/bioc/html/limma.html) 
which has to be installed differently (see also help on [Bioconductor](https://bioconductor.org)):
```{r install3, echo=TRUE, eval=FALSE}
## Installation of limma 
BiocManager::install("limma")
```

This vignette is also accessible from R command-line or on CRAN at [wrMisc](https://CRAN.R-project.org/package=wrMisc):
```{r install4, echo=TRUE, eval=FALSE}
## Now you can open this vignette out of R:
vignette("wrMiscVignette1", package="wrMisc")
```

Before using the functions of this package, we actually need to load the package first (best on a fresh R-session):

```{r setup1}
library("wrMisc")

## This is 'wrMisc' version number :
packageVersion("wrMisc")
```



## Speed Optimized Functions In The Package wrMisc

In high-throughput experiments in biology (like transcriptomics, proteomics etc...) many different features get measured a number if times (different samples like patients or evolution of a disease). The resulting data typically contain many (independent) rows (eg >1000 different genes or proteins who's abundance was measured) and much fewer columns that may get further organized in groups of replicates. 
As R is a versatile language, multiple options exist for assessing the global characteristics of such data, some are more efficient on a computational point of view.
In order to allow fast treatment of very large data-sets some tools have been re-designed for optimal performance.


### Assessing Basic Information About Variability (for matrix)

Many measurement techniques applied in high throughput manner suffer from precision.
This means, the same measurements taken twice in a row (ie repeated on the same subject) will very likely not give an identical result. 
For this reason it is common practice to make replicate measurements to i) estimate mean (ie representative) values and ii) asses the factors contributing to the variablity observed.
Briefly, technical replicates represent the case where multiple read-outs of the very same sample are generated and the resulting variability is associated to technical issues during the process of taking measures. Biological replicates represent independant samples and reflect therefore the varibility a given parameter may have in a certain population of individuals.
With the tools presented here, both technical and biological replicates can be dealt with. 
In several cases the interpretation of the resulting numbers should consider the experimental setup, though.

Let's make a simple matrix as toy data:
```{r basicVariability, echo=TRUE}
grp1 <- rep(LETTERS[1:3], c(3,4,3))
sampNa1 <- paste0(grp1, c(1:3,1:4,1:3))
set.seed(2016); dat1 <- matrix(round(c(runif(50000) +rep(1:1000,50)),3), 
  ncol=10, dimnames=list(NULL,sampNa1))
dim(dat1)
head(dat1)
```

Now lets estimate the standard deviation _(sd)_ for every row:
```{r sdForEachRow, echo=TRUE}
head(rowSds(dat1))
system.time(sd1 <- rowSds(dat1))
system.time(sd2 <- apply(dat1, 1, sd))
```

On most systems the equivalent calculation using *apply()* will run much slower compared to `rowSds`.

Note, there is a minor issue with rounding :
```{r usingApply, echo=TRUE}
table(round(sd1, 13)==round(sd2, 13))
```

Similarly we can easily calculate the CV (coefficient of variation, ie sd / mean, see also [CV](https://en.wikipedia.org/wiki/Coefficient_of_variation)) for every row using `rowCVs` :

```{r calculateRowCV, echo=TRUE}
system.time(cv1 <- rowCVs(dat1))
system.time(cv2 <- apply(dat1, 1, sd) / rowMeans(dat1))
# typically the calculation using rowCVs is much faster
head(cv1)
# results from the 'conventional' way
head(cv2)
```

Note, these calculations will be very efficient as long as the number of rows is much higher (>>) than the number of columns.


### Data Organized In (Sub-)Groups As Sets Of Columns

Now, let's assume our data is contains 3 initial samples measured as several replicates (already defined in _grp1_).
Similarly, we can also calculate the sd or CV for each line while splitting into groups of replicates (functions `rowGrpMeans`, `rowGrpSds` and `rowGrpCV`): 

```{r rowGrpMeans1, echo=TRUE}
# we already defined the grouping :
grp1

## the mean for each group and row
system.time(mean1Gr <- rowGrpMeans(dat1, grp1))
```

```{r sdOrCVbyGrp, echo=TRUE}
## Now the sd for each row and group
system.time(sd1Gr <- rowGrpSds(dat1, grp1))
# will give us a matrix with the sd for each group & line 
head(sd1Gr)

# Let's check the results of the first line :
sd1Gr[1,] == c(sd(dat1[1,1:3]), sd(dat1[1,4:7]), sd(dat1[1,8:10]))

# The CV :
system.time(cv1Gr <- rowGrpCV(dat1, grp1))
head(cv1Gr)
```


#### Counting Number Of NAs Per Row And Group Of Columns

Some data, like with quantitative proteomics measures, may contain an elevated number of _NAs_ (see also the package [wrProteo](https://CRAN.R-project.org/package=wrProteo) for further options for dealing with such data). 
Furthermore, many other packages on CRAN and Bioconductor cover this topic, see also the [missing data task-view](https://CRAN.R-project.org/view=MissingData) on CRAN.
Similar as above there is an easy way to count the number of _NAs_ to get an overview how NAs are distributed. 

Let's assume we have measures for 200 features (eg gene-abundaces) from 8 groups of samples :
```{r rowGrpNA1, echo=TRUE}
mat2 <- matrix(1, nrow=200, ncol=40)
set.seed(2026); mat2[sample.int(prod(dim(mat2)), nrow(mat2), replace=FALSE)] <- NA
set.seed(2025); grp2 <- as.factor(sample.int(n=8, size=ncol(mat2), replace=TRUE))
  table(grp2)
```

Now we can easily count the number of NAs per row and set of replicates.
```{r rowGrpNA2, echo=TRUE}
## number of NAs per row and group
head(rowGrpNA(mat2, grp2))
```

It is also possible to return the ratio of NA values or both the number of _NAs_ and the size of the sub-groups.
```{r rowGrpNA3, echo=TRUE}
head(rowGrpNA(mat2, grp2, mode="ratio"))
head(rowGrpNA(mat2, grp2, mode="complete"))
```

This function allows also treating objects created by testing from package [wrProteo](https://CRAN.R-project.org/package=wrProteo), the group-information is typically already available in such objects.
Finally, all results may get collapsed in single column/vector when using any of the _..Collapse_ modes.
```{r rowGrpNA4, echo=TRUE}
## mimick output from testing from package wrProteo
dat1 <- list(quant=mat2, isNA =is.na(mat2), setup=list(grp=grp2))
head(rowGrpNA(dat1, mode="simple"))
head(rowGrpNA(dat1, mode="complete"))
head(rowGrpNA(dat1, mode="ratioCollapse"), 3)
```



### Fast NA-omit For Very Large Objects

The function _na.omit()_ from the package _stats_ also keeps a trace of all omitted instances. 
This can be penalizing in terms of memory usage when handling very large vectors with a high content of NAs (eg >10000 NAs). 
If you don't need to document precisely which elements got eliminated, the function `naOmit()` may offer 
smoother functioning for very large objects. 

```{r naOmit, echo=TRUE}
aA <- c(11:13,NA,10,NA)
 
str(naOmit(aA))

# the 'classical' na.omit also stores which elements were NA
str(na.omit(aA))
```

  
### Minimum Distance/Difference Between Values

If you need to find the closest neighbour(s) of a numeric vector, the function `minDiff()` will tell you the 
distance ("dif","ppm" or "ratio") and index ("best") of the closest neighbour. 
In case of multiple shortest distances the index if the first one is reported, and the column "nbest" will display a value of >1.

```{r minDiff, echo=TRUE}
set.seed(2017); aa <- 10 *c(0.1 +round(runif(20),2), 0.53, 0.53)
head(aa)

minDiff(aa,ppm=FALSE)
```

When you look at the first line, the value of 10.2 has one single closest value which is 10.4,
which is located in line number 19 (the column 'best' gives the index of the best).
Line number 19 points back to line number 1. 
You can see, that some elements (like 5.7) occure multiple times (line no 3 and 9), multiple occurences are counted in the column _ncur_.
This is why column _nbest_ for line 15 (_value_ =6.0) indicates that it appears twice as closest value _nbest_.



## Working With Lists (And Lists Of Lists)   {#WorkingWithLists}

### Partial unlist
When input from different places gets collected and combined into a list, this may give a collection of different types of data.
The function `partUnlist()` will to preserve multi-column elements as they are (and just bring down one level):
```{r partUnlist_1, echo=TRUE}
bb <- list(fa=gl(2,2), ve=31:33, L2=matrix(21:28,ncol=2), li=list(li1=11:14,li2=data.frame(41:44)))
partUnlist(bb)
partUnlist(lapply(bb,.asDF2))
```

This won't be possible using _unlist()_.
```{r unlist_1, echo=TRUE}
head(unlist(bb, recursive=FALSE))
```

To uniform such data to obtain a list with one column only for each list-element, the function `asSepList()` provides help : 
```{r asSepList, echo=TRUE}
bb <- list(fa=gl(2,2), ve=31:33, L2=matrix(21:28,ncol=2), li=list(li1=11:14,li2=data.frame(41:44)))
asSepList(bb)
```

### Appending/Combining Lists

Separate lists may be combined using the _append()_ command, which also allows treating simple vectors.

```{r lappend1, echo=TRUE}
li1 <- list(a=1, b=2, c=3)
li2 <- list(A=11, b=2, C=13)
append(li1, li2)
```

However, this way there is no checking if some of the list-elements are present in both lists and thus will appear twice.
The function `appendNR()` allows to checking if some list-elements will appear twice, and thus avoid such duplicate entries.


```{r lappend2, echo=TRUE}
appendNR(li1, li2)
```


### rbind On Lists

When a matrix (or data.frame) gets split into a list, like in the example using _by()_, as a reverse-function such lists can get joined using `lrbind()` in an _rbind_-like fashion.

```{r lrbind, echo=TRUE}
dat2 <- matrix(11:34, ncol=3, dimnames=list(letters[1:8], colnames=LETTERS[1:3]))
lst2 <- by(dat2, rep(1:3,c(3,2,3)), as.matrix)
lst2

# join list-elements (back) into single matrix
lrbind(lst2)
```


#### cbind On Lists

In order to combine list-elements into a data.frame (or matrix), base R can do the job - as long as there is no problem with the number of rows.

```{r lrbind2, echo=TRUE}
li2 <- list(a=11:13, b=matrix(21:26, nc=2, dimnames=list(letters[11:13],c("B","C"))), data.frame(d=41:43, e=51:53) )

## cbind like (to data.frame) 
as.data.frame(li2) 

## cbind like and convert into matrix (as long as all data are of same type, ie here all numeric)
as.matrix(as.data.frame(li2)) 
```


### Merge Multiple Matrices From List

When combining different datasets the function  `mergeMatrixList()` allows merging multiple matrices (or data.frames) into a single matrix.
Two types of mode of operation are available : i) Returning only the common/shared elements (as defined by the rownames), this is default _mode='intersect'_ ;
alternatively one may ii) fuse/merge all matrices together without any loss of data (using _mode='union'_, additional _NA_s may appear when a given rowname is absent in one of the input matrices).

Furthermore, one may specifically select which columns should be used for fusing using the argument _useColumn_.


```{r mergeMatrixList, echo=TRUE}
mat1 <- matrix(11:18, ncol=2, dimnames=list(letters[3:6],LETTERS[1:2]))
mat2 <- matrix(21:28, ncol=2, dimnames=list(letters[2:5],LETTERS[3:4]))
mat3 <- matrix(31:38, ncol=2, dimnames=list(letters[c(1,3:4,3)],LETTERS[4:5]))
#
mergeMatrixList(list(mat1, mat2), useColumn="all")

# with custom names for the individual matrices
mergeMatrixList(list(m1=mat1, m2=mat2, mat3), mode="union", useColumn=2)
```

Similarly, separate entries may be merged using  `mergeMatrices()` :

```{r mergeMatrices, echo=TRUE}
mergeMatrices(mat1, mat2)

mergeMatrices(mat1, mat2, mat3, mode="union", useColumn=2)

## custom names for matrix-origin
mergeMatrices(m1=mat1, m2=mat2, mat3, mode="union", useColumn=2)

## flexible/custom selection of columns
mergeMatrices(m1=mat1, m2=mat2, mat3, mode="union", useColumn=list(1,1:2,2))
```



### Fuse Content Of List-Elements With Redundant (Duplicated) Names

When list-elements have the same name, their content (of named numeric or character vectors) 
may get fused using `fuseCommonListElem()` according to the names of the list-elements :

```{r fuseCommonListElem, echo=TRUE}
val1 <- 10 +1:26
names(val1) <- letters
(lst1 <- list(c=val1[3:6], a=val1[1:3], b=val1[2:3] ,a=val1[12], c=val1[13]))

## here the names 'a' and 'c' appear twice :
names(lst1)

## now, let's fuse all 'a' and 'c'
fuseCommonListElem(lst1)
```


### Filtering Lines And/Or Columns For All List-Elements Of Same Size

In a number of cases the information in various list-elements is somehow related.
Eg, in S3-objects produced by [limma](https://bioconductor.org/packages/release/bioc/html/limma.html), or data produced using [wrProteo](https://CRAN.R-project.org/package=wrProteo) several instances of matrix or data.frame refer to data that are related. 
Some matrixes may conatain abundance data (or weights, etc) while another matrix or data.frame may contain the annotation information related to each line of the abundance data.
So if one wants to filter the data, ie remove some lines, this should be done in the same way with all related list-elements. 
This way one may maintain a conventient 1:1 matching of lines.

The function `filterLiColDeList()` searches if other list-elements have suitable dimensions and will then run the same filtering as in the 'target' list-element.
In consequence this can be used with the output of wrProteo to remove simultaneously the same lines and/or columns.

```{r listBatchReplace1, echo=TRUE}
lst1 <- list(m1=matrix(11:18, ncol=2), m2=matrix(21:30, ncol=2), indR=31:34,
  m3=matrix(c(21:23,NA,25:27,NA), ncol=2))
filterLiColDeList(lst1, useLines=2:3)
filterLiColDeList(lst1, useLines="allNA", ref=3)
```


### Replacements In List

The function `listBatchReplace()` works similar to _sub()_ and allows to search & replace exact matches to a character string along all elements of a list. 

```{r replInList1, echo=TRUE}
(lst1 <- list(aa=1:4, bb=c("abc","efg","abhh","effge"), cc=c("abdc","efg","efgh")))
listBatchReplace(lst1, search="efg", repl="EFG", silent=FALSE)
```


### Organize Values Into List And Sort By Names 

Named numeric or character vectors can be organized into lists using `listGroupsByNames()`, 
based on their names (only the part before any extensions starting with a point gets considered).
Of course, other separators may be defined using the argument _sep_. 

```{r listGroupsByNames, echo=TRUE}
ser1 <- 1:7; names(ser1) <- c("AA","BB","AA.1","CC","AA.b","BB.e","A")

listGroupsByNames(ser1)
```
If no names are present, the content of the vector itself will be used as name :
```{r listGroupsByNames2, echo=TRUE}
listGroupsByNames((1:10)/5)
```

### Batch-filter List-Elements

In the view of object-oriented programming several methods produce results integrated into lists or S3-objects (eg 
[limma](https://bioconductor.org/packages/release/bioc/html/limma.html)).
The function `filterList()` aims facilitating the filtering of all elements of lists or S3-objects. 
List-elements with inappropriate number of lines will be ignored.

```{r filterList, echo=TRUE}
set.seed(2020); dat1 <- round(runif(80),2)
list1 <- list(m1=matrix(dat1[1:40], ncol=8), m2=matrix(dat1[41:80], ncol=8), other=letters[1:8])
rownames(list1$m1) <- rownames(list1$m2) <- paste0("line",1:5)
# Note: the list-element list1$other has a length different to that of filt. Thus, it won't get filtered.
filterList(list1, list1$m1[,1] >0.4)       # filter according to 1st column of $m1 ...
filterList(list1, list1$m1 >0.4) 
```

### Transform Columns Of Matrix To List Of Vectors

At some occasions it may be useful separate columns of a matrix into separate vectors inside a list.
This can be done using `matr2list()`:

```{r matr2list, echo=TRUE}
(mat1 <- matrix(1:12, ncol=3, dimnames=list(letters[1:4],LETTERS[1:3])))
str(matr2list(mat1))
```




## Working With Arrays  {#WorkingWithArrays}

Let's get stared with a little toy-array:
```{r array0, echo=TRUE}
(arr1 <- array(c(6:4,4:24), dim=c(4,3,2), dimnames=list(c(LETTERS[1:4]),
  paste("col",1:3,sep=""),c("ch1","ch2"))))
```

### CV (Coefficient Of Variance) With Arrays

Now we can obtain the CV (coefficient of variance) by splitting along 3rd dimesion (ie this is equivalent to an _apply_ along the 3rd dimension) using `arrayCV()`:

```{r arrayCV1, echo=TRUE}
arrayCV(arr1)

# this is equivalent to
cbind(rowCVs(arr1[,,1]), rowCVs(arr1[,,2]))
```
  
Similarly we can split along any other dimension, eg the 2nd dimension : 
```{r arrayCV2, echo=TRUE}
arrayCV(arr1, byDim=2)
```

### Slice 3-dim Array In List Of Matrixes (Or Arrays)

This procedure is similar to (re-)organizing an initial array into clusters, here we split along a user-defined factor/vector.
If a clustering-algorithm produces the cluster assignments, this function can be used to organize the input data accordingly using `cutArrayInCluLike()`.

```{r cutArrayInCluLike, echo=TRUE}
cutArrayInCluLike(arr1, cluOrg=c(2,1,2,1))
```

Let's cut by filtering along the 3rd dimension for all lines where column 'col2' is >7, and then display only the content of columns 'col1' and 'col2' (using `filt3dimArr()`):

```{r filt3dimArr, echo=TRUE}
filt3dimArr(arr1, displCrit=c("col1","col2"), filtCrit="col2", filtVal=7, filtTy=">")
```



## Working With Redundant Data  {#WorkingWithRedundantData}

$_Semantics_$ : Please note, that there are two ways of interpreting the term '**unique**' :

* In regular understanding one describes this way an event which occurs only once, and thus does not occur/happen anywhere else.

* The command `unique()` will eliminate redundant entries to obtain a shorter 'unique' output vector, ie in the resultant vector all values/content (values) occur only once. 
However, from the result of _unique()_ you cannot tell any more which ones were not unique initially ! 

In some applications (eg proteomics) initial identifiers (IDs) may occur multiple times in the data and we frequently need to identify events/values that occur only once, as the first meaning of '_unique_'. 
This package provides (additional) functions to easily distinguish values occurring just once (ie _unique_) from those occurring multiple times. Furthermore, there are functions to rename/remove/combine replicated elements, eg `correctToUnique()` or `nonAmbiguousNum()`, so that no elements or lines of data get lost.


### Identify What Is Repeated (and Where Repeated Do Occur)

```{r repeated1, echo=TRUE}
## some text toy data
tr <- c("li0","n",NA,NA, rep(c("li2","li3"),2), rep("n",4))
```
The function _table()_ (from the package _base_) is very useful get some insights when working with smaller objects, but may be slow to handle very large objects.
As mentioned, _unique()_ will make everything unique, and afterwards you won't know any more who was unique in the first place !
The function `duplicated()` (also from package base) helps us getting the information who is repeated.

```{r repeated2, echo=TRUE}
table(tr)
unique(tr) 
duplicated(tr, fromLast=FALSE)
```

```{r repeated3, echo=TRUE}
aa <- c(11:16,NA,14:12,NA,14)
names(aa) <- letters[1:length(aa)]
aa
```

`findRepeated()` (from this package) will return the position/index (and content/value) of repeated elements. However, the output in form of a list is not very convenient to the human reader.

```{r findRepeated, echo=TRUE}
findRepeated(aa) 
```


`firstOfRepeated()` tells the index of the first instance of repeated elements, which elements you need to make the vector 'unique', and which elements get stripped off when making unique.
Please note, that _NA_ (no matter if they occure once or more times) are automatically in the part suggested to be removed.
```{r firstOfRepeated, echo=TRUE}
firstOfRepeated(aa)

aa[firstOfRepeated(aa)$indUniq]          # only unique with their names

unique(aa)                               # unique() does not return any names !
```


### Correct Vector To Unique (While Maintaining The Original Vector Length)

If necessary, a counter can be added to non-unique entries, thus no individual values get eliminated and the length and order of the resultant object maintains the same using `correctToUnique()`.

This is of importance when assigning rownames to a data.frame : Assigning redundant values/text as rownames of a data.frame will result in an error !

```{r correctToUnique1, echo=TRUE}
correctToUnique(aa)

correctToUnique(aa, sep=".", NAenum=FALSE)       # keep NAs (ie without transforming to character)
```
You see from the last example above, that this function has an argument for controlling enumerating elements.

### Mark Any Duplicated (ie Ambiguous) Elements by Changing Their Names (and Separate from Unqiue)

First, the truly unique values are reported and then the first occurance of repeated elements is given, _NA_ instances get ignored.
This can be done using `nonAmbiguousNum()` which maintains the length of the initial character vector.

```{r nonAmbiguousNum, echo=TRUE}
unique(aa)                                    # names are lost

nonAmbiguousNum(aa)
nonAmbiguousNum(aa, uniq=FALSE, asLi=TRUE)    # separate in list unique and repeated 
```



### Compare Multiple Vectors And Sort By Number Of Common/Repeated Values/Words

The main aim of the function `sortByNRepeated()` is allowing to compare multiple vectors for common values/words and providing an output sorted by number of repeats.

Suppose 3 persons are asked which cities they wanted to visit. 
Then we would like to make a counting of the most frequently cited cities.
Here we consider individual choices as equally ranked.
By default intra-repeats are eliminated.

```{r sortByNRepeated, echo=TRUE}
cities <- c("Bangkok","London","Paris", "Singapore","New York City", "Istambul","Delhi","Rome","Dubai")
sortByNRepeated(x=cities[c(1:4)], y=cities[c(2:3,5:8)])

## or (unlimited) multiple inputs via list
choices1 <- list(Mary=cities[c(1:4)], Olivia=cities[c(2:3,5:8)], Paul=cities[c(5:3,9,5)])    # Note : Paul cited NYC twice !
table(unlist(choices1))
sortByNRepeated(choices1)
sortByNRepeated(choices1, filterIntraRep=FALSE)  # without correcting multiple citation of NYC by Paul
```


### Combine Multiple Matrixes Where Some Column-Names Are The Same

Here, it is supposed that you want to join 2 or more matrixes describing different properties of the same collection of individuals (as rows).
Common column-names are interpreted that their respective information should be combined (either as average or as sum). 
This can be done using `cbindNR()` :

```{r cbindNR, echo=TRUE}
## First we'll make some toy data :
(ma1 <- matrix(1:6, ncol=3, dimnames=list(1:2,LETTERS[3:1])))
(ma2 <- matrix(11:16, ncol=3, dimnames=list(1:2,LETTERS[3:5])))

## now we can join 2 or more matrixes  
cbindNR(ma1, ma2, summarizeAs="mean")       # average of both columns 'C'
```


### Filter Matrix To Keep Only First Of Repeated Lines

This ressembles to the functioning of _unique()_, but applies to a user-specified column of the matrix.

```{r firstLineOfDat, echo=TRUE}
(mat1 <- matrix(c(1:6, rep(1:3,1:3)), ncol=2, dimnames=list(letters[1:6],LETTERS[1:2])))
```

The function `firstLineOfDat()` allows to access/extract the first line of repeated instances.

```{r firstLineOfDat2, echo=TRUE}
firstLineOfDat(mat1, refCol=2)
```

This function was rather designed for dealing with character input, it allows concatenating all columns and to remove redundant.

```{r firstOfRepLines, echo=TRUE}
mat2 <- matrix(c("e","n","a","n","z","z","n","z","z","b", 
  "","n","c","n","","","n","","","z"), ncol=2)
firstOfRepLines(mat2, out="conc")

# or as index :
firstOfRepLines(mat2)
```


### Filter To Unique Column-Content Of Matrix, Add Counter And Concatenated Information

```{r nonredDataFrame, echo=TRUE}
(df1 <- data.frame(cbind(xA=letters[1:5], xB=c("h","h","f","e","f"), xC=LETTERS[1:5])))
```
The function `nonredDataFrame()` offers to include a counter of redundant instances encountered (for 1st column specified) :

```{r nonredDataFrame2, echo=TRUE}
nonredDataFrame(df1, useCol=c("xB","xC")) 

# without counter or concatenating
df1[which(!duplicated(df1[,2])),]
# or
df1[firstOfRepLines(df1,useCol=2),]
```



### Get First Of Repeated By Column

```{r get1stOfRepeatedByCol, echo=TRUE}
mat2 <- cbind(no=as.character(1:20), seq=sample(LETTERS[1:15], 20, repl=TRUE),
  ty=sample(c("full","Nter","inter"),20,repl=TRUE), ambig=rep(NA,20), seqNa=1:20)
(mat2uniq <- get1stOfRepeatedByCol(mat2, sortBy="seq", sortSupl="ty"))

# the values from column 'seq' are indeed unique
table(mat2uniq[,"seq"])

# This will return all first repeated (may be >1) but without furter sorting 
#  along column 'ty' neither marking in comumn 'ambig').
mat2[which(duplicated(mat2[,2],fromLast=FALSE)),]
```

### Transform (ambigous) Matrix To Non-ambiguous Matrix (In Respect To Given Column)

```{r nonAmbiguousMat, echo=TRUE}
nonAmbiguousMat(mat1,by=2)
```
Here another example, ambiguous will be marked by an '_' :
```{r nonAmbiguousMat2, echo=TRUE}
set.seed(2017); mat3 <- matrix(c(1:100,round(rnorm(200),2)), ncol=3,
  dimnames=list(1:100,LETTERS[1:3]));
head(mat3U <- nonAmbiguousMat(mat3, by="B", na="_", uniqO=FALSE), n=15)
head(get1stOfRepeatedByCol(mat3, sortB="B", sortS="B"))
```

### Combine Replicates From List To Matrix

```{r combineReplFromListToMatr, echo=TRUE}
lst2 <- list(aa_1x=matrix(1:12, nrow=4, byrow=TRUE), ab_2x=matrix(24:13, nrow=4, byrow=TRUE))
combineReplFromListToMatr(lst2)
```


### Combine Redundant Lines From List with (Multiple) Matrix According to Reference

The function `combineRedundLinesInList()` provides help for combining/summarizing lines of numeric data which may be summaried according to reference vector or matrix (part of the same input-list).
Initial data and reference will be aligned based on rownames and the content of reference (or the column specified by \code{refColNa}).
 
```{r combineRedundLinesInListAcRef, echo=TRUE}
x1 <- list(quant=matrix(11:34, ncol=3, dimnames=list(letters[8:1], LETTERS[11:13])), 
  annot=matrix(paste0(LETTERS[c(1:4,6,3:5)],LETTERS[c(1:4,6,3:5)]), ncol=1, 
  dimnames=list(paste(letters[1:8]),"xx")) )
combineRedundLinesInList(lst=x1, refNa="annot", datNa="quant", refColNa="xx")
```



### Non-redundant Lines Of Matrix

```{r nonRedundLines, echo=TRUE}
mat4 <- matrix(rep(c(1,1:3,3,1),2), ncol=2, dimnames=list(letters[1:6],LETTERS[1:2]))
nonRedundLines(mat4)
```


### Filter For Unique Elements /2

```{r filtSizeUniq, echo=TRUE}
# input: c and dd are repeated  :
filtSizeUniq(list(A="a", B=c("b","bb","c"), D=c("dd","d","ddd","c")), filtUn=TRUE, minSi=NULL)

# here a,b,c and dd are repeated  :
filtSizeUniq(list(A="a", B=c("b","bb","c"), D=c("dd","d","ddd","c")), ref=c(letters[c(1:26,1:3)],
  "dd","dd","bb","ddd"), filtUn=TRUE, minSi=NULL)   
```


### Make Non-redundant Matrix 

```{r makeNRedMatr, echo=TRUE}
t3 <- data.frame(ref=rep(11:15,3), tx=letters[1:15],
  matrix(round(runif(30,-3,2),1), nc=2), stringsAsFactors=FALSE)
  
# First we split the data.frame in list  
by(t3,t3[,1], function(x) x)
t(sapply(by(t3,t3[,1],function(x) x), summarizeCols, me="maxAbsOfRef"))
(xt3 <- makeNRedMatr(t3, summ="mean", iniID="ref"))
(xt3 <- makeNRedMatr(t3, summ=unlist(list(X1="maxAbsOfRef")), iniID="ref"))
```


#### Example : Summarize table for longest of transcripts

In the previous example for each subgroup a summarization was calculated.
In other cases you may just want to select a line according to values from a single column.
Suppose you want to select the line corresponding to the longest transcript.


```{r makeNRedMatr2, echo=TRUE}
set.seed(2024)
df2 <- data.frame(transcrID=paste("TrID", 101:124, sep=""), geneID=paste("geID",rep(201:206,each=4)), 
  geneLe=round(runif(24, min=50, max=1500)), a=101:124, b=224:201)
df2 <- df2[-1*c(1,4:7,12:15),]  

(dfLongest <- makeNRedMatr(df2, summ=unlist(list(X1="maxOfRef")), iniID="geneID"))

 summarizeCols(df2[1:2,c(1:5,3)], me="min")  
 summarizeCols(df2[1:2,c(1:5,3)], me="mean") 
 summarizeCols(df2[1:2,c(1:5,3)], me="maxOfRef") 
 summarizeCols(df2[1:6,c(1:5,3)], me="maxOfRef")

(xt3 <- makeNRedMatr(t3, summ=unlist(list(X1="maxOfRef")), iniID=c("ref")))  
```


### Combine/Reduce Redundant Lines Based On Specified Column

```{r combineRedBasedOnCol, echo=TRUE}
matr <- matrix(c(letters[1:6],"h","h","f","e",LETTERS[1:5]), ncol=3,
  dimnames=list(letters[11:15],c("xA","xB","xC")))
combineRedBasedOnCol(matr, colN="xB")
combineRedBasedOnCol(rbind(matr[1,],matr), colN="xB")
```


### Convert Matrix (eg With Redundant) Row-Names To data.frame

```{r convMatr2df, echo=TRUE}
x <- 1
dat1 <- matrix(1:10, ncol=2)
rownames(dat1) <- letters[c(1:3,2,5)]
## as.data.frame(dat1)  ...  would result in an error
convMatr2df(dat1)
convMatr2df(data.frame(a=as.character((1:3)/2), b=LETTERS[1:3], c=1:3))
tmp <- data.frame(a=as.character((1:3)/2), b=LETTERS[1:3], c=1:3, stringsAsFactors=FALSE)
convMatr2df(tmp)
tmp <- data.frame(a=as.character((1:3)/2), b=1:3, stringsAsFactors=FALSE)
convMatr2df(tmp) 
```


### Find And Combine Points Located Very Close In X/Y Space

```{r combineOverlapInfo, echo=TRUE}
set.seed(2013)
datT2 <- matrix(round(rnorm(200)+3,1), ncol=2, dimnames=list(paste("li",1:100,sep=""),
  letters[23:24]))
# (mimick) some short and longer names for each line
inf2 <- cbind(sh=paste(rep(letters[1:4],each=26), rep(letters,4),1:(26*4),sep=""),
  lo=paste(rep(LETTERS[1:4],each=26), rep(LETTERS,4), 1:(26*4), ",", 
  rep(letters[sample.int(26)],4), rep(letters[sample.int(26)],4), sep=""))[1:100,] 
## We'll use this to test :  
head(datT2, n=10)
## let's assign to each pair of x & y values a 'cluster' (column _clu_, the column _combInf_ tells us which lines/indexes are in this cluster)
head(combineOverlapInfo(datT2, disThr=0.03), n=10)
## it is also possible to rather display names (eg gene or protein-names) instead of index values
head(combineOverlapInfo(datT2, suplI=inf2[,2], disThr=0.03), n=10)
```


### Bin And Summarize Values According To Their Names
```{r getValuesByUnique, echo=TRUE}
dat <- 11:19
names(dat) <- letters[c(6:3,2:4,8,3)]
## Here the names are not unique.
## Thus, the values can be binned by their (non-unique) names and a representative values calculated.

## Let's make a 'datUniq' with the mean of each group of values :
datUniq <- round(tapply(dat, names(dat), mean),1)
## now we propagate the mean values to the full vector 
getValuesByUnique(dat, datUniq)
cbind(ini=dat,firstOfRep=getValuesByUnique(dat, datUniq),
  indexUniq=getValuesByUnique(dat, datUniq, asIn=TRUE))
```


### Regrouping Simultaneaously by Two Factors

For example, if you wish to create group-labels considering the eye- and hair-color of a small group students (supposed a sort of controlled vocabulary was used),
the function `combineByEitherFactor()` will help. So basically, this is an empiric segmentation-approach for two categorical variables.
Please note, that with large data-sets and very disperse data this approach will not provide great results.
In the example below we'll attempt to 'cluster' according to columns _nn_ and _qq_, the resultant cluster number can be found in column _grp_.

```{r combineByEitherFactor, echo=TRUE}
nn <- rep(c("a","e","b","c","d","g","f"),c(3,1,2,2,1,2,1))
qq <- rep(c("m","n","p","o","q"),c(2,1,1,4,4))
nq <- cbind(nn,qq)[c(4,2,9,11,6,10,7,3,5,1,12,8),]
## Here we consider 2 columns 'nn' and 'qq' whe trying to regroup common values
##  (eg value 'a' from column 'nn' and value 'o' from 'qq') 
combineByEitherFactor(nq, 1, 2, nBy=FALSE)
```
The argument _nBy_ simply allows adding an additional column with the group/cluster-number.

```{r combineByEitherFactor2, echo=TRUE}
## the same, but including n by group/cluster
combineByEitherFactor(nq, 1, 2, nBy=TRUE)
## Not running further iterations works faster, but you may not reach 'convergence' immediately
combineByEitherFactor(nq,1, 2, nBy=FALSE)
```

```{r combineByEitherFactor3, echo=TRUE}
##  another example
mm <- rep(c("a","b","c","d","e"), c(3,4,2,3,1))
pp <- rep(c("m","n","o","p","q"), c(2,2,2,2,5))
combineByEitherFactor(cbind(mm,pp), 1, 2, con=FALSE, nBy=TRUE)
```


### Batch Replacing Of Values Or Character-Strings

The function `multiCharReplace()` facilitates multiple replacements in a vector, matrix or data.frame.

```{r multiCharReplace1, echo=TRUE}
# replace character content
x1 <- c("ab","bc","cd","efg","ghj")
multiCharReplace(x1, cbind(old=c("bc","efg"), new=c("BBCC","EF")))

# works also on matrix and/or to replace numeric content : 
x3 <- matrix(11:16, ncol=2)
multiCharReplace(x3, cbind(12:13,112:113))
```

Sometimes data get imported using different encoding for what should be interpreted as _FALSE_ and _TRUE_ :

```{r multiCharReplace2, echo=TRUE}
# replace and return logical vactor
x2 <- c("High","n/a","High","High","Low")
multiCharReplace(x2,cbind(old=c("n/a","Low","High"), new=c(NA,FALSE,TRUE)), convTo="logical")
```


### Multi-to-multi Matching Of (Concatenated) Terms

The function allows to split (if necessary, using _strsplit()_) two vectors and compare each isolated tag (eg identifyer) from the 1st vector/object against each isolated tag from the second vector/object. This runs like a loop of one to many comparisons. The basic output is a list with indexes of which element of the 1st vector/object has matches in the 2nd vector/object. Since this is not convenient to the human reader, tabular output can be created, too.

```{r multiMatch1, echo=TRUE}
aa <- c("m","k","j; aa","m; aa; bb; o","n; dd","aa","cc")
bb <- c("aa","dd","aa; bb; q","p; cc") 
## result as list of indexes
(bOnA <- multiMatch(aa, bb, method="asIndex"))   # match bb on aa
## more convenient to the human reader
(bOnA <- multiMatch(aa, bb))                     # match bb on aa
(bOnA <- multiMatch(aa, bb, method="matchedL"))  # match bb on aa
```


### Comparing Global Patterns        {#ComparingGlobalPatterns}

In most programming languages it is fairly easy to compare _exact_ content of character vectors or factors with unordered levels.
However, sometimes - due to semantic issues - some people may call a color 'purple' while others call it 'violet'.
Thus, without using controled vocabulary the _exact_ terms may vary.

Here, let's address the case, where no dictionaries of controled vocabulary are available for substituting equivalent terms.
Thus, we'll compare 4 vectors of equal length and check if the words/letters used could be substituted to result in the first vector.
Vectors _aa_ and _ab_ have the same global pattern, ie after repeating a word twice it moves to another word.
Vectors _ac_ and _ad_ have different general patterns, either with alternating words or falling back to a word previsously used.

Based and extended on a post on stackoverflow [https://stackoverflow.com/questions/71353218/extracting-flexible-general-patterns/](https://stackoverflow.com/questions/71353218/extracting-flexible-general-patterns/) :


```{r compGlobPat1, echo=TRUE}
aa <- letters[rep(c(3:1,4), each=2)]
ab <- letters[rep(c(5,8:6), each=2)]        # 'same general' pattern to aa
ac <- letters[c(1:2,1:3,3:4,4)]             # NOT 'same general' pattern to any other
ad <- letters[c(6:8,8:6,7:6)]               # NOT 'same general' pattern to any other
```

The basic pattern can be extracted combining match() and unique():
```{r compGlobPat2, echo=TRUE}
## get global patterns
cbind(aa= match(aa, unique(aa)),
  ab= match(ab, unique(ab)),
  ac= match(ac, unique(ac)),
  ad= match(ad, unique(ad)) )
```

Let's make a data.frame with the annotation toy-data from above. 
Each line is supposed to represent a sample, and the columns show different aspects of annotation.

```{r compGlobPat3, echo=TRUE}
bb <- data.frame(ind=1:length(aa), a=aa, b=ab, c=ac, d=ad)
```
Via the function `replicateStructure()` is it possible to compare annotation as different columns for equivalent global patterns.

By default, this function excludes all columns not designating any replicates, like the numbers in the first column ($ind).
Also it will try to find the column with the median number of levels, when comparing to all other columns.

The output is a list with  *\$col* inidicating which column(s) may be used, *\$lev* for the correpsonding global pattern, *\$meth* for the method finally used and 
_\$allCols_ for documenting the global pattern in each column (whether it was selected or not).


```{r compGlobPat4, echo=TRUE}
replicateStructure(bb)
```

Besides, it is also possible to combine all columns if one considers they contribute complementary substructures of the overal annotation.

```{r compGlobPat5, echo=TRUE}
replicateStructure(bb, method="combAll")
```
However, when combining multiple columns it may happen -like in the example above- that finally no more lines remain being considered as replicates.

This can also be found when one column describes the groups and another gives the order of the replicates therein.
However, for calling a (standard) statistical test it may be necessary exclude these replicate-numbers to designate the groups of replicates.

To overcome the problem of loosing the understanding of replicate-structure when combining all factors, it is possible to look for non-orthogonal structures,
ie to try excluding columns which (after combining) would suggest no replicates after combining all columns.
See the example below :

```{r compGlobPat6, echo=TRUE}
replicateStructure(bb, method="combNonOrth")
```

Please see also the function _chooseGroupNames()_ which may help choosing among different types of patterns (ie low or high number of groups of replicates) (see section [Working With Redundant Data] (#WorkingWithRedundantData)).



## Search For Similar (Numeric) Values  {#SearchForSimilarNumericValues}

This section addresses values that are not truly _identical_ but may differ only in the very last digit(s) 
and thus may be in a pragmatic view get considered and treated as 'about the same'.
The simplest approach would be to round values and then look for identical values. 
The functions presented here (like `checkSimValueInSer()`) offer this type of search in a convenient way.

Of course the user must define a threshold for how similar may retained as positive (in the the logical vector returned).
With the function _checkSimValueInSer()_ this threshod must be given as [ppm](https://simple.wikipedia.org/wiki/Parts_per_million) (parts per million).

```{r checkSimValueInSer, echo=TRUE}
va1 <- c(4:7,7,7,7,7,8:10) + (1:11)/28600
checkSimValueInSer(va1, ppm=5)
data.frame(va=sort(va1), simil=checkSimValueInSer(va1))
```


### Find Similar Numeric Values Of Two Columns Of A Matrix

The search for similar values may be preformed as absolute distance or as 'ppm' (as it is eg usual in proteomics when comparing measured and theoretically expected mass).

```{r findCloseMatch1, echo=TRUE}
aA <- c(11:17); bB <- c(12.001,13.999); cC <- c(16.2,8,9,12.5,15.9,13.5,15.7,14.1,5)
(cloMa <- findCloseMatch(x=aA, y=cC, com="diff", lim=0.5, sor=FALSE))       
```
The result of _findCloseMatch()_ is a list organized by each 'x', telling all instances of 'y' found within the distance tolerance given by _lim_.
Using `closeMatchMatrix()` the result obtained above, can be presented in a more convenient format for the human eye.

```{r closeMatchMatrix2, echo=TRUE}
# all matches (of 2d arg) to/within limit for each of 1st arg ('x'); 'y' ..to 2nd arg = cC
# first let's display only one single closest/best hit
(maAa <- closeMatchMatrix(cloMa, aA, cC, lim=TRUE))  #
```

Using the argument _limitToBest=FALSE_ we can display all distances within the limits imposed, some values/points may occur multiple times.
For example, value number 4 of 'cC' (=12.5) or value number 3 of 'aA' (=13) now occur multiple times...

```{r closeMatchMatrix3, echo=TRUE}
(maAa <- closeMatchMatrix(cloMa, aA, cC, lim=FALSE,origN=TRUE))  #
(maAa <- closeMatchMatrix(cloMa, cbind(valA=81:87, aA), cbind(valC=91:99, cC), colM=2,
  colP=2, lim=FALSE))
(maAa <- closeMatchMatrix(cloMa, cbind(aA,valA=81:87), cC, lim=FALSE))  #
a2 <- aA; names(a2) <- letters[1:length(a2)];  c2 <- cC; names(c2) <- letters[10 +1:length(c2)]
(cloM2 <- findCloseMatch(x=a2, y=c2, com="diff", lim=0.5, sor=FALSE)) 
(maA2 <- closeMatchMatrix(cloM2, predM=cbind(valA=81:87, a2),
  measM=cbind(valC=91:99, c2), colM=2, colP=2, lim=FALSE, asData=TRUE))
(maA2 <- closeMatchMatrix(cloM2, cbind(id=names(a2), valA=81:87,a2), cbind(id=names(c2),
  valC=91:99,c2), colM=3, colP=3, lim=FALSE)) 
```


### Find Similar Numeric Values From Two Vectors/Matrixes

For comparing two sets of data one may use `findSimilarFrom2sets()`.

```{r findSimilFrom2sets, echo=TRUE}
aA <- c(11:17); bB <- c(12.001,13.999); cC <- c(16.2,8,9,12.5,12.6,15.9,14.1)
aZ <-  matrix(c(aA,aA+20), ncol=2, dimnames=list(letters[1:length(aA)],c("aaA","aZ")))
cZ <-  matrix(c(cC,cC+20), ncol=2, dimnames=list(letters[1:length(cC)],c("ccC","cZ")))
findCloseMatch(cC, aA, com="diff", lim=0.5, sor=FALSE)
findSimilFrom2sets(aA, cC)
findSimilFrom2sets(cC, aA)
findSimilFrom2sets(aA, cC, best=FALSE)
findSimilFrom2sets(aA, cC, comp="ppm", lim=5e4)
findSimilFrom2sets(aA, cC, comp="ppm", lim=9e4, bestO=FALSE)
# below: find fewer 'best matches' since search window larger (ie more good hits compete !)
findSimilFrom2sets(aA, cC, comp="ppm", lim=9e4, bestO=TRUE)
```


### Fuse Previously Identified Pairs To 'Clusters'

When you have already identified the closest neighbour of a set of values, you may want to 
re-organize/fuse such pairs to a given number of total clusters (using `fusePairs()`).

```{r fusePairs, echo=TRUE}
(daPa <- matrix(c(1:5,8,2:6,9), ncol=2))
fusePairs(daPa, maxFuse=4)
```

### Eliminate Close (Overlapping) Points (In Bivariate x & y Space)

When visualizing larger data-sets in an x&y space one may find many points overlapping when their values are almost the same.  
The function `elimCloseCoord()` aims to do reduce a bivariate data-set to 'non-overlapping' points, somehow similar to human perception.

```{r elimCloseCoord1, echo=TRUE}
da1 <- matrix(c(rep(0:4,5),0.01,1.1,2.04,3.07,4.5), ncol=2); da1[,1] <- da1[,1]*99; head(da1)
elimCloseCoord(da1)
```


### Mode Of (Continuous) Data

Looking for the _mode_ is rather easy with counting data, the result of _table()_ will get you there quickly.
However, with continuous data the mode may be more tricky to defne and identify. 
Intuitively most people consider the mode asthe peak of a density estimation (which remains to be defined and estimated).
With continuous data most frequent (precise) value may be quite different/distant to the most dense region of data.
The function `stableMode()` presented here has different modes of operation, at this point there is no clear rule which mode may perform most satisfactory in different situations. 

```{r stableMode, echo=TRUE}
set.seed(2012); dat <- round(c(rnorm(120,0,1.2), rnorm(80,0.8,0.6), rnorm(25,-0.6,0.05), runif(200)),3)
dat <- dat[which(dat > -2 & dat <2)]
stableMode(dat)
```

Now we can try to show on a plot :
```{r stableMode2, fig.height=8, fig.width=9, fig.align="center",  echo=TRUE}
layout(1:2)
plot(1:length(dat), sort(dat), type="l", main="Sorted Values", xlab="rank", las=1)
abline(h=stableMode(dat, silent=TRUE), lty=2,col=2)
legend("topleft",c("stableMode"), text.col=2, col=2, lty=2, lwd=1, seg.len=1.2, cex=0.8, xjust=0, yjust=0.5) 


plot(density(dat, kernel="gaussian", adjust=0.7), xlab="Value of dat", main="Density Estimate Plot")
useCol <- c("red","green","blue","grey55")
legend("topleft",c("dens","binning","BBmisc","allModes"), text.col=useCol, col=useCol,
  lty=2, lwd=1, seg.len=1.2, cex=0.8, xjust=0, yjust=0.5) 
abline(v=stableMode(dat, method="dens", silent=TRUE), lty=2, col="red", lwd=2)
abline(v=stableMode(dat, method="binning", silent=TRUE), lty=2, col="green")
abline(v=stableMode(dat, method="BBmisc", silent=TRUE), lty=2, col="blue")  
abline(v=stableMode(dat, method="allModes"), lty=2, col="grey55")  
```

Please note, that plotting data modelled via a Kernell function (as above) also relies on strong hypothesis which may not be well justified in a number of cases !
For this reason, the _sorted values_ were plotted, too.

As you can see from this example above, looking for the most frequent exact value may not be a perfect choice for continous data. 
In this example the method _'allModes'_ (ie the multiple instances of most frequent exact values) gave partially usable results (dashed grey lines), due to the rounding to 3 digits. 
As you can see in the example above, the method _'allModes'_ may give multiple ties !
More rounding will make to data more discrete and ultimately ressemble cunting data. However, with rounding some of the finer resolution/details will get lost. 



### Most Frequently Occuring Value  (traditional mode)

The function  `stableMode()` can also be used to locate _the_ most frequently occuring exact value of numeric or character vectors.
As we just saw at the end of the previous example, the argument _method="allModes"_ allows finding all ties (if present).

```{r stableMode3, echo=TRUE}
set.seed(2021)
x <- sample(letters, 50000, replace=TRUE)
stableMode(dat, method="mode")
stableMode(dat, method="allModes")
```



## Text-Manipulations    {#Text-Manipulations}

There are several packages offering interesting functions for manipulating text. Here are a few functions to complement these.

### Protect Special Characters
The function `protectSpecChar()` allows protecting the majority of special characters which may influence the outcome of _grep()_ and related functions so thay they can be used easier in searches using _grep()_ or alike.

```{r protectSpecChar1, echo=TRUE}
aa <- c("abc","abcde","ab.c","ab.c.e","ab*c","ab\\d")
grepl("b.", aa)             # all TRUE
grepl(protectSpecChar("b."), aa)
```


### Trimming Text Character To Specific Length

The function `truncateVect()` gives for convenience more options than _substr_.
It is possible to add extra text when truncation has occured (default '...') so that the user can see that truncation of longer entries has been performed.

Furthermore, using the argument _sep it is possible to respect entities between separators (within a string of characters) and only cut at/before such separators.
The resulting text vecor may thus be shorter than specified globally with argument _nMax_.

```{r truncateVect1, echo=TRUE}
txt1 <- c("abc", "abcdefgh", NA, "abc/def/gh")
truncateVect(txt1, nMax=7, appendChar="..")
truncateVect(txt1, nMax=7, sep="/", appendChar="..")
```



### Trimming Redundant Text

Automatic annotation has the tendency to concatenate many parameters into a single names.
The function `trimRedundText()` was designed to allow trimming redundant text from left and/or right side of a character-vector 
(when the same portion of text appears in _each_ element). 
However, as in some cases (like the first element of the example below) nothing would remain, it is possible to define a _minimum_ width for the remaining/resulting text.

```{r trimRedundText1, echo=TRUE}
txt1 <- c("abcd","abcde","abcdefg","abcdE",NA,"abcdEF")
trimRedundText(txt1)
```


### Removing Redundant/Shared Words

A more gentle way to make text non-redundant consists in removing redundant text isporposed by the function `rmSharedWords()`.
Multiple separators may be used (and combined) to specify 'words', a minimum length of what mat be considered a word can be defined, too (default at min 2 characters).
For example, this can be used to make column-names shorter and more precise.

```{r rmSharedWords1, echo=TRUE}
txt2 <- c("abc d","abc de","abc defg","abc dE",NA,"abc dEF")
rmSharedWords(txt2)
```

In contrast to trimRedundText() numeric parts may remain 'intact', see example below.
```{r rmSharedWords2, echo=TRUE}
txt3 <- c("ab 100 m","ab 120 m","ab 1000 m")
trimRedundText(txt3)
rmSharedWords(txt3)
```


### Extract Common Part Of Text

The original idea was to do something resembling the inverse process of trimming redundant text (example above), but this time to discard the variable text.

In the end this is not as trivial when 'common' or 'redundant' text is not at the beginning or end of a chain of characters. 
In particular with very large text this is an active field of research (eg for sequence alignment). 
The function presented here is a very light-weight solution designed for smaller and simple settings, like inspecting column-names.
Furthermore, the function `keepCommonText()` only reports the first (longest) hit. 
So, when there are multiple conserved 'words' of equal length, only the first of them will be identified.

When setting the argument 'hiResol=FALSE' this function has an option to decrease the resulution of searching, which in turn increases the speed, howevere, at cost of missing the optimal solution.
In this case the resultant chain of characters should be inspected if it can be further extended/optimized.

With terminal common text :
```{r keepCommonText1, echo=TRUE}
txt1 <- c("abcd","abcde","abcdefg","abcdE",NA,"abcdEF")
trimRedundText(txt1, side="left")         # remove redundant 
keepCommonText(txt1, side="terminal")     # keep redundant
keepCommonText(txt1, side="center")       # computationally easier   
```

With internal coomon text:
```{r keepCommonText2, echo=TRUE}
txt2 <- c("abcd_abc_kjh", "bcd_abc123", "cd_abc_po")
keepCommonText(txt2, side="center")       
```


### Manipulating Enumerator-Extensions

Human operators may have many ways to write enumerators like 'xx_sample_1', 'xx_Sample_2', 'xx_s3', 'xx_4', etc.
Many times you may find such text as names or column-names for measures underneith.

The functions presented below will work only if _consistent numerators_, ie (text +) digit-character(s) are at the end of all character-strings to be treated.

Please note, that with large vectors testing/checking a larger panel of enumerator-abreviations may result in slower performance.
In cases of such larger data-sets it may be more effective to first study the data and then run simple subsitions using _sub()_ targeted for this very case.


#### Remove/Modify Enumerators

The aim of this function consists in identifying a _common_ pattern for terminal enumeratos (ie at end of words/character strings) and to subsequently modify or remove them.
As separator-symbols and separator-words are given indedently all combinations thereof may be tested.
Furthermore the user has the choice to (automatically) all truncated versions of separator-words (eg _Sam_ instead of _Sample_).

As basic setting `rmEnumeratorName()` allows to identify and then modify a _common_ terminal enumerator from all elements of a character string :
```{r rmEnumeratorName1, echo=TRUE}
xx <- c("hg_Re1","hjRe2_Re2","hk-Re3_Re33")
rmEnumeratorName(xx)
rmEnumeratorName(xx, newSep="--")
rmEnumeratorName(xx, incl="anyCase")
```

Furthermore, this function allows scanning a matrix of text-data and to perform similar operations to the _first_ column found containing a  _common_ terminal enumerator.

```{r rmEnumeratorName2, echo=TRUE}
xy <- cbind(a=11:13, b=c("11#11","2_No2","333_samp333"), c=xx)
rmEnumeratorName(xy)
rmEnumeratorName(xy,incl=c("anyCase","trim2","rmEnumL"))
```

If you which to remove/subsitute mutiple types of enumerators the function \code{rmEnumeratorName} must be run independently, see last example below.

```{r rmEnumeratorName3, echo=TRUE}
xz <- cbind(a=11:13, b=c("23#11","4#2","567#333"), c=xx)
apply(xz, 2, rmEnumeratorName, sepEnum=c("","_"), newSep="_", silent=TRUE)
```


#### Unify Enumerators

The (slightly older) function `unifyEnumerator()` offers less options, in particular the potential separator-words must be given explicitly, only lower/upper-case may be kept flexible.

```{r unifyEnumerator1, echo=TRUE}
unifyEnumerator(c("ab-1","ab-2","c-3"))
unifyEnumerator(c("ab-R1","ab-R2","c-R3"))
unifyEnumerator(c("ab-1","c3-2","dR3"), stringentMatch=FALSE)
```


### Find/Choose Column Most Likely Containing Sample-Names

When information about a collection of samples is given in a table, the function  `unifyEnumerator()` was designed to find the column most likely containg sample-names 
and it derives then the structure of groups of replicates by removing terminal enumerators from sample-names.
Initial tables (as frequently found in transcriptomics and proteomics) may not have consistent schemes of naming columns (due to human annotators not using controlled vocabulary) 
and may contain additional columns with redundant information (elements/conditions that were kept constant for all samples.    

Internally this function uses _rmSharedWords()_ to further simplify resultant names.

```{r chooseGroupNames1, echo=TRUE}
(mat <- cbind(a=letters[1:6], b=paste(rep(c("b","B"), each=3), 1:3), c=rep(1,6), 
  d=gl(3,2), e=rep(c("e","E"),3), f=paste(rep(c("F","f","ff"), each=2), 1:2)))
  
chooseGroupNames(mat, method="median")         # col 2 (b/B)
chooseGroupNames(mat, method="median", fullReport=TRUE) 
chooseGroupNames(mat, method="min")            # col 2 (b/B)
chooseGroupNames(mat, method="max")            # col 6 (F/f/ff)
chooseGroupNames(mat, method="max", asUnique=FALSE) # col 1 (a..)
```

Please see also the function _replicateStructure()_ which allows inspecting patterns of replicating elements (see section [Comparing Global Patterns] (#ComparingGlobalPatterns)).


### Find Common Unit

The function `checkUnitPrefix` aims to find a unit-abbreviation or -name occurring in all elements of a character-vector.
The unit name may be preceeded by different decimal prefixes (eg 'k','M', see argument _pref_) which may vary within the vector.
By default some common SI-units will be searched, see argument _unit_.

```{r checkUnitPrefix1, echo=TRUE}
x1 <- c("10fg WW","xx 10fg 3pW"," 1pg 2.0W")
checkUnitPrefix(x1)

## different separators between digit and prefix:
x2 <- c("10fg WW","xx 8_fg 3pW"," 1 pg-2.0W")
checkUnitPrefix(x2, stringentSearch=TRUE)
checkUnitPrefix(x2, stringentSearch=FALSE)
```



### Adjust Decimal Prefixes And Extact Numeric+Unit Part

The function `adjustUnitPrefix()` provides help extracting the numeric part of character vectors and allows adjusting to a single million-unit type.
This can be used to convert a vector of mixed prefixes like  'z','a','f','p','n','u' and 'm' (note: the 'u' is used for 'micro').
The output is a character vector with all prefix+unit expressions adjusted to use the same prefix everywhere (numeric+separator+prefix+unit). 
Redundant additional text may get (optionally) trimmed (see argument _returnType="trim"_), the numeric part names + unit is give in the names.

Please note that decimal/comma digits will not be recognized properly, the function may/will consider the decimal sign as just another separator 
(as '.' is part af the default selection of separators).

```{r adjustUnitPrefix1, echo=TRUE}
adjustUnitPrefix(c("10.psec", "2 fsec"), unit="sec")
```

Using the argument _returnType_ you can choose how much of the remaining text should be shown.
```{r adjustUnitPrefix2, echo=TRUE}
x2 <- c("abCc 500_nmol ABC", "abEe5_umol", "", "abFF_100_nmol_G", "abGg 2_mol", "abH.1 mmol")
rbind( adjustUnitPrefix(x2, unit="mol", returnType="allText") , 
  adjustUnitPrefix(x2, unit="mol", returnType="trim"),
  adjustUnitPrefix(x2, unit="mol", returnType=""))
```

If the _unit_ -name is not knonw in advance, you can try to figure out. In the example it is shown that the unit-name can be determined using the function _checkUnitPrefix()_.
```{r adjustUnitPrefix3, echo=TRUE}
x3 <- c("2.psec abc","300 fsec etc", "34 5fsec")
adjustUnitPrefix(x3, unit=checkUnitPrefix(x3))
```


### Merging Multiple Named Vectors To Matrix

The function `mergeVectors()` allows merging of multiple named vectors (each element needs to be named !).
Basically, all elements carrying the same name across different input-vectors will be aligned in the same column of the output (input-vectors appear as lines).
Different to _merge()_ which allows merging only 2 data.frames, here multiple vectors may be merge at once.

```{r mergeVectors1, echo=TRUE}
x1 <- c(a=1, b=11, c=21)
x2 <- c(b=12, c=22, a=2)
x3 <- c(a=3, d=43)
mergeVectors(vect1=x1, vect2=x2, vect3=x3)
```

```{r mergeVectors2, echo=TRUE}
mergeVectors(vect1=x1, vect2=x2, vect3=x3, inclInfo=TRUE)   # return list with additional info
```

In the example below we'll add another vector, nuty this time _without_ named elements.
In the absence of names there are no anchors and in consequence the last vector cannot get merged to the rest.
You can see a message telling that this vector was ignored/omitted.

```{r mergeVectors3, echo=TRUE}
x4 <- 41:44            # no names - not conform for merging and will be ignored
mergeVectors(x1, x2, x3, x4)
```



### Match All Lines of Matrix To Reference Note

This function allows adjusting the order of lines of a matrix \code{mat} to a reference character-vector \code{ref},
even when initial direct matching of character-strings using \code{match} is not possible/successful.
In this case, various variants of using \code{grep} will be used to see if unambiguous matching is possible of characteristic parts of the text.
All columns of \code{mat} will be tested an the column giving the best results will be used.

```{r matchMatrixLinesToRef1, echo=TRUE}
## Note : columns b and e allow non-ambigous match, not all elements of e are present in a
mat0 <- cbind(a=c("mvvk","axxd","bxxd","vv"),b=c("iwwy","iyyu","kvvh","gxx"), c=rep(9,4),
  d=c("hgf","hgf","vxc","nvnn"), e=c("_vv_","_ww_","_xx_","_yy_"))
matchMatrixLinesToRef(mat0[,1:4], ref=mat0[,5])
matchMatrixLinesToRef(mat0[,1:4], ref=mat0[1:3,5], inclInfo=TRUE)

matchMatrixLinesToRef(mat0[,-2], ref=mat0[,2], inclInfo=TRUE)   # needs 'reverse grep'
```



### Order Matrix According To Reference

The function `orderMatrToRef()` has the aim of facilitating bringing a matrix of text/data in the order of a given reference (character vector).
This function will try all columns of the input-matrix to see which gives the best coverage/ highest number of matches to the reference.
If no hits are found, this function will try by partial matching (using _grep()_) all entries of the reference and vice-versa all entries of the matrix.

```{r orderMatrToRef1, echo=TRUE}
mat1 <- matrix(paste0("__",letters[rep(c(1,1,2,2,3),3) +rep(0:2,each=5)], rep(1:5)), ncol=3)
orderMatrToRef(mat1, paste0(letters[c(3,4,5,3,4)],c(1,3,5,2,4)))

mat2 <- matrix(paste0("__",letters[rep(c(1,1,2,2,3),3) +rep(0:2,each=5)], c(rep(1:5,2),1,1,3:5 )), ncol=3)
orderMatrToRef(mat2, paste0(letters[c(3,4,5,3,4)],c(1,3,5,1,4)))

mat3 <- matrix(paste0(letters[rep(c(1,1,2,2,3),3) +rep(0:2,each=5)], c(rep(1:5,2),1,1,3,3,5 )), ncol=3)
orderMatrToRef(mat3, paste0("__",letters[c(3,4,5,3,4)],c(1,3,5,1,3)))
```


### Value Matching With Option For Concatenated Terms

Sometimes we need to match terms in concatenated tables.
The function `concatMatch()` was designed to behave similar to _match()_  but also allowing to serach among concatenated terms and some further text-simplifications.

```{r concatMatch1, echo=TRUE}
## simple example without concatenations or text-extensions
x0 <- c("ZZ","YY","AA","BB","DD","CC","D")
tab0 <- c("AA","BB,E","CC","FF,U")
match(x0, tab0)
concatMatch(x0, tab0)         # same result as match(), but with names

## now let's construct somthing similar but with concatenations and text-extensions
x1 <- c("ZZ","YY","AA","BB-2","DD","CCdef","Dxy")            # modif of single ID (no concat)
tab1 <- c("AA","WW,Vde,BB-5,E","CCab","FF,Uef")
match(x1, tab1)                   # match finds only the 'simplest' case (ie "AA")
concatMatch(x1, tab1)             # finds all hits as in example above

x2 <- c("ZZ,Z","YY,Y","AA,Z,Y","BB-2","DD","X,CCdef","Dxy")  # conatenated in 'x'
tab2 <- c("AA","WW,Vde,BB-5,E","CCab,WW","FF,UU")
concatMatch(x2, tab2)               # concatenation in both 'x' and 'table'
```



### Check for (Strict) Order

Thi function `checkStrictOrder()` was designed to scan each line of an (numeric) input matrix for up- down- or equal-development, ie the chang to the next value on the right.
For example when working with a matrix of with 4 columns one can look 3 times a the neighbour value following to the right (in the same line), thus the output will mention 3 events (for each line).
If _all counts_ are 'up' and 0 counts are 'down' or 'eq', the line follows a permanently increase (not necessarily linear), etc.

In some automated procedures (where the numer of columns of initial input may vary) it may be easier to test if any 0 occur.
For this reason the argument _invertCount_ was introduced, in this case a line with a '0' occurring characterizes a constant behaviour (for the respective column).

```{r checkStrictOrder1, echo=TRUE}
set.seed(2005); mat1 <- rbind(matrix(round(runif(40),1),nc=4), rep(1,4))
head(mat1)
checkStrictOrder(mat1); mat1[which(checkStrictOrder(mat1)[,2]==0),]
```

A slightly more general way of testing can be done using  `checkGrpOrder()`. Here, simlpy a logical value will produced for each line of input indicating if there is constant behaviour.
When the argument _revRank=TRUE_ (default) constant up- or constant down-characteristics will be tested

```{r checkGrpOrder1, echo=TRUE}
head(mat1)
checkGrpOrder(mat1)
checkGrpOrder(mat1, revRank=FALSE)    # only constant 'up' tested
```




## Working With Regressions    {#WorkingWithRegressions}

### Best Starting Point For Linear Regressions (Start of linearity)

In many types of measurments the very low level measures are delicate.
Especially when the readout starts with a baseline signal before increasing amounts of the analyte start producing a linear relationship.
In such cases some of the very lowest levels of the analyte are masked by the (random) baseline signal.
The function `linModelSelect()` presented here allows omitting some of the lowest analyte measures to focus on the linear part of the dose-response relationship.

```{r linModelSelect1, echo=TRUE}
li1 <- rep(c(4,3,3:6), each=3) + round(runif(18)/5,2)
names(li1) <- paste0(rep(letters[1:5], each=3), rep(1:3,6))
li2 <- rep(c(6,3:7), each=3) + round(runif(18)/5, 2)
dat2 <- rbind(P1=li1, P2=li2)
exp2 <- rep(c(11:16), each=3)
exp4 <- rep(c(3,10,30,100,300,1000), each=3)

## Check & plot for linear model 
linModelSelect("P1", dat2, expect=exp2)
linModelSelect("P2", dat2, expect=exp2)
```

This function was designed for use with rather small data-sets with no (or very few) measures of base-line.
When larger panels of data ara available, it may be better to first define a confidence interval for the base-line measurement
and then only to consider points outside this confidence interval for regressing dose-response relationships
(see also [Detection limit](https://en.wikipedia.org/wiki/Detection_limit)).



### High Throughput Testing For Linear Regressions

Once we have run multiple linear regressions on differt parts of the data we might wat to compare them in a single plot.
Below, we construct 10 series of data that get modeled the same way, ideally one would obtain a slope close to 1.0.
We still allow omitting some starting points, if the resulting model would fit better.

```{r plotLinModelCoef1, echo=TRUE}
set.seed(2020)
x1 <- matrix(rep(c(2,2:5),each=20) + runif(100) +rep(c(0,0.5,2:3,5),20), 
  byrow=FALSE, ncol=10, dimnames=list(LETTERS[1:10],NULL))
## just the 1st regression :
   summary(lm(b~a, data=data.frame(b=x1[,1], a=rep(1:5,each=2))))
## all regressions
x1.lmSum <- t(sapply(lapply(rownames(x1), linModelSelect, dat=x1, 
  expect=rep(1:5,each=2), silent=TRUE, plotGraph=FALSE), 
  function(x) c(x$coef[2,c(4,1)], startFr=x$startLev)))
x1.lmSum <- cbind(x1.lmSum, medQuantity=apply(x1,1,median))
x1.lmSum[,1] <- log10(x1.lmSum[,1])
head(x1.lmSum)
```

Now we can try to plot :
```{r plotLinModelCoef2, echo=TRUE}
wrGraphOK <- requireNamespace("wrGraph", quietly=TRUE)      # check if package is available
if(wrGraphOK) wrGraph::plotW2Leg(x1.lmSum, useCol=c("Pr(>|t|)","Estimate","medQuantity","startFr"), 
  legendloc="topleft", txtLegend="start at")
```



## Combinatorics Issues   {#CombinatoricsIssues}

### All Pairwise Ratios

`ratioAllComb()` calculates all possible pairwise ratios between all individual calues of x and y.

```{r ratioAllComb0, echo=TRUE}
set.seed(2014); ra1 <- c(rnorm(9,2,1), runif(8,1,2))
```

Let's assume there are 2 parts of 'x' for which we would like to know the representative ratio :
The ratio of medians does not well reflect the typical ratio (if each element has the same chance to be picked).

```{r ratioAllComb1, echo=TRUE}
median(ra1[1:9]) / median(ra1[10:17])
```

Instead, we'll build all possible ratios and summarize then.

```{r ratioAllComb2, echo=TRUE}
summary( ratioAllComb(ra1[1:9], ra1[10:17]))
boxplot(list(norm=ra1[1:9], unif=ra1[10:17], rat=ratioAllComb(ra1[1:9],ra1[10:17])))
```


###  Count Frequency Of Terms Combined From Different Drawings (combineAsN)

The main idea of this function is to count frequency of terms when combining different drawings.
Suppose, you are asking students for their prefered hobbies.
Now, you want to know how many terms will occur in common in groups of 3 students.
In the example below, simple letters are shown instead of names of hobbies ...

In the simplest way of using `combineAsN()` does something similar to _table_ :
Here we're looking at the full combinatorics of making groups of _nCombin_ students and let's count the frequency of terms found 3 times identical, 2 times or only once (ie not cited by the others).
In case multiple groups of _nCombin_ students can be formed, the average of the counts, standard error of the mean (sem), 95% confidence interval (CI) and sd aregiven to resume the results.

```{r combineAsN1, echo=TRUE}
tm1 <- list(a1=LETTERS[1:7], a2=LETTERS[3:9], a3=LETTERS[6:10], a4=LETTERS[8:12])
combineAsN(tm1, nCombin=3, lev=gl(1,4))[,1,]
```

One may imagine that different locations/coties/countries will give different results.
Thus, we'll declare the different origins/location using the _lev_ argument.
Now, this function focusses (by default) on combinations of students from _nCombin_ different origins/location and
counts how many hobbies were mentioned as all different ('sing', ie number of hobbies only one student mentioned),
single repeat ('doub') or three times repeated ('trip'), plus minumum twice or 'any' (ie number of hobies citied no matter how many repeats).
The output is an array, the 3rd dimension contains the counts, fllowed by sem, CI and sd.

```{r combineAsN2, echo=TRUE}
## different levels/groups in list-elements
tm4 <- list(a1=LETTERS[1:15], a2=LETTERS[3:16], a3=LETTERS[6:17], a4=LETTERS[8:19],
  b1=LETTERS[5:19], b2=LETTERS[7:20], b3=LETTERS[11:24], b4=LETTERS[13:25], c1=LETTERS[17:26],
  d1=LETTERS[4:12], d2=LETTERS[5:11], d3=LETTERS[6:12], e1=LETTERS[7:10])
te4 <- combineAsN(tm4, nCombin=4, lev=substr(names(tm4),1,1))
str(te4)
te4[,,1]           # the counts part only
```


## Import/Export

### Batch-Reading Of CSV Files

Some software do produce a series of csv files, where a large experiment/data-set get recorded as multiple files.
The function `readCsvBatch()` was designed for reading multiple csv files of exactly the same layout and to join their content.
As output a list with the content of each file can be produced (one matrix per file), or the data may be fused into an array, as shown below.  


```{r readCsvBatch, echo=TRUE}
path1 <- system.file("extdata", package="wrMisc")
fiNa <-  c("pl01_1.csv","pl01_2.csv","pl02_1.csv","pl02_2.csv")
datAll <- readCsvBatch(fiNa, path1, silent=TRUE)
str(datAll)
```

When setting the first argument _fileNames_ to _NULL_, you can read all files of a given path.
```{r readCsvBatch2, echo=TRUE}
## batch reading of all csv files in specified path :
datAll2 <- readCsvBatch(fileNames=NULL, path=path1, silent=TRUE)
str(datAll2)
```


### Batch-Reading Of Tabulated Files

The function `readTabulatedBatch()` allows fast batch reading of tabulated files. 
All files specified (or all files from a given directory) will be read into separate data.frames of a list.
Default options are US-style comma, automatic testing for head in case the package _data.table_ is available (otheriwse : no header).
Furthermore it is possible to design a given (numeric) column and directly filter for all lines passing a given threshold, allowing to get smaller objects.


```{r readTabulatedBatch1, echo=TRUE}
path1 <- system.file("extdata", package="wrMisc")
fiNa <-  c("a1.txt","a2.txt")
allTxt <- readTabulatedBatch(fiNa, path1)
str(allTxt)
```


### Reading/Importing Incomplete Tables

Sometimes were may get confronted with data which look like 'incomplete' tables. 
In such cases some rows do not contain as many elements/columns as other columns. 
Files with this type of data may pose a problem for `read.table()` (from the _utils_ package).
In some cases using the argument _fill=TRUE_ may allow to overcome this problem.
The function _readVarColumns()_ (from this package) was designed to provide better help in such odd cases.
Basically, each line is read and parsed separately, the user should check/decide on the separator to be used.

The example below lists people's names in different locations, some locations have more persons ... 
Sometimes exporting such data will generate shorter lines in locations with fewer elements (here 'London') and no additional separators will get added (to mark all empty fields) towards the end.
The function `readVarColumns()` (from this package) provides help to read such data, if the content (and separators) of the last columns are missing.

```{r readVarColumns, echo=TRUE}
path1 <- system.file("extdata", package="wrMisc")
fiNa <- "Names1.tsv"
datAll <- readVarColumns(fiName=file.path(path1,fiNa), sep="\t")
str(datAll)
```

In this example _readVarColumns()_ would give a warning (and column-names are not recognized), if you use the argument _header=TRUE_ you'll get an error and nothing gets read.



### Converting Url For Reading Tabulated Data From GitHub

GitHub (https://github.com) allows sharing code and data.
In order to properly read tabulated (txt, tsv or csv) data directly from a given url from the GitHub pages, the user typically needs switch to the 'Raw' view.
The function `gitDataUrl()` allows to conventiently switch any url (on GitHub) to the format from 'Raw view', suitable for directly reading the data using _read.delim()_ , _read.table()_ or _read.csv()_ etc ...).

```{r readGit1, echo=TRUE}
## An example url with tabulated data :
url1 <- "https://github.com/bigbio/sdrf-annotated-datasets/blob/main/datasets/PXD001819/PXD001819.sdrf.tsv"
gitDataUrl(url1)
```

The example below shows how this is used in the function _readSampleMetaData()_ in [wrProteo](https://CRAN.R-project.org/package=wrProteo).
```{r readGit2, echo=TRUE}
dataPxd <- try(read.delim(gitDataUrl(url1), sep='\t', header=TRUE))
str(dataPxd)
```

---




## Data Vectorization   {#Vectorization}

In many scientific domains raw data often come as coordinates in form of pairs of start/end points. 
While correlation measures linear association, vector-based metricsÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Âdistance and angleÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Âcapture both magnitude and direction of change.
The  `vectorDistAngle()` function helps by transforming paired coordinates into polar form (distance and angle).


```{r vectorDistAngle1, echo=TRUE}
x <- matrix(c(0, 3, 0.5, 4, 1, 1), ncol=2, byrow=TRUE)
y <- matrix(c(0, 0, 1, 3, 0.5, 5), ncol=2, byrow=TRUE)
(vectDist <- vectorDistAngle(x, y))
```
Below, a graphical representation of the the example-vectors (which were initially defined by their start- and end-points).
```{r vectorDistAngle2, echo=TRUE}
plot(cbind(x=as.numeric(x), y=as.numeric(y)), main="Example for vectorDistAngle()",las=1)
arrows(x[,1], y[,1], x[,2], y[,2])
text(x[,2], 0.1 +y[,2], paste0("dist=",round(vectDist[,1],2),", angle=",round(vectDist[,2],2)), adj=1)
```

---


## Normalization 

The main reason of normalization is to remove variability in the data which is not directly linked to the (original/biological) concept of a given experiment. 
High throughput data from real world measurements may easily contain various deformations due to technical reasons, eg slight temperature variations, electromagnetic interference, instability of reagents etc. 
In particular, transferring constant amounts of liquids/reagents in highly repeated steps over large experiments is often also very challenging, small variations of the amounts of liquid (or similar) are typically addressed by normalization. However, applying aggressive normalization to the data also brings considerable risk of starting to loose some of the effects one intended to study.
At some point it may rather be better to eliminate a few samples or branches of an experiment to avoid too invasive intervention. This shows that quality control can be tightly linked to decisions about data-normalization.                      {#Normalization}
In conclusion, normalization may be far more challenging than simply running some algorithms.. 

In general, the use has to assume/define some hypothesis to justify intervention.
Sometimes specific elements of an experiment are known to be not affected and can therefore be used to normalize the rest.
Eg, if you observe growth of trees in a forest, big blocks of rock on the floor are assumed no to change their location. 
So one could use them as alignment-marks to superpose pictures taken at slightly different positions.

The hypothesis of no global changes is very common : During the course of many biological experiments (eg change of nutrient) one 
assumes that only a small portion of the elements measured (eg the abundance of all different gene-products) do change,
since many processes of a living cell like growth, replication and interaction with neighbour-cells are assumed not to be affected.
So, if one assumes that there are no global changes one normalizes the input-data in a way that the average or median across each experiment will give the same value.
In analogy, if one takes photographs on a partially cloudy day, most cameras will adjust light settings (sun r clouds) so that global luminosity stays the same. 
However, if too many of the measured elements are affected, this normalization approach will lead to (additional) loss of information.

It is _essential_ to understand the type of deformation(s) data may suffer from in order to choose the appropriate approacges for normalization. 
Of course, graphical representations ([PCA](https://en.wikipedia.org/wiki/Principal_component_analysis), [MA-plots](https://en.wikipedia.org/wiki/MA_plot), etc) are extremely important to identifying abnormalities and potential problems. 
The package [wrGraph](https://CRAN.R-project.org/package=wrGraph) offers also complementary options useful in the context of normalization.
Again, graphical representation(s) of the data help to visualize how different normalization procedures affect outcomes.

Before jumping into normalization it may be quite useful to _filter_ the data first.
The overall idea is, that most high-throughput experiments do produce some non-meaningful data (artefacts) and it may be wise to remove such 'bad' data
first, as they may effect normalization (in particular _extreme values_). 
A special case of problematic data concerns _NA_-values.


### Filter Lines Of Matrix To Reduce Content Of NAs

Frequent _NA_-values may represent another potential issue. Unfortunately, there is no general optimal advice for handeling NA-values.
To get started, you should try to investigate how and why NA-values occurred to check if there is a special 'meaning' to them.
For example, on some measurement systems values below detection limit may be simply reported as NAs.

High number of NAs in specific columns may point to technical problems or very different samples.
If the second case doesn't seem to apply, one might consider eliminiating such columns of low-quality data. 

If the lines of your data represent different features quantified (eg proteins, or transcripts), then lines almost entirely composed of NA-values represent features
that may not be well exploited anyway. Therefore many times one tries to filter away lines of 'bad' data (ie too high content of NAs).
 
                                     
Please note, that imputing _NA_-values represents another option instead of filtering and removing, multiple other packages address this in detail, too.
All decisions of which approach to choose should be data-driven.


#### Filter For Each Group Of Columns For Sufficient Data As Non-NA

Filter for each group of columns for sufficient data as non-NA
The function `presenceGrpFilt()` allows to

```{r presenceGrpFilt1, echo=TRUE}
dat1 <- matrix(1:56,ncol=7)
dat1[c(2,3,4,5,6,10,12,18,19,20,22,23,26,27,28,30,31,34,38,39,50,54)] <- NA
grp1 <- gl(3,3)[-(3:4)]
dat1

## now let's filter
presenceGrpFilt(dat1, grp=grp1, presThr=0.75)  # stringent
presenceGrpFilt(dat1, grp=grp1, presThr=0.25)  # less stringent

presenceGrpFilt(dat1, grp=grp1, presThr=0.25)  # less stringent
```


#### Filter As Separate Pairwise Groups Of Samples

If you want to use your data in a pair-wise view (like running t-tests on each line) the function `presenceFilt()`
allows to eliminate lines containing too many _NA_-values for each pair-wise combination of the groups/levles.

```{r presenceFilt, echo=TRUE}
grp2 <- factor(rep(letters[4:2],c(2,2,3)))
presenceFilt(dat1, gr=grp2, maxGr=1, ratM=0.1)
presenceFilt(dat1, gr=grp2, maxGr=2, rat=0.5)
```

Here it is also possible to custom select only a few pairwise comparisons 
(when an elevated number of groups will trigger a rather high number of pairwise comparisons) :

```{r presenceFilt2, echo=TRUE}
presenceFilt(dat1, gr=grp2, useComp=c("d-c","b-d"), maxGr=0, ratM=0.1)
```


#### Cleaning Replicates

This procedures aims to remove (by setting to as _NA_) the most extreme of noisy replicates.
Thus, it is assumed that all columns of the input matrix (or data.frame) are replicates of the other columns.
The _nOutl_ most distant points are identified and will be set to _NA_.

```{r cleanReplicates, echo=TRUE}

(mat3 <- matrix(c(19,20,30,40, 18,19,28,39, 16,14,35,41, 17,20,30,40), ncol=4))
cleanReplicates(mat3, nOutl=1)
cleanReplicates(mat3, nOutl=3)

```


### The Function normalizeThis()      {#NormalizeThis}

In biological high-throughput data columns typically represent different samples, which may be organized as replicates. 
During high-throughput experiments thousands of (independent) elements are measured (eg abundance of gene-products), they are represented by rows.
As real-world experiments are not always as perfect as we may think, small changes in the signal measured may easily happen.
Thus, the aim of normalizing is to remove or reduce any trace/variability in the data not related to the original experiement but due to imperfections during detection.

Note, that some experiments may produce a considerable amount of missing data (NAs) which require special attention (dedicated developments exist in other R-packages eg in [wrProteo](https://CRAN.R-project.org/package=wrProteo)). 
My general advice is to first carefully look where such missing data is observed and to pay attention to replicate measurements 
where a given element once was measured with a real numeric value and once as missing information (NA). 


```{r normalizeThis0, echo=TRUE}
set.seed(2015); rand1 <- round(runif(300) +rnorm(300,0,2),3)
dat1 <- cbind(ser1=round(100:1 +rand1[1:100]), ser2=round(1.2*(100:1 +rand1[101:200]) -2),
  ser3=round((100:1 +rand1[201:300])^1.2-3))
dat1 <- cbind(dat1, ser4=round(dat1[,1]^seq(2,5,length.out=100) +rand1[11:110],1))
## Let's introduce some NAs
dat1[dat1 <1] <- NA
## Let's get a quick overview of the data
summary(dat1)
## some selected lines (indeed, the 4th column appears always much higher)
dat1[c(1:5,50:54,95:100),]
```

Our toy data may be normalized by a number of different criteria. 
In real applications the nature of the data and the type of deformation detected/expected will largely help 
deciding which normalization might be the 'best' choice. Here we'll try first normalizing by the mean,
ie all columns will be forced to end up with the same column-mean. 
The trimmed mean does not consider values at extremes (as outliers are frequently artefacts and display extreme values).
When restricting even stronger which values to consider one will eventually end up with the median (3rd method used below).

```{r normalizeThis1, echo=TRUE}
no1 <- normalizeThis(dat1, refGrp=1:3, meth="mean")
no2 <- normalizeThis(dat1, refGrp=1:3, meth="trimMean", trim=0.4)
no3 <- normalizeThis(dat1, refGrp=1:3, meth="median")
no4 <- normalizeThis(dat1, refGrp=1:3, meth="slope", quantFa=c(0.2,0.8))
```

It is suggested to verify normalization results by plots. 
Note, that  [Box plots](https://en.wikipedia.org/wiki/Box_plot) may not be appropriate in some cases (eg multimodal distributions),
for displaying more details you may consider using [Violin-Plots](https://en.wikipedia.org/wiki/Violin_plot) from packages [vioplot](https://CRAN.R-project.org/package=vioplot) or [wrGraph](https://CRAN.R-project.org/package=wrGraph), another option might be a (cumulated) frequency plot (eg in package [wrGraph](https://CRAN.R-project.org/package=wrGraph)).

```{r normalizeThis_plot1, echo=FALSE,eval=TRUE}
boxplot(dat1, main="raw data", las=1)
```

You can see clearly, that the 4th data-set has a problem of range. So we'll see if some proportional normalization
may help to make it more comparable to the other ones.
 
```{r normalizeThis_plot2, echo=FALSE,eval=TRUE}
layout(matrix(1:4, ncol=2))
boxplot(no1, main="mean normalization", las=1)
boxplot(no2, main="trimMean normalization", las=1)
boxplot(no3, main="median normalization", las=1)
boxplot(no4, main="slope normalization", las=1)
```


### Normalize By Rows        {#RowNormalize}

The standard approach for normalizing relies on consisting all columns as collections of data who's distribution is not supposed to change.
In some cases/projects we may want to formulate a much more 'engaged' hypothesis : We consider the content of all columns strictly as the same.
For example this may be the case when comparing a dataset consisting of technical replicates only (the data may have many 'holes', ie may have sparse character).
In such cases one may use the function `rowNormalize()` which tries to find the average or mean optimal within-line normalization factor.

Besides, an additional mode of operation for _sparse data_ has been added :
Basically, once a row contains just one NA, this row can't be used any more to derive a normalization factor for all rows.
Thus, with many NA-values the number of 'complete' rows will be low or even 0 redering this approach inefficient or impossible.
Once the content of NA-values is above a customizable threshold, the data will be broken in smaller subsets with fewer groups of fewer columns,
 thus increasing the chances of finding 'complete' subsets of data which will be normalized first and added to other subsets in later steps.

This approach relies on the **hypothesis** that *all data in a given line should be (aproximately) the same value* !
Thus, this procedure is particularly well adopted to the case when _all_ samples are multiple replicate measurements of the _same_ sample.


```{r rowNormalize1, echo=TRUE}
set.seed(2); AA <- matrix(rbinom(110, 10, 0.05), nrow=10)
AA[,4:5] <- AA[,4:5] *rep(4:3, each=nrow(AA))

AA1 <- rowNormalize(AA)
round(AA1, 2)
```

Now, let's make this sparse and try normalizing:

```{r rowNormalize2, echo=TRUE}
AC <- AA
AC[which(AC <1)] <- NA

(AC1 <- rowNormalize(AC))
```

Like with _normalizeThis()_ we can define some reference-lines (only these lines will be considered to determine normalization-factors)

```{r rowNormalize3, echo=TRUE}
(AC3 <- rowNormalize(AC, refLines=1:5, omitNonAlignable=TRUE))
```

Please note, that the iterative procedure for _sparse data_ may consume large amounts of computational resources, in particular when
a small number of subgroups has been selected.



### Matrix Coordinates Of Values/Points According To Filtering

Sometimes one needs to obtain the coordinates of values/points of a matrix according to a given filtering condition.
The standard approach using _which()_ gives only a _linearized_ index but not row/column, which is sufficient for replacing indexed values.
If you need to know the true row/column indexes, you may use `coordOfFilt()`.

```{r coordOfFilt1, echo=TRUE}
set.seed(2021); ma1 <- matrix(sample.int(n=40, size=27, replace=TRUE), ncol=9)
## let's test which values are >37
which(ma1 >37)      # doesn't tell which row & col
coordOfFilt(ma1, ma1 >37)
```


### Trimmed Mean

Under certain circumstances using the trimmed mean may be more stable towards outlyer values.
The base function  `mean()` allows to preform symmetric trimming, thus with more trimming the result will start converging to the _mean_.
The function `trimmedMean()` (from this package) gives more flexible options for assinging different upper- and lower fractions of the initial data to be trimmed.
When outlyer values always appear at the high (or low) end of data, such proceeding may be useful.
However, the user is encouraged to use this with caution since there is also a risk of introducing bias.


```{r trimmedMean1, echo=TRUE}
x <- c(17:11,27:28)
mean(x)
mean(x, trim=0.15)       # symmetric trimming
mean(x[x < 25])          # manual trimming
trimmedMean(x, trim=c(l=0, u=0.7))   # asymmetric trim
```


###  Blockwise Normalization Of 2 or 3 Data-Sets   {#blockNormalize}

In some instances you may want to make data-sets globally comparable without completely "normamlizing" all columns, in order to preseve some of the inherent structure of each of the data-sets.
Such procedures typically consiste in rescaling each data-set to common boundaries or to have the same overall median (without median-normalizing each column).

Instead of normalizing all columns of joined data-sets the alternative of blockwise procedures treat each initial data-set as a given block without addressing each column independently.
The function `blockNormalize()` performs block quantile normalization on 2 or 3 datasets (vectors, matrices or data.frames) to align their overall distributions while preserving the internal rank structure within each block.
This function was designed to make 2 or 3 data-sets globally comparable without intervening too much to the internal structures.

As result, all output blocks (up to 2 blocks) will have identical distributions (the mean of their sorted values)
The relative ordering (ie ranks) within each original block is preserved.
This function resembles somehow to the function normalizeBetweenArrays() from package limma, which does quantile normalization - but not for arbitrary blocks (using entire arrays only).


```{r blockNormalize1, echo=TRUE}
## Basic usage with vectors 
x <- c(1, 5, 3, 7, 2)
y <- (1:5)*10
## Align distributions (default: x and y will have identical distributions)
norm1 <- blockNormalize(x, y)
table(sort(norm1$x) == sort(norm1$y))  # all TRUE with 'quantile.block'
```


The primary us of this function will likely consist in normalizing matrixes or data.frames
```{r blockNormalize2, echo=TRUE}
## matrix-example (like with omics-data)
set.seed(2026); mat1 <- matrix(rnorm(70), nrow=10, dimnames=list(letters[1:10],LETTERS[1:7])) *5  # 10 lines x 10 samples
set.seed(2025); mat2 <- matrix(rnorm(70, mean=5), nrow=10)^2 -15
mat2[which(mat2 < 1.8)] <- mat2[which(mat2 < 1.8)] + 32

norm2 <- blockNormalize(mat1, mat2, method="rescale", range=c(0.1, 10))
sapply(norm2, range)

norm3 <- blockNormalize(mat1, mat2, method="median")
sapply(norm3, quantile, c(0.25,0.5,0.75), na.rm=TRUE)

norm4 <- blockNormalize(mat1, mat2, method="quantile.block")
sapply(norm4, quantile, c(0.25,0.5,0.75), na.rm=TRUE)
```

The resulting distribution :
```{r blockNormalize3, echo=TRUE}
layout(matrix(1:4, ncol=2))
boxplot(cbind(mat1, NA, mat2), main="initial", las=1)
boxplot(cbind(norm2$x, NA, norm2$y), main="rescale block", las=1)
boxplot(cbind(norm3$x, NA, norm3$y), main="median block", las=1)
boxplot(cbind(norm4$x, NA, norm4$y), main="quantile.block", las=1)
```

You can see that relative variability inside each dataset will show up differently depending on the normalization procedure chosen.

Under some circumstances you may want to define different now ranges for each data-set.
This might be of interest if the data-sets follow somehow different distributions, in particuar in respect to (rare) extreme values.
In some cases it my be of interest to not provide absolute boundaries but given quantiles for lower and/or upper boundaries. 

In some cases it my be of interest not defining absolute boundaries but rather use quantiles for lower and/or upper boundaries. 

the overal distributions look like this:
```{r blockNormalize4, echo=TRUE}
## the overall distribution of blocks
layout(matrix(1:4, ncol=2))
boxplot(cbind(mat1=as.numeric(mat1), mat2=as.numeric(mat2)), main="initial (overall)",las=1)
boxplot(cbind(mat1=as.numeric(norm2$x), mat2=as.numeric(norm2$x)), 
  main="rescale block norm (overall)",las=1)
boxplot(cbind(mat1=as.numeric(norm3$x), mat2=as.numeric(norm3$x)), 
  main="median block norm (overall)",las=1)
boxplot(cbind(mat1=as.numeric(norm4$x), mat2=as.numeric(norm4$x)), 
  main="quantile.block norm (overall)",las=1)
```

In some cases (rare) extreme values may have strong impact on the outcome of re-scaling.
In such cases you can rather define two quantiles of the data to get normalized to predefined values, and the remaining data will get adjusted in a linear fashion.
This way it is poissible to align the major part of 2 datasets while extreme values live their 'own lives' (if you choose to conserve their extreme character).
Otherwise the  _method="quantile.block"_ will help bringing extreme values closer to the main bulk of data.





## Statistical Testing  {#StatisticalTesting}

### Normal Random Number Generation with Close Fit to Expected mean and sd

When creating random values to an expected _mean_ and _sd_, the results ontained using the standard function `rnorm()` 
may deviate somehow from the expected mean and sd, in particular with low _n_. 
To still produce random values fitting closely to the expected _mean_ and _sd_ you may use the function `rnormW()`. 
The case of _n=2_ is quite simple with one possible results. 
In other cases (_n>2_), there will be a random initiation which can be fixed using the argument _seed_.


```{r rnormW1, echo=TRUE}
## some sample data :
x1 <- (11:16)[-5]
mean(x1); sd(x1)
```

```{r rnormW2, echo=TRUE}
## the standard way for gerenating normal random values
ra1 <- rnorm(n=length(x1), mean=mean(x1), sd=sd(x1))
## In particular with low n, the random values deviate somehow from expected mean and sd :
mean(ra1) -mean(x1) 
sd(ra1) -sd(x1)
```

```{r rnormW3, echo=TRUE}
## random numbers with close fit to expected mean and sd :
ra2 <- rnormW(length(x1), mean(x1), sd(x1))
mean(ra2) -mean(x1) 
sd(ra2) -sd(x1)   # much closer to expected value
```

Thus, the second data-sets fits even with few _n_ very well to the global characteristics defined/expected.


### Moderated Pair-Wise t-Test from limma

If you are not familiar with the way data is handled in the Bioconductor package [limma](https://bioconductor.org/packages/release/bioc/html/limma.html) 
and you would like to use some of the tools for running moderated t-tests therein, this will provide easy access using `moderTest2grp()` :
```{r moderTest2grp, echo=TRUE}
set.seed(2017); t8 <- matrix(round(rnorm(1600,10,0.4),2), ncol=8,
  dimnames=list(paste("l",1:200), c("AA1","BB1","CC1","DD1","AA2","BB2","CC2","DD2")))
t8[3:6,1:2] <- t8[3:6,1:2]+3     # augment lines 3:6 for AA1&BB1
t8[5:8,5:6] <- t8[5:8,5:6]+3     # augment lines 5:8 for AA2&BB2 (c,d,g,h should be found)
t4 <- log2(t8[,1:4]/t8[,5:8])
fit4 <- moderTest2grp(t4, gl(2,2))
## now we'll use limma's topTable() function to look at the 'best' results
if("list" %in% mode(fit4)) {  # if you have limma installed we can look further
  library(limma)
  topTable(fit4, coef=1,n=5)                      # effect for 3,4,7,8
  fit4in <- moderTest2grp(t4, gl(2,2), testO="<")
  if("list" %in% mode(fit4in)) topTable(fit4in, coef=1,n=5) }
```

### Multiple Moderated Pair-Wise t-Tests From limma

If you want to make multiple pair-wise comparisons using `moderTestXgrp()` :
```{r moderTestXgrp, echo=TRUE}
grp <- factor(rep(LETTERS[c(3,1,4)], c(2,3,3)))
set.seed(2017); t8 <- matrix(round(rnorm(208*8,10,0.4),2), ncol=8,
  dimnames=list(paste(letters[], rep(1:8,each=26),sep=""), paste(grp,c(1:2,1:3,1:3),sep="")))
t8[3:6,1:2] <- t8[3:6,1:2] +3                    # augment lines 3:6 (c-f) 
t8[5:8,c(1:2,6:8)] <- t8[5:8,c(1:2,6:8)] -1.5    # lower lines 
t8[6:7,3:5] <- t8[6:7,3:5] +2.2                  # augment lines 
## expect to find C/A in c,d,g, (h)
## expect to find C/D in c,d,e,f
## expect to find A/D in f,g,(h)  
test8 <- moderTestXgrp(t8, grp) 
head(test8$p.value, n=8) 
```

#### Choosing amongst multiple possible pairwise comparisons

If you would like to run all possible pairwise comparisons you can set argument _useComparison_ to 'all'.

```{r moderTestXgrp2, echo=TRUE}
test8a <- moderTestXgrp(t8, grp, useComparison="all")
head(test8a$p.value, n=3) 
```

Besides, there are multiple ways to select which pairwise comparison(s) you would like to perform.

```{r moderTestXgrp3, echo=TRUE}
## multiple ways for choosing same comparison(s)
test8b <- moderTestXgrp(t8, grp, useCo=c("A-D"))   # name of comparison(s) 
test8c <- moderTestXgrp(t8, grp, useCo=2)          # the 2nd of all possible
test8d <- moderTestXgrp(t8, grp, useCo=cbind(samp="A", ref="D"))
test8e <- moderTestXgrp(t8, grp, useCo=cbind(samp=1, ref=3))

head(test8b$p.value, n=3) 
head(test8c$p.value, n=3) 
head(test8d$p.value, n=3) 
head(test8e$p.value, n=3) 

identical(test8b, test8c)
identical(test8b, test8d)
```


In some cases one might like a more explicite name of pairwise combined groups.
Using the argument _sep_ a specific separator may be given or searched from groups like _'combine2'_ .

```{r moderTestXgrp4, echo=TRUE}
## all comparisons with more explicite pairwise combined names
test8f <- moderTestXgrp(t8, grp, sep="combine2", useCo="all") 
head(test8f$p.value, n=8)
```



### Transform p-values To Local False Discovery Rate (lfdr)

To get an introduction into local false discovery rate estimations you may read [Strimmer 2008](https://doi.org/10.1093/bioinformatics/btn209). 
A convenient way to get lfdr values calculated by the package [fdrtool](https://CRAN.R-project.org/package=fdrtool) is available via the function `pVal2lfdr()`.

Note, that the toy-example used below is too small for estimating meaningful lfdr values.
For this reason the function _fdrtool()_ from package [fdrtool](https://CRAN.R-project.org/package=fdrtool) will issue warnings.

```{r pVal2lfdr, echo=TRUE}
set.seed(2017); t8 <- matrix(round(rnorm(160,10,0.4),2), ncol=8, dimnames=list(letters[1:20],
  c("AA1","BB1","CC1","DD1","AA2","BB2","CC2","DD2")))
t8[3:6,1:2] <- t8[3:6,1:2] +3   # augment lines 3:6 (c-f) for AA1&BB1
t8[5:8,5:6] <- t8[5:8,5:6] +3   # augment lines 5:8 (e-h) for AA2&BB2 (c,d,g,h should be found)
head(pVal2lfdr(apply(t8, 1, function(x) t.test(x[1:4], x[5:8])$p.value)))
```


### Confindence Intervals (under Normal Distribution)

The [confindence interval (CI)](https://en.wikipedia.org/wiki/Confidence_interval) is a common way of describing the uncertainity of measured or estimated values. 
The function `confInt()` allows calculating the confidence interval of the mean (using the functions _qt()_ and _sd()_) under 
a given [significance level (alpha)](https://en.wikipedia.org/wiki/Statistical_significance).
assuming that the [Normal distribution](https://en.wikipedia.org/wiki/Normal_distribution) is valid.

```{r fcCI, echo=TRUE}
set.seed(2022); ran <- rnorm(50)
confInt(ran, alpha=0.05)
## plot points and confindence interval of mean
plot(ran, jitter(rep(1, length(ran))), ylim=c(0.95, 1.05), xlab="random variable 'ran'",main="Points and Confidence Interval of Mean (alpha=0.05)", ylab="", las=1)
points(mean(ran), 0.97, pch=3, col=4)     # mean
lines(mean(ran) +c(-1, 1) *confInt(ran, 0.05), c(0.97, 0.97), lwd=4, col=4)  # CI
legend("topleft","95% conficence interval of mean", text.col=4,col=4,lty=1,lwd=1,seg.len=1.2,cex=0.9,xjust=0,yjust=0.5)
```


### Extract Groups Of Replicates From Pair-Wise Column-Names

When running multiple pairwise tests (using *moderTestXgrp()*) the column-names are concatenated group-names. 
To get the index of which group has been used in which pair-wise set you may use the function `matchSampToPairw()`, as shown below.

```{r matchSampToPairw, echo=TRUE}
## make example if limma is not installed
if(!requireNamespace("limma", quietly=TRUE)) test8 <- list(FDR=matrix(1, nrow=2, ncol=3, dimnames=list(NULL,c("A-C","A-D","C-D"))))
matchSampToPairw(unique(grp), colnames(test8$FDR)) 
```


### Extract Numeric Part Of Column-Names

When running multiple pairwise tests (using *moderTestXgrp()*) the results will be in adjacent columns and the group-names reflected in the column-names.
In the case measurements from multiple levels of a given variable are compared it is useful to extract the numeric part, the function `numPairDeColNames()` provides support to do so. 
When extracting just the numeric part, unit names will get lost, though. Note, if units used are not constant (eg seconds and milliseconds mixed) the extracted numeric values do not reflect the real quantitative context any more.

```{r pairWiseConc1, echo=TRUE}
mat1 <- matrix(1:8, nrow=2, dimnames=list(NULL, paste0(1:4,"-",6:9)))
numPairDeColNames(mat1)
```


### Automatic Determination Of Replicate Structure Based On Meta-Data

In order to run statistical testing the user must know which sample should be considered replicate of whom.
The function `replicateStructure()` aims to provide help by checking all column of a matrix of meta-data with the aim of identifying the replicate-status.

To do so, all columns are examined how many groups of replicats they may design. Depending on the argumen _method_ various options for choosing automatically exist :
The default _method="combAll"_ will select the column with the median number of groups (not counting all-different or all-same columns)).
When using as _method="combAll"_ (ie combine all columns that are neither all-different nor all-same), there is risk all lines (samples) will be be considered different and no replicates remain.
To avoid this situation the argument -method_ can be set to _"combNonOrth"_.
Then, it will be checked if adding more columns will lead to complete loss of replicates, and -if so- concerned columns omitted.


```{r replicateStructure1, echo=TRUE}
## column a is all different, b is groups of 2,
## c & d  are groups of 2 nut NOT 'same general' pattern as b
strX <- data.frame(a=letters[18:11], b=letters[rep(c(3:1,4), each=2)],
 c=letters[rep(c(5,8:6), each=2)], d=letters[c(1:2,1:3,3:4,4)],
 e=letters[rep(c(4,8,4,7),each=2)], f=rep("z",8) )
strX

replicateStructure(strX[,1:2])
replicateStructure(strX[,1:4], method="combAll")
replicateStructure(strX[,1:4], method="combAll", exclNoRepl=FALSE)
replicateStructure(strX[,1:4], method="combNonOrth", exclNoRepl=TRUE)
replicateStructure(strX, method="lowest")
```


### Addressing Pairwise Comparisons

There are multiple ways of specifying pairwise comparions (eg 'A-B', or c('A','B'), or using indexes), the function `convPairwiseSetup()`  allows converting between different types 
and returns a list with multiple formats for addressing specific quesions. 
If the separator for concantenating is known this may be helpful, but not obligatory. In many cases the function will manage to identify independently which separator has been used.


```{r convPairwiseSetup1, echo=TRUE}
## concatenated names of groups
convPairwiseSetup(c("B-C","D-A"), LETTERS[1:4])

## separate names of groups
convPairwiseSetup(c("B","C"), LETTERS[1:3])
convPairwiseSetup(2:3, LETTERS[1:3])
convPairwiseSetup(2:3, LETTERS[1:3], sep="__")
convPairwiseSetup(matrix(c("B","D","C","A"), ncol=2), LETTERS[1:4])
```

#### Suggesting A Separator For Pairwise Combinations

In many cases the user doesn't choose a specific separator to be used for concatenating group-names.  
The function `convPairwiseSetup()` allows checking a panel of separators to choose a 'unique' one which does not occur in any of the group-names. 

```{r suggestSeparator1, echo=TRUE}
getPWseparator(grp=LETTERS[1:3])
getPWseparator(grp=c("B-C","D","E")) 
getPWseparator(grp=c("B-C","D","E"), includeGrp=TRUE) 
```

Of course you can also check your preferred separators, the first found compatible (ie unique) will be reported.
```{r suggestSeparator2, echo=TRUE}
potSep <- c("-", "D", " -compared to- ")
getPWseparator(grp=c("B-C","D","E"), includeGrp=TRUE, potSep=potSep)
```


By using the argument _includeGrp_ the output will be a list including the input instead of simply the suggested separator.
```{r suggestSeparator3, echo=TRUE}
getPWseparator(grp=c("B-C","D","E"), includeGrp=TRUE) 
```


#### Identify The Separator Used In Concatenated Text

The same function may be used to identify which separator has been used, by checking a panel of classical candidates for separators
```{r identifySeparator1, echo=TRUE}
## Identify separator used
getPWseparator(compNames=c("B-C","B-D","C-D")) 
getPWseparator(compNames=c("B-C","B-D","C-D"), includeGrp=TRUE)
```

Besides, the function  `findHeadAndTail()` allows (unbiased) identifying separators without having to define candidates to check,
as it proceeds by removing names of groups from beginning and end of concatenated terms. 
However, there is a slight risk that some special characters may not allow finding the proper solution.

```{r identifySeparator2, echo=TRUE}
## Identify separator used
findHeadAndTail(LETTERS[4:2], c("D-X","D-C"))

grp1 <- c("C","ACC","CC","B.B","B.BA","B","CA")
pwNa1 <- "B.B-CC" 
findHeadAndTail(grp1, pwNa1)

pwNa2 <- c("B.B-CC", "CA-ACC")
findHeadAndTail(grp1, pwNa2)
```



## Working With Clustering  {#WorkingWithClustering}

Multiple concepts for clustering have been deeveloped, most of them allow extracting a vector with the cluster-numbers.
Here some functions helping to work with the output of such clustering results are presented.


### Prepare Data For Clustering

The way how to prepare data for clustering may be as important as the choice of the actual clustering-algorithm ...

Many clustering algorithms are available in R (eg see also [CRAN Task View: Cluster Analysis & Finite Mixture Models](https://CRAN.R-project.org/view=Cluster)), many of them require the input data to be standardized.
The regular way of standardizing sets all elements to mean=0 and sd=1.
To do so, the function `scale()` may be used. 

```{r std1, echo=TRUE}
dat <- matrix(2*round(runif(100),2), ncol=4)
mean(dat); sd(dat)

datS <- scale(dat)
apply(datS, 2, sd)
# each column was teated separately
mean(datS); sd(datS); range(datS)
# the mean is almost 0.0 and the sd almost 1.0

datB <- scale(dat, center=TRUE, scale=FALSE)
mean(datB); sd(datB); range(datB)              # mean is almost 0
```

However, if you want the entire data-set and not each column sparately, you may use `standardW()`.
Thus, relative differences visible within a line will be conserved.
Furthermore, in case of 3-dim arrays, this function returns also the same dimensions as the input.

```{r std2, echo=TRUE}
datS2 <- standardW(dat)
apply(datS2, 2, sd)
summary(datS2)
mean(datS2); sd(datS2)

datS3 <- standardW(dat, byColumn=TRUE)
apply(datS3, 2, sd)
summary(datS3)
mean(datS3); sd(datS3)
```


Sometimes it is sufficient to only set the minimum and maximum to a given range.

```{r scale1, echo=TRUE}
datR2 <- apply(dat, 2, scaleXY, 1, 100)
summary(datR2); sd(datR2)
```

Please note that this function shares some overlap with _adjBy2ptReg()_ (which has less options and will get deprecated in the future)


### Characterize Clustering Results

Here a very basic clustering example...

```{r clu01, echo=TRUE}
nGr <- 3
irKm <- stats::kmeans(iris[,1:4], nGr, nstart=nGr*4)             # no need to standardize
   table(irKm$cluster, iris$Species)
   #wrGraph::plotPCAw(t(as.matrix(iris[,1:4])), sampleGrp=irKm,colBase=irKm$cluster,useSymb=as.numeric(as.factor(iris$Species)))
```

Using the function `reorgByCluNo()` we can now 'apply' the clustering result to the initial data to obtain other information.

```{r clu02, echo=TRUE}
## sort results by cluster number
head(reorgByCluNo(iris[,-5], irKm$cluster))
tail(reorgByCluNo(iris[,-5], irKm$cluster))
```

Let's calculate the median and sd values for each cluster:

```{r clu03, echo=TRUE}
## median an CV
ir2 <- reorgByCluNo(iris[,-5], irKm$cluster, addInfo=FALSE, retList=TRUE)
```


```{r clu04, echo=TRUE}
sapply(ir2, function(x) apply(x, 2, median))
```

```{r clu05, echo=TRUE}
sapply(ir2, colSds)
```

Besides, we have already seen the function `cutArrayInCluLike()` in section [Working with Arrays](#WorkingWithArrays) 'Working with Arrays'.


### Remove or Reassign Orphans

In some some circumstances clusters/groups with very vew individuals are not productive during further evalualtions (in particular in the context of interaction-netwoks).
The function `rmOrphans()` allows identifying and modifying cluster- or group-assignments of such very small groups ('orphans').

In the example below a vector of cluster-assignments ('x') is treated by different options to remove orphans :

```{r rmOrphans1, echo=TRUE}
x=c(3:1,3:4,4:6,5:3)
cbind(x, def=rmOrphans(x), assign1=rmOrphans(x, reassign=TRUE), 
  assign1=rmOrphans(x, minN=0.2, reassign=TRUE) )
```


## Tree-Like Structures   {#TreeLikeStructures}


### Filter Lists Of Connected Nodes, Extension Of Networks As 'Sandwich'

When interogating network-databases (like String for proteins or the coexpressionDB for gene co-expression) typically a (semi-)quantitatve
value is supplied with the connection of node 'A' to node 'B'.  
In many cases, it may be useful to filter the initial query-output to retain only strong interactions.
Furthermore, it may be of interest to expand such networks by nodes allowing to (further) inter-connect initial query-nodes 
(so called 'Sandwich' nodes as they are in the middle of initial nodes), for such nodes a separate (eg even more stringent) threshold can be applied.

Here let's suppose nodes have 3-digit names (ie numbers). 7 nodes of an initial query gave 1 to 7 conected nodes, 
the results are presented as list of data.frames where the 1st column is the connected node and the 2nd column the quality score of the connection (edge).
Furthemore, let's assume that here lower scores are better.

```{r filterNetw0, echo=TRUE}

lst2 <- list('121'=data.frame(ID=as.character(c(141,221,228,229,449)),11:15), 
  '131'=data.frame(ID=as.character(c(228,331,332,333,339)),11:15), 
  '141'=data.frame(ID=as.character(c(121,151,229,339,441,442,449)),c(11:17)), 
  '151'=data.frame(ID=as.character(c(449,141,551,552)),11:14),
  '161'=data.frame(ID=as.character(171),11),
  '171'=data.frame(ID=as.character(161),11),
  '181'=data.frame(ID=as.character(881:882),11:12) )
```

Now, we'd like to keep the core network consisting of all (dirctly) interconnected nodes with scores below 20 :

```{r filterNetw1, echo=TRUE}
(nw1 <- filterNetw(lst2, limInt=20, sandwLim=NULL, remOrphans=FALSE))
```

In the resulting output the 1st column now represents the query-nodes, the 2nd column all connected nodes based on filtering scores for edges,
and the 3rd colum the score for the edges.

Let's also remove all nodes not connected to a backbone at least 3 nodes long, ie remove orphan pairs of nodes :

```{r filterNetw2, echo=TRUE}
(nw2 <- filterNetw(lst2, limInt=20, sandwLim=NULL, remOrphans=TRUE))
```

If you want to expand this network by nodes allowing to further interconnect the nodes from above, 
we can add all 'sandwich' nodes (let's use a threshold of inferior/equal to 14 which will use only the better 'sandwich'-edges) :

```{r filterNetw3, echo=TRUE}
(nw3 <- filterNetw(lst2, limInt=20, sandwLim=14, remOrphans=TRUE))
```


### Convert Collection Of Pairs Of Nodes To Propensity Matrix

Many times networks get created from pairs of nodes. One way to represent the full network is via propensisty matrixes.
Several advanced tools and packages rather accept such propensisty matrixes as input.
Here, it is assumed that each line of the input represents a separate pair of nodes connected by an edge.

```{r propMatr1, echo=TRUE}
pairs3L <- matrix(LETTERS[c(1,3,3, 2,2,1)], ncol=2)      # loop of 3
(netw13pr <- pairsAsPropensMatr(pairs3L))                # as prop matr
```



### Characterize Individual Contribution Of Single Edges In Tree-Structures

```{r contribToContigPerFrag, echo=TRUE}
path1 <- matrix(c(17,19,18,17, 4,4,2,3), ncol=2,
  dimnames=list(c("A/B/C/D","A/B/G/D","A/H","A/H/I"), c("sumLen","n")))
contribToContigPerFrag(path1)
```


### Count Same Start- And End- Sites Of Edges (Or Fragments)

If you have a set of fragments from a common ancestor and the fragment's start- and end-sites 
are marked by index-positions (integers), you can make a simple graphical display :

```{r simpleFragFig, echo=TRUE}
frag1 <- cbind(beg=c(2,3,7,13,13,15,7,9,7, 3,3,5), end=c(6,12,8,18,20,20,19,12,12, 4,5,7))
rownames(frag1) <- letters[1:nrow(frag1)]
simpleFragFig(frag1)
```

Now we can make a matrix telling if some fragments do start or end at exactely the same position. 
```{r countSameStartEnd, echo=TRUE}
countSameStartEnd(frag1)
```


## Support for Graphical Output   {#SupportForGraphicalOutput}

### Convenient Paste-Collapse

The function `pasteC()` allows adding quotes and separating the last element by specific text (eg 'and').
```{r pasteC, echo=TRUE}
pasteC(1:4)
pasteC(letters[1:4],quoteC="'")
```


### Transform Numeric Values to Color-Gradient

By default most color-gradients end with a color very close to the beginning.
```{r color-gradient1, echo=TRUE}
set.seed(2015); dat1 <- round(runif(15),2)
plot(1:15, dat1, pch=16, cex=2, las=1, col=colorAccording2(dat1),
  main="Color gradient according to value in y")
# Here we modify the span of the color gradient
plot(1:15, dat1, pch=16, cex=2, las=1, 
  col=colorAccording2(dat1, nStartO=0, nEndO=4, revCol=TRUE), main="blue to red")
# It is also possible to work with scales of transparency
plot(1:9, pch=3, las=1)
points(1:9, 1:9, col=transpGraySca(st=0, en=0.8, nSt=9,trans=0.3), cex=42, pch=16)
```


### Assign New Transparency To Given Colors
 
For this purpose you may use `convColorToTransp`.
```{r convColorToTransp, fig.height=6, fig.width=3, echo=TRUE}
col0 <- c("#998FCC","#5AC3BA","#CBD34E","#FF7D73")
col1 <- convColorToTransp(col0,alph=0.7)
layout(1:2)
pie(rep(1,length(col0)), col=col0, main="no transparency")
pie(rep(1,length(col1)), col=col1, main="new transparency")
```


### Print Matrix-Content As Plot

There are many ways of creating reports. If you want simply to combine a few plots into a pdf, the function `tableToPlot()` 
may be helpful to add a small table (eg overview of points/samples/files used in other plots of the same pdf). 
This function prints tables in the current graphical output/window (which may by a pdf-device).


## Other Convenience Functions  {#OtherConvenienceFunctions}

### Writing Compact Dates (more options ...)

Many times it may be useful to add the date to filenames when saving data or plots as files.
The built-in functions _date()_, _Sys.Date()_ and _Sys.Time()_ are a good way to start.

Generally I like to use abbreviated month-names since the order of writing the month is different in Europe compared to the USA.
So, this may help avoiding mis-interpreting dates instead of writing the number of the Month.
For example, 2021-03-05 means in Europe March 5th while in other places it means May 3rd.

You may also look at the standardized format for *numeric dates* [norm ISO 8601](https://en.wikipedia.org/wiki/ISO_8601), 
which matches to _Sys.Date()_ (from package _base_) and _sysDate(style="univ5")_ (package _wrMisc_) .

The R-functions mentioned above (_date()_, _Sys.Date()_, from the _base_ package) use local language settings.
For using English languange names you may use the function `sysDate` from this package (ie wrProteo). 
It allows producing compact versions of current the date, **independent to local language settings** (or not -if you prefer), ie locale-specific, 
(yes, in some languages - like French - the first 3 letters of the month may give ambiguous results !) 
and to avoid white space ' ' (which I prefer to avoid in file-names).
Please look at the function's help-page for all available options.

```{r sysDate1, echo=TRUE}
## To get started
Sys.Date()

## Compact English names (in European order), no matter what your local settings are :
sysDate() 
```

The table below shows a number of options to write the date in English or using local month-names :

```{r DateTab, echo=TRUE}
tabD <- cbind(paste0("univ",1:6), c(sysDate(style="univ1"), sysDate(style="univ2"), 
    sysDate(style="univ3"), sysDate(style="univ4"), as.character(sysDate(style="univ5")), 
    sysDate(style="univ6")), paste0("   local",1:6), 
  c(sysDate(style="local1"), sysDate(style="local2"), sysDate(style="local3"), 
    sysDate(style="local4"), sysDate(style="local5"), sysDate(style="local6")))   
knitr::kable(tabD, caption="Various ways of writing current date")
```


## Acknowledgements

The author would like to acknowledge the support by the [IGBMC](https://www.igbmc.fr) (CNRS UMR 7104, Inserm U 1258, UdS), [CNRS](http://www.cnrs.fr/en), 
[Universit&eacute; de Strasbourg (UdS)](https://www.unistra.fr/fr) and [Inserm](https://www.inserm.fr).



## Session-Info

```{r sessionInfo, echo=FALSE}
sessionInfo()
```

