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

## Introduction
This package contains a collection of various low-level tools which may be of interest for general re-use. 
These functions were accumulated over a number of years when treating hight-throughput data from biomedical applications.
Besides, these functions are used/integrated in more specialized functions dedicated to specific applications in other packages (eg [wrProteo](https://CRAN.R-project.org/package=wrProteo) or [wrGraph](https://CRAN.R-project.org/package=wrGraph)).
To get started, we need to load the package "[wrMisc](https://CRAN.R-project.org/package=wrMisc)" available from [CRAN](https://cran.r-project.org/).


```{r setup, include=FALSE,echo=FALSE, messages=FALSE, warnings=FALSE}
suppressPackageStartupMessages({
    library(wrMisc)
})
#start_vignette("wrMiscVignette1")
```

```{r install, eval=FALSE}
# If not already installed, we have to install the package it first.
install.packages("wrMisc")
```

```{r setup1}
library("wrMisc")
# This is version no:
packageVersion("wrMisc")
```


## Speed optimized functions in the package wrMisc

In hight-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 conatain 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 mesurement 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.

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 variance) for every row :

```{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.

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: 

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

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

### Fast NA-omit for very large objects
The function _na.omit()_ from the package [stats](https://stat.ethz.ch/R-manual/R-devel/library/stats/) also keeps a trace of all omitted instances. 
This can be penalizing in terms of memory usage when handeling 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 such 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 distaces 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) occur multiple times (line no 3 and 9), multiple occurances are counted in the column _ncur_.
This is why column _nbest_ for line 15 (_value_ =6.0) inidicates that it appears twice as closest value _nbest_.



## Working with lists (and lists of lists)

### 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),c=31:33,L2=matrix(21:28,ncol=2),li=list(li1=11:14,li2=data.frame(41:44)))
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),c=31:33, L2=matrix(21:28,ncol=2), li=list(li1=11:14,li2=data.frame(41:44)))
asSepList(bb)
```


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


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


### 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 listBatchReplace, 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 progamming 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 inapropriate 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

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




## Working with arrays

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_ alon the 3rd dimension):
```{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 intial 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.
```{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' :
```{r filt3dimArr, echo=TRUE}
filt3dimArr(arr1,displCrit=c("col1","col2"), filtCrit="col2", filtVal=7, filtTy=">")
```


## Working with redundant data

_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()` makes a vector with some redundant entries 'unique', ie in the resultant vector all values/content (values) occur only once. However, initially repeated values will still be present. Also, you cannot tell any more which ones were not unique initially ! Thus, the result of _unique()_ does not tell which values were '_unique_' in the first place.

In some applications (eg proteomics) initial identifyers (IDs) may occur multiple times in the data and we frequently need to isolate events/values that occur only once, as the first meaning of '_unique_'. 
This package provides functions to easily distinguish values occuring just once (ie _unique_) from those occuring multiple times. Furthermore, there are functions to rename/remove/combine replicated elements.

### 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 unqiue, 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 ist is not very convenient to the human eye.
```{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 will be added to non-unique entries, thus no individual values get eliminated and the length and order of the resultant object maintains the same.

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

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

correctToUnique(aa, sep=".", NAenu=FALSE)       # keep NAs (ie without transforming to character)
```

### 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.

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

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


### 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 theur respective information should be combined (either as average or as sum). 
```{r cbindNR, echo=TRUE}
## First we'll make soe 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])))
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 make unique based on one column and based concatenate to other user-specified column(s)
This function also includes a counter of redundant instances encountered (for 1st column specified)
```{r nonredDataFrame, echo=TRUE}
(df1 <- data.frame(cbind(xA=letters[1:5],xB=c("h","h","f","e","f"),xC=LETTERS[1:5])))

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


### 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"))
```

### 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 whish 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 empric 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)
```


## Search for similar (numeric) values

```{r checkSimValueInSer, echo=TRUE}
va1 <- c(4:7,7,7,7,7,8:10)+(1:11)/28600
checkSimValueInSer(va1)
cbind(va=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 convient format for the human eye.

```{r closeMatchMatrix1, 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 closeMatchMatrix2, 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, deb=TRUE))  #
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, deb=FALSE)) 
```


### Find similar numeric values from two vectors/matrixes

```{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,deb=TRUE)
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.
```{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 elimCloseCoord, 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)
```


## Import/Export

### Batch-reading of csv files

Some programs produce a series of csv files, where a large experiment/data-set was split in multiple files.
The function _readCsvBatch()_ was designed for reading multiple csv files of exactely 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)
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)
```

### Reading incomplete tables

Sometimes were may get confronted with data which look like 'incomplete' tables. 
In such cases some rows do not conatain as many elements/columns as other columns. 
Files with this type of data pose a problem for _read.table()_ (from the _utils_ package).
The function _readVarColumns()_ (from this package) was designed to provide help in such cases.
Basically each line is read an parsed separetely, the user should check the proper separator is used.

The example below lists people's names in different locations, some locations have more persons ... 
Sometimes exporting such data will gererate shorter lines in locations with fewer elements (here 'London') and no additonal 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 separtors) 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)
```


## 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 throuput data from real world measurements may easily contain various deformations due to technical reasons, eg slight temperature variations, electromagnetic interferance, instability of reagents etc.
In paticular, transferring constant amounts of liquids/reagents in highly repeated steps over large experiments is ofter also very challenging, 
small variations of the amounts of liquid (or similar) are typically adressed 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 tighly linked to decisions about data-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 therefor 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 interacion 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 mesured alements are affected, this normalization approach will lead to (additional) loss of information.

I suggest the user also to include graphical representation(s) of the data helping to visualize variability in various samples along a given experiment and 
how different normalization procedures affect these outcomes. 

Before jumping into normalization it may be quite useful to _filter_ the data first.
The overal 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 such problematic data concerns _NA_-values.


### Filter lines of matrix to reduce content of NAs 

Frequent _NA_-values may represent another potential issue. With NA-values there is no general optimal advice.
To get started, you should try to investigate how and why NA-values occured 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.
If the lines of your data represent different features quantified (eg proteins), than lines with mostly NA-values represent features
that may not be well exploited anyway. Therefore many times one tries to filter away lines of 'bad' data. 
Of course, if there is a column (sample) with an extremely high content of NAs, one should also investigate what might be particular 
with this column (sample), to see if one might be better of to eliminate the entire column.

The function _presenceFilt()_ allows to eliminate lines containing too many _NA_-values.

```{r presenceFilt, 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
dat1; presenceFilt(dat1,gr=gl(3,3)[-(3:4)],maxGr=0)
presenceFilt(dat1,gr=gl(2,4)[-1],maxGr=1,ratM=0.1)
presenceFilt(dat1,gr=gl(2,4)[-1],maxGr=2,rat=0.5)
```

```{r cleanReplicates, echo=TRUE}

mat3 <- matrix(c(19,20,30, 18,19,28, 16,14,35),ncol=3)
cleanReplicates(mat3,nOutl=1)
```

Please note, that imputing _NA_-values represents another option instead of filtering, multiple other packages address this in detail. 
All decisions of which approach to use should be data-driven.

### 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.
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 a missing information. 
Of course, graphical representations ([PCA](https://en.wikipedia.org/wiki/Principal_component_analysis), [MA-plots](https://en.wikipedia.org/wiki/MA_plot), etc) are frequently 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.


```{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))
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 dat 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 outlyers 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 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")
```

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


## Statistical testing

### 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 :
```{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
library(limma)
topTable(fit4,coef=1,n=5)                      # effect for 3,4,7,8
fit4in <- moderTest2grp(t4,gl(2,2),testO="<")
topTable(fit4in,coef=1,n=5)
```

### Multiple moderated pair-wise t-tests from limma
If you want to make multiple pair-wise comparisons :
```{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)
```


### Transform p-values to local false dicovery rate (lfdr)
To get an introduction into local false dicovery rate estimations you may read [Strimmer 2008](https://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-9-303).  An overview of R packages in this context was prepared by the [strimmerlab](http://www.strimmerlab.org/notes/fdr.html).
Note, that the toy-example used below is too small for estimating really meaningful lfdr values.
For this reason the function _fdrtool()_ from package [fdrtool](https://CRAN.R-project.org/package=fdrtool) may 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)))
```


## Tree-like structures


### 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 grapgical 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

### Convenient paste-collapse
This function allows adding quotes and separating the last element by specific text (eg 'and').
```{r pasteC, echo=TRUE}
pasteC(1:4)
```

### 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,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,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)
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
```{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 are simply combining a few plots into a pdf, that the function _xx_ 
may be helpful to add a small table (eg overview of points/samples used in following plots), 
which can be printed directly into the current pdf-device.


## Session-Info

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