content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' Extract last two numeric parts from character vector #' #' \code{extractLast2numericParts} extracts last 2 (integer) numeric parts between punctuations out of character vector 'x'. #' Runs faster than \code{gregexpr} . #' Note: won't work correctly with decimals or exponential signs !! (such characters will be considered as punctuation, ie as separator) #' @param x main character input #' @param silent (logical) suppres messages #' @param callFrom (character) allow easier tracking of message(s) produced #' @return (numeric) matrix with 2 columns (eg from initial concatenated coordinates) #' @seealso \code{gregexpr} from \code{\link[base]{grep}} #' @examples #' extractLast2numericParts(c("M01.1-4","M001/2.5","M_0001_03-16","zyx","012","a1.b2.3-7,2")) #' @export extractLast2numericParts <- function(x,silent=FALSE,callFrom=NULL) { fxNa <- .composeCallName(callFrom,newNa="extractLast2numericParts") z <- gsub("[[:alpha:]]|[[:blank:]]","",x) # simplify: remove any text or blank characters aa <- strsplit(z,"[[:punct:]]",fixed=FALSE) chLe <- sapply(aa,length) >1 if(any(!chLe)) {aa <- aa[which(chLe)]; if(!silent) message(fxNa,sum(!chLe)," elements not fitting -> discard")} out <- t(sapply(aa,function(y) {le <- length(y); as.numeric(c(y[le-(1:0)]))})) rownames(out) <- if(any(chLe)) x[which(chLe)] else x out}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/extractLast2numericParts.R
#' Filter three-dimensional array of numeric data #' #' Filtering of matrix or (3-dim) array \code{x} : filter column according to \code{filtCrit} (eg 'inf') and threshold \code{filtVal} #' #' and extract/display all col matching 'displCrit'. #' #' @param x array (3-dim) of numeric data #' @param filtVal (numeric, length=1) for testing inferior/superor/equal condition #' @param filtTy (character, length=1) which type of testing to perform (may be 'eq','inf','infeq','sup','supeq', '>', '<', '>=', '<=', '==') #' @param filtCrit (character, length=1) which column-name consider when filtering filter with 'filtVal' and 'filtTy' #' @param displCrit (character) column-name(s) to display #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of messages produced #' @param debug (logical) additional messages for debugging #' @seealso \code{\link{filterList}}; \code{\link{filterLiColDeList}}; #' @return This function returns a list of filtered matrixes (by 3rd dim) #' @examples #' arr1 <- array(11:34, dim=c(4,3,2), dimnames=list(c(LETTERS[1:4]), #' paste("col",1:3,sep=""), c("ch1","ch2"))) #' filt3dimArr(arr1,displCrit=c("col1","col2"),filtCrit="col2",filtVal=7) #' @export filt3dimArr <- function(x, filtVal, filtTy=">", filtCrit=NULL, displCrit=NULL, silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="filt3dimArr") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(length(dim(x)) != 3) stop("Expecting 3-dim array as input for 'x'") if(debug) message(fxNa,"f3d1") if(is.character(displCrit) && length(displCrit) >0) { chCrit <- match(displCrit, colnames(x)) if(any(is.na(chCrit))) stop("Can't find (",sum(is.na(chCrit)),") 'displCrit' in colnames of 'x'") else displCrit <- chCrit} if(is.character(filtCrit) && length(filtCrit) >0) { chCrit <- match(filtCrit, colnames(x)) if(any(is.na(chCrit))) stop("Can't find (",sum(is.na(chCrit)),") 'filtCrit' in colnames of 'x'") else filtCrit <- chCrit} if(length(filtCrit) <1) filtCrit <- 1:ncol(x) if(length(displCrit) <1) displCrit <- 1:ncol(x) if(length(displCrit) <1) displCrit <- colnames(x) if(length(filtTy) <1) filtTy <- ">" else filtTy <- filtTy[1] if(!(filtTy %in% c("inf","infeq","sup","supeq","eq",">",">=","<","<=","=="))) { stop("cannot identify type of filter specified") } ## out <- list() out[[1]] <- x[.filterSw(x[,filtCrit,1], fiTy=filtTy, checkVa=filtVal, indexRet=TRUE), displCrit,1] # start with 1st di if(dim(x)[3] >1) for(i in 2:(dim(x)[3])) out[[i]] <- x[.filterSw(x[,filtCrit,i], fiTy=filtTy, checkVa=filtVal, indexRet=TRUE), displCrit, i] out } #' Filter 3-dim array of numeric data (main) #' #' Filtering of matrix or array \code{x} (may be 3-dim array) according to \code{fiTy} and \code{checkVa} #' #' #' @param x array (3-dim) of numeric data #' @param fiTy (character) which type of testing to perform ('eq','inf','infeq','sup','supeq', '>', '<', '>=', '<=', '==') #' @param checkVa (logical) s #' @param indexRet (logical) if \code{TRUE} (default) rather return index numbers than filtered values #' @seealso \code{\link{filt3dimArr}}; \code{\link{filterList}}; \code{\link{filterLiColDeList}}; #' @return This function returns either index (position within 'x') or concrete (filtered) result #' @examples #' arr1 <- array(11:34, dim=c(4,3,2), dimnames=list(c(LETTERS[1:4]), #' paste("col",1:3,sep=""),c("ch1","ch2"))) #' filt3dimArr(arr1,displCrit=c("col1","col2"),filtCrit="col2",filtVal=7) #' .filterSw(arr1, fiTy="inf", checkVa=7) #' @export .filterSw <- function(x, fiTy, checkVa, indexRet=TRUE){ ## filterswitch function : filter values of 'x' to satisfy 'check' (vector of FALSE or TRUE) ## 'indexRet' .. if TRUE rather return index numbers than filtered values ## returns either index (position within 'x') or concrete (filtered) result if(fiTy == "==") fiTy <- "eq" if(fiTy == "<") fiTy <- "inf" if(fiTy == "<=") fiTy <- "infeq" if(fiTy == ">") fiTy <- "sup" if(fiTy == ">=") fiTy <- "supeq" if(!(fiTy %in% c("inf","infeq","sup","supeq","eq",">",">=","<","<=","=="))) { stop("cannot identify type of filter specified") } if(indexRet) { switch(fiTy, eq = which(x == checkVa), sup = which(x > checkVa), supeq = which(x >= checkVa), inf = which(x < checkVa), infeq = which(x <= checkVa) ) } else { switch(fiTy, eq = x[which(x == checkVa)], sup = x[which(x > checkVa)], supeq = x[which(x >= checkVa)], inf = x[which(x < checkVa)], infeq = x[which(x <= checkVa)] ) } }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/filt3dimArr.R
#' Filter for unique elements #' #' This function aims to identify and remove duplicated elements in a list and maintain the list-structure in the output. #' \code{filtSizeUniq} filters 'lst' (list of character-vectors or character-vector) for elements being unique (to 'ref' or if NULL to all 'lst') and of character length. #' In addition, the min- and max- character length may be filtered, too. Eg, in proteomics this helps removing peptide sequences which would not be measured/detected any way. #' #' @param lst list of character-vectors or character-vector #' @param ref (character) optional alternative 'reference', if not \code{NULL} used in addition to 'lst' for considering elements of 'lst' as unique #' @param minSize (integer) minimum number of characters, if \code{NULL} set to 0 #' @param maxSize (integer) maximum number of characters #' @param filtUnique (logical) if \code{TRUE} return unique-only character-strings #' @param byProt (logical) if \code{TRUE} organize output as list (by names of input, eg protein-names) - if 'lst' was named list #' @param inclEmpty (logical) optional including empty list-elements when all elements have been filtered away - if 'lst' was named list #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return list of filtered input #' @seealso \code{\link{correctToUnique}}, \code{\link[base]{unique}}, \code{\link[base]{duplicated}} #' @examples #' filtSizeUniq(list(A="a",B=c("b","bb","c"),D=c("dd","d","ddd","c")),filtUn=TRUE,minSi=NULL) #' # input: 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) # a,b,c,dd repeated #' @export filtSizeUniq <- function(lst, ref=NULL, minSize=6, maxSize=36, filtUnique=TRUE, byProt=TRUE, inclEmpty=TRUE,silent=FALSE,debug=FALSE, callFrom=NULL) { ## filter protein sequences for size/length and for unique fxNa <- .composeCallName(callFrom,newNa="filtSizeUniq") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE chNa <- grep("\\.$", names(utils::head(lst))) # check for attached tailing '.' if(!is.list(lst)) {byProt <- FALSE; inclEmpty <- FALSE} if(length(chNa) <= min(2,length(lst))) names(lst) <- paste(names(lst),".",sep="") pep <- unlist(lst) chNa <- max(sapply(lst,length),na.rm=TRUE) if(chNa >1) names(pep) <- sub("\\.$","",names(pep)) # remove tailing '.' of names if list-element has length=1 nPep <- length(pep) nAA <- nchar(pep) if(length(minSize) <1) minSize <- 0 if(length(maxSize) <1) {maxSize <- 40 if(!silent) message(fxNa," can't understant 'maxSize', setting to default=40")} ## filter by size chAA <- nAA >= minSize & nAA <= maxSize if(any(!chAA)) {pep <- if(all(!chAA)) NULL else pep[which(chAA)] if(!silent) message(fxNa,nPep - length(pep)," out of ",nPep," peptides beyond range (",minSize,"-",maxSize,")")} ## filter unique /reundant if(filtUnique) { nPe2 <- length(pep) if(length(ref) >0) {pep0 <- pep; pep <- c(pep,unique(unlist(ref))) } else pep0 <- NULL chDup <- duplicated(pep,fromLast=FALSE) if(any(chDup)) { chDu2 <- duplicated(pep,fromLast=TRUE) if(length(ref) >0) {pep <- pep0; chDup <- chDup[1:nPe2]; chDu2 <- chDu2[1:nPe2]} pep <- list(unique=pep[which(!chDu2 & !chDup)],allRedund=pep[which(!(!chDu2 & !chDup))], firstOfRed=pep[which(chDu2 & !chDup)]) if(!silent) message(fxNa,length(pep$allRedund)," out of ",nPe2," peptides redundant") } else {if(length(ref) >0) {pep <- pep0; chDup <- chDup[1:nPe2]}} } ## if(byProt) { fac <- sub("\\.[[:digit:]]+$","",names(if(filtUnique) pep$unique else pep)) pep <- tapply(if(filtUnique) pep$unique else pep,fac,function(x) x) if(length(pep) <1) pep <- character() if(inclEmpty) { iniPro <- sub("\\.$","",names(lst)) curPro <- names(pep) newNo <- sum(!iniPro %in% curPro) if(newNo >0){ pep[length(curPro)+(1:newNo)] <- lapply(1:newNo,function(x) character()) names(pep)[length(curPro)+(1:newNo)] <- iniPro[which(!iniPro %in% curPro)]} } } pep } #' Filter for size #' #' This function aims to filter for size #' #' @param x main inpuy #' @param minSize (integer) minimum number of characters, if \code{NULL} set to 0 #' @param maxSize (integer) maximum number of characters #' @return list of filtered input #' @seealso \code{\link{filtSizeUniq}}; \code{\link{correctToUnique}}, \code{\link[base]{unique}}, \code{\link[base]{duplicated}} #' @examples #' aa <- 1:10 #' @export .filtSize <- function(x, minSize=5, maxSize=36) {nCha <- nchar(x); x[which(nCha >= minSize & nCha <= maxSize)]} # filter by size (no of characters)
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/filtSizeUniq.R
#' Filter lines(rows) and/or columns from all suitable elements of list #' #' Filter all elements of list (or S3-object) according to criteria designed to one selected reference-element of the list. #' All simple vectors, matrix, data.frames and 3-dimensional arrays will be checked if matching number of rows and/or columns to decide if they should be filtered the same way. #' If the reference element has same number of rows and columns simple (1-dimensional) vectors won't be filtered since it not clear if this should be done to lines or columns. #' #' @details #' This function is used eg in package wrProteo to simultaneaously filter raw and transformed data. #' #' @param lst (list or S3 object) main input #' @param useLines (integer, logcial or character) vector to assign lines to keep when filtering along lines; #' set to \code{NULL} for no filtering; if '\code{allNA}' all lines composed uniquely of \code{NA} values will be removed. #' @param useCols (integer, logcial or character) vector for filtering columns; set to \code{NULL} for no filtering; if '\code{allNA}' all columns uniquely \code{NA} values will be removed #' @param ref (integer) index for designing the elment of 'lst' to take as reference for checking which other list-elements have suitable number of rows or columns #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns the correct(ed) input (object of same class, of same length) #' @seealso \code{\link{moderTest2grp}} for single comparisons, \code{\link[limma]{lmFit}} #' @examples #' 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)) #' ## here $m2 has more lines than $m1, and thus will be ignored when ref=1 #' filterLiColDeList(lst1, useLines=2:3) #' filterLiColDeList(lst1, useLines="allNA", ref=4) #' #' @export filterLiColDeList <- function(lst, useLines, useCols=NULL, ref=1, silent=FALSE, callFrom=NULL, debug=FALSE) { ## filter all list-elements matching number of lines from the 'ref'-th list-element ## 'ref' .. designs list-element where number of rows will be compared to other list-elements to decide which list-elements (have same number of rows and thus) will be filtered fxNa <- .composeCallName(callFrom, newNa="filterLiColDeList") msg <- "invalid argument 'ref' (should be index to existing element of 'lst')" doFilt <- TRUE chLe <- c(lst=length(lst), useLines=length(useLines), ref=length(ref)) if(any(chLe <0)) doFilt <- FALSE if(doFilt) { if(length(ref) >1) { warning("'ref' should be of length=1 (ie only ONE reference) ! Reducing to first .."); ref <- ref[1]} if(ref > length(lst)) stop(msg) dims <- lapply(lst, dim) ## filter lines if(length(useLines) >0) { if(identical(useLines,"allNA")) { chFormat <- length(dim(lst[[ref]])) >1 if(!chFormat) { lst[[ref]] <- as.matrix(lst[[ref]]) message(fxNa,"It appears lst[[ref]] is not matrix (or data.frame) ! Trying to reformat ..") dims <- lapply(lst, dim) # update } useLines <- rowSums(is.na(lst[[ref]])) < ncol(lst[[ref]]) } if(debug) {message(fxNa," fLCL1"); fLCL1 <- list(lst=lst,useLines=useLines,useCols=useCols,ref=ref,dims=dims,useLines=useLines) } if(is.logical(useLines)) { # convert logical argument to index ch <- identical(length(useLines), dims[[ref]][1]) if(!ch && !silent) message(fxNa,"Problem/ignoring filtering lines : 'useLines' is of le length ",length(useLines)," but expecting ",dims[[ref]][1]," !") useLines <- if(ch) which(useLines) else NULL } if(is.numeric(useLines)) { useLines <- naOmit(useLines) if(min(useLines) <1 || max(useLines) > dims[[ref]][1]) { if(!silent) message(fxNa,"'useLines' may not design lines higher than number of lines in ref, neither may not be negative") useLines <- NULL } } if(debug) {message(fxNa," fLCL2"); fLCL2 <- list() } if(length(useLines) >0 && identical(length(useLines), dims[[ref]][1])) { if(!silent) message(fxNa,"'useLines' seems empty, nothing to do ...") } else { useEl <- sapply(dims, function(x) if(length(x) >1) x[1] else 0) == dims[[ref]][1] # compare to ref if(any(useEl)) for(i in which(useEl)) {lst[[i]] <- if(length(dims[[i]])==2) lst[[i]][useLines,] else lst[[i]][useLines,,]} if(!silent) message(fxNa,"successfully filtered ",pasteC(names(lst)[which(useEl)],quoteC="'")," from ",dims[[ref]][1]," to ",length(useLines)," lines") } ## check for single vectors matching nrow of ref (as long nrow not equal ncol of ref) chV <- sapply(dims, length)==0 & dims[[ref]][1]==dims[[ref]][2] if(any(chV)) { chV <- which(chV) chL <- sapply(lst[chV], length) == dims[[ref]][1] if(any(chL)) for(i in which(chL)) {lst[[i]] <- lst[[i]][useLines]} } if(debug) {message(fxNa," fLCL2b"); fLCL2b <- list() } } if(debug) {message(fxNa," fLCL3"); fLCL3 <- list(lst=lst,useLines=useLines,useCols=useCols,ref=ref,doFilt=doFilt) } ## filter columns if(length(useCols) >0) { if(is.logical(useCols)) { ch <- length(useCols) == dims[[ref]][2] useLines <- if(ch) which(useCols) else NULL } if(debug) {message(fxNa," fLCL4a"); fLCL4a <- list(lst=lst,useLines=useLines,useCols=useCols,ref=ref,doFilt=doFilt,useCols=useCols) } if(is.numeric(useCols)) { useCols <- naOmit(useCols) if(min(useCols) <1 || max(useCols) > dims[[ref]][2]) { if(!silent) message(fxNa,"'useCols' may not design columns higher than number of columns in ref, neither may not be negative") useCols <- NULL } } if(debug) {message(fxNa," fLCL4b"); fLCL4b <- list() } if(length(useCols) >0 && length(useCols)==dims[[ref]][2]) { if(!silent) message(fxNa,"'useCols' seems empty, nothing to do ...") } else { useEl <- sapply(dims, function(x) if(length(x) >1) x[2] else 0) == dims[[ref]][2] if(any(useEl)) for(i in which(useEl)) {message(fxNa,"i=",i); lst[[i]] <- if(length(dims[[i]])==2) lst[[i]][,useCols] else lst[[i]][,useCols,]} if(!silent) message(fxNa,"successfully filtered ",pasteC(names(lst)[which(useEl)],quoteC="'")," from ",dims[[ref]][2]," to ",length(useCols)," columns") } if(debug) {message(fxNa," fLCL4c"); fLCL4c <- list() } ## check for single vectors matching ncol of ref (as long nrow not equal ncol of ref) chV <- sapply(dims, length)==0 & dims[[ref]][1]==dims[[ref]][2] if(any(chV)) { chV <- which(chV) chL <- sapply(lst[chV], length) == dims[[ref]][2] if(any(chL)) for(i in which(chL)) {lst[[i]] <- lst[[i]][useCols] } } } } else if(!silent) message(fxNa,"Incomplete data - nothing to do; either 'lst','useLines' or 'ref' is empty !") lst }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/filterLiColDeList.R
#' Filter for unique elements #' #' This function aims to apply a given filter-citerium, a matrix or vector of \code{FALSE/TRUE} which is typically combined with a second layer #' which filters for a min content of filer-passing values per line for the first/main criterium. #' Then all lines concerned will be removed. This will be done for all list-elements (of appropriate size) of the input-list #' (while maintaining the list-structure in the output) not matching the filtering criteria. #' #' @param lst (list) main input, each vector, matrix or data.frame in this list will be filtered if its length or number of lines fits to \code{filt} #' @param filt (logical) vector of \code{FALSE/TRUE} to use for filtering. If this a matrix is given, the value of \code{minLineRatio} will be applied as threshod of min content of \code{TRUE} for each line of \code{filt} #' @param minLineRatio (numeric) in case \code{filt} is a matrix of \code{FALSE/TRUE}, this value will be used as threshold of min content of \code{TRUE} for each line of \code{filt} #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of message(s) produced #' @return filtered list #' @seealso \code{\link{correctToUnique}}, \code{\link[base]{unique}}, \code{\link[base]{duplicated}}, \code{\link{extrColsDeX}} #' @examples #' 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) #' filterList(list1, list1$m1[,1] >0.4) #' filterList(list1, list1$m1 >0.4) #' @export filterList <- function(lst,filt,minLineRatio=0.5,silent=FALSE,callFrom=NULL) { ## adjust all elements of lst to filtering ## minLineRatio (numeric) min ratio of columns where ## assumes that all elements of lst are in correct order ! fxNa <- .composeCallName(callFrom, newNa="filterList") if(length(filt) <1) stop(" 'filt' seems to empty") if(length(dim(filt)) >1) { if(length(minLineRatio) <1 | !is.numeric(minLineRatio)) { minLineRatio <- 0.5 if(!silent) message(fxNa," argument 'minLineRatio' must be numeric ! Setting to default (0.5)")} filt <- rowSums(filt) >= ncol(filt)*minLineRatio } chFi <- sub("(TRUE)|(FALSE)|T|F","",filt) if(any(nchar(chFi) >0)) stop(" 'filt' contains non-logical elements") if(is.logical(filt)) filt <- as.logical(filt) if(all(!filt)) stop("nothing passes filtering") ## main if(any(!filt)) { nFilt <- length(filt) filt <- which(filt) lstDim <- lapply(lst, dim) chLst <- sapply(lstDim,length) ==2 msg <- c(" element '","' : "," not suitable for filter") ## filter all matrix & data.frames if(any(chLst)) { for(i in which(chLst)) if(nrow(lst[[i]]) ==nFilt) { lst[[i]] <- if(length(filt) >1 & length(dim(lst[[i]])) >1) lst[[i]][filt,] else { matrix(lst[[i]][filt,],ncol=ncol(lst[[i]]),dimnames=list(rownames(lst[[i]])[filt],colnames(lst[[i]]))) } } else { if(!silent) message(fxNa,msg[1],names(lst)[i],msg[2],"number of lines",msg[3]) }} ## filter all vectors chLst <- sapply(lstDim,length) ==1 if(any(chLst)) { for(i in which(chLst)) if(nrow(lst[[i]]) ==nFilt) lst[[i]] <- lst[[i]][filt] else { if(!silent) message(fxNa,msg[1],names(lst)[i],msg[2],"length of vector",msg[3]) }} } else if(!silent) message(fxNa,"all elements pass filter (nothing to remove)") lst }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/filterList.R
#' Filter nodes & edges for extracting networks #' #' This function allows extracting and filtering network-data based on fixed threshold (\code{limInt}) and add sandwich-nodes (nodes inter-connecting initial nodes) out of node-based queries. #' #' #' @param lst (list, composed of multiple matrix or data.frames ) main input (each list-element should have same number of columns) #' @param filtCol (integer, length=1) which column of \code{lst} should be usd to filter using thresholds \code{limInt} and \code{sandwLim} #' @param limInt (numeric, length=1) filter main edge-scores according to \code{filterAsInf} #' @param sandwLim (numeric, length=1) filter sandwich connection edge-scores accodring to \code{filterAsInf} #' @param filterAsInf (logical) filter as 'inferior or equal' or 'superior or equal' #' @param outFormat (character) may be 'matrix' for tabular output, 'all' as list with matrix and list of node-names #' @param remOrphans (logical) remove networks consisting only of 2 connected edges #' @param remRevPairs (logical) remove duplicate edges due to reverse massping (eg A - B and B - A); NOTE : use only when edges don't have orientation ! #' @param elemNa (character) used only for messages #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of message(s) produced #' @param debug (logical) display additional messages for debugging #' @return This function returns a matrix or data.frame #' @seealso in \code{\link[base]{cbind}} #' @examples #' #' 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) ) #' #' lst2 <- list('121'=data.frame(ID=as.character(c(141,221,228,229,449)),11:15, 21:25), #' '131'=data.frame(ID=as.character(c(228,331,332,333,339)),11:15, 21:25), #' '141'=data.frame(ID=as.character(c(121,151,229,339,441,442,449)), c(11:17), 21:27), #' '151'=data.frame(ID=as.character(c(449,141,551,552)), 11:14, 21:24), #' '161'=data.frame(ID=as.character(171), 11,21), '171'=data.frame(ID=as.character(161), 11,21), #' '181'=data.frame(ID=as.character(881:882), 11:12,21:22) ) #' #' (te1 <- filterNetw(lst2, limInt=90, remOrphans=FALSE)) #' (te2 <- filterNetw(lst2, limInt=90, remOrphans=TRUE)) #' #' (te3 <- filterNetw(lst2, limInt=13, remOrphans=FALSE)) #' (te4 <- filterNetw(lst2, limInt=13, remOrphans=TRUE)) #' #' #' @export filterNetw <- function(lst, filtCol=3, limInt=5000, sandwLim=5000, filterAsInf=TRUE, outFormat="matrix", remOrphans=TRUE, remRevPairs=TRUE, elemNa="genes", silent=FALSE, callFrom=NULL, debug=FALSE) { ## fxNa <- .composeCallName(callFrom, newNa="filterNetw") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(any(sapply(c("mat","matr","matrix","all"), identical, outFormat))) {asMatrix <- TRUE} else {asMatrix <- FALSE} if(length(names(lst)) <1) stop("Invalid format of 'lst' : has NO names") ## check input list for duplicate queries lstNa <- names(lst) chDu <- duplicated(lstNa, fromLast=FALSE) if(any(chDu)) { lst <- lst[-1*which(chDu)] if(!silent) message(fxNa,"Entry has ",sum(chDu)," duplicate entry-names, removing duplicates") lstNa <- names(lst) } # update useID <- list(query=lstNa) if(debug) {message(fxNa,"fiNe1 passed ini check")} ## check format ch2dim <- sapply(lapply(lst, dim), length) ==2 ## remove any non-matrix or data.frame if(any(!ch2dim)) { if(all(!ch2dim)) {lst <- list(); chDim <- NULL; warning(fxNa,"Invalid input, should be list of matrixes or data.frames !!") } else { lst <- lst(which(ch2dim)) chDim <- lapply(lst, dim) # update if(!silent) message(fxNa,"Note: ",sum(!ch2dim)," out of ",length(ch2dim)," list-elements are not matrix or data.frame, removing") } } else chDim <- lapply(lst, dim) colNa <- colnames(lst[[1]]) if(debug) {message(fxNa,"fiNe2, passed remove any non-matrix or data.frame")} ## check if add'l column for quality/intensity data available chQ <- sapply(lst, function(x) ncol(x) >1) ## check filtCol argument (assume format of lst as checked) msg <- "Invalid entry for 'filtCol': should be integer (of length=1) to designate which column to use or column-name" if(length(filtCol) <1) {if(ncol(lst[[1]]) >1) {filtCol <- 2; message(fxNa,msg,"; setting to 2")} else stop(msg," -too short")} if(length(filtCol) >1) {filtCol <- filtCol[1]; message(fxNa,msg," -use 1st")} if(!is.numeric(filtCol)) {filtCol <- which(colnames(lst[[1]])==filtCol) if(length(filtCol) <1) {filtCol <- 2; message(fxNa, msg,"; setting to 2")} } else { if(filtCol > ncol(lst[[1]]) | filtCol <2) { filtCol <- 2; message(fxNa, msg,"; setting to 2")} } ## check input format if filtering can be applied (reset 'limInt' to NULL if can't be used) if(length(limInt)==1 && is.numeric(limInt) && !any(is.na(limInt))) { # valid threshod for filtering chDimQ <- all(sapply(chDim, function(x) x[2]) >1) if(!chDimQ) { limInt <- sandwLim <- NULL if(!silent) message(fxNa,"Data have no second column with numeric data for filtering, ignoring 'limInt' and 'sandwLim'") } } else limInt <- NULL if(debug) message(fxNa,"fiNe3, check input format if filtering can be applied") ## check if reverse-(direct)mapping has same score - only if .filterNetw is not launched (.filterNetw does this check, too) if(remRevPairs && !asMatrix && all(chQ)) { # run only if no conversion to matrix, otherwise do this check after lrbind() sepCha <- "__" chRe <- cbind(pri=rep(names(lst), sapply(lst,nrow)), sec=lrbind(lst) ) chR2 <- paste(chRe[,2], chRe[,1], sep=sepCha) %in% paste(chRe[,1], chRe[,2], sep=sepCha) if(any(chR2)) { if(!all(chR2)) chRe <- chRe[which(chR2),] # data with any reverse mapping only tmp <- apply(as.matrix(chRe[,1:2]), 1, function(x) paste(sort(x), sep=sepCha)) tmp <- paste(tmp[1,], tmp[2,], sep=sepCha) if(debug) {message(fxNa,"fiNe4, opional check if reverse-(direct)mapping has same score")} tmp2 <- by(as.matrix(chRe), tmp, function(x) length(unique(x[,3])) ==1) if(any(!tmp2)) warning(fxNa,"Reverse value for ",sum(!tmp2)," pairs incoherent !! (", pasteC(sub(sepCha,"& ", names(tmp2)[utils::head(which(!tmp2))])),")") } } ## filter all for thresh limInt, subseq filter sandwLim, establish list of all connected nodes if(all(chQ) && length(limInt)==1 && is.numeric(limInt) && !any(is.na(limInt))) { # valid threshod for filtering lst <- lapply(lst, function(x) x[which(if(!isFALSE(filterAsInf)) x[,filtCol] <= limInt else x[,filtCol] >= limInt),]) chDi <- sapply(lst, function(x) length(dim(x)) <2) if(any(chDi)) lst[which(chDi)] <- lapply(lst[which(chDi)], function(x) matrix(x, nrow=1, dimnames=list(NULL,colNa))) # reset to matrix-type if lost at filtering chN <- sapply(lst, length) if(all(chN <1)) warning(fxNa,"NOTHING remaining after filtering for 'limInt'=",limInt," !!") if(debug) {message(fxNa,"fiNe5, filter all for thresh limInt")} ## now check for possible sandwLim filter if(any(sapply(c("def","default","auto"), identical, sandwLim))) sandwLim <- limInt if(length(sandwLim)!=1 | !is.numeric(sandwLim) | any(is.na(sandwLim))) sandwLim <- NULL if(debug) { message(fxNa,"fiNe6, check for possible sandwLim filter")} } else sandwLim <- NULL ## extract 2nd nodes, apply sandwLim (if applicable) lst <- lapply(lst, function(x) if(length(sandwLim) <1 || ncol(x) <2) x[which(x[,1] %in% useID$query),] else x[which(x[,1] %in% useID$query | if(!isFALSE(filterAsInf)) x[,filtCol] <= sandwLim else x[,filtCol] >= sandwLim ),]) chDi <- sapply(lst, function(x) length(x) >0 && length(dim(x)) <2) # in case of list of matrixes, some may become simple vectors due to indexing if(any(chDi)) lst[which(chDi)] <- lapply(lst[which(chDi)], function(x) matrix(x, nrow=1, dimnames=list(NULL,colNa))) # reset to matrix-type if lost at filtering all2nd <- unlist(lapply(lst, function(x) x[,1]), use.names=FALSE) # extr 2nd node IDs (after add'l filtering) if(debug) {message(fxNa,"fiNe7, extracting 2nd nodes, apply sandwLim")} ## remove empty (due to filtering) chLe <- sapply(lst, length) >0 if(any(!chLe)) { lst <- lst[which(chLe)] if(all(!chLe)) { if(!silent) message(fxNa,"NOTHING remaining after filtering !!") } else if(!silent) message(fxNa,"Removed ",sum(!chLe)," out of ",length(chLe)," queries without data passing filtering") lstNa <- names(lst) # update useID <- list(query=lstNa) # update } ## look for Sandwich nodes/genes useID$sandwID <- NULL ## a sandwich node/gene has too aoocur at min 2x in query-results (and may not be part of init query) chDup <- duplicated(all2nd, fromLast=FALSE) & !(all2nd %in% lstNa) # needed to be defined as sandwich useID$sandwID <- if(any(chDup)) unique(all2nd[which(chDup)]) else NULL if(debug) {message(fxNa,"fiNe8, sandwich nodes/genes")}; fiNe8 <- list(lst=lst,all2nd=all2nd,useID=useID,chDup=chDup,chLe=chLe,filtCol=filtCol, limInt=limInt,chQ=chQ) ## filter to keep connected network only (and reduce all to IDs & filtCol) useID2 <- if(length(limInt) ==1) unique(unlist(useID)) else useID$query lst <- lapply(lst, function(x) {y <- which(x[,1] %in% useID2); if(length(y) >0) {if(length(y) >1) x[y,c(1,filtCol)] else { z <- data.frame(x[y,1], x[y,filtCol]); colnames(z) <- colnames(x)[c(1,filtCol)]; z} }}) chLe <- sapply(lst, length) if(any(chLe <1)) { lst <- lst[which(chLe >0)] if(!silent) message(fxNa,"",sum(chLe <1)," element(s) had no data remaining after filtering ..." ) } if(debug) {message(fxNa,"fiNe9, filter to keep connected network only")} if(length(lst) <1) message(fxNa,"NOTE: NOTHING remaining after filtering for connected networks ") else { if(!isFALSE(asMatrix)) { ## convert to matrix, remove duplicates lst <- .filterNetw(lst, remOrphans=remOrphans, reverseCheck=remRevPairs, filtCol=filtCol, callFrom=fxNa, silent=silent, debug=debug) isSandw <- lst[,2] %in% useID$sandwID lst <- cbind(lst, toSandw=if(is.data.frame(lst)) isSandw else as.numeric(isSandw)) if(!isFALSE(remRevPairs)) { te1x <- apply(as.matrix(lst[,c(1,filtCol)]), 1, sort) ## need to sort le/ri !! lst <- lst[which(!duplicated(paste(te1x[1,], te1x[2,]), fromLast=FALSE)),] # corrected for duplicate pairs } } else { ## prepare output as list lst <- lapply(lst, function(x) {ch1 <- x[,1] %in% unlist(useID) if(sum(ch1) >0) { if(sum(ch1) >0) x[which(ch1),] else matrix(x[which(ch1),], nrow=1, dimnames=list(NULL, colnames(x)))} else NULL }) if(!silent) message(fxNa,"Network of ",sum(useID$query %in% lstNa)," (init) ",elemNa," plus ", sum(useID$sandwID %in% lstNa)," sandw-",elemNa ) # } } if(any(sapply(c("all"), identical, outFormat))) lst <- list(useID=useID, netw=lst) lst } #' Filter nodes & edges for extracting networks (main) #' #' This function allows extracting and filtering network-data based on fixed threshold (\code{limInt}) and add sandwich-nodes (nodes inter-connecting initial nodes) out of node-based queries. #' #' #' @param lst (list, composed of multiple matrix or data.frames ) main input (each list-element should have same number of columns) #' @param remOrphans (logical) remove networks consisting only of 2 connected edges #' @param reverseCheck (logical) #' @param filtCol (integer, length=1) which column of \code{lst} should be usd to filter using thresholds \code{limInt} and \code{sandwLim} #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of message(s) produced #' @param debug (logical) display additional messages for debugging #' @return This function returns a matrix or data.frame #' @seealso \code{\link{filterNetw}} and other CRAN package dedeicated to networks #' @examples #' ab <- 1:10 #' @export .filterNetw <- function(lst, remOrphans=TRUE, reverseCheck=TRUE, filtCol=2, callFrom=NULL, silent=FALSE, debug=FALSE) { ## fxNa <- .composeCallName(callFrom, newNa=".filterNetw") sepCha <- "__" # characters used in paste when fusing 2 nodes lstLe <- sapply(lst, nrow) names(lstLe) <- names(lst) ## transform list to matrix/data.frame lst <- lrbind(lst, silent=TRUE) if(any(dim(lst) <1) && length(dim(lst)) <2) stop("Invalid input format ! Bizzare, lrbind() did NOT manage to produce a matrix or data.frame") colnames(lst)[1] <- "Node2" if(ncol(lst) >1) colnames(lst)[2] <- "edgeScore" lst <- data.frame(Node1=rep(names(lstLe), lstLe), lst) if(debug) {message(fxNa,".fiNe.1 transform list to matrix/data.frame")} ## check for (reverse-)pairs chR2 <- paste(lst[,filtCol], lst[,1], sep=sepCha) %in% paste(lst[,1], lst[,filtCol], sep=sepCha) if(any(chR2)) { chRe <- if(!all(chR2)) lst[which(chR2),] else lst # data with any reverse mapping only tmp <- apply(as.matrix(chRe[,1:2]), 1, function(x) paste(sort(x), sep=sepCha)) # pairs of sorted nodes tmp <- paste(tmp[1,], tmp[2,], sep=sepCha) names(tmp) <- rownames(chRe) ## check for consistent score with reverse pairs if(reverseCheck && ncol(lst) >2) { tmp2 <- by(as.matrix(chRe), tmp, function(x) length(unique(x[,3])) ==1) if(any(!tmp2)) warning(fxNa,"Reverse value for ",sum(!tmp2)," pairs incoherent !! (", pasteC(sub(sepCha,"& ", names(tmp2)[utils::head(which(!tmp2))])),")") } if(debug) {message(fxNa,".fiNe.2 check for consistent score with reverse pairs")} ## remove duplicates (ie remove 2nd occurance due to reverse pairs) dupP <- duplicated(tmp, fromLast=FALSE) if(any(dupP)) {lst <- lst[-1*as.integer(names(tmp)[which(dupP)]),] if(!silent) message(fxNa,"Removing ",sum(dupP)," (reverse) redundant mappings")} } if(debug) {message(fxNa,".fiNe.3 remove duplicates")} ## lstN <- c(as.character(lst[,1]), as.character(lst[,2])) if(remOrphans) { ## need number of connections to decide on low-connected chNo <- duplicated(lstN, fromLast=TRUE) if(any(chNo)) { chNo2 <- chNo | duplicated(lstN, fromLast=FALSE) if(debug) {message(fxNa,".fiNe.4 number of connections to decide on low-connected")} if(!all(chNo2)) { hiNo <- unique(lstN[which(chNo2)] ) ## which pairs of connections to keep (any node connected to a hiNo ?) chLi <- rowSums(matrix(lstN %in% hiNo, ncol=2)) >0 if(all(!chLi) & !silent) warning(fxNa,"NONE of the nodes has any further connections, argument 'remOrphans' removes everything") lst <- lst[which(chLi),] if(debug) {message(fxNa,".fiNe.5 which pairs of connections to keep")} } } } ## rownames(lst) <- 1:nrow(lst) lstN <- unique(c(as.character(lst[,1]), as.character(lst[,2]))) lst }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/filterNetw.R
#' Find close numeric values between two vectors #' #' \code{findCloseMatch} finds close matches (similar values) between two numeric vectors ('x','y') based on method 'compTy' and threshold 'limit'. #' Return list with close matches of 'x' to given 'y', the numeric value dependes on 'sortMatch' (if FALSE then always value of 'y' otherwise of longest of x&y). #' Note: Speed & memory improvement if 'sortMatch'=TRUE (but result might be inversed!): adopt search of x->y or y->x to searching matches of each longest to each shorter (ie flip x &y). #' Otherwise, if length of 'x' & 'y' are very different, it may be advantagous to use a long(er) 'x' and short(er) 'y' (with 'sortMatch'=FALSE). #' Note: Names of 'x' & 'y' or (if no names) prefix letters 'x' & 'y' are always added as names to results. # ' Note: Takes much RAM if x & y are large #' #' @param x numeric vector for comparison #' @param y numeric vector for comparison #' @param compTy (character) may be 'diff' or 'ppm', will be used with threshold from argument 'limit' #' @param limit (numeric) threshold value for retaining values, used with distace-type specified in argument 'compTy' #' @param asIndex (logical) optionally rather report index of retained values #' @param maxFitShort (numeric) limit output to max number of elements (avoid returning high number of results if filtering was not enough stringent) #' @param sortMatch (logical) if TRUE than matching will be preformed as 'match longer (of x & y) to closer', this may process slightly faster (eg 'x' longer: list for each 'y' all 'x' that are close, otherwise list of each 'x'), #' @param silent (logical) suppress messages #' @param debug (logical) display additional messages for debugging #' @param callFrom (character) allow easier tracking of message(s) produced #' @return This function returns a list with close matches of 'x' to given 'y', the numeric value dependes on 'sortMatch' (if FASLE then always value of 'y' otherwise of longest of x&y) #' @seealso \code{\link{checkSimValueInSer}} and (from this package) \code{.compareByDiff}, for convient output \code{\link{countCloseToLimits}} #' @examples #' aa <- 11:14 ; bb <- c(13.1,11.5,14.3,20:21) #' findCloseMatch(aa,bb,com="diff",lim=0.6) #' findCloseMatch(c(a=5,b=11,c=12,d=18),c(G=2,H=11,I=12,J=13)+0.5, comp="diff", lim=2) #' findCloseMatch(c(4,5,11,12,18),c(2,11,12,13,33)+0.5, comp="diff", lim=2) #' findCloseMatch(c(4,5,11,12,18),c(2,11,12,13,33)+0.5, comp="diff", lim=2, sort=FALSE) #' .compareByDiff(list(c(a=10,b=11,c=12,d=13),c(H=11,I=12,J=13,K=33)+0.5),limit=1) #' return matrix #' #' a2 <- c(11:20); names(a2) <- letters[11:20] #' b2 <- c(25:5)+c(rep(0,5),(1:10)/50000,rep(0,6)); names(b2) <- LETTERS[25:5] #' which(abs(b2-a2[8]) < a2[8]*1e-6*5) #' find R=18 : no10 #' findCloseMatch(a2, b2, com="ppm", lim=5) #' find Q,R,S,T #' findCloseMatch(a2, b2, com="ppm", lim=5,asI=TRUE) #' find Q,R,S,T #' findCloseMatch(b2, a2, com="ppm", lim=5,asI=TRUE,sort=FALSE) #' findCloseMatch(a2, b2, com="ratio", lim=1.000005) #' find Q,R,S,T #' findCloseMatch(a2, b2, com="diff", lim=0.00005) #' find S,T #' @export findCloseMatch <- function(x, y, compTy="ppm", limit=5, asIndex=FALSE, maxFitShort=100, sortMatch=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom,newNa="findCloseMatch") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE compMeth <- c("ppm","diff","ratio") msg <- c(paste("argument 'compTy' may be one of",pasteC(compMeth,qu="'",la=" or "))," , trimming to length=1") if(length(compTy) <1) stop(msg[1]) else if(length(compTy)>1) {compTy <- compTy[1]; message(msg)} if(!compTy %in% compMeth) stop(msg[1]) if(is.null(names(x))) names(x) <- paste0("x",equLenNumber(1:length(x))) # need default names to know which of 'x' in results ! if(is.null(names(y))) names(y) <- paste0("y",equLenNumber(1:length(y))) # if(any(names(x) %in% names(y))) message(fxNa,"Note that some names do overlap (beware not to confuse...) !") dat <- list(x,y) if(sortMatch) dat <- dat[order(sapply(dat,length), decreasing=FALSE)] if(is.character(maxFitShort)) if(length(grep("%$", maxFitShort)) >0) { maxFitShort <- ceiling(length(dat[[1]])*as.numeric(sub("%$","",maxFitShort))/100) } else stop("can't interpret 'maxFitShort'") tm2 <- switch(compTy, ppm=.compareByPPM(dat, limit, distVal=!asIndex), diff=.compareByDiff(dat, limit, distVal=!asIndex), ratio=.compareByLogRatio(dat, limit, distVal=!asIndex)) if(debug) {message(fxNa,"fCM1")} cSu <- colSums(!is.na(tm2)) cPi <- which(cSu >0) if(length(cPi) <1) return(NULL) else { if(any(cSu > maxFitShort)) { # case of fitting close to (very) large number of elements -> keep maxFitShort lowest (+ set others to NA) if(!silent) message(fxNa,sum(cSu > maxFitShort,na.rm=TRUE)," column elements at too many 'close elements' try to reduce ..") for(i in 1:which(cSu > maxFitShort)) {limDis <- sort(tm2[,i], decreasing=TRUE, na.last=TRUE)[maxFitShort] tmX <- which(tm2[,i] <= limDis) if(nrow(tm2) > maxFitShort && length(tmX) >= min(maxFitShort*1.15, floor(nrow(tm2)*0.96))) tm2[,i] <- NA else tm2[which(tm2[,i] >limDis),i] <- NA} cPi <- which(colSums(!is.na(tm2)) >0) # refresh } if(debug) {message(fxNa,"fCM2")} rSu <- rowSums(!is.na(tm2)) if(any(rSu > maxFitShort)) { # case of fitting close to (very) large number of elements -> keep maxFitShort lowest (+ set others to NA) if(!silent) message(fxNa,sum(rSu > maxFitShort ,na.rm=TRUE)," row elements at too many 'close elements' try to reduce ..") for(i in 1:which(rSu > maxFitShort)) {limDis <- sort(tm2[i,],decreasing=TRUE,na.last=TRUE)[maxFitShort] tmY <- which(tm2[i,] <= limDis) if(ncol(tm2) > maxFitShort & length(tmY) >= min(maxFitShort*1.15,floor(ncol(tm2)*0.96))) tm2[i,] <- NA else tm2[i,which(tm2[i,] >limDis)] <- NA} rPi <- which(rowSums(!is.na(tm2)) >0) # refresh (rows with some distance values) } else rPi <- which(rSu >0) if(debug) {message(fxNa,"fCM3")} zz <- if(nrow(tm2) >1) as.matrix(tm2[,cPi])[rPi,] else matrix(tm2[,cPi], nrow=1, dimnames=list(rownames(tm2),colnames(tm2)[cPi])) if(length(dim(zz)) <2) zz <- matrix(zz, nrow=length(rPi)) if(is.null(colnames(zz)) || is.null(rownames(zz))) dimnames(zz) <- list(rownames(tm2)[rPi], colnames(tm2)[cPi]) out <- if(asIndex) {if(length(cPi) >1) apply(!is.na(zz), 2, which) else which(!is.na(zz)) #list of indexes dat,function(z) which(z)) } else {if(length(cPi) >1) apply(zz, 2, naOmit) else naOmit(zz)} if(!is.list(out)) {out <- as.list(out); zn <- rownames(zz)[apply(!is.na(zz),2,which)]; for(j in 1:length(out)) names(out[[j]]) <- zn[j]} if(is.null(names(out))) names(out) <- rep(names(cPi), length(out))[1:length(out)] out }} #' Compare by PPM #' #' This function allows to compare by ppm #' #' @param dat list of 2 numerical vectors #' @param limit (numeric, length=1) threshold value for retaining values, used with distace-type specified in argument 'compTy' #' @param distVal (logical) to toggle outpout as matrix of numeric (distance values above 'limit', others NA) or matrix of logical #' @return This function returns a list with close matches of 'x' to given 'y', the numeric value dependes on 'sortMatch' (if FASLE then always value of 'y' otherwise of longest of x&y) #' @seealso \code{\link{findCloseMatch}}, \code{\link{checkSimValueInSer}}, and also \code{.compareByDiff}, for convient output \code{\link{countCloseToLimits}} #' @examples #' cc <- list(aa=11:14, bb=c(13.1,11.5,14.3,20:21)) #' .compareByPPM(cc, 1) #' @export .compareByPPM <- function(dat, limit, distVal=FALSE){ ## compare both vectors from list 'dat' for similar values based on ppm ## 'dat' .. list of 2 numerical vectors ## 'distVal'.. (logical) to toggle outpout as matrix of numeric (distance values above 'limit', others NA) or matrix of logical ## 'limit'.. (numeric, length=1) threshold to be applied ## return logical matrix with rows for 1st & cols for 2nd element of dat (used in findCloseMatch() ) ref <- matrix(rep(dat[[1]],each=length(dat[[2]])), nrow=length(dat[[2]]), dimnames=list(names(dat[[2]]),names(dat[[1]]))) # matr of short que <- matrix(rep(dat[[2]],length(dat[[1]])), nrow=length(dat[[2]]), dimnames=list(names(dat[[2]]),names(dat[[1]]))) if(distVal) {tm2 <- (2*(que <= ref) -1)*abs(que/ref -1)/1e-6; tm2[which(!abs(que/ref -1) < limit*1e-6)] <- NA } else tm2 <- abs(que/ref -1) < limit*1e-6 tm2 } #' Compare by log-ratio #' #' This function allows to compare by log-ratio #' #' @param dat list of 2 numerical vectors #' @param limit (numeric, length=1) threshold value for retaining values, used with distace-type specified in argument 'compTy' #' @param distVal (logical) to toggle outpout as matrix of numeric (distance values above 'limit', others NA) or matrix of logical #' @return This function returns a list with close matches of 'x' to given 'y', the numeric value dependes on 'sortMatch' (if FASLE then always value of 'y' otherwise of longest of x&y) #' @seealso \code{\link{findCloseMatch}}, \code{\link{checkSimValueInSer}}, and also \code{.compareByDiff}, for convient output \code{\link{countCloseToLimits}} #' @examples #' cc <- list(aa=11:14, bb=c(13.1,11.5,14.3,20:21)) #' .compareByLogRatio(cc, 1) #' @export .compareByLogRatio <- function(dat, limit, distVal=FALSE){ ## compare both vectors from 'dat' for similar values based on (log)ratio ## 'dat' .. list of 2 numerical vectors ## 'distVal'.. (logical) to toggle outpout as matrix of numeric (distance values above 'limit', others NA) or matrix of logical ## 'limit'.. (numeric, length=1) threshold to be applied ## return logical matrix of (used in findCloseMatch() ) ref <- matrix(rep(dat[[1]], each=length(dat[[2]])), nrow=length(dat[[2]]), dimnames=list(names(dat[[2]]),names(dat[[1]]))) # matr of short que <- matrix(rep(dat[[2]], length(dat[[1]])), nrow=length(dat[[2]]), dimnames=list(names(dat[[2]]),names(dat[[1]]))) if(distVal) {tm2 <- abs(log2(ref/que)); tm2[which(!abs(log2(ref/que)) <= log2(abs(limit)))] <- NA } else tm2 <- abs(log2(ref/que)) <= log2(abs(limit)) tm2 } #' Compare by distance/difference #' #' This function allows to compare by distance/difference #' #' @param dat list of 2 numerical vectors #' @param limit (numeric, length=1) threshold value for retaining values, used with distace-type specified in argument 'compTy' #' @param distVal (logical) to toggle outpout as matrix of numeric (distance values above 'limit', others NA) or matrix of logical #' @return This function returns a list with close matches of 'x' to given 'y', the numeric value dependes on 'sortMatch' (if FASLE then always value of 'y' otherwise of longest of x&y) #' @seealso \code{\link{findCloseMatch}}, \code{\link{checkSimValueInSer}}, and also \code{.compareByLogRatio}, for convient output \code{\link{countCloseToLimits}} #' @examples #' cc <- list(aa=11:14, bb=c(13.1,11.5,14.3,20:21)) #' @export .compareByDiff <- function(dat, limit, distVal=FALSE){ ## compare both vectors from 'dat' for similar values based on (absolute) difference ## 'dat' .. list of 2 numerical vectors ## 'distVal'.. (logical) to toggle outpout as matrix of numeric (distance values above 'limit', others NA) or matrix of logical ## 'limit'.. (numeric, length=1) threshold to be applied ## return logical matrix of (used in findCloseMatch() ) ref <- matrix(rep(dat[[1]], each=length(dat[[2]])), nrow=length(dat[[2]]), dimnames=list(names(dat[[2]]),names(dat[[1]]))) # matr of short que <- matrix(rep(dat[[2]], length(dat[[1]])), nrow=length(dat[[2]]), dimnames=list(names(dat[[2]]),names(dat[[1]]))) if(distVal) { tm2 <- que-ref chLi <- abs(tm2) > abs(limit) if(any(chLi)) tm2[which(chLi)] <- NA } else tm2 <- abs(ref -que) <= abs(limit) tm2 }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/findCloseMatch.R
#' Find repeated elements #' #' \code{findRepeated} gets index of repeated items/values in vector 'x' (will be treated as character). #' Return (named) list of indexes for each of the repeated values, or \code{NULL} if all values are unique. #' This approach is similar but more basic compared to \code{\link{get1stOfRepeatedByCol}}. #' @param x character vector #' @param nonRepeated (logical) if \code{=TRUE}, return list with elements \code{$rep} and \code{$nonrep} #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of message(s) produced #' @return (named) list of indexes for each of the repeated values, or NULL if all values unique #' @seealso similar approach but more basic than \code{\link{get1stOfRepeatedByCol}} #' @examples #' aa <- c(11:16,14:12,14); findRepeated(aa) #' @export findRepeated <- function(x, nonRepeated=FALSE,silent=FALSE,callFrom=NULL) { y <- as.character(x) tab <- table(y) tab2 <- which(tab >1) if(length(tab2) >0){ out <- lapply(names(tab)[tab2],function(z) which(y %in% z)) # slightly faster than which(!is.na(match(y,z)))) names(out) <- x[sapply(out,utils::head,1)] # use initial value of repeated items as name } else out <- NULL if(nonRepeated) out <- list(rep=out,nonrep=match(names(tab)[which(tab <2)],y)) out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/findRepeated.R
#' Find similar numeric values from two vectors/matrixes #' #' \code{findSimilFrom2sets} compares to vectors or matrixes and returns combined view including only all close (by \code{\link[wrMisc]{findCloseMatch}}). #' Return matrix (predMatr) with add'l columns for index to and 'grp' (group of similar values (1-to-many)), 'nGrp' (n of grp), 'isBest' or 'nBest', 'disToMeas' #' (distance/difference between pair) & 'ppmToPred' (distance in ppm). #' Note: too wide 'limitComp' will result in large window and many 'good' hits will compete (and be mutually exlcuded) if selection 'bestOnly' is selected #' @param predMatr (matrix or numeric vector) dataset number 1, referred to as 'predicted', the colum speified in argument \code{colPre} points to the data to be used #' @param measMatr (matrix or numeric vector) dataset number 2, referred to as 'measured', the colum speified in argument \code{colMeas} points to the data to be used #' @param colMeas (integer) which column number of 'measMatr' to consider #' @param colPre (integer) which column number of 'predMatr' to consider #' @param compareTy (character) 'diff' (difference) 'ppm' (relative difference) #' @param limitComp (numeric) limit used by 'compareTy' #' @param bestOnly (logical) allows to filter only hits with min distance (defined by 'compareTy'), 3rd last col will be 'nBest' - otherwise 3rd last col 'isBest' #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of messages produced #' @param debug (logical) for bug-tracking: more/enhanced messages #' @return This function returns a matrix (predMatr) with add'l columns for index to and 'grp' (group of similar values (1-to-many)), 'nGrp' (n of grp), 'isBest' or 'nBest', 'disToMeas' (distance/difference between pair) & 'ppmToPred' (distance in ppm) #' @seealso \code{\link{checkSimValueInSer}} \code{\link{findCloseMatch}} \code{\link{closeMatchMatrix}} #' @examples #' 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) #' @export findSimilFrom2sets <- function(predMatr, measMatr, colMeas=1, colPre=1, compareTy="diff", limitComp=0.5,bestOnly=FALSE,silent=FALSE,callFrom=NULL,debug=FALSE){ fxNa <- .composeCallName(callFrom,newNa="findSimilFrom2sets") namesXY <- c(deparse(substitute(predMatr)), deparse(substitute(measMatr)), deparse(substitute(colPre)), deparse(substitute(colMeas))) ## check input predMatr <- .vector2Matr(predMatr,colNa=if(length(dim(predMatr)) >1) colnames(predMatr) else namesXY[1]) measMatr <- .vector2Matr(measMatr,colNa=if(length(dim(measMatr)) >1) colnames(measMatr) else namesXY[2]) badColNa <- c("dif","ppm","nInRange","isBest","nBest") fxCh <- function(colN, matr, argN=NULL) { if(is.character(colN)) { # check argument 'colN' as (character or number) to matrix 'matr', return numeric index msg <- c("Problem to ","find colname from ","locate number from "," reset to default=1") ch <- which(colN==colnames(matr)) if(length(ch) >0) ch[1] else {message(msg[1:2],argN,msg[4]); 1} } else {colN <- as.integer(colN); if(colN <1 || colN >ncol(matr)) {colN <- 1; message(msg[c(1,3)],argN,msg[4])} else colN}} colMeas <- fxCh(colMeas, measMatr, namesXY[4]) colPre <- fxCh(colPre, predMatr, namesXY[3]) if(length(badColNa) >0) if(any(badColNa %in% colnames(measMatr))) message(fxNa,"Problem with colnames of ",namesXY[2]) ## main prefMatch <- c("^x","^y") # fixed, since findCloseMatch() called wo initial names closeMatch <- findCloseMatch(as.numeric(predMatr[,colPre]), as.numeric(measMatr[,colMeas]), compTy=compareTy, limit=limitComp, sortMatch=FALSE, silent=silent, debug=debug, callFrom=fxNa) if(debug) {message(fxNa,"xxfindSimilFrom2sets2\n")} out <- closeMatchMatrix(closeMatch=closeMatch, predMatr=predMatr, measMatr=measMatr, prefMatch=prefMatch, colMeas=colMeas, colPred=colPre, limitToBest=bestOnly, callFrom=fxNa,debug=debug,silent=silent) if(!is.null(out)) { colnames(out)[1:ncol(predMatr)] <- colnames(predMatr) colnames(out)[1:ncol(measMatr) +ncol(predMatr) +1] <- colnames(measMatr) out <- out[order(out[,colPre]),]} # order by predicted out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/findSimilFrom2sets.R
#' Select groups within given range #' #' This function aims to help finding streches/segments of data with a given maximum number of NA-instances. # To do so, it searches independently each line of the input-matrix 'dat' for sretches with a given maximum of NA-instaces (\code{'maxNA'}. #' This function is used to inspect/filter each lines of 'dat' for a subset with sufficient presence/absence of NA values (ie limit number of NAs per level of 'grp'). #' Note : optimal perfomance with n.lines >> n.groups #' @param dat (matrix or data.frame) main input #' @param grp (factor) information which column of 'dat' is replicate of whom #' @param maxNA (interger) max number of tolerated NAs #' @param callFrom (character) allow easier tracking of message(s) produced #' @return matrix with boundaries of 1st and last usable column (NA if there were no suitable groups found) #' @examples #' dat1 <- matrix(1:56,nc=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 #' rownames(dat1) <- letters[1:nrow(dat1)] #' findUsableGroupRange(dat1,gl(3,3)[-(3:4)]) #' @export findUsableGroupRange <- function(dat,grp,maxNA=1,callFrom=NULL){ fxNa <- .composeCallName(callFrom,newNa="findUsableGroupRange") msg <- "expecting (2dim) numeric matrix or data.frame with >1 columns and >1 rows" if(length(dim(dat)) !=2) stop(msg) if(ncol(dat) <2) stop(msg) if(is.data.frame(dat)) dat <- as.matrix(dat) if(length(grp) != ncol(dat)) stop("Number of columns in 'dat' not matching levels of 'grp'") nGrp <- table(grp) nGrp <- nGrp[order(unique(grp))] if(length(nGrp) <2) stop(" too few levels in 'grp' !") if(any(nGrp <= maxNA)) stop(" some levels of 'grp' with too few instances !") ## main out <- ou2 <- rep(0,nrow(dat)) for(i in length(levels(grp)):1) { tmp <- dat[,which(grp==levels(grp)[i])] out[which(rowSums(is.na(tmp)) < maxNA)] <- i } for(i in 1:length(levels(grp))) { tmp <- dat[,which(grp==levels(grp)[i])] ou2[which(rowSums(is.na(tmp)) < maxNA)] <- i } out <- cbind(from=out,to=ou2) rownames(out) <- rownames(dat) out[which(out <1)] <- NA out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/findUsableGroupRange.R
#' Filter matrix to keep only first of repeated lines #' #' This function aims to reduce the complexity of a matrix (or data.frame) in case column 'refCol' has multiple lines with same value. #' In this case, it reduces the input-data to 1st line of redundant entries and returns a matrix (or data.frame) without lines identified as redundant entries for 'refCol'). #' in sum, this functions works lile useng \code{unique} on a given column, and propagates the same treatment to all other columns. #' @param dat (matrix or data.frame) main input #' @param refCol (integer) column number of reference-column #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return matrix (same number of columns as input) #' @seealso \code{\link{firstOfRepeated}}, \code{\link[base]{unique}}, \code{\link[base]{duplicated}} #' @examples #' (mat1 <- matrix(c(1:6,rep(1:3,1:3)),ncol=2,dimnames=list(letters[1:6],LETTERS[1:2]))) #' firstLineOfDat(mat1) #' @export firstLineOfDat <- function(dat, refCol=2, silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="firstLineOfDat") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE msg <- " expecting matrix or data.frame with >= 2 columns" if(length(dim(dat)) <2) stop(msg) if(ncol(dat) < 2) stop(" expecting matrix or data.frame with >= 2 columns") if(is.character(refCol)) refCol <- which(refCol==colnames(dat)) if(refCol > ncol(dat)) { if(!silent) message(fxNa," 'refCol' was set too high, reset to last column of 'dat'") refCol <- ncol(dat) } .getFirst <- function(x) x[1] # value at 1st position useCol <- (1:ncol(dat))[-1*refCol] useLi <- tapply(1:nrow(dat), as.factor(dat[,refCol]), .getFirst) out <- if(length(useLi) >1) dat[useLi,] else matrix(dat[useLi,], ncol=ncol(dat), dimnames=list(rownames(dat)[useLi],colnames(dat))) out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/firstLineOfDat.R
#' Reduce to first occurance of repeated lines #' #' This function concatenattes all columns of input-matrix and then searches like \code{unique} for unique elements, optionally the indexes of unique elements may get returned. #' Note: This function reats input as character (thus won't understand \code{10==10.0} ). #' Returns simplified/non-redundant vector/matrix (ie fewer lines), or respective index. #' faster than \code{\link{firstOfRepeated}} #' @param mat initial matrix to treat #' @param outTy for output type: 'ind'.. index to 1st occurance (non-red),'orig'..non-red lines of mat, 'conc'.. non-red concateneted values, 'num'.. index to which group/category the lines belong #' @param useCol (integer) custom choice of which columns to paste/concatenate #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return simplified/non-redundant vector/matrix (ie fewer lines for matrix), or respective index #' @seealso \code{\link[base]{unique}}, \code{\link{nonAmbiguousNum}}, faster than \code{\link{firstOfRepeated}} which gives more detail in output (lines/elements/indexes of omitted) #' @examples #' mat <- matrix(c("e","n","a","n","z","z","n","z","z","b", #' "","n","c","n","","","n","","","z"),ncol=2) #' firstOfRepLines(mat,out="conc") #' @export firstOfRepLines <- function(mat, outTy="ind", useCol=NULL, silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom,newNa="firstOfRepLines") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(length(dim(mat)) !=2) stop(" expecting matrix or data.frame with >1 lines") if(!outTy %in% c("ind","orig","conc","num","all")) outTy <- "ind" if(is.null(useCol)) useCol <- 1:ncol(mat) ch <- if(nrow(mat) >1) .pasteCols(mat[,useCol],sep="") else paste(mat,collapse="") dup <- duplicated(ch, fromLast=FALSE) switch(outTy, ind=which(!dup), # index to 1st occurance orig=mat[which(!dup),], # non-red lines of mat conc=ch[!dup], # 1st occurance of concatenated num=if(any(dup)) match(ch, ch[!dup]) else 1:length(ch), all=list(ind=which(!dup), conc=ch[!dup], num=if(any(dup)) match(ch,ch[!dup]) else 1:length(ch)))} #' Extract NA-neighbour values #' #' This function allows extracting NA-neighbour value #' @param x initial matrix to treat #' @param grp (factor) grouing of replicates #' @return snumeric vector #' @seealso \code{\link[base]{unique}}, \code{\link{nonAmbiguousNum}}, faster than \code{\link{firstOfRepeated}} which gives more detail in output (lines/elements/indexes of omitted) #' @examples #' .extrNAneighb(c(11:14,NA), rep(1,5)) #' @export .extrNAneighb <- function(x, grp){ ## extract values of numeric vector 'x' when NA in same group 'grp' ## (used for estimatating/replacing NA by low values) out <- NULL y <- 1:length(x) NAgr <- (grp)[which(is.na(x))] for(i in unique(NAgr)) out <- c(out, naOmit(x[which(grp==i)])) out } #' Paste-concatenate all columns of matrix #' #' This function allows paste columns #' @param mat inital matrix #' @param sep (character) separator #' @return simplified/non-redundant vector/matrix (ie fewer lines for matrix), or respective index #' @seealso \code{\link[base]{unique}}, \code{\link{nonAmbiguousNum}}, faster than \code{\link{firstOfRepeated}} which gives more detail in output (lines/elements/indexes of omitted) #' @examples #' .pasteCols(matrix(11:16,ncol=2), sep="_") #' @export .pasteCols <- function(mat, sep=""){ ## paste all columns if(!is.matrix(mat)) mat <- as.matrix(mat) if(ncol(mat)==1) return(mat) if(nrow(mat) > ncol(mat)){ out <- paste(mat[,1],mat[,2], if(ncol(mat) >2) mat[,3], if(ncol(mat) >3) mat[,4],sep=sep) if(ncol(mat) >4) for(i in 5:ncol(mat)) out <- paste(out,mat[,i]) } else out <- apply(mat, 1, paste, collapse=sep) names(out) <- rownames(mat) out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/firstOfRepLines.R
#' Find first of repeated elements #' #' This function works similar to \code{unique}, but provides additional information about which elements of original input \code{'x'} are repeatd by providing indexes realtoe to the input. #' \code{firstOfRepeated} makes list with 3 elements : $indRepeated.. index for first of repeated 'x', $indUniq.. index of all unique + first of repeated, $indRedund.. index of all redundant entries, ie non-unique (wo 1st). #' Used for reducing data to non-redundant status, however, for large numeric input the function nonAmbiguousNum() may perform better/faster. #' NAs won't be considered (NAs do not appear in reported index of results), see also firstOfRepLines() . #' @param x (charcter or numeric) main input #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of message(s) produced #' @param debug (logical) display additional messages for debugging #' @return list with indices: $indRepeated, $indUniq, $indRedund #' @seealso \code{\link[base]{duplicated}}, \code{\link{nonAmbiguousNum}}, \code{\link{firstOfRepLines}} gives less detail in output (lines/elements/indexes of omitted not directly accessible) and works fsster #' @examples #' x <- c(letters[c(3,2:4,8,NA,3:1,NA,5:4)]); names(x) <- 100+(1:length(x)) #' firstOfRepeated(x) #' x[firstOfRepeated(x)$indUniq] # only unique with names #' @export firstOfRepeated <- function(x, silent=FALSE, debug=FALSE, callFrom=NULL) { fxNa <- .composeCallName(callFrom,newNa="firstOfRepeated") chNA <- is.na(x) dupH <- duplicated(x, fromLast=FALSE) dupL <- duplicated(x, fromLast=TRUE) out <- list() out$indRepeated <- which(!dupH & dupL & !chNA) names(out$indRepeated) <- x[out$indRepeated] out$indUniq <- which(!dupH & !chNA) out$indRedund <- which(dupH | chNA) out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/firstOfRepeated.R
#' Fuse annotation matrix to initial matrix #' #' In a number of instances experimental measurements and additional information (annotation) are provided by separate objects (matrixes) as they may not be generated the same time. #' The aim of this function is provide help when matching approprate lines for 2 sets of data (experimental measures in \code{iniTab} and annotation from \code{annotTab}) for fusing. #' \code{fuseAnnotMatr} adds suppelmental columns/annotation to an initial matrix \code{iniTab} : using column 'refIniT' as key (in \code{iniTab}) to compare with key 'refAnnotT' (from 'annotTab'). #' The columns to be added from \code{annotTab} must be chosen explicitely. #' Note: if non-unique IDs in iniTab : runs slow (but save) due to use of loop for each unique ID. #' @param iniTab (matrix), that may have lines with multiple (=repeated) key entries #' @param annotTab (matrix) containing reference annotation #' @param refIniT (character) type of reference (eg 'Uniprot') #' @param refAnnotT (character) column name to use for reference-annotation #' @param addCol (character) column-namess of 'annotTab' to use/extract (if no matches found, use all) #' @param debug (logical) for bug-tracking: more/enhanced messages #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of message(s) produced #' @return combined matrix (elements not found in 'annotTab' are displayed as NA) #' @seealso \code{\link[base]{merge}} #' @examples #' tab0 <- matrix(rep(letters[1:25],8),ncol=10) #' tab1 <- cbind(Uniprot=paste(tab0[,1],tab0[,2]),col1=paste(tab0[,3], #' tab0[,4],tab0[,5]," ",tab0[,7],tab0[,6])) #' tab2 <- cbind(combName=paste(tab0[,1],tab0[,2]),col2=paste(tab0[,8],tab0[,9],tab0[,10])) #' fuseAnnotMatr(tab1,tab2[c(20:11,2:5),],refIni="Uniprot",refAnnotT="combName",addCol="col2") #' fuseAnnotMatr(tab2[c(20:11,2:5),],tab1,refAnnotT="Uniprot",refIni="combName",addCol="col1") #' @export fuseAnnotMatr <- function(iniTab,annotTab,refIniT="Uniprot",refAnnotT="combName", addCol=c("ensembl_gene_id","description","geneName","combName"),debug=TRUE,silent=FALSE,callFrom=NULL){ fxNa <- .composeCallName(callFrom,newNa="fuseAnnotMatr") argN <- c(deparse(substitute(iniTab)),deparse(substitute(annotTab))) concSym <- "; " # exeption to IDs (IDs from 'iniTab' containing these characters won't be considered) chMatr <- list(dim(iniTab),dim(annotTab)) msg <- c(paste(argN,collapse=" &"),"must be matrix or data.frame","are expected to have >1 rows and >1 columns") if(any(sapply(chMatr,length) <1)) stop(msg[1:2]) if(any(unlist(chMatr) <2) & !silent) message(fxNa,msg[c(1,3)]) if(length(unique(annotTab[,refAnnotT])) < nrow(annotTab)) annotTab <- combineRedBasedOnCol(annotTab,refAnnotT,callFrom=fxNa) chKey <- c(refIniT %in% colnames(iniTab), refAnnotT %in% colnames(annotTab)) if(any(!chKey)) stop(paste(c(refIniT,refAnnotT)[which(!chKey)],collapse=" & ")," not found in initial matrix(es) !!") useCol <- which(colnames(annotTab) %in% addCol) if(length(useCol) <1 | identical(refAnnotT,addCol)) { if(!silent) message(fxNa," NONE of 'addCol' found in ",argN[2],"!! use/return all cols") useCol <- 1:ncol(annotTab) } else if(length(addCol) < length(useCol)) message(fxNa,length(addCol)-length(useCol)," columns of 'addCol' not found in ",argN[2]) chKey <- sum(annotTab[,refAnnotT] %in% iniTab[,refIniT],na.rm=TRUE) if(chKey <1 & !silent) message(fxNa," NO matches of keys found between ",msg[1]," !!") uniqGe <- unique(iniTab[,refIniT]) chConcSym <- grep(concSym,uniqGe) if(length(chConcSym) >0) uniqGe <- uniqGe[-1*grep(concSym,uniqGe)] # if(length(uniqGe) == nrow(iniTab)) { annotTa2 <- as.data.frame(annotTab[,unique(c(which(colnames(annotTab)==refAnnotT),useCol))],stringsAsFactors=FALSE) out <- merge(iniTab,annotTa2,all.x=TRUE,by.x=refIniT,by.y=refAnnotT) } else { if(length(uniqGe) >2 & !silent) message(fxNa," non-unique IDs found : be patient ! (running loop across all IDs)") supAnn <- matrix(NA,nrow(iniTab),length(useCol),dimnames=list(iniTab[,"Uniprot"],colnames(annotTab)[useCol])) # (empty) for cbind for(i in uniqGe) { useLi <- which(rownames(supAnn)==i) if(length(useLi) >0) { j <- which(annotTab[,refAnnotT]==i) if(length(j) >0) supAnn[useLi,] <- matrix(rep(annotTab[j,useCol],each=length(useLi)),nrow=length(useLi)) }} out <- cbind(iniTab,supAnn) } as.matrix(out) }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/fuseAnnotMatr.R
#' Fuse content of list-elements with redundant (duplicated) names #' #' \code{fuseCommonListElem} fuses (character or numeric) elements of list re-occuring under same name, so that resultant list has unique names. #' Note : will not work with list of matrixes #' #' @param lst (list) main input, list of numeric vectors #' @param initOrd (logical) preserve initial order in output (if TRUE) or otherwise sort alphabetically #' @param removeDuplicates (logical) allow to remove duplicate entries (if vector contains names, both the name and the value need to be identical to be removed; note: all names must have names with more than 0 characters to be considered as names) #' @param callFrom (character) allows easier tracking of message(s) produced #' @return fused list (same names as elements of input) #' @seealso \code{\link[base]{unlist}} #' @examples #' 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]) #' fuseCommonListElem(lst1) #' @export fuseCommonListElem <- function(lst,initOrd=TRUE,removeDuplicates=FALSE,callFrom=NULL) { ## fuse (character or numeric) elements of list re-occuring under same name, so that resultant list has unique names ## will not work with list of matrixes ## return fused list (same names as elements of input) fxNa <- .composeCallName(callFrom,newNa="fuseCommonListElem") chDim <- sapply(lst, function(x) length(dim(x)) < 2) if(any(!chDim)) stop(fxNa, " need list of numeric vectors for fusing !") chDup <- duplicated(names(lst),fromLast=FALSE) if(any(chDup)) { iniNa <- names(lst) chDup <- chDup | duplicated(names(lst), fromLast = TRUE) tmp <- lst[which(chDup)] tmp <- tmp[order(names(tmp))] nMa <- sapply(tmp, length) names(nMa) <- names(tmp) names(tmp) <- NULL tmp2 <- tapply(unlist(tmp), factor(rep(names(nMa), nMa)), function(x) x) if(removeDuplicates) { hasNa <- sapply(tmp2,function(x) all(nchar(names(x)) >0) ) chDu <- if(!all(hasNa)) lapply(tmp2,duplicated,fromLast=FALSE) else { lapply(tmp2,function(x) duplicated(x) & duplicated(names(x)))} hasDu <- sapply(chDu,any) if(any(hasDu)) { tmp2[which(hasDu)] <- lapply(tmp2[which(hasDu)],function(x) { if(all(nchar(names(x)) >0)) x[which(!duplicated(x) & !duplicated(names(x)))] else x[which(!duplicated(x))] }) }} ## now need to re-integrate modified elements chDuR <- duplicated(names(lst),fromLast=TRUE) lst <- lst[which(!chDup & !chDuR)] suplLi <- length(lst) + (1:length(tmp2)) lst[suplLi] <- tmp2 names(lst)[suplLi] <- names(tmp2) if(initOrd) lst <- lst[match(unique(iniNa),names(lst))] } lst}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/fuseCommonListElem.R
#' Fuse pairs to generate cluster-names #' #' Fuse previously identified pairs to 'clusters', return vector with cluster-numbers. #' @param datPair 2-column matrix where each line represents 1 pair #' @param refDatNames (NULL or character) allows placing selected pairs in context of larger data-set (names to match those of 'datPair') #' @param inclRepLst (logical) if TRUE, return list with 'clu' (clu-numbers, default output) and 'refLst' (list of clustered elements, only n>1) #' @param maxFuse (integer, default NULL) maximal number of groups/clusters #' @param silent (logical) suppress messages #' @param debug (logical) display additional messages for debugging #' @param callFrom (character) allow easier tracking of message(s) produced #' @return This function returns a vector with cluster-numbers #' @examples #' daPa <- matrix(c(1:5,8,2:6,9), ncol=2) #' fusePairs(daPa, maxFuse=4) #' @export fusePairs <- function(datPair, refDatNames=NULL, inclRepLst=FALSE, maxFuse=NULL, debug=FALSE, silent=TRUE, callFrom=NULL) { fxNa <- .composeCallName(callFrom,newNa="fusePairs") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE msg <- " 'datPair' should be matrix of 2 cols with paired rownames" if(length(dim(datPair)) !=2) stop(msg) else if(ncol(datPair) <2) stop(msg) if(!is.matrix(datPair)) datPair <- if(nrow(datPair) >1) as.matrix(datPair) else matrix(datPair,nrow=1,dimnames=dimnames(datPair)) if(is.null(maxFuse)) maxFuse <- nrow(datPair)+1 else { if(!silent) message(fxNa," use of 'maxFuse' at ",maxFuse," may increase 'artificially' the number of groups/clusters")} if(!is.null(refDatNames)) { chRef <- unique(as.character(datPair[,1:2])) %in% as.character(refDatNames) if(sum(!chRef,na.rm=TRUE) >0) { if(!silent) message(fxNa,sum(!chRef,na.rm=TRUE)," names from 'datPair' missing in 'refDatNames', ignore") refDatNames <- refDatNames } } refDatNa <- if(is.null(refDatNames)) unique(as.character(datPair[,1:2])) else refDatNames if(is.null(rownames(datPair))) rownames(datPair) <- 1:nrow(datPair) nPt <- length(unique(as.character(datPair[,1:2]))) similDat <- list(which(refDatNa %in% datPair[1,1:2])) # similDat .. index of refDatNa per cluster if(debug) {message(fxNa," dim(datPair) ",nrow(datPair)," ",ncol(datPair))} if(nrow(datPair) >1) for(i in 2:nrow(datPair)) { basTest <- datPair[i,1:2] %in% as.character(datPair[1:(i-1),1:2]) # see if (any of) new pair already seen before chPr <- sapply(similDat, function(x) sum(datPair[i,1:2] %in% refDatNa[x])) # for each clu : number of common with cur query if(debug) message(fxNa," basTest ",pasteC(basTest)) if(any(chPr >0) && length(similDat[[which.max(chPr)]]) < maxFuse) { # add to existing cluster if(sum(basTest)==1){ similDat[[which.max(chPr)]] <- unique(sort(c(similDat[[which.max(chPr)]], which(refDatNa %in% datPair[i,1:2])))) } else { # fuse clusters instead of adding isMax <- which(chPr==max(chPr)) if(length(isMax) >1) { if(debug) message(fxNa," iter no ",i," fuse clusters : max ",pasteC(isMax)) similDat[[isMax[1]]] <- unique(unlist(similDat[which(chPr==max(chPr))])) similDat <- similDat[-isMax[2]] } else if(debug) message(fxNa," iter no ",i," : loop, already fused")} # don't make loops circular } else { # create new cluster if(debug) message(fxNa,"Create new cluster no ",length(similDat)+1," for ",pasteC(which(refDatNa %in% datPair[i,1:2]))) similDat[[length(similDat)+1]] <- which(refDatNa %in% datPair[i,1:2]) } } msg <- "Trouble ahead, some elements are indexed more than 1x in 'similDat' !!!" if(any(table(unlist(similDat)) >1) && maxFuse < nrow(datPair) && !silent) message(fxNa,msg) out <- rep(1:length(similDat), sapply(similDat,length)) names(out) <- unlist(lapply(similDat, function(x) refDatNa[x])) if(debug) {message(fxNa," fP2")} if(length(refDatNa) > length(unlist(similDat))) { tmp <- refDatNa[which(!(refDatNa %in% as.character(as.matrix(datPair[,1:2]))))] out2 <- (1:length(tmp)) +length(out) names(out2) <- tmp out <- c(out,out2) } out <- out[order(convToNum(.trimFromStart(names(out)), remove=NULL, sciIncl=TRUE))] if(inclRepLst) list(clu=out, repLst=similDat) else out } #' Distances beteenw sorted points of 2-columns #' #' This function returns distances beteenw sorted points of 2-column matrix 'x' #' #' @param x (matrix or data.frame, min 2 columns) main input #' @param asSum (logical) if \code{TRUE} (default) the sum of all distances will be returned, otherwise the individual distances #' @return This function returns a numeric vector with distances #' @examples #' daPa <- matrix(c(1:5,8,2:6,9), ncol=2) #' .neigbDis(daPa) #' @export .neigbDis <- function(x, asSum=TRUE) { # return (sum of) distances betw sorted points of 2-column matrix 'x' if(nrow(x) ==2) sqrt(sum(abs(x[1,] -x[2,]))) else { x <- x[order(rowMeans(x)),] out <- sqrt(rowSums((x[-nrow(x),]-x[-1,])^2, na.rm=TRUE)) if(!isFALSE(asSum)) sum(out, na.rm=TRUE) else out } }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/fusePairs.R
#' Get first of repeated by column #' #' \code{get1stOfRepeatedByCol} sorts matrix 'mat' and extracts only 1st occurance of values in column 'sortBy'. #' Returns then non-redundant matrix (ie for column 'sortBy', if 'markIfAmbig' specifies existing col, mark ambig there). #' Note : problem when sortSupl or sortBy not present (or not intended for use) #' #' @param mat (matrix or data.frame) numeric vector to be tested #' @param sortBy column name for which elements should be made unique, numeric or character column; 'sortSupl' .. add'l colname to always select specific 1st) #' @param sortSupl default="ty" #' @param asFirstLast (character,length=2) to force specific strings from coluln 'sortSupl' as first and last when selecting 1st of repeated terms, default=c("full","inter") #' @param markIfAmbig (character,length=2) 1st will be set to 'TRUE' if ambiguous/repeated, 2nd will get (heading) prefix, default=c("ambig","seqNa") #' @param asList (logical) to return list with non-redundant ('unique') and removed lines ('repeats') #' @param abmiPref (character) prefix to note ambiguous entries/terms, default="_" #' @return depending on 'asList' either list with non-redundant ('unique') and removed lines ('repeats') #' @seealso \code{\link{firstOfRepeated}} for (more basic) treatment of simple vector, \code{\link{nonAmbiguousNum}} for numeric use (much faster !!!) #' @examples #' aa <- 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) #' get1stOfRepeatedByCol(aa) #' @export get1stOfRepeatedByCol <- function(mat,sortBy="seq",sortSupl="ty",asFirstLast=c("full","inter"),markIfAmbig=c("ambig","seqNa"),asList=FALSE,abmiPref="_"){ msg <- " 'mat' should be matrix or data.frame with >1 lines & >1 columns" if(length(dim(mat)) !=2) stop(msg) else if(any(dim(mat) <2)) stop(msg) if(is.character(sortBy)) if(!sortBy %in% colnames(mat)) stop(" invalid 'sortBy'") # check better to allow alternative use of vector instead of colname ?? num <- if(is.numeric(mat[,sortBy])) mat[,sortBy] else as.numeric(as.factor(mat[,sortBy])) if(is.data.frame(mat)) mat <- as.matrix(mat) reps <- which(mat[,sortBy] %in% names(which(table(mat[,sortBy]) >1))) if(length(reps) >0){ sel <- mat[reps,] supl <- gsub(asFirstLast[1],"a",gsub(asFirstLast[2],"z",sel[,sortSupl])) # allow 'full' to come 1st & 'inter' as last sel <- sel[order(sel[,sortBy],supl),] selFi <- sel[which(diff(c(-1,as.numeric(as.factor(sel[,sortBy])))) >0),] # main selection of 1st of repeated if(length(dim(selFi))<2) selFi <- matrix(selFi,nrow=1,dimnames=list(NULL,names(selFi))) if(markIfAmbig[1] %in% colnames(mat)) selFi[,markIfAmbig[1]] <- TRUE # mark ambiguous as 'TRUE' if(markIfAmbig[2] %in% colnames(mat)) selFi[,markIfAmbig[2]] <- paste(abmiPref,selFi[,markIfAmbig[2]],sep="") out <- rbind(mat[-1*reps,],selFi) if(asList) out <- list(unique=out,repeats=mat[reps,]) } else out <- if(asList) list(unique=out) else mat out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/get1stOfRepeatedByCol.R
#' Print matrix-content as plot #' #' When data have repeated elements (defined by names inside the vector), it may be advantageous to run some operations #' only on a unique set of the initial data, or somtimes all repeated occurances need to be replaced by a common (summarizing) value. #' This function allows to re-introduce new values from on second vector with unique names, to return a final vector of initial input-length and order of names (elements) like initial, too. #' Normally the user would provide 'datUniq' (without repeated names) containing new values which will be expanded to structure of 'dat', #' if 'datUniq' is not provided a vector with unique names will be made using the first occurance of repeated value(s). #' For more complex cases the indexing relative to 'datUniq' can be returned (setting \code{asIndex=TRUE}). #' Note: If not all names of 'dat' are found in 'datUniq' the missing spots will be returned as \code{NA}. #' #' @param dat (numeric or character) main long input, must have names #' @param datUniq (numeric or character) will be used to impose values on \code{dat}, must have names that should match names (at least partially) from \code{dat} #' @param asIndex (logical) if \code{TRUE} index values will be returned instead of replacing values #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return vector of length \code{dat} with imposed values, or index values if \code{asIndex=TRUE} #' @seealso \code{\link[base]{unique}}, \code{\link{findRepeated}}, \code{\link{correctToUnique}}, \code{\link{treatTxtDuplicates}} #' @examples #' dat <- 11:19 #' names(dat) <- letters[c(6:3,2:4,8,3)] #' ## let's make a 'datUniq' with the mean of repeated values : #' datUniq <- round(tapply(dat,names(dat),mean),1) #' ## now propagate the mean values to the full vector #' getValuesByUnique(dat,datUniq) #' cbind(ini=dat,firstOfRep=getValuesByUnique(dat,datUniq), #' indexUniq=getValuesByUnique(dat,datUniq,asIn=TRUE)) #' @export getValuesByUnique <- function(dat, datUniq=NULL, asIndex=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL) { ## main fxNa <- .composeCallName(callFrom, newNa="getValuesByUnique") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(length(dat) <1 | is.null(names(dat))) stop("'dat' must be vector of length >0 with names; no names nothing to do") if(length(datUniq) >0) if(is.null(names(datUniq))) { if(!silent) message(fxNa," 'datUniq' has no names; unable to use ! (using default instead)") datUniq <- NULL } if(is.null(datUniq)) datUniq <- dat[!duplicated(names(dat))] if(identical(dat,datUniq)) {out <- if(asIndex) 1:length(dat) else dat } else { out <- rep(NA,length(dat)) names(out) <- names(dat) ## note: this step performs much faster using match than via as.integer(as.factor) ! ind <- match(names(dat),names(datUniq)) if(!asIndex) out[which(!is.na(ind))] <- datUniq[naOmit(ind)] else out <- ind chNa <- is.na(out) if(any(chNa)) { if(!silent) message(fxNa," ",sum(chNa)," name(s) of 'dat' not found in 'datUniq' !") } } out}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/getValuesByUnique.R
#' Convert ulr-name for reading in raw-mode #' #' This functions converts a given urlName so that from data from git-hub can be read correctly that tabular data. #' Thus, this will remove '/blob/' and change starting characters to 'raw.githubusercontent.com' #' #' #' #' @param urlName (charachter) main url-address #' @param replTxt (NULL or matrix) adjust/ custom-modify search- and replacement items; should be matrix with 2 columns, #' the 1st colimn entries will be used as 'search-for' and the 2nd as 'replace by' fro each row. #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return corrected urlName #' @seealso \code{\link[base]{sub}}; #' @examples #' url1 <- paste0("https://github.com/bigbio/proteomics-metadata-standard/blob/", #' "master/annotated-projects/PXD001819/PXD001819.sdrf.tsv") #' gitDataUrl(url1) #' #' #' #' @export gitDataUrl <- function(urlName, replTxt=NULL, silent=FALSE, debug=FALSE, callFrom=NULL) { ## convert urlName from git that tabular data can be read correctly, ie remove '/blob/' & change start to 'raw.githubusercontent.com' fxNa <- .composeCallName(callFrom, newNa="gitDataUrl") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(length(urlName) <1) { if(!silent) message(fxNa,"'urlName' is empty, nothing to do") } else { if((any(length(dim(replTxt)) !=2, dim(replTxt) < 1:2))) replTxt <- rbind( c("^https://github.com/", "https://raw.githubusercontent.com/"), c("/blob/master/", "/master/")) chGit <- grepl(replTxt[1,1], urlName) if(any(chGit)) { for(i in 1:nrow(replTxt)) urlName <- sub(replTxt[i,1], replTxt[i,2], urlName)} } urlName }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/gitDataUrl.R
#' Html special character conversion #' #' Converts 'txt' so that (the most common) special characters (like 'beta','micro','square' etc) will be displayed correctly whe used for display in html (eg at mouse-over). #' Note : The package \href{https://CRAN.R-project.org/package=stringi}{stringi} is required for the conversions (the input will get returned if \code{stringi} is not available). #' Currently only the 16 most common special characters are implemented. #' #' @param txt character vector, including special characters #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a corrected character vector adopted for html display #' @seealso tables on \url{https://www.htmlhelp.com/reference/html40/entities/latin1.html}, #' \url{https://www.degraeve.com/reference/specialcharacters.php}, or \code{https://ascii.cl/htmlcodes.htm} #' @examples #' ## we'll use the package stringi to generate text including the 'micro'-symbol as input #' x <- if(requireNamespace("stringi", quietly=TRUE)) { #' stringi::stri_unescape_unicode("\\u00b5\\u003d\\u0061\\u0062")} else "\"x=axb\"" #' htmlSpecCharConv(x) #' @export htmlSpecCharConv <- function(txt, silent=FALSE, callFrom=NULL, debug=FALSE) { fxNa <- .composeCallName(callFrom, newNa="htmlSpecCharConv") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(!requireNamespace("stringi", quietly=TRUE)) { message(fxNa,"Package 'stringi' needed for conversion not found ! Please install from CRAN. Returning initial 'txt'") } else { speCh <- c("\\u00b5","\\u00ba","\\u00b9","\\u00b2","\\u00b3",beta="\\u00df","\\u00e0", ced="\\u00e7", "\\u00e8","\\u00e9", ae="\\u00e2","\\u00f6","\\u00fc","\\u00f7","\\u00f5",x="\\u00d7") conv <- try(stringi::stri_unescape_unicode(speCh), silent=TRUE) if(inherits(conv, "try-error")) { warning(fxNa,": UNABLE to tun stringi::stri_unescape_unicode() !"); txt <- NULL } else { conv <- matrix(c(conv, "&micro","&ordm","&sup1","&sup2","&sup3","&szlig", "&agrave","&ccedil","&egrave","&eacute","&auml", "&ouml","&uuml","&divide","&otilde","&times"), ncol=2) conv <- rbind(conv, c('"','&quot')) for(i in 1:nrow(conv)) { che <- grep(conv[i,1], txt) if(length(che) >0) txt[che] <- gsub(conv[i,1], conv[i,2], txt[che]) } } } txt }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/htmlSpecCharConv.R
#' Extract Longest Common Text Out Of Character Vector #' #' @description #' This function allows recovering the single longest common text-fragments (from center, head or tail) out of character vector \code{txt}. #' Only the first of all of the longest solutions will be returned. #' #' @details #' Please note, that finding common parts between chains of characters is not a completely trivial task. #' This topic still has ongoing research for the application of sequence-alignments, where chains of characters to be compared get very long. #' This function uses a k-mer inspirated approach. #' The initial aim with this function was allowing to treat smaller chains of characters (and finding shorter strteches of common text), like eg with column-names. #' #' Important : This function identifies only the first best hit, ie other shared/common character-chains of the same length will not be found ! #' #' Using the argument \code{hiResol=FALSE} it is possible to accelerate the search aprox 3x (with larger character-vectors), however, frequently the very best solution may not be found. #' This means, that in this case the result should rather be considered a 'seed', allowing check if further extension may improve the result, #' ie for identifying a (slightly) longer chain of common characters. #' #' With longer vectors and longer character chains this may get demanding on computational reesources, the argument \code{hiResol=FALSE} allows reducing this at the price of missing the best solution. #' With this argument single common/matching characters will not be searched if all text-elements are longer than 500 characters, an empty character vector will be returned. #' #' When argument \code{side} is either \code{left}, \code{right} or \code{terminal} only terminal common text may be found (a potentially even longer internal text will be lost). #' Of course, choosing this option makes searches much faster. #' #' This function does not return the position of the shared/common characters within the text, you may use \code{gregexpr} or \code{regexec} to locate them. #' #' #' @param txt character vector to be treated #' @param minNchar (integer) minumin number of characters that must remain #' @param side (character) may be be either 'center', 'any', 'terminal', 'left' or 'right'; only with \code{side='center'} or \code{'any'} internal text-segments may be found #' #' @param hiResol (logical) find best solution, but at much higher comptational cost (eg 3x slower, however \code{hiResol=FALSE} rather finds anchor which may need to get extended) #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of messages produced #' @param debug (logical) display additional messages for debugging #' @return This function returns a character vector of length=1, ie only one (normally the longest) common sequence of characters is identified. #' If nothing is found common/shared an empty character-vector is returned #' @seealso Use \code{gregexpr} or \code{regexec} in \code{\link[base]{grep}} for locating the identified common characters in the initial query. #' @seealso Inverse : Trim redundant text (from either side) to keep only varaible part using \code{\link{trimRedundText}}; #' you may also look for related functions in package \href{https://CRAN.R-project.org/package=stringr}{stringr} #' @examples #' txt1 <- c("abcd_abc_kjh", "bcd_abc123", "cd_abc_po") #' keepCommonText(txt1, side="center") # trim from right #' #' txt2 <- c("ddd_ab","ddd_bcd","ddd_cde") #' trimRedundText(txt2, side="left") # #' keepCommonText(txt2, side="center") # #' @export keepCommonText <- function(txt, minNchar=1, side="center", hiResol=TRUE, silent=TRUE, callFrom=NULL, debug=FALSE) { ## ## fxNa <- .composeCallName(callFrom, newNa="keepCommonText") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(!isFALSE(hiResol)) hiResol <- TRUE side <- try(as.character(side), silent=TRUE) if(inherits(side, "try-error")) stop("Invalid entry for 'side', must be character, 'center','any', 'terminal', 'left' or 'right'") out <- lastOK <- NULL # initialize txOK <- TRUE ## check of input if(length(txt) <1 || all(is.na(txt))) { txOK <- FALSE; out <- NA if(!silent) message(fxNa,"Empty or all NA input, no common text possible") } if(txOK) { chNa <- is.na(txt) if(any(chNa)) txt <- txt[which(!chNa)] if(length(txt)==1) { out <- txt # length=1 .. full text if(debug) message(fxNa,"Single (valid) vector-element")} if(length(txt) >0 && length(out) <1) { chSame <- all(sapply(txt[-1], function(x) x==txt[1])) # all the same no need for extensive testing if(all(chSame)) { out <- out[1] if(!silent) message(fxNa,"All text identical") } } nChar <- nchar(txt) if(length(out) <1 && any(nChar <1)) { out <- "" if(!silent) message(fxNa,"Some text elements are empty, no common text possible")} if(debug) {message(fxNa,"kCT1"); kCT1 <- list(txt=txt,side=side,minNchar=minNchar,out=out,chSame=chSame,nChar=nChar,hiResol=hiResol)} ## search at terminal positions if(length(txt) >0 && any(c("left","terminal") %in% side)) { txTr <- .trimRight(txt, minNchar=minNchar, silent=silent, callFrom=fxNa) if(nchar(txt[1]) > nchar(txTr[1])) { out <- txt <- sub(txTr[1],"",txt[1]) nChar <- nchar(txt)} # update if(debug) {message(fxNa,"kCT1a")} } if(length(txt) >0 && any(c("right","terminal") %in% side)) { txTr <- .trimLeft(txt, minNchar=minNchar, silent=silent, callFrom=fxNa) if(nchar(txt[1]) > nchar(txTr[1])) out <- sub(txTr[1],"",txt[1]) # nChar <- nchar(txt) # update } } if(debug) {message(fxNa,"kCT2"); kCT2 <- list(txt=txt,side=side,minNchar=minNchar,out=out,chSame=chSame,nChar=nChar,hiResol=hiResol)} ## search anywhere (incl center) if(length(txt) >0 && any(c("center","any") %in% side)) { ch1 <- min(nChar, na.rm=TRUE) if(ch1 -1 > minNchar) { # sufficient characters in all instances if(!hiResol && !silent) message(fxNa,"Please note that using the argument hiResol=FALSE, the optimal solution may not be found, you may check if the result can be further extended") ch2 <- txt[which.min(nChar)] kMer <- 2 kMerIni <- kMer ## first round stSpl <- seq(1, ch1 -kMer +1, by=if(hiResol) 1 else kMer) words <- unique(substr(rep(ch2, length(stSpl)), stSpl, stSpl+kMer-1)) ch3 <- sapply(lapply(words, grep, txt[-which.min(nChar)]), length) == length(txt) -1 lastOK <- if(any(ch3)) list(kMer=kMer,words=words, ch3=ch3) else NULL ## now searh for longer if any matches found above while(any(ch3) && kMer < ch1 -2) { kMer <- kMer +2 stSpl <- seq(1, ch1 -kMer +1, by=if(hiResol) 1 else kMer) words <- unique(substr(rep(ch2, length(stSpl)), stSpl, stSpl +kMer -1)) if(debug) message(fxNa,"Increase kMer from ",kMer -2," to ",kMer,"; testing ",length(words)," character-chains") ch3 <- sapply(lapply(words, grep, txt[-which.min(nChar)]), length) == length(txt) -1 if(any(ch3)) lastOK <- list(kMer=kMer,words=words, ch3=ch3) } if(debug) {message(fxNa,"kCT3"); kCT3 <- list(txt=txt,side=side,minNchar=minNchar,out=out,chSame=chSame,nChar=nChar,hiResol=hiResol,lastOK=lastOK, words=words,stSpl=stSpl,kMer=kMer,ch2=ch2,ch3=ch3)} ## have reached too long words try step down, 1 less if(all(kMer > 1, !ch3, kMer > lastOK$kMer +1)) { if(kMer==2) { # nothing found at kMer=2, try split in single characters & look for common character if(minNchar==1 & any(all(nChar <500), hiResol)) { # run only if hiResol=TRUE or all text entries are less than 500 chars txtSn <- lapply(strsplit(txt, ""), unique) ch3 <- table(unlist(txtSn)) if(any(ch3==length(txt))) out <- names(ch3)[which(ch3==length(txt))[1]] } } else { kMer <- kMer -1 stSpl <- seq(1, ch1 -kMer +1, by=if(hiResol) 1 else kMer) words <- unique(substr(rep(ch2, length(stSpl)), stSpl, stSpl+kMer-1)) if(debug) message(fxNa,"Decrease kMer from ",kMer +1," to ",kMer,"; testing ",length(words)," character-chains") ch3 <- sapply(lapply(words, grep, txt[-which.min(nChar)]), length) == length(txt) -1 if(any(ch3)) lastOK <- list(kMer=kMer,words=words, ch3=ch3) } } if(debug) {message(fxNa,"kCT4")} if(length(lastOK) >0) out <- lastOK$words[which(lastOK$ch3)[1]] } } if(length(out) >0) out else ""}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/keepCommonText.R
#' Transform (factor) levels into index #' #' This function helps transforming a numeric or character vector into indexes of levels (of its original values). #' By default indexes are assigned by order of occurance, ie, the first value of \code{x} will be get the index of 1. #' Using the argument \code{byOccurance=FALSE} the resultant indexes will follow the sorted values. #' #' @param dat (numeric or character vector or factor) main input #' @param byOccurance (logical) toogle if lowest index should be based on alphabetical order or on order of input #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return matrix with mean values #' @seealso \code{\link{rowSds}}, \code{\link[base]{colSums}} #' @examples #' x1 <- letters[rep(c(5,2:3),1:3)] #' levIndex(x1) #' levIndex(x1, byOccurance=FALSE) #' ## with factor #' fa1 <- factor(letters[rep(c(5,2:3),1:3)], levels=letters[1:6]) #' levIndex(fa1) #' levIndex(fa1, byOccurance=FALSE) #' @export levIndex <- function(dat, byOccurance=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL) { ## transform levels into index ## based on https://stackoverflow.com/questions/50898623/how-to-replace-multiple-values-at-once fxNa <- .composeCallName(callFrom, newNa="levIndex") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(length(dat) <1) { out <- NULL; if(!silent) message(fxNa, "'dat' seems to be empty") } else { out <- as.integer(as.factor(dat)) names(out) <- dat if(isTRUE(byOccurance)) { levU <- naOmit(unique(out)) # levels in orig order (non-alpahbetical) corsp <- data.frame(old=levU, new=1:length(levU)) out[out %in% levU] <- (1:length(levU))[match(out, levU, nomatch = 0)] names(out) <- dat } } out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/levIndex.R
#' Test multiple starting levels for linear regression model, select best and plot #' #' The aim of this function is to select the data suiting set of levels of the main input data to construct a linear regression model. #' In real world measurements one may be confronted to the case of very low level analytes below the detection limit (LOD) and resulting read-outs fluctuate around around a common baseline (instead of \code{NA}). #' With such data it may be preferable to omit the read-outs for the lowest concentrations/levels of analytes if they are spread around a base-line value. #' This function allows trying to omit all starting levels designed in \code{startLev}, then the resulting p-values for the linear regression slopes will be checked and the best p-value chosen. #' The input may also be a MArrayLM-type object from package \href{https://bioconductor.org/packages/release/bioc/html/limma.html}{limma} or from \code{\link{moderTestXgrp}} or \code{\link{moderTest2grp}}. #' In the graphical representation all points assocoated to levels omitted are shown in light green. #' For the graphical display additional information can be used : If the \code{dat} is list or MArrayLM-type object, #' the list-elements $raw (according to argument \code{lisNa} will be used to display points initially given as NA ad imputed lateron in grey. #' Logarithmic (ie log-linear) data can be treated by settting argument \code{logExpect=TRUE}. Then the levels will be taken as exponent of 2 for the regression, while the original values will be displayed in the figure. #' #' @param rowNa (character, length=1) rowname for line to be extracted from \code{dat} #' @param dat (matrix, list or MArrayLM-object from limma) main input of which columns should get re-ordered, may be output from \code{\link{moderTestXgrp}} or \code{\link{moderTest2grp}}. #' @param expect (numeric of character) the expected levels; if character, constant unit-characters will be stripped away to extact the numeric content #' @param logExpect (logical) toggle to \code{TRUE} if the main data are logarithmic but \code{expect} is linear #' @param startLev (integer) specify all starting levels to test for omitting here (multiple start sites for modelling linear regression may be specified to finally pick the best model) #' @param lisNa (character) in case \code{dat} is list or MArrayLM-type object, the list-elements with these names will be used as $raw (for indicating initial \code{NA}-values, #' $datImp (the main quantitation data to use) and $annot for displaying the corresponding value from the "Accession"-column. #' @param plotGraph (logical) display figure #' @param tit (character) optional custom title #' @param pch (integer) symbols to use n optional plot; 1st for regular values, 2nd for values not used in regression #' @param cexLeg (numeric) size of text in legend #' @param cexSub (numeric) text-size for line (as subtitle) giving regression details of best linear model) #' @param xLab (character) custom x-axis label #' @param yLab (character) custom y-axis label #' @param cexXAxis (character) \code{cex}-type for size of text for x-axis labels #' @param cexYAxis (character) \code{cex}-type for size of text for y-axis labels #' @param xLabLas (integer) \code{las}-type orientation of x-axis labels (set to 2 for vertical axix-labels) #' @param cexLab (numeric) \code{cex}-type for size of text in x & y axis labels (will be passed to \code{cex.lab} in \code{plot()}) #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a list with $coef (coefficients), $name (as/from input \code{rowNa}), $startLev the best starting level) #' @seealso \code{\link{moderTestXgrp}} for single comparisons, \code{\link[base]{order}} #' @examples #' ## Construct data #' 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) #' #' ## Check & plot for linear model #' linModelSelect("P2", dat2, expect=exp2) #' #' ## Log-Linear data #' ## Suppose dat2 is result of measures in log2, but exp4 is not #' exp4 <- rep(c(3,10,30,100,300,1000), each=3) #' linModelSelect("P2", dat2, expect=exp4, logE=FALSE) # bad #' linModelSelect("P2", dat2, expect=exp4, logE=TRUE) #' #' @export linModelSelect <- function(rowNa, dat, expect, logExpect=FALSE, startLev=NULL, lisNa=c(raw="raw",annot="annot",datImp="datImp"), plotGraph=TRUE, tit=NULL, pch=c(1,3), cexLeg=0.95, cexSub=0.85, xLab=NULL, yLab=NULL, cexXAxis=0.85, cexYAxis=0.9, xLabLas=1, cexLab=1.1, silent=FALSE, debug=FALSE, callFrom=NULL) { ## test for linear models with option to start form multiple later levels (ie omitting some of the early levels) fxNa <- .composeCallName(callFrom, newNa="linModelSelect") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE argNa <- c(deparse(substitute(rowNa)), deparse(substitute(dat)), deparse(substitute(expect))) quantCol <- c("blue","tan2","grey") # figure: 1st for 'used in regression', 2nd for 'not-used', 3rd for 'NA/imputed' legLab <- c("used in regresssion","not used","NA/imputed,used","NA/imputed,not used") # for figure legend .. annoColNa <- c("Accession","GeneName") doSelect <- TRUE if(length(rowNa) <1) {warning(fxNa," argument 'rowNa=",argNa[1],"' contains emty object, nothing to do !"); doSelect <- FALSE} if(length(dat) <1) {warning(fxNa," argument 'dat=",argNa[1],"' contains emty object, nothing to do !"); doSelect <- FALSE} if(length(expect) <1) {warning(fxNa," argument 'expect=",argNa[3],"' contains emty object, nothing to do !"); doSelect <- FALSE} if(doSelect) { if(length(rowNa) >1) { message(fxNa," 'rowNa' should have length of 1 (but is ",length(rowNa),"), truncating ...") rowNa <- rowNa[1] } if(length(expect) <1) stop("Argument 'expect' seems to be empty (should be numeric for each level of dat)") hasAnn <- subPat <- FALSE if(length(startLev) >0) if(!is.numeric(startLev)) stop("Argument 'startLev' must be integer") if(is.list(dat)) { ## 'dat' is list if(lisNa[2] %in% names(lisNa) & lisNa[2] %in% names(dat)) if(annoColNa[2] %in% colnames(dat[[lisNa[2]]])) hasAnn <- TRUE chLi <- lisNa %in% names(dat) if(all(!chLi)) stop("None of the list-elements given in 'lisNa' were found in 'dat' !") if(any(!chLi)) message(fxNa,"Trouble ahead : The elements ",pasteC(lisNa[which(!chLi)], quoteC="'")," not found !!") if(length(grep("^[[:digit:]]$", rowNa)) >0) { # is index linNo <- as.integer(rowNa) rowNa <- dat[[lisNa[2]]][rowNa,annoColNa[1]] } else { linNo <- if(hasAnn) which(dat[[lisNa[2]]][,annoColNa[1]] == rowNa) else which(rownames(dat[[lisNa[1]]]) ==rowNa) if(length(linNo) >1) { if(!silent) message(fxNa,"Name specified in argument 'lisNa' not unique, using first") linNo <- linNo[1] } } dat1 <- dat[[lisNa[3]]][linNo,] # get imputed data } else { ## simple matrix data linNo <- which(rownames(dat) %in% rowNa) if(length(linNo) !=1 && !silent) message(fxNa," Note : ",length(linNo)," lines of 'dat' matched to '",rowNa,"' ! (can use only 1st)") if(length(linNo) >1) linNo <- linNo[1] dat1 <- dat[linNo,]} ## which starting levels to test startLev <- if(length(startLev) <1) 1:floor(length(unique(expect))/2) else as.integer(startLev) expect0 <- expect if(!is.numeric(expect)) { subPat <- "[[:alpha:]]*[[:punct:]]*[[:alpha:]]*" subPat <- paste0(c("^",""),subPat,c("","$")) expect <- try(as.numeric( sub(subPat[2], "", sub(subPat[1], "", as.character(expect))))) } if(inherits(expect, "try-error")) stop(fxNa," Problem extracting the numeric content of 'expect': ",pasteC(expect0,quoteC="'")) if(!is.numeric(expect)) { expect <- as.numeric(as.factor(as.character(expect))) if(!silent) message(fxNa,"Note: 'expect' is not numeric, transforming to integers") } ## MAIN MODEL dat1 <- data.frame(conc=if(logExpect) log2(expect) else expect, quant=dat1, concL=expect) # omics quantitation data is already log2 lm0 <- lapply(startLev, function(x) { lmX <- try(stats::lm(quant ~ conc, data=dat1[which(expect >= sort(unique(expect))[x]),])); lmX }) slopeAndP <- sapply(lm0, function(x) z <- stats::coef(summary(x))[2,c("Estimate","Pr(>|t|)")]) bestReg <- which.min(slopeAndP[2,]) if(!silent) message(fxNa," best slope pVal starting at level no ",bestReg) ## PLOT if(plotGraph) { levExp <- sort(unique(expect)) usedP <- expect >= levExp[bestReg] useCol <- rep(quantCol[1], nrow(dat1)) # initialize as used pch1 <- rep(pch[1], nrow(dat1)) # initialize as used if(any(!usedP)) { useCol[which(!usedP)] <- quantCol[2] # color used for not-used pch1[which(!usedP)] <- pch[2] } # symbol used for not-used chNa <- is.list(dat) && lisNa[1] %in% names(dat) if(any(chNa)) chNa <- is.na(dat[[lisNa[1]]][linNo,]) hasNa <- any(chNa) legCol <- quantCol[if(hasNa) c(1:3,3) else 1:2] legPch <- pch[if(hasNa) c(1,2,1,2) else 1:2] if(hasNa) {useCol[which(chNa)] <- quantCol[3]} else {legLab <- legLab[1:2]} if(length(tit) <1) { tit <- if(hasAnn) dat[[lisNa[2]]][linNo, annoColNa[2]] else paste0(rowNa," (from ",argNa[2],")")} if(length(yLab) <1) yLab <- "measured" if(length(xLab) <1) xLab <- "expected" if(logExpect) xLab <- paste0(xLab," (log-scale)") ## main plot chG <- try(graphics::plot(quant ~ conc, data=dat1, col=useCol, main=tit,ylab=yLab, xlab=xLab, las=1, pch=pch1, cex.lab=cexLab, col.axis="white", cex.axis=0.3,tck=0), silent=TRUE) if(inherits(chG, "try-error")) message(fxNa,"UNABLE to draw figure !!") else { graphics::mtext(paste0("best regr starting at level ",bestReg," (ie ",sort(unique(expect))[bestReg],"), slope=",signif(slopeAndP[1,bestReg],3), ", p=",signif(slopeAndP[2,bestReg],2)), cex=cexSub, col=quantCol[1]) ## use crt= for rotating text on bottom ? ... crt works only for text() graphics::mtext(at=(unique(dat1[,1])), signif(if(logExpect) 2^(unique(dat1[,1])) else unique(dat1[,1]),3), side=1, las=xLabLas,col=1,cex=cexXAxis) # set las to vertical ? graphics::abline(lm0[[bestReg]], lty=2, col=quantCol[1]) graphics::axis(side=2, las=1, col=1, tick=TRUE, cex.axis=cexYAxis) # left axis ptBg <- quantCol chPch <- pch %in% c(21:25) if(any(chPch)) { quantCol[which(chPch)] <- grDevices::rgb(0.2,0.2,0.2,0.4) } chPa <- requireNamespace("wrGraph", quietly=TRUE) if(!chPa) { message(fxNa,": package 'wrGraph' not installed for searching optimal placement of legend") legLoc <- "bottomright" } else legLoc <- try(wrGraph::checkForLegLoc(dat1, sampleGrp=legLab, showLegend=FALSE)$loc, silent=TRUE) if(inherits(legLoc, "try-error")) { legLoc <- "bottomright" message(fxNa,"Did not succeed in determining optimal legend location")} tmp <- try(graphics::legend(legLoc, legLab, pch=legPch, col=legCol, text.col=legCol, pt.bg=ptBg, cex=cexLeg, xjust=0.5,yjust=0.5), silent=TRUE) # as points if("try-error" %in% class(tmp)) message(fxNa,"NOTE : Unable to add legend ! ",as.character(tmp)) } } list(coef=stats::coef(summary(lm0[[bestReg]])), name=rowNa, startLev=bestReg) }}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/linModelSelect.R
#' Fit linear regression, return parameters and p-values #' #' This function fits a linear regression and returns the parameters, including p-values from Anova. #' Here the vector 'y' (scalar response or dependent variable, ie the value that should get estimated) will be estimated according to 'dep' (explanatory or independent variable). #' Alternatively, 'dep' may me a \code{matrix} where 1st column will be used as 'dep and the 2nd column as 'y'. #' #' @param dep (numeric vector, matrix or data.frame) explanatory or dependent variable, if matrix or data.frame the 1st column will be used, if 'y'=\code{NULL} the 2nd column will be used as 'y' #' @param y (numeric vector) independent variable (the value that should get estimated based on 'dep') #' @param asVect (logical) return numeric vector (Intercept, slope, p.intercept, p.slope) or matrix or results #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return numeric vector (Intercept, slope, p.intercept, p.slope), or if \code{asVect}==\code{TRUE} as matrix (p.values in 2nd column) #' @seealso \code{\link[stats]{lm}} #' @examples #' linRegrParamAndPVal(c(5,5.1,8,8.2),gl(2,2)) #' @export linRegrParamAndPVal <- function(dep, y=NULL, asVect=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL) { ## fit linear regression and return parameters, including p-values from Anova fxNa <- .composeCallName(callFrom, newNa="linRegrParamAndPVal") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(debug) message(fxNa,"lRP1") msg <- "'dep' and 'y' should be numeric vectors of equal length, or 'dep' may be matrix where the 1st column will be used as 'dep' and the secod as 'y'" if(length(dim(dep)) ==2) { if(ncol(dep) >1 & length(y) <1) {dF <- as.data.frame(dep[,1:2]); colnames(dF) <- c("x","y") } else { if(length(y) == nrow(dep)) dF <- data.frame(x=dep[,1],y=y) else stop(msg)} } else { if(length(y) == length(dep)) dF <- data.frame(x=dep,y=y) else stop(msg)} ## main if(is.factor(dF[,2])) dF[,2] <- as.numeric(as.character(dF[,2])) z <- stats::coef(summary(stats::lm(y~x,data=dF)))[,c("Estimate","Pr(>|t|)")] rownames(z)[2] <- "slope" if(asVect){ na <- dimnames(z) z <- as.numeric(z) names(z) <- c(na[[1]],paste("p",na[[1]],sep="."))} z }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/linRegrParamAndPVal.R
#' Replacements in list #' #' \code{listBatchReplace} replaces in list \code{lst} all entries with value \code{searchValue} by \code{replaceBy} #' @param lst input-list to be used for replacing #' @param searchValue (character, length=1) #' @param replaceBy (character, length=1) #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a corrected list #' @seealso basic replacement \code{sub} in \code{\link[base]{grep}} #' @examples #' lst1 <- list(aa=1:4, bb=c("abc","efg","abhh","effge"), cc=c("abdc","efg")) #' listBatchReplace(lst1, search="efg", repl="EFG", sil=FALSE) #' @export listBatchReplace <- function(lst, searchValue, replaceBy, silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="listBatchReplace") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE msg1 <- " 'searchValue' and 'replaceBy' should be vectors" if(length(searchValue) <1 || length(replaceBy) <1) stop(fxNa,msg1) if(length(lst) <1 || !inherits(lst, "list")) stop(fxNa," 'lst' should be list with at least 1 element") outNa <- names(lst) if(length(searchValue) ==1 && length(replaceBy) ==1){ out <- lapply(lst, function(x) {x[x==searchValue] <- replaceBy; x}) } else { if(length(searchValue) ==length(replaceBy)) { out <- lapply(lst,function(x) {for(se in 1:length(searchValue)) x[x==searchValue[se]] <- replaceBy[se]; x}) } else if(length(replaceBy) ==1) { out <- lapply(lst,function(x) {for(se in 1:length(searchValue)) x[x==searchValue[se]] <- replaceBy; x}) } else { out <- lst if(!silent) message(fxNa," number of elments in 'searchValue' doesn't match well those from 'replaceBy'; doing nothing")} } names(out) <- outNa out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/listBatchReplace.R
#' Organize values into list and sort by names #' #' Sort values of \code{'x'} by its names and organize as list by common names, the names until \code{'sep'} are used for (re)grouping. #' Note that typical spearators occuring the initial names may need protection by '\\' (this is automatically taken care of for the case of the dot ('.') separator). #' @param x (list) main input #' @param sep (character) separator (note that typcal separators may need to be protected, only automatically added for '.') #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return matrix or data.frame #' @seealso \code{rbind} in \code{\link[base]{cbind}} #' @examples #' listGroupsByNames((1:10)/5) #' ser1 <- 1:6; names(ser1) <- c("AA","BB","AA.1","CC","AA.b","BB.e") #' listGroupsByNames(ser1) #' @export listGroupsByNames <- function(x, sep=".", silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="listGroupsByNames") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(debug) message(fxNa,"lGNB1") if(length(sep) <1) sep <- "\\." if(length(sep) >1) {if(!silent) message(fxNa,"'sep' should be character of length 1"); sep <- sep[1]} if(sep %in% c(".")) sep <- paste("\\",sep,sep="") if(length(names(x)) <1) { message(fxNa," no names found in 'x' !!") names(x) <- spl <- sapply(strsplit(as.character(x), sep), function(y) y[1]) } else spl <- strsplit(names(x),sep) ex1st <- sapply(spl, function(x) x[1]) if(length(ex1st) > length(unique(ex1st))) { out <- lapply(unique(ex1st),function(y) which(ex1st==y)) out <- lapply(out,function(y) c(x[y])) } else out <- as.list(x) if(length(names(out)) <1) names(out) <- sapply(out,function(y) names(y)[1]) out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/listGroupsByNames.R
#' Run lm on segmented data (from clustering) #' #' \code{lmSelClu} runs linear regression on data segmented previously (eg by clustering). #' This functio offers various types of (2-coefficient) linear regression on 2 columns of 'dat' (matrix with 3rd col named 'clu' or 'cluID', numeric elements for cluster-number). #' If argument \code{'clu'} is (default) 'max', the column 'clu' will be inspected to take most frequent value of 'clu', otherwise a numeric entry specifying the cluster to extract is expected. #' Note: this function was initially made for use with results from diagCheck() #' Note: this function lacks means of judging godness of fit of the regression preformed & means for plotting #' @param dat matrix or data.frame #' @param useCol (integer or charcter) specify which 2 columns of 'dat' to use for linear regression #' @param clu (character) name of cluster to be extracted and treatad #' @param regTy (character) change type used for linear regression : 'lin' for 1st col ~ 2nd col, 'res' for residue ~ 2nd col, 'norRes' for residue/2nd col ~2nd col or 'sqNorRes','inv' for 1st col ~ 1/(2nd col), 'invRes' for residue ~ 1/(2nd col) #' @param filt1 (logical or numerical) filter criteria for 1st of 'useCol' , if numeric then select all lines of dat less than max of filt1 #' @param filt2 (logical or numerical) filter criteria for 2nd of 'useCol' , if numeric then select all lines of dat less than max of filt2 #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return lm object (or NULL if no data left) #' @seealso \code{\link[stats]{lm}} #' @examples #' set.seed(2016); ran1 <- runif(220) #' mat1 <- round(rbind(matrix(c(1:100+ran1[1:100],rep(1,50)),ncol=3), #' matrix(c(1:60,68:9+ran1[101:160],rep(2,60)),nc=3)),1) #' colnames(mat1) <- c("a","BB","clu") #' lmSelClu(mat1) #' plot(mat1[which(mat1[,3]=="2"),1:2],col=grey(0.6)) #' abline(lmSelClu(mat1),lty=2,lwd=2) #' # #' mat2 <- round(rbind(matrix(c(1:100+ran1[1:100],rep(1,50)),ncol=3), #' matrix(c(1:60,(2:61+ran1[101:160])^2,rep(2,60)),nc=3)),1) #' colnames(mat2) <- c("a","BB","clu") #' (reg2 <- lmSelClu(mat2,regTy="sqNor")) #' plot(function(x) coef(reg2)[2]+ (coef(reg2)[2]*x^2),xlim=c(1,70)) #' points(mat2[which(mat2[,3]=="2"),1:2],col=2) #' @export lmSelClu <- function(dat, useCol=1:2, clu="max", regTy="lin", filt1=NULL, filt2=NULL, silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="lmSelClu") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE regTyOpt <- c("lin","sqNor","res", "inv","invRes","norRes","sqNorRes","parb","parbRes") msgE <- " Argument 'dat' should matrix or data.frame with at least 3 numeric columns (including column called 'clu')" if(length(dim(dat)) != 2) stop(msgE) if(ncol(dat) <3) stop(msgE) cluCol <- which(colnames(dat) %in% c("clu","cluID")) if(length(cluCol) <1) stop(" Can't find column named 'clu' or 'cluID' (specifying sub-group/cluster)") if(length(clu) >1) { message(fxNa," 'clu' should be of length 1 but is ",length(clu),", truncating...") clu <- clu[1]} if(identical(clu,"max")) { clu <- as.numeric(names(which.max(table(dat[,cluCol[1]])))) } msg2 <- paste(" Argument 'regTy' should be either ",pasteC(regTyOpt)) if(length(regTy) !=1 || sum(regTy %in% regTyOpt) !=1) stop(msg2) lmColNa <- colnames(dat)[-1*cluCol][useCol] if(!is.null(filt1)) dat <- dat[if(is.logical(filt1)) filt1 else { which(dat[,lmColNa[1]] > min(filt1) & dat[,lmColNa[1]] < max(filt1,na.rm=TRUE))},] if(!is.null(filt2)) dat <- dat[if(is.logical(filt2)) filt2 else { which(dat[,lmColNa[2]] > min(filt2) & dat[,lmColNa[2]] < max(filt2,na.rm=TRUE))},] dat <- dat[which(dat[,cluCol]==clu),] if(length(dat) <1) { message(fxNa,": No data left for linear modelling !") return(NULL) } else { message(fxNa," ready for linear modeling of ",nrow(dat)," lines of data, ie cluster '",clu,"'") dat <- data.frame(dat, res=dat[,lmColNa[1]]-dat[,lmColNa[2]]) dat$normRes <- dat$res/dat[,lmColNa[1]] dat$sqNormRes <- dat$res/(dat[,lmColNa[1]]^2) colnames(dat)[which(colnames(dat)==lmColNa[2])] <- "slope" dat$invSlope <- 1/dat$slope switch(regTy, lin = stats::lm(get(lmColNa[1]) ~ slope, data=as.data.frame(dat)), sqNor = stats::lm(get(lmColNa[1])^2 ~ slope, data=as.data.frame(dat)), inv = stats::lm(get(lmColNa[1]) ~ invSlope, data=as.data.frame(dat)), parb= stats::lm(get(lmColNa[1]) ~ invSlope^2, data=as.data.frame(dat)), res = stats::lm(res ~ slope, data=as.data.frame(dat)), invRes = stats::lm(res ~ invSlope, data=as.data.frame(dat)), parbRes= stats::lm(normRes ~ invSlope^2, data=as.data.frame(dat)), norRes = stats::lm(normRes ~ slope, data=as.data.frame(dat)), sqNorRes = stats::lm(sqNormRes ~ slope, data=as.data.frame(dat))) }}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/lmSelClu.R
#' rbind on lists #' #' rbind-like function to append list-elements containing matrixes (or data.frames) and return one long table. #' All list-elements must have same number of columns (and same types of classes in case of data.frames. #' Simple vectors (as list-elements) will be considered as sigle lines for attaching. #' @param lst (list, composed of multiple matrix or data.frames or simple vectors) main input (each list-element should have same number of columns, numeric vectors will be converted to number of columns of other columns/elements) #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns (depending on input) a matrix or data.frame #' @seealso \code{rbind} in \code{\link[base]{cbind}} #' @examples #' lst1 <- list(matrix(1:9, ncol=3, dimnames=list(letters[1:3],c("AA","BB","CC"))), #' 11:13, matrix(51:56, ncol=3)) #' lrbind(lst1) #' @export lrbind <- function(lst, silent=FALSE, debug=FALSE, callFrom=NULL) { fxNa <- .composeCallName(callFrom, newNa="lrbind") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(debug) message(fxNa,"lrb1") argN <- deparse(substitute(lst)) if(!isTRUE(silent)) silent <- FALSE chDf <- sapply(lst, inherits, "data.frame") if(any(chDf)) { iniCla <- sapply(lst[[which(chDf)[1]]], class) # read types of classes of 1st data.frame for(i in which(chDf)) lst[[i]] <- as.matrix(lst[[i]]) } chNum <- sapply(lst, inherits, c("numeric","integer")) nCol <- if(any(!chNum)) ncol(lst[[which(!chNum)[1]]]) else min(sapply(lst, length), na.rm=TRUE) if(any(chNum)) for (i in which(chNum)) lst[[i]] <- matrix(lst[[i]], ncol=nCol) ldim <- sapply(lst, dim) if(length(unique(ldim[2,])) >1) stop("Bad dimension(s): each list-element should have same number of columns") outm <- matrix(nrow=sum(ldim[1,]), ncol=ldim[2,1]) ldim <- rbind(ldim, cumsum(ldim[1,])) ldim <- rbind(ldim, c(1, ldim[3, -1*ncol(ldim)] +1)) for(i in 1:ncol(ldim)) outm[ldim[4,i]:ldim[3,i],] <- lst[[i]] lstColn <- unlist(sapply(lst, colnames)) if(!is.null(lstColn)) if(length(unique(lstColn)) ==ldim[2,1] && !silent) message(fxNa,"Col-names not homogenous or partially absent in ",argN) colnames(outm) <- colnames(lst[[1]]) lstRown <- unlist(sapply(lst, rownames)) if(!is.null(lstRown)) if(length(unique(lstRown)) ==ldim[3, ncol(ldim)]) { rownames(outm) <- unique(lstRown)} else if(!silent) message(fxNa,"Row-names not complete") if(any(chDf)) { outm <- as.data.frame(outm) chCla <- sapply(outm, class) ==iniCla if(any(!chCla)) for(i in which(!chCla)) class(outm[,i]) <- iniCla[i]} outm }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/lrbind.R
#' Make MA-List object #' #' \code{makeMAList} extracts sets of data-pairs (like R & G series) and makes MA objects as \code{MA-List object} (eg for ratio oriented analysis). #' The grouping of columns as sets of replicate-measurements is done according to argumnet \code{'MAfac'}. #' The output is fully compatible to functions of package \href{https://bioconductor.org/packages/release/bioc/html/limma.html}{limma} (Bioconductor). #' #' @details This function requires Bioconductor package \href{https://bioconductor.org/packages/release/bioc/html/limma.html}{limma} being installed. #' #' @param mat main input matrix #' @param MAfac (factor) factor orgnaizing columns of 'mat' (if \code{useF} contains the default 'R' and 'G', they should also be part of \code{MAfac}) #' @param useF (character) two specific factor-leves of \code{MAfac} that will be used/extracted #' @param isLog (logical) tell if data is already log2 (will be considered when computing M and A values) #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return limma-type "MAList" containing M and A values #' @seealso \code{\link{test2factLimma}}, for creating RG-lists within limma: \code{MA.RG} in \code{\link[limma]{normalizeWithinArrays}} #' @examples #' set.seed(2017); t4 <- matrix(round(runif(40,1,9),2), ncol=4, #' dimnames=list(letters[c(1:5,3:4,6:4)], c("AA1","BB1","AA2","BB2"))) #' makeMAList(t4, gl(2,2,labels=c("R","G"))) #' @export makeMAList <- function(mat, MAfac, useF=c("R","G"), isLog=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL){ ## extract sets of data-pairs (like R & G series) and MA objects as MA-List object (eg for ratio oriented analysis) according to 'MAfac' ## 'MAfac' .. factor ## require(limma) fxNa <- .composeCallName(callFrom, newNa="makeMAList") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE chPa <- requireNamespace("limma", quietly=TRUE) if(!chPa) {return(NULL); warning(fxNa,"Package 'limma' not found ! Please install from Bioconductor") } else { if(!all(useF %in% MAfac & length(useF) ==2 & length(MAfac) >1)) stop(" Argument 'useF' should describe 2 elements of 'MAfac'") if(!isLog) { if(any(mat <0) & !silent) message(fxNa,"Negative values will create NAs at log2-transformation !") } out <- try(limma::MA.RG(if(isLog) list(R=2^mat[,which(MAfac==useF[1])], G=2^mat[,which(MAfac==useF[2])]) else { list(R=mat[,which(MAfac==useF[1])], G=mat[,which(MAfac==useF[2])])}, bc.method="subtract", offset=0), silent=TRUE) if(inherits(out, "try-error")) {warning("UNABLE to run limma::MA.RG() '!"); out <- NULL} out } } #' Search character-string and cut either before or after #' #' This function extracts/cuts text-fragments out of \code{txt} following specific anchors defined by arguments \code{cutFrom} and \code{cutTo}. #' #' @param dat (matrix or data.frame) main input #' @param ty (character) type of ratio (eg 'log2') #' @param colNaSep (character) separator #' @return This function returns a numeric vector #' @seealso \code{\link{makeMAList}}, \code{\link[base]{grep}} #' @examples #' .allRatios(matrix(11:14, ncol=2)) #' @export .allRatios <- function(dat, ty="log2", colNaSep="_") { ## calculate all (log2-)ratios between (entire) indiv columns of 'dat' (matrix or data.frame) ## return matrix with ratios (betw columns of dat) out <- matrix(nrow=nrow(dat), ncol=choose(ncol(dat),2)) pwCoor <- upperMaCoord(ncol(dat)) out <- apply(pwCoor, 1, function(x) dat[,x[1]]/dat[,x[2]]) colnames(out) <- apply(pwCoor,1,function(x) paste(colnames(dat)[x[1]],colnames(dat)[x[2]], sep=colNaSep)) if(identical(ty,"log2")) out <- log2(out) if(identical(ty,"log10")) out <- log10(out) if(identical(ty,"log")) out <- log(out) out } #' Calculate ratios for each column to each column of reference-matrix #' #' This function calculates ratio(s) for each column of matrix 'x' versus all/each column(s) of matrix 'y' (reference) #' #' @param x (matrix or data.frame) main input1 #' @param y (matrix or data.frame) main input2 #' @param asLog2 (logical) #' @param sumMeth (character) method #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a numeric vector or matrix in dimension of 'x' (so far summarize all ratios from mult division from mult ref cols as mean or median ) #' @seealso \code{\link{makeMAList}}, \code{\link[base]{grep}} #' @examples #' .allRatioMatr1to2(matrix(11:14, ncol=2), matrix(21:24, ncol=2)) #' @export .allRatioMatr1to2 <- function(x, y, asLog2=TRUE, sumMeth="mean", callFrom=NULL){ ## calculate ratio(s) for each column of matrix 'x' versus all/each column(s) of matrix 'y' (reference) ## return matrix in dimension of 'x' (so far summarize all ratios from mult division from mult ref cols as mean or median ) ## 'log2' .. output as log2 format (before summarizing different ratios obtained for given column of 'x') ## 'sumMeth' .. for method for summarizing the ratios from diff cols of 'y' (default mean, otherwise median) ## variant of .allRatios() but including external reference ('y') fxNa <- .composeCallName(callFrom,newNa=".allRatioMatr1to2") xDimNa <- dimnames(x) yDimNa <- dimnames(y) if(length(xDimNa) <1) x <- matrix(x, ncol=1, dimnames=list(rownames(x),"x1")) if(length(yDimNa) <1) y <- matrix(y, ncol=1, dimnames=list(rownames(y),"y1")) if(nrow(x) != nrow(y)) stop(fxNa," number of rows in 'x' and 'y' must be equal !") ## main out <- apply(x, 2, function(da,re) matrix(rep(da,ncol(re)), ncol=ncol(re))/re, re=y) # is this really ok ? if(!is.list(out)) out <- list(out) if(asLog2) out <- lapply(out,log2) out <- if(identical(sumMeth,"mean")) lapply(out,rowMeans) else lapply(out,function(x) apply(x, 1, stats::median,na.rm=TRUE)) # summarize nLen <- sapply(out,length) if(length(unique(nLen)) >1 | any(nLen <1)) message(fxNa," strange format of results, length of lists: ", paste(nLen,collapse=" ")) out <- out[which(nLen >0)] out <- if(length(out) >1) matrix(unlist(out), nrow=nrow(x), dimnames=xDimNa) else out[[1]] out } #' Get A value for each group of replicates #' #' This function calculates the 'A' value (ie group mean) for each group of replicates (eg for MA-plot) #' #' @param dat (matrix or data.frame) main input #' @param grp (factor) grouping of replicates #' @return This function returns a numeric vector #' @seealso \code{\link{makeMAList}} #' @examples #' .getAmean(matrix(11:18, ncol=4), gl(2,2)) #' @export .getAmean <- function(dat, grp) { ## get A value (ie group mean) for each group of replicates (eg for MA-plot) ## NOTE : this fx is redundant; does about the same as .rowGrpMeans() ! if(length(levels(grp)) <2) stop(" problem: 'grp' as factor should have at least 2 levels") if(length(grp) != ncol(dat)) stop(" problem: length of 'grp' should match numbe of columns in 'dat'") if(!is.factor(grp)) grp <- as.factor(grp) out <- matrix(nrow=nrow(dat), ncol=length(levels(grp)), dimnames=list(rownames(dat), levels(grp))) for(i in 1:length(levels(grp))) out[,i] <- rowMeans(dat[,which(grp==levels(grp)[i])],na.rm=TRUE) out } #' Get A value for each group of replicates based on comp #' #' This function calculates the 'A' value (ie group mean) for each group of replicates (eg for MA-plot) #' \code{comp} is matrix telling which groups to use/compare, assuming that dat are already group-means) #' #' @param dat (matrix or data.frame) main input #' @param comp (matrix) tells which groups to use/compare, assuming that dat are already group-means) #' @return This function returns a numeric vector #' @seealso \code{\link{makeMAList}} #' @examples #' .getAmean(matrix(11:18, ncol=4), gl(2,2)) #' @export .getAmean2 <- function(dat, comp) as.matrix(apply(comp, 1, function(co,x) rowMeans(x[,co],na.rm=TRUE),dat)) # transform dat to A-values for MA-plot (comp is matrix telling which groups to use/compare, assuming that dat are already group-means) #' Get M value for each group of replicates based on comp #' #' This function calculates the 'M' value (ie log-ratio) for each group of replicates based on comp (eg for MA-plot) #' \code{comp} is matrix telling which groups to use/compare, assuming that dat are already group-means) #' #' @param dat (matrix or data.frame) main input #' @param comp (matrix) tells which groups to use/compare, assuming that dat are already group-means) #' @return This function returns a numeric vector #' @seealso \code{\link{makeMAList}} #' @examples #' .getAmean(matrix(11:18, ncol=4), gl(2,2)) #' @export .getMvalue2 <- function(dat, comp) as.matrix(apply(comp, 1, function(co,x) diff(t(x[,co])),dat)) # transform dat to M-values ; comp : matrix (2 columns) indicating which columns should be compared
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/makeMAList.R
#' Make non-redundant matrix #' #' \code{makeNRedMatr} takes matrix or data.frame 'dat' to summarize redundant lines (column argument \code{iniID}) along method specified in \code{summarizeRedAs} #' to treat all lines with redundant \code{iniID} by same approach (ie for all columns the line where specified column is at eg max = 'maxOfRef' ). #' If no name given, the function will take the last numeric (factors may be used - they will be read as levels). #' #' @param dat (matrix or data.frame) main input for making non-redundant #' @param summarizeRedAs (character) summarization method(s), typical choices 'median','mean','min' or 'maxOfRef','maxAbsOfRef' for summarizing according to 1 specified column, may be single method for all or different method for each column (besides col 'iniID') or special method looking at column (if found, first of special methods used, everything else not considered). #' @param iniID (character) column-name used as initial ID (default="iniID") #' @param retDataFrame (logical) if TRUE, check if text-columns may be converted to data.frame with numeric #' @param callFrom (character) allows easier tracking of message(s) produced #' @param silent (logical) suppress messages #' @param debug (logical) for bug-tracking: more/enhanced messages #' @return This function returns a (numeric) matrix or data.frame with summarized data and add'l col with number of initial redundant lines #' @seealso simple/partial functionality in \code{\link{summarizeCols}}, \code{\link{checkSimValueInSer}} #' @examples #' t3 <- data.frame(ref=rep(11:15,3),tx=letters[1:15], #' matrix(round(runif(30,-3,2),1),nc=2),stringsAsFactors=FALSE) #' 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")) #' @export makeNRedMatr <- function(dat, summarizeRedAs, iniID="iniID", retDataFrame=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL) { fxNa <- .composeCallName(callFrom,newNa="makeNRedMatr") maxLaArg <- c("maxOfRef","minOfRef","maxAbsOfRef") summOpt <- c("median","mean","min","max","first","last",maxLaArg) summOpt <- c(summOpt,paste(summOpt,"Complete",sep="")) chSuMeth <- summarizeRedAs %in% summOpt txt <- " argument 'dat' must be matrix or data.frame with >1 line" if(debug) silent <- FALSE if(length(dim(dat)) <1) stop(txt) else if(nrow(dat) <2) return(dat) if(all(!chSuMeth)) stop(fxNa,"Value(s) ",pasteC(utils::head(chSuMeth),quoteC="'")," in argument 'summarizeRedAs' not valid") if(any(!chSuMeth) && !silent) message(fxNa,"TROUBLE ahead ? Some methods specified in 'summarizeRedAs' seem not valid") iniColNa <- colnames(dat) txt <- "'iniID' must be single column name of 'dat' !" if(length(iniID) !=1) stop(fxNa,txt) else if(is.na(iniID)) stop(fxNa,txt) iniIDcol <- colnames(dat) ==iniID if(sum(iniIDcol) <1) stop(fxNa,txt," Cannot identify column '",iniID,"' in input !") ## check/correct for NAs in refID ?(ID for grouping) ?? sumRedMode <- rep("",sum(!iniIDcol)) # need to know which col is numeric when treating each col individually for(i in which(!iniIDcol)) sumRedMode[i] <- mode(dat[,i]) if(sum(summarizeRedAs %in% maxLaArg,na.rm=TRUE) >0) { # has special methods (limit to those) if(!silent && length(summarizeRedAs) >1) message(fxNa,"Canot use all ",length(summarizeRedAs), " methods specified in 'summarizeRedAs', only 1 method can be applied, using 1st of special methods") summarizeRedAs <- summarizeRedAs[which(summarizeRedAs %in% maxLaArg)] if(sum(names(summarizeRedAs) %in% colnames(dat),na.rm=TRUE) >0) { # (col) names identified summarizeRedAs <- summarizeRedAs[which(names(summarizeRedAs) %in% colnames(dat))[1]] } else { summarizeRedAs <- summarizeRedAs[1] lastNum <- sumRedMode %in% c("numeric","integer") lastNum <- which(lastNum)[sum(lastNum,na.rm=TRUE)] if(!silent) message(fxNa,"Which column to use with '",summarizeRedAs,"' not specified, using last numeric '",colnames(dat)[lastNum],"'") names(summarizeRedAs) <- colnames(dat)[lastNum] } } else if(length(summarizeRedAs) < ncol(dat)) { if(length(summarizeRedAs) >1 && !silent) message(fxNa,"Too few (",length(summarizeRedAs),") methods specified, recycling methods") summarizeRedAs <- rep(summarizeRedAs,ncol(dat))[1:(ncol(dat))] } if(any(summarizeRedAs %in% maxLaArg) && sum(names(summarizeRedAs) %in% colnames(dat)>0,na.rm=TRUE)) { tm2 <- which.min(!colnames(dat) %in% names(summarizeRedAs)) # which col of data as key summarizeRedAs <- summarizeRedAs[which.min(!names(summarizeRedAs) %in% colnames(dat)[tm2])] # need short 'summarizeRedAs' with 'maxLast'(or simil) } else { if(length(summarizeRedAs) < sum(!iniIDcol)) { if(!silent) message(fxNa,"Argument 'summarizeRedAs' has to few elements, extening by ",sum(!iniIDcol) -length(summarizeRedAs)," elements") summarizeRedAs <- rep(summarizeRedAs,ceiling(sum(!iniIDcol)/length(summarizeRedAs)))[1:sum(!iniIDcol)] names(summarizeRedAs) <- colnames(dat)[which(!iniIDcol)] }} if(debug) {message(fxNa," xxmakeNRedMatr1")} refID <- dat[,which(iniIDcol)] out <- matrix(NA,nrow=length(unique(refID)),ncol=ncol(dat),dimnames=list(unique(refID),colnames(dat))) # initalize (for all summariz w/o special meth) if(any(summarizeRedAs %in% maxLaArg)) { ## summarize all cols together (based on last col) if(length(names(summarizeRedAs)) <1) { lastNum <- sumRedMode %in% c("numeric","integer") lastNum <- which(lastNum)[sum(lastNum,na.rm=TRUE)] if(!silent) message(fxNa,"Which column to use with '",summarizeRedAs,"' not specified, using last numeric '",colnames(dat)[lastNum],"'") names(summarizeRedAs) <- colnames(dat)[lastNum] } sumRefCo <- colnames(dat)==names(summarizeRedAs) sumRef <- dat[,which(sumRefCo)[1]] tmp <- cbind(dat,ref=sumRef) tmp <- t(sapply(by(tmp, dat[,which(iniIDcol)],function(y) y), summarizeCols,meth=summarizeRedAs)) out <- as.matrix(as.data.frame(tmp))[,-ncol(tmp)] colnames(out) <- colnames(dat) } else { if(length(unique(summarizeRedAs)) >1) { for(i in which(!iniIDcol)) { # various summarization methods defined for each col ... ## key for grouping : iniIDcol key for summarizing : which(sumRefCo) tmp <- tapply(dat[,i], refID, function(x) if(is.numeric(x) & !all(is.na(x))) .summarizeCols(x,me=summarizeRedAs[i]) else .sortMid(x)) out[,i] <- tmp } if(!silent) message(fxNa,"Various summarization methods appear, run col by col") } else { # all summerizatio by same mode, run batch for numeric & batch for character if(!silent) message(fxNa,"Common summarization method '",unique(summarizeRedAs),"', run as batch") if(any(sumRedMode != "numeric")) { i <- which(sumRedMode != "numeric") # & colnames(dat) !=iniID out[,i] <- tmp <- t(sapply(by(dat[,i],refID,function(y) y), function(x) apply(x,2,.sortMid))) } if(any(sumRedMode == "numeric")) { i <- which(sumRedMode == "numeric") # & colnames(dat) !=iniID out[,i] <- tmp <- t(sapply(by(dat[,i],refID,function(y) y), function(x) .summarizeCols(x,me=summarizeRedAs[i][1]))) } } } if(!silent) message(fxNa,"Summarize redundant based on col '",iniID,"' using method(s) : ",pasteC(summarizeRedAs,quoteC="'"), if(any(summarizeRedAs %in% maxLaArg)) c(" and col '",names(summarizeRedAs)[1],"'")," yielding ",ncol(out)," cols") if(debug) {message(fxNa," xxGetRe3")} if(length(dim(tmp)) >1) { if(length(rownames(tmp)) >0) rownames(out) <- rownames(tmp) } else if(length(names(tmp)) >0) rownames(out) <- names(tmp) out <- cbind(out, tapply(dat[,1], dat[,which(iniIDcol)], length)) colnames(out)[ncol(out)] <- if("nRedLi" %in% colnames(out)) paste(colnames(out)[rev(grep("^nRedLi",colnames(out)))[1]],"X",sep=".") else "nRedLi" if(retDataFrame && "character" %in% mode(out)) out <- convMatr2df(out, silent=silent) out } #' Choose most frequent or middle of sorted vector #' #' This function chooses the (first) most frequent or middle of sorted vector #' #' @param x (numeric) main input #' @param retVal (logical) return value of most frequent, if \code{FALSE} return index of (1st) 'x' for most frequent #' @return This function returns a numeric verctor #' @seealso simple/partial functionality in \code{\link{summarizeCols}}, \code{\link{checkSimValueInSer}} #' @examples #' .sortMid(11:14) #' @export .sortMid <- function(x, retVal=TRUE) { ## choose (1st) most frequent or (if all equal) middle of sorted vector ## 'x' .. character vector; return single 'representative' element ## 'retVal'.. return value of most frequent, if FALSE return index of (1st) 'x' for most frequent ## note : in case of equally frequent only one is chose, no warning x <- naOmit(x); if(length(x) >0) {y <- table(x) out <- if(length(unique(y)) <2) names(y)[which.max(y)] else sort(x)[ceiling(length(x)/2)]} else NA if(!retVal) out <- which(x==out[1])[1] out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/makeNRedMatr.R
#' 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 bes resuts will be used. #' #' @details #' This function tests all columns of \code{mat} to find perfect matching results to the reference \code{ref}. #' In case of multiple results the #' In case no direct matching is possible, \code{grep} will be used to find the best partial matching. #' The orderof the rows of input \code{mat} will be adjusted according to the matching results. #' #' If \code{addRef=TRUE}, the reference will be included as additional column to the results, too. #' #' @param mat (matrix or data.frame) main input, all columns of \code{mat} will be tested for (partial) matching of \code{ref} #' @param ref (character, length must match ) reference for trying to match each of the columns of \code{mat} #' @param addRef (logical), if \code{TRUE} the content of \code{ref} will be added to \code{mat} as additional column #' @param inclInfo (logical) allows returning list with new matrix and additional information #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns the input matrix in an adjusted order (plus an optional additional column showing the reference) #' or if \code{inclInfo=TRUE} a list with $mat (adjusted matrix), $byColumn, $newOrder and $method; #' the reference can bee added as additional last column if \code{addRef=TRUE} #' @seealso \code{\link[base]{match}}, \code{\link[base]{grep}}, \code{\link{trimRedundText}}, \code{\link{replicateStructure}} #' @examples #' ## 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' #' @export matchMatrixLinesToRef <- function(mat, ref, addRef=TRUE, inclInfo=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL) { ## find best column for matching lines of mat (matrix) to ref (char vector) via two way grep ## return list $grep (matched matrix), $col best column fxNa <- .composeCallName(callFrom, newNa="matchMatrixLinesToRef") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE byCol <- out <- matElim <- msg <- msgM <- newOr <- NULL # initialize datOK <- length(mat) >0 namesXY <- sub("\\[.*","",c(deparse(substitute(mat)), deparse(substitute(ref)))) .applyOrder <- function(mat, ref, newOr, goodCol, matElim=NULL, chIdenCol=NULL, addRef=TRUE) { ## set rows of matrix 'mat' into new order 'newOr' #; if 'matAlt' give, use instead of 'mat' ## 'goodCol' from counting NAs (eg from match), has names of colnames of mat ## 'ref' .. (character); add'l column to add to output ## 'newOr' ..(integer) new order ## 'chIdenCol' ..(logical) has names of very orig mat ## 'matElim' ..(matrix) add'l matrix to add to output (order will be adjusted like mat) out <- if(length(newOr) ==1 || ncol(mat)==1) matrix(mat[newOr,], nrow=length(newOr), dimnames=list(rownames(mat)[newOr], colnames(mat))) else mat[newOr,] if(length(matElim) >0) { out <- cbind(out, if(length(newOr) ==1 || ncol(matElim)==1) matrix(matElim[newOr,], ncol=ncol(matElim), dimnames=list(rownames(matElim)[newOr], colnames(matElim))) else matElim[newOr,]) if(is.logical(chIdenCol) && length(names(chIdenCol)) >0) chIdenCol <- names(chIdenCol) if(length(names(chIdenCol)) >0) out <- out[,match(names(chIdenCol), colnames(out))]} if(addRef) out <- cbind(out, ref=ref) out } if(length(mat)==1) { out <- mat; if(!silent) message(fxNa,"length of '",namesXY[1],"'(mat) ==1, nothing to do - return as input"); datOK <- FALSE} if(datOK) { if(length(dim(mat)) <2) mat <- matrix(mat, nrow=length(mat), dimnames=list(names(mat), namesXY[1])) if(length(ref) <1) { datOK <- FALSE stop(fxNa,"Argument '",namesXY[2],"' has incorrect length (found ",length(ref),") !")}} if(datOK) if(nrow(mat)==1) {out <- mat; if(!silent) message(fxNa,"'",namesXY[1],"' has single row, nothing to do - return as input"); datOK <- FALSE} if(datOK) { ## remove all columns of mat with identical values fidentVal <- function(x) length(unique(x)) ==1 chIdenCol <- apply(mat, 2, fidentVal) # designate columns not useful (all identical values); has also init colnames (as names) if(all(chIdenCol, na.rm=TRUE)) { datOK <- FALSE if(!silent) message(fxNa,"All lines of '",namesXY[1],"' seem identical, nothing to do for best matching ! (returning NULL)") } else { if(any(chIdenCol, na.rm=TRUE)) { matElim <- if(sum(chIdenCol) >1) mat[,which(chIdenCol)] else matrix(mat[,which(chIdenCol)], ncol=1, dimnames=list(rownames(mat), colnames(mat)[which(chIdenCol)])) matRe <- mat[,which(!chIdenCol)] if(debug) message(fxNa,"Removing ",sum(chIdenCol), "columns of all identical values (have no value for distinguishing lines)") } else matRe <- NULL if(debug) {message(fxNa,"mML1"); mML1 <- list(mat=mat,matRe=matRe,ref=ref,matElim=matElim,chIdenCol=chIdenCol,out=out )} ## try simple match sMa <- apply(if(length(matRe) >0) matRe else mat, 2, function(x) match(ref, x)) chNa <- colSums(is.na(sMa)) if(any(chNa==0)) { newOr <- sMa[,which(chNa==0)[1]] out <- .applyOrder(mat=mat, ref=ref, newOr=newOr, goodCol=chNa, matElim=matElim, chIdenCol=chIdenCol, addRef=addRef) # byCol <- which(chNa==0)[1] msgM <- "direct match" } else { if(debug) {message(fxNa,"mML2"); mML2 <- list()} ## trim redundant text, re-try match mat2 <- apply(if(length(matRe) >0) matRe else mat, 2, trimRedundText, minNchar=1, side="both", silent=silent,callFrom=fxNa,debug=debug) ref2 <- trimRedundText(ref, minNchar=1, side="both", silent=silent,callFrom=fxNa,debug=debug) sMa <- apply(mat2, 2, function(x) match(ref2, x)) chNa <- colSums(is.na(sMa)) if(any(chNa==0)) { newOr <- sMa[,which(chNa==0)[1]] out <- .applyOrder(mat=mat, ref=ref, newOr=newOr, goodCol=chNa, matElim=matElim, chIdenCol=chIdenCol, addRef=addRef) # byCol <- which(chNa==0)[1] msgM <- "direct match after trimming redundant text" } else { ## direct matching not successful, check if grep possible (only when pattern not longer than x) if(debug) {message(fxNa,"mML3"); mML3 <- list(mat=mat,ref=ref,matElim=matElim,chIdenCol=chIdenCol,out=out,chNa=chNa,mat2=mat2,ref2=ref2,sMa=sMa )} leM <- nchar(as.matrix(mat2)) leR <- nchar(ref2) refPoss <- apply(leM, 2, function(x) all(sort(x, decreasing=TRUE)[1:length(leR)] >= sort(leR, decreasing=TRUE))) if(any(refPoss)) { # grep each ref to each col chGre <- apply(mat2, 2, function(x) sapply(ref2, grep, x)) chDL <- sapply(chGre, sapply, length) # number of grp hits ch1 <- colSums(chDL ==1) ==length(ref) if(any(ch1)) { newOr <- chGre[[which(ch1)[1]]] out <- .applyOrder(mat=mat, ref=ref, newOr=newOr, goodCol=chNa, matElim=matElim, chIdenCol=chIdenCol, addRef=addRef) # byCol <- which(ch1)[1] msgM <- "grep of ref after trimming redundant text" } else { refPoss <- FALSE msg <- c("grep matching not successful (",c("no","ambiguous hits")[1 +any(colSums(chDL >1) >0)],")") }} if(any(!refPoss)) { ## check by harmonizing/trimming enumerators mat3 <- apply(mat2, 2, rmEnumeratorName, nameEnum=c("Number","No","#","Replicate","Sample","Speciem"), sepEnum=c(" ","-","_"), newSep="_No", incl=c("anyCase","trim1"), silent=silent, debug=debug, callFrom=fxNa) chCol <- colSums(mat2 ==mat3) < nrow(mat2) # see if change in all elements in a given column if(debug) {message(fxNa,"mML4"); mML4 <- list(mat=mat,mat3=mat3,ref=ref,matElim=matElim,chIdenCol=chIdenCol,chCol=chCol,out=out,chNa=chNa,mat2=mat2,ref2=ref2,sMa=sMa,leM=leM,leR=leR ) } if(any(chCol)) { if(debug) message(fxNa,"Enumerators exist, try matching after harmonizing style ..") if(!all(chCol)) mat3 <- if(sum(chCol) >1) mat3[,which(chCol)] else matrix(mat3[,which(chCol)], nrow=nrow(mat), dimnames=list(rownames(mat2), colnames(mat2)[which(chCol)])) # trim ref3 <- rmEnumeratorName(ref, nameEnum=c("","Number","No","#","Replicate","Sample","Speciem"), sepEnum=c(" ","-","_"), newSep="_No", incl=c("anyCase","trim1"), silent=silent, debug=debug, callFrom=fxNa) chDir <- apply(mat3, 2, match, ref3) chMa <- apply(chDir, 2, function(x) all(1:nrow(mat) %in% x, na.rm=TRUE)) if(debug) {message(fxNa,"mML4b"); mML4b <- list(mat=mat,mat3=mat3,ref=ref,ref3=ref3,matElim=matElim,chIdenCol=chIdenCol,chMa=chMa,chDir=chDir,chCol=chCol,out=out,chNa=chNa,mat2=mat2,ref2=ref2,sMa=sMa,leM=leM,leR=leR ) } if(any(chMa)) { goodCol <- which(chMa)[1] if(debug) message(fxNa,"Found good hit by using column '",names(goodCol),"' ie ",pasteC(utils::head(mat2[,goodCol]))," ...") out <- if(addRef) cbind(mat[chDir[,goodCol],], ref=ref) else mat[chDir[,goodCol],] msgM <- "Match after harmonizing enumerators (& trimming redundant text)" if(debug) {message(fxNa,"mML4c"); mML4c <- list(mat=mat,mat3=mat3,out=out,ref=ref,ref3=ref3,matElim=matElim,chIdenCol=chIdenCol,chMa=chMa,chDir=chDir,chCol=chCol,chNa=chNa,mat2=mat2,ref2=ref2,sMa=sMa,leM=leM,leR=leR ) } } else { if(debug) message(fxNa,"Try matching all after trimming enumerators") mat3 <- apply(mat2, 2, rmEnumeratorName, nameEnum=c("Number","No","#","Replicate","Sample","Speciem"), sepEnum=c(" ","-","_"), newSep="", incl=c("anyCase","trim1","rmEnum"), silent=silent, callFrom=fxNa) ref3 <- rmEnumeratorName(ref, nameEnum=c("","Number","No","#","Replicate","Sample","Speciem"), sepEnum=c(" ","-","_"), newSep="", incl=c("anyCase","trim1","rmEnum"), silent=silent, callFrom=fxNa) chDir <- apply(mat3, 2, match, ref3) chNa <- colSums(is.na(chDir)) <1 if(any(chMa)) { ## need to attribute multiple hits warning(fxNa,"Attribute multiple hits NOT FINISHED !!") } else { message(fxNa," STILL NO MATCH FOUND, try reverse grep of terms wo enumerators ?") invePoss <- apply(leM, 2, function(x) all(sort(x, decreasing=TRUE)[1:length(leR)] <= sort(leR, decreasing=TRUE))) } } } else { ## grep each ref to each col ## need to try reverse matching chRev <- apply(mat2, 2, function(x) sapply(x, grep, ref2)) chRL <- sapply(chRev, sapply, length) # number of grp hits ch1 <- (if(ncol(mat) >1) colSums(chRL ==1) else sum(chRL==1)) ==length(ref) if(any(ch1)) { newOr <- if(is.list(chRev)) order(unlist(chRev[[which(ch1)[1]]], use.names=FALSE)) else chRev[,which(ch1)[1]] # new order for mat if(debug) {message(fxNa,"mML5") } out <- cbind(if(any(dim(mat)==1, length(newOr)==1)) matrix(mat[newOr,], ncol=ncol(mat), dimnames=list(rownames(mat)[newOr], colnames(mat))) else mat[newOr,], if(any(dim(matElim)==1, length(newOr)==1)) matrix(matElim[newOr,], ncol=ncol(matElim), dimnames=list(rownames(matElim)[newOr], colnames(matElim))) else matElim[newOr,]) if(length(matElim) >0) out <- out[,match(names(chIdenCol), colnames(out))] # adjust init col-order if(addRef) out <- cbind(out, ref=ref) byCol <- which(ch1)[1] msgM <- "Reverse grep after trimming redundant text" } else msg <- c(msg,"Tried reverse grep matching, but impossible to find full set of non-ambiguous matches") } } } } if(debug) {message(fxNa,"mML6"); mML6 <- list(mat=mat,ref=ref,matElim=matElim,chIdenCol=chIdenCol,out=out )} if(length(msg) >0 && !silent) message(fxNa,msg,"! Returning NULL") if(debug && length(newOr) >0) message(fxNa,"Successfully found new order by ",msgM," : ",pasteC(newOr, quoteC="'")) } } if(isTRUE(inclInfo)) list(mat=out, byColumn=match(names(byCol), names(chIdenCol)), newOrder=newOr, method=msgM) else out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/matchMatrixLinesToRef.R
#' Value Matching with optional reversing of sub-parts of non-matching elements #' #' This function provides a variant to \code{\link[base]{match}}, where initially non-matching elements of \code{x} #' will be tested by decomposing non-matching elements, reversing the parts in front and after the separator \code{sep} and re-matching. #' If separator \code{sep} does not occur, a warning will be issued, if it occurs more than once, #' the parts before and after the first separartor will be used and a warning issued. #' #' @param x (character) first vector for match #' @param y (character) second vector for match #' @param sep (character) separator between elements #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return index for matching (integer) x to y #' @seealso \code{\link[base]{match}} #' @examples #' tx1 <- c("a-b","a-c","d-a","d-b","b-c","d-c") #' tmp <- triCoord(4) #' tx2 <- paste(letters[tmp[,1]],letters[tmp[,2]],sep="-") #' ## Some matches won't be found, since 'a-d' got reversed to 'd-a', etc... #' match(tx1,tx1) #' matchNamesWithReverseParts(tx1,tx2) #' @export matchNamesWithReverseParts <- function(x, y, sep="-", silent=FALSE, debug=FALSE, callFrom=NULL) { fxNa <- .composeCallName(callFrom,newNa="matchNamesWithReverseParts") if(length(x) <1) stop(" Nothing to do, 'x' seems empty") if(length(y) <1) stop(" Nothing to do, 'y' seems empty") ma1 <- match(x,y) if(any(is.na(ma1))) { sup <- which(is.na(ma1)) x2 <- strsplit(x[sup],sep) chX <- sapply(x2,length) if(any(chX <2) && !silent) message(fxNa,"Can't find separator ('",sep,"') in ",sum(chX <2)," elements of 'x'") if(any(chX >2) && !silent) message(fxNa,"BEWARE, results may be different to expected ! Separator ('", sep,"') occurs more than once in ",sum(chX >2)," elements of 'x'") x2 <- sapply(x2,function(z) if(length(z) >1) paste(z[2],z[1],sep=sep) else z) x[sup] <- x2 ma1 <- match(x,y) } ma1 }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/matchNamesWithReverseParts.R
#' Match names to concatenated pairs of names #' #' @description #' The column-names of multiple pairwise testing contain the names of the initial groups/conditions tested, plus there is a separator (eg '-' in \code{moderTestXgrp}). #' Thus function allows to map back which groups/conditions were used by returning the index of the respective groups used in pair-wise sets. #' #' @details #' There are two modes of operation : 1) Argument \code{sep} is set to \code{NULL} : The names of initial groups/conditions (\code{grpNa}) #' will be tested for exact pattern matching either at beginning or at end of pair-wise names (\code{pairwNa}). #' This approach has the advantage that it does not need to be known what character(s) were used as separator (or they may change), #' but the disadvantage that in case the perfect \code{grpNa} was not given, the longest best match of \code{grpNa} will be returned. #' #' 2) The separator \code{sep} is given and exact matches at both sides will be searched. #' However, if the character(s) from \code{sep} do appear inside \code{grpNa} no matches will be found. #' #' If some \code{grpNa} are not found in \code{pairwNa} this will be marked as NA. #' #' @param grpNa (character) the names of the groups of replicates (ie conditions) used to test #' @param pairwNa (character) the names of pairwise-testing (ie 'concatenated' \code{sampNa} #' @param sep (character) if not \code{NULL} the characters given will be used via \code{stringsplit} #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return matrix of 2 columns with inidices of \code{sampNa} with \code{pairwNa} as rows #' @seealso (for running multiple pair-wise test) \code{\link{moderTestXgrp}}, \code{\link[base]{grep}}, \code{\link[base]{strsplit}} #' @examples #' pairwNa1 <- c("abc-efg","abc-hij","efg-hij") #' grpNa1 <- c("hij","abc","abcc","efg","klm") #' matchSampToPairw(grpNa1, pairwNa1) #' #' pairwNa2 <- c("abc-efg","abcc-hij","abc-hij","abc-hijj","zz-zz","efg-hij") #' matchSampToPairw(grpNa1, pairwNa2) #' @export matchSampToPairw <- function(grpNa, pairwNa, sep=NULL, silent=FALSE, debug=FALSE, callFrom=NULL) { ## return index of grpNa for each pairwNa fxNa <- .composeCallName(callFrom, newNa="matchSampToPairw") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE chPw <- duplicated(pairwNa) if(any(chPw)) {if(!silent) message(fxNa,"Some entries of 'pairwNa' are duplicated, removing") pairwNa <- pairwNa[-which(chPw)]} chNa <- duplicated(grpNa) if(any(chNa)) {if(!silent) message(fxNa,"Some entries of 'grpNa' are duplicated, removing") grpNa <- grpNa[-which(chNa)]} if(length(grpNa) <2) stop("Insufficient 'grpNa' furnished") if(length(pairwNa) <1) stop("Insufficient 'pairwNa' furnished") if(length(sep) >1) {sep <- naOmit(as.character(sep))[1] if(!silent) message(fxNa,"'sep' should be of length=1, using first entry")} if(any(is.na(sep))) { sep <- NULL if(!silent) message(fxNa,"invalid entry for 'sep', setting to NULL")} ## main if(length(sep==1)) { spl <- strsplit(pairwNa, as.character(sep)) chLe <- sapply(spl, length) if(any(chLe <2)) stop(" Problem: Separator '",sep,"' seems NOT to occur in 'pairwNa' !") if(any(chLe >2)) { if(!silent) message(fxNa," separator '",sep,"' seems to occur multiple times in ",sum(chLe >2),"'pairwNa', using 1st and last of strsplit") spl[which(chLe >2)] <- lapply(spl[which(chLe >2)], function(x) x[c(1,length(x))]) } out <- t(sapply(spl, match, grpNa)) } else { le <- apply(sapply(pairwNa, function(x) {w <- sapply(grpNa, function(y) length(grep(paste0("^",y),x)) >0) if(sum(w) >1) {v <- rep(FALSE, sum(w)); v[which.max(nchar(grpNa)[which(w)])] <- TRUE; w[which(w)] <- v}; w} ), 2, which) ri <- apply(sapply(pairwNa, function(x) {w <- sapply(grpNa, function(y) length(grep(paste0(y,"$"),x)) >0) if(sum(w) >1) {v <- rep(FALSE, sum(w)); v[which.max(nchar(grpNa)[which(w)])] <- TRUE; w[which(w)] <- v}; w} ), 2, which) if(is.list(le)) {le[which(sapply(le,length) <1)] <- NA; le <- unlist(le)} if(is.list(ri)) {ri[which(sapply(ri,length) <1)] <- NA; ri <- unlist(ri)} out <- cbind(le,ri) } #if(length(pairwNa)==nrow(out)) names(out) <- pairwNa dimnames(out) <- list(pairwNa,c("le","ri")) out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/matchSampToPairw.R
#' Transform columns of matrix to list of vectors #' #' convert matrix to list of vectors: each column of 'mat' as vector of list #' @param mat (matrix) main input #' @param concSym (character) symbol for concatenating: concatenation of named vectors in list names as colname(s)+'concSym'+rowname #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return matrix or array (1st dim is intraplate-position, 2nd .. plate-group/type, 3rd .. channels) #' @seealso \code{\link{convToNum}} #' @examples #' mat1 <- matrix(1:12,ncol=3,dimnames=list(letters[1:4],LETTERS[1:3])) #' mat2 <- matrix(LETTERS[11:22],ncol=3,dimnames=list(letters[1:4],LETTERS[1:3])) #' matr2list(mat1); matr2list(mat2) #' @export matr2list <- function(mat, concSym=".", silent=FALSE, debug=TRUE, callFrom=NULL) { if(!is.matrix(mat)) mat <- as.matrix(mat) isNum <- is.numeric(mat) outNa <- rownames(mat) out <- as.list(as.data.frame(rbind(colnames(mat), mat))) out <- lapply(out,function(x) { x <- as.character(x); nam <- x[1]; # 1st element was introduced for transmitting name of current column useSep <- nam=="" | outNa=="" # check if any of name-parts for concatenation empty -> omit concSym x <- if(isNum) as.numeric(x[-1]) else x[-1] # trim to input & reset to numeric names(x) <- paste0(nam, ifelse(useSep,"",concSym), outNa); x}) out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/matr2list.R
#' Merge Multiple Matrices #' #' This function allows merging of multiple matrix-like objects. #' The matix-rownames will be used to align common elements, either be returning all common elements \code{mode='intersect'} or containg all elements \code{mode='union'} (the result may contains additional \code{NA}s). #' #' #' @details #' Custom column-names can be given by entering matrices like named arguments (see examples below). #' The choice of columns tu use may be adopted to each matrix entered, in this case the argument \code{useColumn} may be a list with matrix-names to use or a list of indexes (see examples below). #' #' Note, that matrices may contain repeated rownames (see examples, \code{mat3}). In this case only the first of repeated rownames will be considered (and lines of repeated names ignored). #' #' @param ... (matrix or data.frame) multiple matrix or data.frame objects may be entered #' @param mode (character) allows choosing restricting to all common elements (\code{mode='intersect'}) or union (\code{mode='union'}) #' @param useColumn (integer, character or list) the column(s) to consider, may be \code{'all'} to use all, integer to select specific indexes or list of indexes or colnames for cutom-selection per matrix #' @param na.rm (logical) suppress \code{NA}s #' @param extrRowNames (logical) decide whether columns with all values different (ie no replicates or max divergency) should be excluded #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a matrix containing all selected columns of the input matrices to fuse #' @seealso \code{\link[base]{merge}}, \code{\link{mergeMatrixList}} #' @examples #' 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])) #' #' mergeMatrices(mat1, mat2) #' mergeMatrices(mat1, mat2, mat3, mode="union", useCol=2) #' ## custom names for matrix-origin #' mergeMatrices(m1=mat1, m2=mat2, mat3, mode="union", useCol=2) #' ## flexible/custom selection of columns #' mergeMatrices(m1=mat1, m2=mat2, mat3, mode="union", useCol=list(1,1:2,2)) #' @export mergeMatrices <- function(..., mode="intersect", useColumn=1, na.rm=TRUE, extrRowNames=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL) { ## merge n matrix (or data.frame) entries, either as all shared lines or as all united/get common lines ## 'useColumn' (integer) column used for merging inpL <- list(...) out <- useColNo <- NULL fxNa <- " -> mergeMatrices" # temporary ## separate spectific arguments from all-input (lazy fitting) fixArg <- c("mode","useColumn","extrRowNames","silent","debug","callFrom") # fixed argument names to check (and adjust) argL <- match.call(expand.dots = FALSE)$... # extr arg names, based on https://stackoverflow.com/questions/55019441/deparse-substitute-with-three-dots-arguments pMa <- pmatch(names(argL), fixArg) # will only find if unique (partial) match pMa[which(nchar(names(argL)) <3)] <- NA # limit to min 3 chars length if(any(!is.na(pMa))) for(i in which(!is.na(pMa))) {assign(fixArg[pMa[i]], inpL[[i]]); names(inpL)[i] <- "replaceReplace"} chRepl <- names(inpL) %in% "replaceReplace" if(any(chRepl)) {inpL <- inpL[-which(chRepl)]; argL <- argL[-which(chRepl)]} if(debug) {message(fxNa,"mM0")} ## more tests if(!isFALSE(na.rm)) silent <- TRUE if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE fxNa <- .composeCallName(callFrom, newNa="mergeMatrices") extrRowNames <- try(as.logical(extrRowNames, silent=TRUE)) if(inherits(extrRowNames, "try-error")) {message(fxNa,"Invalid entry for 'extrRowNames', reset to default =FALSE"); extrRowNames <- FALSE} ## adjust names of matrices if(length(inpL) >1) {replNa <- if(length(names(inpL)) >0) names(inpL) %in% "" else rep(TRUE, length(inpL)) if(any(replNa)) names(inpL)[which(replNa)] <- sub("[[:punct:]].*|[[:space:]].*","",as.character(unlist(argL))[which(replNa)]) } if(debug) {message(fxNa,"mM1"); mM1 <- list(inpL=inpL, out=out,useColumn=useColumn,extrRowNames=extrRowNames,fixArg=fixArg,argL=argL,pMa=pMa, debug=debug,silent=silent)} ## main .mergeMatrices(inpL, mode=mode, useColumn=useColumn, extrRowNames=extrRowNames, na.rm=na.rm, argL=argL, silent=silent, debug=debug, callFrom=fxNa) } #' Merge Multiple Matrices from List #' #' This function allows merging of multiple matrix-like objects from an initial list. #' The matix-rownames will be used to align common elements, either be returning all common elements \code{mode='intersect'} or containg all elements \code{mode='union'} (the result may contains additional \code{NA}s). #' #' #' @details #' Custom column-names can be given by entering matrices like named arguments (see examples below). #' The choice of columns tu use may be adopted to each matrix entered, in this case the argument \code{useColumn} may be a list with matrix-names to use or a list of indexes (see examples below). #' #' Note, that matrices may contain repeated rownames (see examples, \code{mat3}). In this case only the first of repeated rownames will be considered (and lines of repeated names ignored). #' #' @param matLst (list containing matrices or data.frames) main input (multiple matrix or data.frame objects) #' @param mode (character) allows choosing restricting to all common elements (\code{mode='intersect'}) or union (\code{mode='union'}) #' @param useColumn (integer, character or list) the column(s) to consider, may be \code{'all'} to use all, integer to select specific indexes or list of indexes or colnames for cutom-selection per matrix #' @param na.rm (logical) suppress \code{NA}s #' @param extrRowNames (logical) decide whether columns with all values different (ie no replicates or max divergency) should be excluded #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of messages produced #' @param debug (logical) additional messages for debugging #' @return This function returns a matrix containing all selected columns of the input matrices to fuse #' @seealso \code{\link[base]{merge}}, \code{\link{mergeMatrices}} for separate entries #' @examples #' 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)) #' #' mergeMatrixList(list(m1=mat1, m2=mat2, mat3), mode="union", useCol=2) #' @export mergeMatrixList <- function(matLst, mode="intersect", useColumn=1, na.rm=TRUE, extrRowNames=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL) { ## merge list of matrices if(!isFALSE(na.rm)) silent <- TRUE if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE fxNa <- .composeCallName(callFrom, newNa="mergeMatrixList") if(!is.list(matLst) | length(matLst) <1) stop("Invalid entry for 'matLst'") namesX <- deparse(substitute(matLst)) if(debug) {message(fxNa,"mML0"); mML0 <- list(matLst=matLst, useColumn=useColumn,extrRowNames=extrRowNames,namesX=namesX, debug=debug,silent=silent)} ## check names (and provide default names) lstNa <- names(matLst) if(length(lstNa) <1) { namesX2 <- unlist(strsplit(sub("\\)$","",sub("^list\\(","",namesX)), ", ")) names(matLst) <- if(length(namesX2)==length(matLst)) namesX2 else paste0(sub("[[:punct:]].*|[[:space:]].*","",namesX),"_", 1:length(matLst))} if(any("" %in% lstNa)) { names(matLst)[which(lstNa %in% "")] <- paste0(sub("[[:punct:]].*|[[:space:]].*","",namesX),"_", which(lstNa %in% "")) } argL <- names(matLst) if(debug) {message(fxNa,"mML1")} ## main .mergeMatrices(matLst, mode=mode, useColumn=useColumn, extrRowNames=extrRowNames, na.rm=na.rm, argL=argL, silent=silent, debug=debug, callFrom=fxNa) } #' Merge Multiple Matrices (main) #' #' This function allows merging of multiple matrix-like objects from an initial list. #' #' @param inpL (list containing matrices or data.frames) main input (multiple matrix or data.frame objects) #' @param mode (character) allows choosing restricting to all common elements (\code{mode='intersect'}) or union (\code{mode='union'}) #' @param useColumn (integer, character or list) the column(s) to consider, may be \code{'all'} to use all, integer to select specific indexes or list of indexes or colnames for cutom-selection per matrix #' @param extrRowNames (logical) decide whether columns with all values different (ie no replicates or max divergency) should be excluded #' @param na.rm (logical) suppress \code{NA}s #' @param argL (list of arguments) #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of messages produced #' @param debug (logical) additional messages for debugging #' @return This function returns a matrix containing all selected columns of the input matrices to fuse #' @seealso \code{\link{mergeMatrixList}}, \code{\link[base]{merge}}, \code{\link{mergeMatrices}} for separate entries #' @examples #' mat1 <- matrix(11:18, ncol=2, dimnames=list(letters[3:6],LETTERS[1:2])) #' @export .mergeMatrices <- function(inpL, mode="intersect", useColumn=1, extrRowNames=FALSE, na.rm=TRUE, argL=NULL, silent=FALSE, debug=FALSE, callFrom=NULL) { ## merge n matrix (or data.frame) entries, either as all shared lines or as all united/get common lines ## inpL (list) main input : list of matrices fxNa <- .composeCallName(callFrom, newNa=".mergeMatrices") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE out <- NULL chLe <- sapply(inpL, length) if(all(chLe >0)) { chDi <- sapply(inpL, ncol) if(is.list(chDi)) { useInp <- sapply(chDi, length) >0 inpL <- inpL[which(useInp)] if(!silent) message(fxNa,"Removing ",sum(useInp)," empty elements from input") chDi <- sapply(inpL, ncol)} if(any(chDi) <1) { if(!silent) message(fxNa,"Removing ",sum(chDi <1)," non-matrix like elements from input") inpL <- inpL[which(chDi >0)] chDi <- sapply(inpL, ncol) } chLe <- sapply(inpL, length) # update } if(debug) {message(fxNa,"mNM1"); mNM1 <- list(inpL=inpL, out=out,useColumn=useColumn,extrRowNames=extrRowNames,chLe=chLe,chDi=chDi,inpL=inpL)} if(all(chLe >0) && sum(duplicated(chDi), na.rm=TRUE)==length(inpL) -1) { # all valid entries if(debug) {message(fxNa,"mNM1a") } ## final column-names useColNa <- NULL if(length(inpL) >1) { ## names of matrices chName <- nchar(names(inpL)) <1 if(any(chName)) {names(inpL)[which(chName)] <- argL[which(chName)] if(debug) message(fxNa,"Adding object-names to ",sum(chName)," matrices as ",pasteC(argL[which(chName)], quoteC="'")) } chName <- nchar(names(inpL)) <1 # update ## colnames chCoNa <- lapply(inpL, colnames) chCoNa2 <- sapply(chCoNa, length) <1 if(any(chCoNa2)) for(i in which(chCoNa2)) colnames(inpL[[which(chCoNa2)]]) <- 1:ncol(inpL[[which(chCoNa2)]]) # fill empty colnames } ## check for redundant rownames chRNa <- sapply(inpL, function(x) sum(duplicated(rownames(x))) ) if(any(chRNa >0)) {if(!silent) message(fxNa,"Note : The matrices ",pasteC(names(inpL)[which(chRNa >0)], quoteC="'")," contain redundant rownames (which will be ignored)")} ## if(identical(useColumn,"all")) { useColumn <- lapply(inpL, function(x) 1:ncol(x))} if(debug) {message(fxNa,"mNM2"); mNM2 <- list(inpL=inpL, out=out,useColumn=useColumn,useColNa=useColNa,extrRowNames=extrRowNames,chLe=chLe,chDi=chDi,inpL=inpL)} ## prepare empty matrix for results if(!identical(mode,"union")) { # suppose mode is 'intersect' ## get common rownames useLi <- if(na.rm) naOmit(rownames(inpL[[1]])) else rownames(inpL[[1]]) if(length(inpL) >1) for(i in 2:length(inpL)) useLi <- intersect(useLi, if(na.rm) naOmit(rownames(inpL[[i]])) else rownames(inpL[[i]])) useLi <- sort(useLi) # multiple results may get easier to compare ## start extracting data (mode='intersect'): extract of 1st matrix if(!isTRUE(extrRowNames)) { uCol <- if(is.list(useColumn)) useColumn[[1]] else useColumn out <- if(length(inpL) >1) inpL[[1]][match(useLi, rownames(inpL[[1]])), uCol] else inpL[[1]][,uCol] if(length(dim(out)) <2) out <- matrix(out, ncol=1, dimnames=list(useLi, if(is.numeric(useColumn)) colnames(inpL[[1]])[useColumn] else uCol)) if(debug) {message(fxNa,"mNM3"); mNM3 <- list(inpL=inpL, out=out,useLi=useLi,useColumn=useColumn,chDi=chDi,chDi=chDi,useColNa=useColNa)} ## the remaining matrices (mode='intersect') if(length(inpL) >1) { ## get colnames concerned uCol <- if(is.list(useColumn)) {lapply(1:length(useColumn), function(x) {if(is.numeric(x)) colnames(inpL[[x]])[useColumn[[x]]] else x}) } else { if(is.numeric(useColumn)) lapply(inpL, function(x) colnames(x)[useColumn]) else useColumn } if(is.list(uCol)) {uCol <- unlist(uCol)} names(uCol) <- rep(names(useColumn), sapply(useColumn, length)) chNa <- is.na(uCol) if(any(chNa)) { stop("Invalid content of argument 'useColumn'") } chDu <- duplicated(uCol, fromLast=FALSE) if(any(chDu)) uCol <- if(length(useColumn) >1) paste(trimRedundText(names(uCol), side="right"), trimRedundText(uCol), sep=".") else trimRedundText(uCol) ## finish extracting for(i in 2:length(inpL)) { uCo2 <- if(is.list(useColumn)) useColumn[[i]] else useColumn out <- cbind(out, inpL[[i]][match(useLi, rownames(inpL[[i]])), uCo2]) } if(length(useColumn) >1) colnames(out) <- uCol # adjust colnames as composed } } else out <- useLi } else { ## suppose mode='union' doSort=TRUE if(debug) {message("mNM4"); mNM4 <- list(inpL=inpL, out=out, useColumn=useColumn,chDi=chDi,chDi=chDi,useColNa=useColNa)} ## get all rownames useLi <- unlist(lapply(inpL, rownames)) useLi <- if(doSort) unique(sort(useLi)) else unique(useLi) ## get colnames concerned uCol <- if(is.list(useColumn)) {lapply(1:length(useColumn), function(x) {if(is.numeric(x)) colnames(inpL[[x]])[useColumn[[x]]] else x}) } else { if(is.numeric(useColumn)) lapply(inpL, function(x) colnames(x)[useColumn]) else useColumn } if(is.list(uCol)) uCol <- unlist(uCol) chNa <- is.na(uCol) if(any(chNa)) { stop("Invalid content of argument 'useColumn'") } if(length(useColumn) >1) names(uCol) <- if(is.list(useColumn)) rep(names(inpL), sapply(useColumn, length)) else rep(names(inpL), each=length(useColumn)) if(debug) {message("mNM4b"); mNM4b <- list(inpL=inpL, out=out, useColumn=useColumn,chDi=chDi,chDi=chDi,useColNa=useColNa)} out <- matrix(NA, nrow=length(useLi), ncol=length(uCol), dimnames=list(useLi, paste0(names(uCol),".",uCol))) ## 1st matr out[match(rownames(inpL[[1]]), useLi), which(names(uCol) %in% names(inpL)[1])] <- as.matrix(inpL[[1]][,if(is.list(useColumn)) useColumn[[1]] else useColumn]) if(debug) {message("mNM4c"); mNM4c <- list(inpL=inpL, out=out, useColumn=useColumn, chDi=chDi,chDi=chDi,useColNa=useColNa)} ## remaining matrices if(length(inpL) >1) { incCol <- if(is.list(useColumn)) cumsum(sapply(useColumn, length)) else seq_along(inpL)*length(useColumn) # cumsum() gives last of series for(i in 2:length(inpL)) { uCo2 <- if(is.list(useColumn)) useColumn[[i]] else useColumn out[match(rownames(inpL[[i]]), useLi), which(names(uCol) %in% names(inpL)[i])] <- inpL[[i]][,uCo2] } } } } else if(!silent) message(fxNa,"Invalid entries, all ",length(inpL)," elements must have 2 dimensions") out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/mergeMatrices.R
#' Merge selected columns out of 2 matrix or data.frames #' #' This function merges selected columns out of 2 matrix or data.frames. #' 'selCols' will be used to define columns to be used; optionally may be different for 'dat2' : define in 'supCols2'. #' Output-cols will get additions specified in newSuff (default '.x' and '.y') #' #' @param dat1 matrix or data.frame for fusing #' @param dat2 matrix or data.frame for fusing #' @param selCols will be used to define columns to be used; optionally may be different for 'dat2' : define in 'supCols2' #' @param supCols2 if additional column-names should be extracted form dat2 #' @param byC (character) 'by' value used in \code{\link[base]{merge}} #' @param useAll (logical) use all lines (will produce NAs when given identifyer not found un 2nd group of data) #' @param setRownames (logical) if \code{TRUE}, will use values of col used as 'by' as rownames instead of showing as add'l col in output #' @param newSuff (character) prefix (argument 'suffixes' in \code{merge}) #' @param silent (logical) suppress messages #' @param debug (logical) display additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a data.frame containing the merged columns #' @seealso \code{\link[base]{merge}}, merge 3 data.frames using \code{\link{mergeSelCol3}} #' @examples #' mat1 <- matrix(c(1:7,letters[1:7],11:17), ncol=3, dimnames=list(LETTERS[1:7],c("x1","x2","x3"))) #' mat2 <- matrix(c(1:6,c("b","a","e","f","g","k"), 31:36), #' ncol=3, dimnames=list(LETTERS[11:16],c("y1","x2","x3"))) #' mergeSelCol(mat1, mat2, selC=c("x2","x3")) #' @export mergeSelCol <- function(dat1, dat2, selCols, supCols2=NULL, byC=NULL, useAll=FALSE, setRownames=TRUE, newSuff=c(".x",".y"), silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom,newNa="mergeSelCol") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE msg <- " should be matrix or data.frame (with >0 lines)" ms2 <- c(" can't find "," columns specfied in 'selCols' in ") if(length(dim(dat1)) !=2) stop(" Argument dat1",msg) if(length(dim(dat2)) !=2) stop(" Argument dat2",msg) if(is.null(byC)) {byC <- naOmit(colnames(dat1)[match(colnames(dat2),colnames(dat1))])[1] message(fxNa,"Automatically selecting '",byC,"' as 'by'")} if(length(byC) >1) { byC <- byC[1]; message(fxNa,"reducing 'by' to length 1")} if(!(byC %in% colnames(dat1) & byC %in% colnames(dat1))) stop(ms2[1],byC," in both 'dat1' & 'dat2'") if(debug) {message(fxNa," byC ",byC)} if(length(byC) <1 | is.na(byC)) stop(" Problem with 'by' : no valid column-names") if(is.null(supCols2)) supCols2 <- selCols if(sum(selCols %in% colnames(dat1), na.rm=TRUE) < length(selCols)) stop(ms2[1],length(selCols),ms2[2],"dat1 !") if(sum(supCols2 %in% colnames(dat2), na.rm=TRUE) < length(supCols2)) stop(ms2[1],length(supCols2),ms2[2],"dat2 !") sel3 <- which(colnames(dat1) %in% unique(c(byC,selCols))) sel4 <- which(colnames(dat2) %in% unique(c(byC,supCols2))) if(any(length(sel3) <2, length(sel4) <2)) { out <- dat1; message(fxNa,"Nothing to do") } else { out <- merge(as.data.frame(dat1[,sel3]),as.data.frame(dat2[,sel4]), by=byC,all=useAll, suffixes=newSuff)} if(setRownames) {rownames(out) <- out[,byC]; out <- out[,-1*which(colnames(out) ==byC)]} out } #' mergeSelCol3 #' #' successive merge of selected columns out of 3 matrix or data.frames. #' 'selCols' will be used to define columns to be used; optionally may be different for 'dat2' : define in 'supCols2'. #' Output-cols will get additions specified in newSuff (default '.x' and '.y') #' #' @param dat1 matrix or data.frame for fusing #' @param dat2 matrix or data.frame for fusing #' @param dat3 matrix or data.frame for fusing #' @param selCols will be used to define columns to be used; optionally may be different for 'dat2' : define in 'supCols2' #' @param supCols2 if additional column-names should be extracted form dat2 #' @param supCols3 if additional column-names should be extracted form dat3 #' @param byC (character) 'by' value used in \code{\link[base]{merge}} #' @param useAll (logical) use all lines (will produce NAs when given identifyer not found un 2nd group of data) #' @param setRownames if \code{TRUE}, will use values of col used as 'by' as rownames instead of showing as add'l col in output #' @param newSuff (character) prefix (argument 'suffixes' in \code{merge}) #' @param silent (logical) suppress messages #' @param debug (logical) display additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a data.frame containing the merged columns #' @seealso \code{\link[base]{merge}}, \code{\link{mergeSelCol}} #' @examples #' mat1 <- matrix(c(1:7,letters[1:7],11:17),ncol=3,dimnames=list(LETTERS[1:7],c("x1","x2","x3"))) #' mat2 <- matrix(c(1:6,c("b","a","e","f","g","k"),31:36), ncol=3, #' dimnames=list(LETTERS[11:16],c("y1","x2","x3"))) #' mat3 <- matrix(c(1:6,c("c","a","e","b","g","k"),51:56), ncol=3, #' dimnames=list(LETTERS[11:16],c("z1","x2","x3"))) #' mergeSelCol3(mat1, mat2, mat3, selC=c("x2","x3")) #' @export mergeSelCol3 <- function(dat1, dat2, dat3, selCols, supCols2=NULL, supCols3=NULL, byC=NULL, useAll=FALSE, setRownames=TRUE, newSuff=c(".x",".y",".z"), silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="mergeSelCol3") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE msg <- c(" Argument dat"," should be matrix or data.frame (with >0 lines)") ms2 <- c(" Can't find "," columns specfied in 'selCols' in dat") if(length(dim(dat1)) !=2) stop(msg[1],"1",msg[2]) if(length(dim(dat2)) !=2) stop(msg[1],"2",msg[2]) if(length(dim(dat3)) !=2) stop(msg[1],"3",msg[2]) allCo <- list(colnames(dat1), colnames(dat2), colnames(dat3)) if(is.null(byC)) { byC <- allCo[[1]][which(allCo[[1]] %in% allCo[[2]] & allCo[[1]] %in% allCo[[3]])[1]] message(fxNa,"automatically selecting '",byC,"' as 'by'")} if(length(byC) >1) { byC <- byC[1]; message(fxNa,"Reducing 'by' to length 1")} if(!(byC %in% colnames(dat1) & byC %in% colnames(dat1))) stop(ms2[1],byC," in both 'dat1' & 'dat2'") if(length(byC) <1 | is.na(byC)) stop(" Problem with 'by' : no valid column-names") if(is.null(supCols2)) supCols2 <- selCols if(is.null(supCols3)) supCols3 <- selCols if(sum(selCols %in% allCo[[1]], na.rm=TRUE) < length(selCols)) stop(ms2[1],length(selCols),ms2[2],"1 !") if(sum(supCols2 %in% allCo[[2]], na.rm=TRUE) < length(supCols2)) stop(ms2[1],length(supCols2),ms2[2],"2 !") if(sum(supCols3 %in% allCo[[3]], na.rm=TRUE) < length(supCols3)) stop(ms2[1],length(supCols3),ms2[2],"3 !") sel0 <- list(which(allCo[[1]] %in% unique(c(byC,selCols))), which(allCo[[2]] %in% unique(c(byC,supCols2))), which(allCo[[3]] %in% unique(c(byC, supCols3)))) if(any(sapply(sel0,length) <2) ) { out <- dat1; message(fxNa,"Nothing to do ..") } else { out <- merge(as.data.frame(dat1[,sel0[[1]]]), as.data.frame(dat2[,sel0[[2]]]), by=byC, all=useAll, suffixes=newSuff) out <- merge(out, as.data.frame(dat3[,sel0[[3]]]), by=byC, all=useAll) co1 <- (1:ncol(out))[-1*unlist(lapply(paste0(newSuff,"$"), grep, colnames(out)))][-1] if(length(newSuff) >2) colnames(out)[co1] <- paste0(colnames(out)[co1], newSuff[3]) } if(setRownames) {rownames(out) <- out[,byC]; out <- out[,-1*which(colnames(out) ==byC)]} out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/mergeSelCol.R
#' Merge Named Vectors #' #' This function allows merging for 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). #' If vectors are not given using a name (see first example below), they will be names 'x.1' etc (see argument \code{namePrefix}). #' #' @details #' Note : The arguments '\code{namePrefix}', '\code{NAto0}', '\code{callFrom}' and '\code{silent}' must be given with full name to be recognized as such (and not get considered as vector for merging). #' #' @param ... all vectors that need to be merged #' @param namePrefix (character) prefix to numers used when vectors are not given with explicit names (second exammple) #' @param NAto0 (logical) optional replacemet of \code{NA}s by 0 #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a matrix of merged values #' @seealso \code{\link[base]{merge}} (for two data.frames) #' @examples #' 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) #' x4 <- 41:44 # no names - not conform for merging #' mergeVectors(x1, x2, x3, x4) #' @export mergeVectors <- function(..., namePrefix="x.", NAto0=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL) { ## merge for simple named vectors (each element needs to be named) fxNa <- .composeCallName(callFrom, newNa="mergeVectors") if(isTRUE(debug)) silent <- FALSE if(!isTRUE(silent)) silent <- FALSE inpL <- list(...) chNa <- sapply(inpL, function(x) length(unique(names(x)))==length(x) && length(x) >0) if(any(!chNa)) {if(!silent) message(fxNa," Vectors must be longer than 0 and must have names on each element for merging; omit ",sum(!chNa)," (out of ",length(inpL),") vector(s)") inpL <- inpL[which(chNa)] } if(length(inpL)==1 && is.list(inpL[[1]])) inpL <- inpL[[1]] chNa <- names(inpL) if(length(names(inpL)) <1) { names(inpL) <- paste0(namePrefix,1:length(inpL))} if(length(inpL) >0) { if(isTRUE(NAto0)) inpL <- lapply(inpL, function(x) {chNa <- is.na(x); if(any(chNa)) x[which(chNa)] <- 0; x}) spe <- sort(unique(unlist(lapply(inpL, names)))) ta3 <- matrix(NA, nrow=length(inpL), ncol=length(spe), dimnames=list(names(inpL), spe)) for(i in 1:length(inpL)) ta3[i, match(names(inpL[[i]]), spe)] <- inpL[[i]] ta3 } else NULL }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/mergeVectors.R
#' Extended version of merge for multiple objects (even without rownames) #' #' \code{mergeW2} povides flexible merging out of 'MArrayLM'-object (if found, won't consider any other input-data) or of separate vectors or matrixes. #' The main idea was to have somthing not adding add'l lines as merge might do, but to stay within the frame of the 1st argument given, even when IDs are repeated, #' so the output follows the order of the 1st argument, non-redundant IDs are created (orig IDs as new column). #' If no 'MArrayLM'-object found: try to combine all elements of input '...', input-names must match predefined variants 'chInp'. #' IDs given in 1st argument and not found in later arguments will be displayed as NA in the output matrix of data.frame. #' Note : (non-data) arguments must be given with full name (so far no lazy evaluation, may conflict with names in 'inputNamesLst'). #' Note : special characters in colnames bound to give trouble. #' Note : when no names given, \code{mergeW2} will presume order of elements (names) from 'inputNamesLst'. #' PROBLEM : error after xxMerg3 when several entries have matching (row)names but some entries match only partially (what to do : replace with NAs ??) #' @param ... all data (vectors, matrixes or data.frames) intendes for merge #' @param nonRedundID (logical) if TRUE, allways add 1st column with non-redundant IDs (add anyway if non-redundant IDs found ) #' @param convertDF (logical) allows converting output in data.frame, add new heading col with non-red rownames & check which cols should be numeric #' @param selMerg (logical) if FALSE toggle to classic merge() (will give more rows in output in case of redundant names #' @param inputNamesLst (list) named list with character vectors (should be unique), search these names in input for extracting/merging elements use for 'lazy matching' when checking names of input, default : 7 groups ('Mvalue', 'Avalue','p.value','mouseInfo','Lfdr','link','filt') with common short versions #' @param noMatchPursue (logical) allows using entries where 0 names match (just as if no names given) #' @param standColNa (logical) if TRUE return standard colnames as defined in 'inputNamesLst' (ie 'chInp'), otherwise colnames as initially provided #' @param lastOfMultCols may specify input groups where only last col will be used/extracted #' @param duplTxtSep (character) separator for counting/denomiating multiple occurances of same name #' @param debug (logical) for bug-tracking: more/enhanced messages and intermediate objects written in global name-space #' @param silent (logical) suppress messages #' @param callFrom (character) allows easier tracking of message(s) produced #' @return matrix or data.frame of fused data #' @seealso \code{\link[base]{merge}} #' @examples #' t1 <- 1:10; names(t1) <- letters[c(1:7,3:4,8)] #' t2 <- 20:11; names(t2) <- letters[c(1:7,3:4,8)] #' t3 <- 101:110; names(t3) <- letters[c(11:20)] #' t4 <- matrix(100:81,ncol=2,dimnames=list(letters[1:10],c("co1","co2"))) #' t5 <- cbind(t1=t1,t52=t1+20,t53=t1+30) #' t1; t2; t3; cbind(t1,t2) #' mergeW2(Mval=t1,p.value=t2,debug=FALSE) #' @export mergeW2 <- function(...,nonRedundID=TRUE,convertDF=TRUE,selMerg=TRUE,inputNamesLst=NULL,noMatchPursue=TRUE,standColNa=FALSE, lastOfMultCols=c("p.value","Lfdr"),duplTxtSep="_",silent=FALSE,debug=FALSE,callFrom=NULL){ inp <- list(...) out = NULL chAnnCol <- c("mouseOver","link","uniqUniprot","Uniprot","firstOfMultUnipr","combUnipr","custMouOv","customMouseOver") # colnames in MArrayLM$annot to extract chInp <- if(is.list(inputNamesLst) & length(inputNamesLst)>1) inputNamesLst else { # names of list-elements to allowed to extract list(Mvalue=c("Mvalue","Mval","M.value","M.val","Mv","M"), Avalue=c("Avalue","Aval","Amean","A.value","A.val","Av","A"), Amatr=c("Amatrix","Amatri","Amatr","Amat","Ama","Am","A.matrix","A.matr","A.mat","A.m"), p.value=c("pValue","pVal","p.value","p.val","pVa","pV","p"), Lfdr=c("Lfdr","lfdr","FDR","fdr","FdrList"), means=c("allMeans","means"), mouseInfo=c("mouseInfo","info","inf","mou","mouse"), link=c("link","www"),filt=c("filtFin","filter","filt","fi"), info2=c("shortInfo","info2","suplInfo"), annot=c("annot","annotation"))} if(debug) silent <- FALSE fxNa <- .composeCallName(callFrom,newNa="mergeW2") if(length(unlist(chInp)) > length(unique(unlist(chInp)))) stop(fxNa,"Problem with redundant names in (predefined/custom) 'inputNamesLst'") if(length(inp) <1) stop(fxNa," No valid entries !") ## note: potential problem with multiple classes per objet cheCla <- lapply(inp,class) cheCla2 <- sapply(cheCla,paste,collapse=" ") if(debug) message(fxNa," class of arguments : ",pasteC(cheCla2)) if("MArrayLM" %in% unlist(cheCla)) { tmp <- inp[[which(grep("MArrayLM",cheCla2))]] if(!silent) message(fxNa,"Found 'MArrayLM'-object with ",length(names(tmp))," types of data for ",length(tmp)," elements/genes") tm2 <- .convertNa(names(tmp),chInp) if(length(naOmit(tm2)) > length(unique(naOmit(tm2)))) { tm2ta <- table(naOmit(tm2)) msg <- c(fxNa,"PROBLEM : multiple names of MArrayLM-obj do match to (single) type of data searched '") for(i in which(tm2ta >1)) { if(!silent) message(msg,names(tm2ta)[i],"' : found ",pasteC(names(tmp)[which(tm2==names(tm2ta)[i])],quoteC="'"), " -> using last (otherwise try to modify 'chInp')") tm3 <- which(tm2==(names(tm2ta)[i])) tm2[tm3[-1*length(tm3)]] <- NA } } if(sum(!is.na(tm2)) >0) {names(tmp)[!is.na(tm2)] <- naOmit(tm2) # set names of interest in MArray-obj to standard names if(!silent) message(fxNa,"Resetting names in 'MArrayLM'-obj to standardized names") } if(length(inp) >1) { ## regular case (not 'MArrayLM' class) chLe <- length(grep("MArrayLM",cheCla2)) <1 & sapply(inp,length) >0 & !is.na(.convertNa(names(inp),chInp)) inp2 <- if(sum(chLe) >0) inp[which(chLe)] else NULL } else inp2 <- NULL inp <- list() useMaEl <- naOmit(match(names(chInp),names(tmp))) # pick only elements of interest out of list with mult options for(i in 1:length(useMaEl)) inp[[i]] <- tmp[[useMaEl[i]]] names(inp) <- names(tmp)[useMaEl] if(length(inp2) >0) { for(i in names(inp2)) inp[[i]] <- inp2[[i]] # (re)inject information given besides MArrayLM (replacing) useMaEl <- naOmit(match(names(chInp),names(tmp))) # update if(!silent) message(fxNa," adding ",length(inp2)," non MArrayLM objects: ",pasteC(names(inp2),quoteC="'"))} ## ++ need to specify which question (MAarray may contain results for multiple comparisons !!) ## immediately pick relevant cols and rename p.value & Lfdr & annot ?? colNa <- lapply(inp,colnames) rmIntercept <- TRUE ## <<== supl parameter ?? exclNa <- "(Intercept)" if(any(unlist(colNa) %in% exclNa) & rmIntercept) { # ready to remove cols names "(Intercept)" useEl <- which(sapply(colNa,function(x) any(x %in% exclNa))) if(length(useEl) >0) for(i in useEl) { useCo <- which(!colnames(inp[[i]]) %in% exclNa) inp[[i]] <- if(length(useCo) <1) NULL else {if(length(useCo) >1) inp[[i]][,useCo] else matrix( inp[[i]][,useCo],nrow=nrow(inp[[i]]),dimnames=list(rownames(inp[[i]]),colnames(inp[[i]])[useCo]))} if(ncol(inp[[i]])==1) colnames(inp[[i]]) <- names(inp)[i] } # if only 1 col remaining rename to name of list-element } ## (MArrayLM-only) filter suitable cols from annot : if(any(chInp$annot %in% names(inp)) & length(chAnnCol) >0) { tmp <- which.max(names(inp) %in% chInp$annot) # use last of names from 'inp' recognized as annot if(length(dim(inp[[tmp]])) >0) inp[[tmp]] <- inp[[tmp]][,which(colnames(inp[[tmp]]) %in% chAnnCol)] } # select specific cols ## cheCla <- sapply(inp,class) # update } else { if(debug) message(fxNa,"No 'MArrayLM'-object; eximine ",length(inp)," elements (",pasteC(names(inp),quoteC="'"),")") if(is.list(inp) & length(inp)==1) {inp <- inp[[1]]; cheCla <- sapply(inp,class) }} ## if(debug) message(fxNa,"Examine ",length(inp)," elements (",pasteC(names(inp),quoteC="'"),")") if(any(sapply(inp,length) <1)) { ## remove empty elements if(!silent) message(fxNa,"Remove empty element(s) : ",pasteC(names(inp)[which(sapply(inp,length) <1)],quoteC="'")) inp <- inp[which(sapply(inp,length) >0)] cheCla <- sapply(inp,class) } ## no names given : presume 'chInp' ... if(is.null(names(inp))) { names(inp) <- names(chInp)[1:length(inp)] txt <- "CAUTION: arguments are given without names, PRESUME same order of arguments as given in 'inputNamesLst' ! ie " if(!silent) message(fxNa,txt,pasteC(names(inp),quoteC="'")) } cheCla2 <- sapply(cheCla,paste,collapse=" ") chLis <- grep("list",cheCla2) if(length(chLis) >0) { # if lists (still) present in 'lst': try to bring elements searched down one level for(i in chLis) { # select list elements potentially containing elements to extract useEl <- which( sapply(names(inp[[i]]) %in% chInp)) ## note : bringing multiple elements dow one level (and elim initial) if(length(useEl) >0) { for(j in 1:length(useEl)) inp[[length(inp)+1]] <- inp[[i]][[j]] inp <- inp[-i] }} if(debug) message(fxNa,"revised (list) names(inp) ",pasteC(names(inp))) } ## check for 1st input element matching (Mval essential), in case of merge keep names of 1st (Mval) if(!any(names(inp) %in% chInp[[1]])) stop(" essential argument group (for) '",names(chInp)[1],"' missing !") ## stdInpNa <- .convertNa(names(inp),chInp) # standardized input-names ## remove non-name-conform list-groups if(any(is.na(stdInpNa))) { if(!silent) message(fxNa,"Remove non-recognized elements/arguments ",pasteC(names(inp)[which(is.na(stdInpNa))],quo="'")) inp <- inp[-1*which(is.na(stdInpNa))] stdInpNa <- .convertNa(names(inp),chInp)} ## check for arguments matching multiple times if(length(stdInpNa) > length(unique(stdInpNa))) { tmp <- table(names(which())) if(!silent) message(fxNa,"Arguments ",pasteC(names(inp)[which(tmp >1)],quoteC="'")," match multiple times in 'inputNamesLst', use only 1st per group") inp <- inp[firstOfRepeated(stdInpNa)$indUniq] # keep only 1st of mult stdInpNa <- .convertNa(names(inp),chInp) } ## transform all non-matrix to matrix chConDim <- sapply(inp,function(x) length(dim(x)) >1) # check for matrix if(any(!chConDim)) for(i in which(!chConDim)) inp[[i]] <- matrix(inp[[i]],ncol=1,dimnames=list(names(inp[[i]]),names(chConDim)[i])) colNa <- lapply(inp,colnames) msg <- c("Potential trouble ahead, "," colnames !") if(any(nchar(unlist(colNa)) <1) & !silent) message(fxNa,msg[1],sum(nchar(unlist(colNa)) <1)," missing",msg[2]) n2 <- c(length(unique(unlist(colNa))), length(unlist(colNa))) if(n2[2] > n2[1] & !silent) message(fxNa,msg[1], n2[2]-n2[1]," non-unique",msg[2]) ## option: extract only last of multiple Cols (for p.value, ...) renameSingToStd <- TRUE lastOfMultCols <- names(inp)[which(stdInpNa %in% .convertNa(lastOfMultCols,chInp))] if(length(lastOfMultCols) >0) { if(!silent) message(fxNa,"Use only last column for elements ",pasteC(lastOfMultCols,quoteC="'")) for(i in which(names(inp) %in% lastOfMultCols)) { xx <- inp[[i]] inp[[i]] <- matrix(xx[,ncol(xx)],ncol=1,dimnames=list(rownames(xx),if(renameSingToStd) names(chInp)[i] else colnames(xx)[ncol(xx)]))} # rename to standard name (defined in 'chInp') } else if(debug) message(fxNa,"Argument 'lastOfMultCols' has no matches to groups presented in 'inputNamesLst' !!") ## remove special characters from colnames (if reorderig at end of procedure) for(i in length(inp)) colnames(inp[[i]]) <- .replSpecChar(colnames(inp[[i]]),replBy="_") chInp <- lapply(chInp,.replSpecChar,replBy="_") ## check for conflicting (col)-names -> rename by adding name of group + '.' + orig (col)name (for all cols of group) allColNa <- unlist(lapply(inp,colnames)) if(length(unique(allColNa)) < length(allColNa)) { multNa <- names(table(allColNa))[which(table(allColNa)>1)] if(!silent) message(fxNa,"Problem with repeated (col)names ",pasteC(multNa,quoteC="'"),", need to rename (by adding group-name)!!") while(length(multNa) >0) { i <- multNa[1] tmp <- which(sapply(lapply(inp,colnames),function(x) i %in% x)) tmp <- tmp[-1*which.min(sapply(inp[tmp],ncol))] for(j in tmp) colnames(inp[[j]]) <- paste(names(inp)[j],colnames(inp[[j]]),sep=".") # main renaming of repeated colnames allColNa <- unlist(lapply(inp,colnames)) # need to update multNa <- names(table(allColNa))[which(table(allColNa)>1)] } } ## ## ++ main joining ++ chNaLe <- sapply(inp,function(x) c(le=nrow(x),leNa=length(rownames(x)),nrNa=length(unique(rownames(x))))) # each elem of 'inp' .. separ col chNaLe <- rbind(chNaLe,nFound=rep(NA,ncol(chNaLe))) for(i in 2:length(inp)) chNaLe[4,i] <- sum(rownames(inp[[i-1]]) %in% rownames(inp[[i]])) # number of names matching to Mval ## look for unique (row)names useCol4na <- chNaLe[2,-1]==chNaLe[1,1] & chNaLe[3,-1] >1 # same length and >1 non-red names if(sum(useCol4na) >1) useCol4na[-1*which.max(chNaLe[3,1+useCol4na])] <- FALSE # for multiple potent names choose one with highest non-red nRedID <- if(chNaLe[1,1] >0) rownames(inp[[1]]) else { if(any(useCol4na)) rownames(inp[[which.max(useCol4na)+1]]) else 1:nrow(inp[[1]])} # if names exist in Mval -> priority, else best of same le if(!is.null(nRedID)) nRedID <- treatTxtDuplicates(nRedID,sep=duplTxtSep,onlyCorrectToUnique=TRUE,callFrom=fxNa) # warning if NULL ## check for identical rownames between elements to combine (cbind/merge) ## special case : search for annot (last element) with non-matching names but matching 1st col -> rename colnames of annot to allow simple merging compLastNa <- if(names(inp)[length(inp)] %in% chInp[[length(chInp)]]) { # check if last of 'inp' in last group of 'chInp' present, ie annot if(!identical(rownames(inp)[[length(inp)]],rownames(inp[[1]])) & any(all(inp[[length(inp)]][,1]==rownames(inp[[1]])),all( inp[[length(inp)]][,1] ==gsub("\\+","; ",rownames(inp[[1]]))))) TRUE else FALSE} else FALSE if(compLastNa) rownames(inp[[length(inp)]]) <- rownames(inp[[1]]) inpNa <- lapply(inp,rownames) chConNi <- cbind(idNa=sapply(inpNa[-1],function(x) all(x==inpNa[[1]])), noNaButEqLi=sapply(inp[-1], function(x) length(rownames(x)) <1 & nrow(x)==nrow(inp[[1]])), partNa=sapply(inpNa[-1],function(x) if(length(x)>0) sum(x %in% rownames(inp[[1]]),na.rm=TRUE) >0 else FALSE), hasNaButNoMatch=sapply(inpNa[-1],function(x) length(x) >0 & length(x)==nrow(inp[[1]]) & all(!x %in% inpNa[[1]]))) if(any(chConNi[,2]) & !silent) message(fxNa,"No (row)names found in ",pasteC(names(inp)[which(chConNi[,2])+1],quoteC="'"), " but presume same as '",names(inp)[1],"'") if(any(chConNi[,4]) & noMatchPursue) { for(j in which(chConNi[,4])) rownames(inp[[j+1]]) <- rownames(inp[[1]]) chConNi[which(chConNi[,4]),2] <- TRUE txt <- c("CAUTION: none of the (row)names in "," matching, since same length presume names of '") if(!silent) message(fxNa,txt[1],pasteC(names(inp)[chConNi[,4]],quoteC="'"),txt[2],names(inp)[1],"'")} if(debug) {cat("Counting of matching names etc 'chConNi' :\n"); print(chConNi); cat("\n")} chConNa <- chConNi[,1] | chConNi[,2] | chConNi[,3] # fuse for decision cbind : all names identical or (names absent & same nrow) ## remove elements wo names AND different length if(all(!chConNa)) stop(fxNa," No arguments left for merging !?! (check input !!)") if(any(!chConNa)) { if(!silent) message(fxNa,"Cannot figure out how to join, OMIT element(s) ",pasteC(names(inp[1+which(!chConNa)]),quoteC="'")) inp <- inp[c(1,1+which(chConNa))] inpNa <- lapply(inp,rownames) chConNi <- cbind(idNa=sapply(inpNa[-1],function(x) identical(x,inpNa[[1]])), eqNumLines= sapply(inp[-1], function(x) length(rownames(x)) <1 & nrow(x)==nrow(inp[[1]])), eqNuLinesAndNoNames=rep(NA,length(inp[-1])), anyNa=sapply(inpNa[-1],function(x) if(length(x)>0) sum(x %in% rownames(inp[[1]]),na.rm=TRUE)>0 else FALSE), partNa=sapply(inpNa[-1],function(x) if(length(x)>0) sum(x %in% rownames(inp[[1]]),na.rm=TRUE) <nrow(inp[[1]]) else FALSE) ) chConNi[,"eqNuLinesAndNoNames"] <- chConNi[,"eqNumLines"] & !chConNi[,"anyNa"] chConNa <- chConNi[,1] | chConNi[,2] } out <- inp[[1]] ## main cbind chConNa <- chConNi[,1] | chConNi[,2] names(chConNa) <- rownames(chConNi) nCol <- sapply(inp,function(x) {dm <- dim(x); if(length(dm)>0) ncol(x) else 1}) if(any(chConNa)) for(i in which(chConNa)) { # simple cbind when names are identical or all absent (&same length) tmp <- inp[[names(chConNa)[i]]] multCol <- FALSE out <- cbind(out,tmp)} if(any(!chConNa)) message(fxNa,"Cannot use ",pasteC(names(chConNa)[which(!chConNa)],quoteC="'")," , different (partial?) matching than others !") newColNa <- if(standColNa) as.list(.convertNa(names(inp)[chConNa],chInp)) else as.list(names(inp)[chConNa]) if(any(nCol[c(TRUE,chConNa)] >1)) for(i in which(nCol > 1 & c(TRUE,chConNa))) newColNa[[i]] <- paste(newColNa[[i]],colnames(inp[[i]]),sep=".") # colnames for multi-col input colnames(out) <- unlist(newColNa) ## (could not handle as cbind ->) have to combine via merge-like : if(any(!chConNa)) for(i in which(!chConNa)) { # names do differ -> do some sort of 'merge' msg <- c(" .. for case of (partially) different ","(row)names ","in '","") useEl <- which(names(inp)==names(chConNa[i])) if(!silent) message(fxNa,"loop ",i,msg[1:3],names(inp)[useEl],"', prepare for merging") tmp <- rownames(inp[[useEl]]) toMerNa <- rownames(inp[[useEl]]) # at this level all elements should have names ## nonunique rownames/IDs : if in place, merge does all combinations, if used as NULL -> warning message when creating toMer; ## if set how to re-integrate ?? rownames(inp[[useEl]]) <- 1:nrow(inp[[useEl]]) # avoid warning in case of non-unique IDs !! toMer <- data.frame(id=toMerNa,inp[[useEl]],stringsAsFactors=FALSE) if(selMerg) { if(is.null(rownames(inp[[useEl]]))) {if(nrow(toMer)==nrow(out)) { toMer[,1] <- rownames(out) } else stop("problem with missing names in '",names(inp)[useEl],"', no ",useEl," and different nrow !!")} dim0 <- dim(out) out <- cbind(out,matrix(NA,nrow=nrow(out),ncol=ncol(toMer)-1,dimnames=list(NULL,colnames(toMer)[-1]))) mat <- match(rownames(out),toMer[,1]) n1 <- c(length(unique(naOmit(mat))),length(naOmit(mat))) msg <- c(" : multiple assoc for "," element(s) ","(don't know which one to choose !) ; ","from ref not found") if(n1[1] <nrow(toMer) & !silent) message(fxNa," ",names(chConNa[i]),msg[1],n1[2]-n1[1],msg[2:3], sum(is.na(mat)),msg[c(2,4)]) out[which(!is.na(mat)),(dim0[2]+1):ncol(out)] <- as.matrix(toMer[naOmit(mat),-1]) } else { ## note when using merge() : does all combinations ! (ie output will have more lines than input !!), may give warning message out <- merge(data.frame(id=rownames(out),out),toMer,by="id",all.x=TRUE) } } ## put in order matching chInp: ## OK with single occurance per set of names tmp <- .convertNa(names(inp),chInp) goodOrd <- 1:ncol(out) if(length(tmp) <ncol(out)){ goodOrd <- naOmit(match(names(chInp),tmp)) } else if(!silent) message(fxNa,"Can't adjust order of cols i output (since some elements have multiple columns)") ## goodOrd <- if(length(tmp) <ncol(out)) 1:ncol(out) else naOmit(match(names(chInp),tmp)) # if single column entries, set in order of chInp out <- out[,goodOrd] # since merging non-complete elements at end changed order ... if(convertDF) out <- convMatr2df(out,duplTxtSep=duplTxtSep) # convert matrix to df if(is.data.frame(out)) for(i in ncol(out)) {if(is.character(out[,i])) out[,i] <- convToNum(out[,i],remove=NULL,sciIncl=TRUE)} # keep text entries (eg annotation columns !) if("filt" %in% names(chInp)) { # convert any col type filt to logical useCol <- match(chInp[["filt"]],colnames(out)) if(sum(!is.na(useCol)) >0) { tmp <- as.logical(out[,naOmit(useCol)[1]]) if(sum(is.na(tmp)) <1) out[,naOmit(useCol)[1]] <- tmp else message( fxNa," cannot figure out how to convert '",colnames(out)[naOmit(useCol)[1]],"' to logical !") }} out } #' Convert/standardize names of 'query' to standard names from 'ref' #' #' This function converts/standardizes names of 'query' to standard names from 'ref' (list of possible names (char vect) where names define standardized name). #' It takes 'query' as character vector and return character vecor (same length as 'query') with 'converted/corrected' names #' #' @param query (matrix or data.frame, min 2 columns) main input #' @param ref (list) list of multiple possible names associated to given group, reference name for each group is name of list #' @param partMatch (logical) allows partial matching (ie name of 'ref' must be in head of 'query') #' @return This function returns a character vector #' @examples #' daPa <- matrix(c(1:5,8,2:6,9), ncol=2) #' @export .convertNa <- function(query,ref,partMatch=TRUE){ ## convert/standardize names of 'query' to standard names from 'ref' (list of possible names (char vect) where names define standardized name) ## take 'query' as character vector and return character vecor (same length as 'query') with 'converted/corrected' names ## names that are not found in 'ref' will be returned as NA ## 'ref' .. list of multiple possible names associated to given group, reference name for each group is name of list ## 'partMatch' allows partial matching (ie name of 'ref' must be in head of 'query') if(!partMatch) { out <- apply(sapply(ref,function(x) query %in% x),1,function(y) if(any(y)) which.max(y) else NA) # perfect match out[!is.na(out)] <- names(ref)[out[!is.na(out)]] } else { se <- sapply(ref,function(x) {unique(unlist(sapply(paste("^",x,sep=""),grep,query)))}) out <- rep(NA,length(query)) ##cat(" pos ",unlist(se)," insert ",rep(names(se),sapply(se,length)),"\n") out[unlist(se)] <- rep(names(se),sapply(se,length)) } #unlist(se) out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/mergeW2.R
#' Minimum distance/difference between values #' #' This function aims to find the min distance (ie closest point) to any other x (numeric value), ie intra 'x' and #' returns matrix with 'index','value','dif','ppm','ncur','nbest','best'. #' At equal distance to lower & upper neighbour point, the upper (following) point is chosen (as single best). #' In case of multiple ex-aequo distance returns 1st of multiple, may be different at various repeats. #' #' @param x (numeric) vector to search minimum difference #' @param digSig number of significant digits, used for ratio or ppm column #' @param ppm (logical) display distance as ppm (1e6*diff/refValue, ie normalized difference eg as used in mass spectrometry), otherwise the ratio is given as : value(from 'x') / closestValue (from 'x') #' @param initOrder (logical) return matrix so that 'x' matches exactely 2nd col of output #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a matrix #' @seealso \code{\link[base]{diff}} #' @examples #' set.seed(2017); aa <- 100*c(0.1 +round(runif(20),2),0.53,0.53) #' minDiff(aa); #' minDiff(aa,initO=TRUE,ppm=FALSE); .minDif(unique(aa)) #' @export minDiff <- function(x, digSig=3, ppm=TRUE, initOrder=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL) { ## for comparison of 2 vectors see .clostestNumByRat() or fxNa <- .composeCallName(callFrom, newNa="minDiff") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE y <- try(as.numeric(x), silent=TRUE) if(inherits(y, "try-error")) stop(fxNa,"Invalid entry : Unable to transform 'x' into numeric vector") if(debug) message(fxNa,"mD0") so <- .minDif(y, initOrder=FALSE, rat=TRUE) chNegDif <- which(so[,5] <1) # for orientation if(length(chNegDif) >0) so[chNegDif, c(3)] <- -1*so[chNegDif, c(3)] # neg 'dif' if 'value' is lower than best/closest(~ref) so <- cbind(so, ncur=1, nbest=1) if(length(digSig) >0 && !ppm) if(is.numeric(digSig)) so[,"rat"] <- signif(so[,"rat"], digits=digSig) # finalize ratio result repInd <- which(c(diff(so[,2]),NA) ==0) # index of repeated vals exept last of series if(length(repInd) >0) { # repeated values, need to correct 'so' firOf <- repInd[c(1,1 +which(diff(repInd) >1))] # first of repeated (values for diff incorrect) ,length(repVa) repIn2 <- sort(unique(c(repInd, repInd +1))) # index of all repeated tab <- table(so[repIn2,2]) lasOf <- repIn2[cumsum(tab)] # index of last of rep; correct dist is in last of series ! z2 <- so[firOf -1, 1:2] z3 <- so[lasOf +1, 1:2] if(length(dim(z2)) <2) z2 <- matrix(z2, nrow=1, dimnames=list(NULL,names(z2))) if(length(dim(z3)) <2) z3 <- matrix(z3, nrow=1, dimnames=list(NULL,names(z3))) zz <- rbind(so[firOf,1:2], z2[which(!z2[,2] %in% so[firOf,2]),]) zz <- rbind(zz,z3[which(!z3[,2] %in% zz[,2]),]) if(debug) message(fxNa,"mD1") s3 <- .minDif(zz[,2], initOrder=FALSE) s3[,1] <- zz[s3[,1],1] # correct to full range indexes s3[,4] <- zz[s3[,4],1] # correct to full range indexes s3 <- s3[which(s3[,1] %in% so[repIn2,1]),] if(length(dim(s3)) <2) s3 <- matrix(s3, nrow=1, dimnames=list(NULL,names(s3))) so[repIn2,3:5] <- matrix(rep(s3[,3:5], rep(tab,3)), ncol=3) so[repIn2,6] <- rep(tab,tab) } so[,7] <- so[match(so[,4], so[,1]),6] # change from n.current to n of best chNA <- is.na(so[,2]) if(any(chNA)) so[which(chNA),3:7] <- NA if(ppm) {colnames(so)[5] <- "ppm" so[,5] <- 1e6*so[,3]/so[,2] } if(length(digSig) >0) if(is.numeric(digSig)) { so[,3] <- signif(so[,3], digits=digSig) so[,5] <- signif(so[,5], digits=digSig) } so[if(initOrder) order(so[,1]) else 1:nrow(so), c(1:3,5:7,4)] } #' find closest neighbour to numeric vector #' #' This function aims to find closest neighbour to numeric vector #' #' @param z (numeric) vector to search minimum difference #' @param initOrder (logical) return matrix so that 'x' matches exactely 2nd col of output #' @param rat (logical) express result as ratio #' @return This function returns a matrix with index,value,dif,best #' @seealso \code{\link[stats]{dist}} #' @examples #' .minDif(c(11:15,17)) #' @export .minDif <- function(z, initOrder=TRUE, rat=TRUE){ ## find closest neighbour to numeric vector 'z', return matrix with index,value,dif,best ## note that 'dif' is reported as absolule ! ## 'sortRet' .. if TRUE return in orig order of values in 2nd col of dat ## however, repeated values will NOT be evalualted correctly !! z <- cbind(index=1:length(z), value=z)[order(z),] if(rat) so <- cbind(z, dif=c(diff(z[,2]),Inf), best=c(z[-1,1],NA)) sw <- cbind(diA=so[,3], diB=c(Inf, so[-nrow(so),3])) alt <- which(sw[,1] > sw[,2]) if(length(alt) >0) {so[alt,4] <- so[alt -1,1] so[alt,3] <- so[alt -1,3]} if(rat) {so <- cbind(so, rat=so[,2]/so[match(so[,4], so[,1]),2]) } if(initOrder) so[order(so[,1]),] else so }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/minDiff.R
#' Moderated pair-wise t-test from limma #' #' Runs moderated t-test from package 'limma' on each line of data. #' Note: This function requires the package \href{https://bioconductor.org/packages/release/bioc/html/limma.html}{limma} from bioconductor. #' The limma contrast-matrix has to be read by column, the lines in the contrast-matrix containing '+1' will be compared to the '-1' lines, eg grpA-grpB . #' Local false discovery rates (lfdr) estimations will be made using the CRAN-package \href{https://CRAN.R-project.org/package=fdrtool}{fdrtool} (if available). #' #' @param dat matrix or data.frame with rows for multiple (independent) tests, use ONLY with 2 groups; assumed as log2-data #' @param grp (factor) describes column-relationship of 'dat' (1st factor is considered as reference -> orientation of M-values !!) #' @param limmaOutput (logical) return full (or extended) MArrayLM-object from limma or 'FALSE' for only the (uncorrected) p.values #' @param addResults (character) types of results to add besides basic limma-output, data are assumed to be log2 ! (eg "lfdr" using fdrtool-package, "FDR" or "BH" for BH-FDR, "BY" for BY-FDR, #' "bonferroni" for Bonferroni-correction, "qValue" for lfdr by qvalue, "Mval", "means" or "nonMod" for non-moderated test and he equivaent all (other) multiple testing corrections chosen here) #' @param testOrientation (character) for one-sided test (">","greater" or "<","less"), NOTE : 2nd grp is considered control/reference, '<' will identify grp1 < grp2 #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of message(s) produced #' @return This function returns a limma-type object of class \code{MArrayLM} #' @seealso \code{\link[limma]{lmFit}} and the \code{eBayes}-family of functions in package \href{https://bioconductor.org/packages/release/bioc/html/limma.html}{limma}, \code{\link[stats]{p.adjust}} #' @examples #' 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]) #' ## Two-sided testing #' fit4 <- moderTest2grp(t4,gl(2,2)) #' # If you have limma installed we can now see further #' if("list" %in% mode(fit4)) limma::topTable(fit4, coef=1, n=5) # effect for 3,4,7,8 #' #' ## One-sided testing #' fit4in <- moderTest2grp(t4,gl(2,2),testO="<") #' # If you have limma installed we can now see further #' if("list" %in% mode(fit4)) limma::topTable(fit4in, coef=1, n=5) #' @export moderTest2grp <- function(dat, grp, limmaOutput=TRUE, addResults=c("lfdr","FDR","Mval","means"), testOrientation="=", silent=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="moderTest2grp") runTest <- TRUE if(!isTRUE(silent)) silent <- FALSE if(!isFALSE(limmaOutput)) limmaOutput <- TRUE if(any(length(dat) <1, length(dim(dat)) !=2, dim(dat) < c(1,3))) stop("Invalid argument 'dat'; must be matrix or data.frame with min 1 lines and 3 columns") if(length(grp) != ncol(dat)) stop("Check parameters: Number of columns of 'dat' doesn't match to length of 'grp'") if(!is.factor(grp)) grp <- as.factor(grp) if(length(levels(grp)) <2) stop(" need at least 2 groups in argument 'grp'") if(length(levels(grp)) >2) {message(fxNa," capable only of treating 2 groups in argument 'grp' (ignore rest)") grp[which(grp %in% levels(grp)[-(1:2)])] <- NA } packages <- c("limma", "fdrtool", "qvalue") checkPkg <- function(pkg) requireNamespace(pkg, quietly=TRUE) checkPkgs <- sapply(packages, checkPkg) if(!checkPkgs[1]) {warning(fxNa,"Package 'limma' not found ! Please install first from Bioconductor"); runTest <- FALSE} if(runTest) { if(limmaOutput & length(addResults) >0) if("all" %in% addResults) addResults <- c("BH", "BY","lfdr","qValue","bonferroni","Mval","means","nonMod") if(!checkPkgs[2] & any("lfdr" %in% tolower(addResults))) { if(!silent) message(fxNa," package 'fdrtool' not found, omitting .. Please install from CRAN for enabeling 'lfdr'") addResults <- addResults[which(!tolower(addResults) %in% "lfdr")] } if(!checkPkgs[3] & any(c("qvalue","qval") %in% tolower(addResults))) { if(!silent) message(fxNa," package 'qvalue' not found, omitting .. Please install from Bioconductor for enabeling 'qValue'") addResults <- addResults[which(!tolower(addResults) %in% c("qvalue","qval"))] } ## treat non-unique row-names ? if(length(rownames(dat) >0)) if(length(unique(rownames(dat))) < nrow(dat)) { if(!silent) message(fxNa," detected ",nrow(dat) -length(unique(rownames(dat)))," non-unique rownames of 'dat' !")} altHyp <- "two.sided" # default, change only if explicit sign recognized if(length(testOrientation) <1) testOrientation <- altHyp if(testOrientation %in% c("<","less","inf")) altHyp <- "less" if(testOrientation %in% c(">","greater","sup")) altHyp <- "greater" datDesign <- stats::model.matrix(~ grp) if(nrow(datDesign) < ncol(dat)) datDesign <- rbind(datDesign, matrix(rep(0,length(levels(grp))*(ncol(dat)-nrow(datDesign))), ncol=ncol(datDesign))) fit1 <- try(limma::eBayes(limma::lmFit(dat, design=datDesign)), silent=TRUE) ## Fitting linear model if(inherits(fit1, "try-error")) { runTest <- FALSE warning(fxNa," UNABLE to run limma::lmFit() and/or limma::eBayes(); can't run this function !")} } if(runTest) { fit1$means <- rowGrpMeans(dat, grp) chNA <- colSums(is.na(fit1$p.value)) if(any(chNA==nrow(dat))) fit1$p.value <- fit1$p.value[,-1*which(chNA==nrow(dat))] ## modif to adjust for different H0 (29mar18) tx <- c("testing alternative hypothesis: true difference in means is "," than 0 (ie focus on "," results with A ",altHyp," than B)") if(identical(altHyp,"greater")) { ch <- fit1$means[,1] > fit1$means[,2] if(!silent) message(fxNa,tx[1],altHyp,tx[2],sum(ch),tx[3:5]) if(any(ch)) fit1$p.value[which(ch),] <- fit1$p.value[which(ch),]/2 if(any(!ch)) fit1$p.value[which(!ch),] <- 1- fit1$p.value[which(!ch),]/2 # !(A > B) .. A <= B } if(identical(altHyp,"less")){ ## testing for Ho A > B ch <- fit1$means[,2] > fit1$means[,1] if(!silent) message(fxNa,tx[1],altHyp,tx[2],sum(ch),tx[3:5]) if(any(ch)) fit1$p.value[which(ch),] <- fit1$p.value[which(ch),]/2 if(any(!ch)) fit1$p.value[which(!ch),] <- 1- fit1$p.value[which(!ch),]/2 # !(A > B) .. A <= B } if(!limmaOutput) out <- fit1$p.value[,2] else { out <- fit1 ## further inspect & correct values of 'addResults' ? if("Mval" %in% addResults) out$Mval <- (out$means[,1] - out$means[,2]) if(any(c("FDR","BH") %in% toupper(addResults))) out$FDR <- if(is.matrix(out$p.value)) { apply(out$p.value, 2, stats::p.adjust, meth="BH")} else stats::p.adjust(out$p.value, meth="BH") if("BY" %in% toupper(addResults)) out$BY <- if(is.matrix(out$p.value)) { apply(out$p.value, 2, stats::p.adjust, meth="BY")} else stats::p.adjust(out$p.value, meth="BY") if("lfdr" %in% tolower(addResults)) {out$lfdr <- if(is.matrix(out$p.value)) { apply(out$p.value, 2, pVal2lfdr)} else pVal2lfdr(out$p.value) } if(any(c("qval","qvalue") %in% tolower(addResults))) { out$qVal <- if(is.matrix(out$p.value)) { try(apply(out$p.value, 2, function(x) qvalue::qvalue(x,lfdr.out=TRUE)$lfdr), silent=TRUE) } else try(qvalue::qvalue(out$p.value,lfdr.out=TRUE)$lfdr, silent=TRUE) if(inherits(out$qVal, "try-error")) { if(!silent) message(fxNa," Problem with pi0 estimation, setting pi0=1 like BH-FDR") out$qVal <- if(is.matrix(out$p.value)) { apply(out$p.value, 2, function(x) qvalue::qvalue(x, pi0=1, lfdr.out=TRUE)$lfdr) } else qvalue::qvalue(out$p.value, pi0=1, lfdr.out=TRUE)$lfdr } } if(any(c("bonferroni","bonf") %in% tolower(addResults))) out$bonf <- if(is.matrix(out$p.value)) { apply(out$p.value, 2, stats::p.adjust, meth="bonferroni")} else stats::p.adjust(out$p.value, meth="bonferroni") } if("nonMod" %in% addResults) { gr1 <- which(grp==levels(grp)[1]) gr2 <- which(grp==levels(grp)[2]) altHyp <- testOrientation if(altHyp=="=") altHyp <- "two.sided" out$nonMod.p <- apply(dat, 1, function(x) stats::t.test(x[gr1], x[gr2], alternative=altHyp)$p.value) if(any(c("FDR","BH") %in% toupper(addResults))) out$nonMod.FDR <- stats::p.adjust(out$nonMod.p, method="BH") if("BY" %in% toupper(addResults)) out$nonMod.BY <- stats::p.adjust(out$nonMod.p, method="BY") if(any(c("lfdr") %in% tolower(addResults))) out$nonMod.lfdr <- try(pVal2lfdr(out$nonMod.p), silent=TRUE) if(any(c("qval","qvalue") %in% tolower(addResults))) { out$nonMod.qVal <- try(qvalue::qvalue(out$nonMod.p, lfdr.out=TRUE)$lfdr, silent=TRUE) if(inherits(out$nonMod.qVal, "try-error")) { if(!silent) message(fxNa," Problem with pi0 estimation (non-shrinked p-values) fro qValue, setting pi0=1 like BH-FDR") out$qVal <- if(is.matrix(out$p.value)) qvalue::qvalue(out$nonMod.p, pi0=1, lfdr.out=TRUE)$lfdr }} if(any(c("bonferroni","bonf") %in% tolower(addResults))) out$nonMod.bonf <- stats::p.adjust(out$nonMod.p, method="bonferroni") } out }}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/moderTest2grp.R
#' Multiple moderated pair-wise t-tests from limma #' #' Runs all pair-wise combinations of moderated t-tests from package 'limma' on each line of data against 1st group from 'grp'. #' Note: This function requires the package \href{https://bioconductor.org/packages/release/bioc/html/limma.html}{limma} from bioconductor. #' The limma contrast-matrix has to be read by column, the lines in the contrast-matrix containing '+1' will be compared to the '-1' lines, eg grpA-grpB . #' #' @param dat matrix or data.frame with rows for multiple (independent) tests, use ONLY with 2 groups; assumed as log2-data !!! #' @param grp (factor) describes column-relationship of 'dat' (1st factor is considered as reference -> orientation of M-values !!) #' @param limmaOutput (logical) return full (or extended) MArrayLM-object from limma or 'FAlSE' for only the (uncorrected) p.values #' @param addResults (character) types of results to add besides basic limma-output, data are assumed to be log2 ! (eg "lfdr" using fdrtool-package, "FDR" or "BH" for BH-FDR, "BY" for BY-FDR, #' "bonferroni" for Bonferroni-correction, "qValue" for lfdr by qvalue, "Mval", "means" or "nonMod" for non-moderated test and he equivaent all (other) multiple testing corrections chosen here) #' @param testOrientation (character) for one-sided test (">","greater" or "<","less"), NOTE : 2nd grp is considered control/reference, '<' will identify grp1 < grp2 #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of message(s) produced #' @return This function returns a limma-type MA-object (list) #' @seealso \code{\link{moderTest2grp}} for single comparisons, \code{\link[limma]{lmFit}} and the \code{eBayes}-family of functions in package \href{https://bioconductor.org/packages/release/bioc/html/limma.html}{limma} #' @examples #' 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) #' # If you have limma installed we can now see further #' if("list" %in% mode(test8)) head(test8$p.value, n=8) #' @export moderTestXgrp <- function(dat, grp, limmaOutput=TRUE, addResults=c("lfdr","FDR","Mval","means"), testOrientation="=", silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="moderTestXgrp") runTest <- TRUE if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(!isFALSE(limmaOutput)) limmaOutput <- TRUE if(any(length(dat) <1, length(dim(dat)) !=2, dim(dat) < c(1,3))) { runTest <- FALSE warning(fxNa,"Invalid argument 'dat'; must be matrix or data.frame with min 1 lines and 3 columns") } if(runTest) { if(length(grp) != ncol(dat)) { runTest <- FALSE warning(fxNa,"Check parameters: Number of columns of 'dat' doesn't match to length of 'grp'") }} if(runTest) { if(!is.factor(grp)) grp <- as.factor(grp) if(length(levels(grp)) <2) stop(" Need at least 2 groups in argument 'grp'") ## check packae dependencies packages <- c("limma", "fdrtool", "qvalue") checkPkg <- function(pkg) requireNamespace(pkg, quietly=TRUE) checkPkgs <- sapply(packages, checkPkg) if(!checkPkgs[1]) { runTest <- FALSE; warning(fxNa,"Package 'limma' not found ! Unable to run tests. Please install first from Bioconductor")} } if(debug) {message(fxNa,"mTX1"); mTX1 <- list(dat=dat,grp=grp,limmaOutput=limmaOutput,addResults=addResults,testOrientation=testOrientation,runTest=runTest)} if(runTest) { if(limmaOutput & length(addResults) >0) if("all" %in% addResults) addResults <- c("BH", "BY","lfdr","qValue","bonferroni","Mval","means","nonMod") if(!checkPkgs[2] & any("lfdr" %in% tolower(addResults))) { if(!silent) message(fxNa,"Package 'fdrtool' not found, omitting .. Please install from CRAN for enabeling 'lfdr'") addResults <- addResults[which(!tolower(addResults) %in% "lfdr")] } if(!checkPkgs[3] & any(c("qvalue","qval") %in% tolower(addResults))) { if(!silent) message(fxNa,"Package 'qvalue' not found, omitting .. Please install from Bioconductor for enabeling 'qValue'") addResults <- addResults[which(!tolower(addResults) %in% c("qvalue","qval"))] } if(debug) {message(fxNa,"mTX2")} ## treat non-unique row-names ? if(length(rownames(dat) >0)) if(length(unique(rownames(dat))) < nrow(dat)) { if(!silent) message(fxNa,"Detected ",nrow(dat) -length(unique(rownames(dat)))," non-unique rownames of 'dat' !")} altHyp <- "two.sided" # default, change only if explicit sign recognized if(length(testOrientation) <1) testOrientation <- altHyp if(testOrientation %in% c("<","less","inf")) altHyp <- "less" if(testOrientation %in% c(">","greater","sup")) altHyp <- "greater" ## prepare modeling datDesign <- stats::model.matrix(~ -1 + grp) # can't use directly, need contrasts !! colnames(datDesign) <- sub("^grp","", colnames(datDesign)) comp <- triCoord(length(levels(grp))) rownames(comp) <- paste(levels(grp)[comp[,1]], levels(grp)[comp[,2]],sep="-") contr.matr <- matrix(0, nrow=length(levels(grp)), ncol=nrow(comp), dimnames=list(levels(grp), rownames(comp))) for(j in 1:nrow(comp)) contr.matr[comp[j,],j] <- c(1,-1) if(debug) {message(fxNa,"mTX3"); mTX3 <- list(dat=dat,grp=grp,limmaOutput=limmaOutput,addResults=addResults,testOrientation=testOrientation,runTest=runTest,datDesign=datDesign,comp=comp,contr.matr=contr.matr )} ## see eg https://support.bioconductor.org/p/57268/; https://www.biostars.org/p/157068/ globFilt <- 1:nrow(dat) # so far apply testing to all lines ## main fit0 <- try(limma::lmFit(dat[globFilt,], datDesign), silent=TRUE) # testing part 1 if(inherits(fit0, "try-error")) { runTest <- FALSE warning(fxNa," Problem running lmFit(), unable to run tests; check if package 'limma' is properly installed !")} if(debug) {message(fxNa,"mTX4")} } if(runTest) { fit1 <- limma::eBayes(limma::contrasts.fit(fit0, contrasts=contr.matr)) # variant to run all contrasts at same time compNa <- colnames(fit1$contrasts) if(is.null(compNa) & !silent) message(fxNa," Note: Could not find names of (multiple) comparisons !") fit1$means <- rowGrpMeans(dat, grp) ## separate running of contrasts, like gxTools, need then to extract & combine all pValues chNA <- colSums(is.na(fit1$p.value)) if(any(chNA==nrow(dat))) fit1$p.value <- fit1$p.value[,-1*which(chNA==nrow(dat))] ## modif to adjust for different H0 (29mar18) tx <- c("testing alternative hypothesis: true difference in means is "," than 0 (ie focus on "," results with A ",altHyp," than B)") if(identical(altHyp,"greater")){ ch <- fit1$means[,1] > fit1$means[,2] if(!silent) message(fxNa,tx[1],altHyp,tx[2],sum(ch),tx[3:5]) if(any(ch)) fit1$p.value[which(ch),] <- fit1$p.value[which(ch),]/2 if(any(!ch)) fit1$p.value[which(!ch),] <- 1- fit1$p.value[which(!ch),]/2 # !(A > B) .. A <= B } if(identical(altHyp,"less")){ ch <- fit1$means[,2] > fit1$means[,1] if(!silent) message(fxNa,tx[1],altHyp,tx[2],sum(ch),tx[3:5]) if(any(ch)) fit1$p.value[which(ch),] <- fit1$p.value[which(ch),]/2 if(any(!ch)) fit1$p.value[which(!ch),] <- 1- fit1$p.value[which(!ch),]/2 # !(A > B) .. A <= B } if(is.null(colnames(fit1$t))) colnames(fit1$t) <- compNa if(is.null(colnames(fit1$p.value))) colnames(fit1$p.value) <- compNa ## add various multiple testing corrections if(!limmaOutput) out <- fit1$p.value[,2] else { out <- fit1 ## further inspect & correct values of 'addResults' ? if("Mval" %in% addResults) out$Mval <- (out$means[,1] - out$means[,2]) if(any(c("FDR","BH") %in% toupper(addResults))) out$FDR <- if(is.matrix(out$p.value)) { apply(out$p.value, 2, stats::p.adjust, meth="BH")} else stats::p.adjust(out$p.value, meth="BH") if("BY" %in% toupper(addResults)) out$BY <- if(is.matrix(out$p.value)) { apply(out$p.value, 2, stats::p.adjust, meth="BY")} else stats::p.adjust(out$p.value, meth="BY") if("lfdr" %in% tolower(addResults)) {out$lfdr <- if(is.matrix(out$p.value)) { apply(out$p.value, 2, pVal2lfdr)} else pVal2lfdr(out$p.value) } if(any(c("qval","qvalue") %in% tolower(addResults))) { out$qVal <- if(is.matrix(out$p.value)) { try(apply(out$p.value, 2, function(x) qvalue::qvalue(x,lfdr.out=TRUE)$lfdr), silent=TRUE)} else try(qvalue::qvalue(out$p.value,lfdr.out=TRUE)$lfdr, silent=TRUE) if(inherits(out$qVal, "try-error")) { if(!silent) message(fxNa," Problem with pi0 estimation, setting pi0=1 like BH-FDR") out$qVal <- if(is.matrix(out$p.value)) { apply(out$p.value, 2, function(x) qvalue::qvalue(x, pi0=1, lfdr.out=TRUE)$lfdr) } else qvalue::qvalue(out$p.value, pi0=1, lfdr.out=TRUE)$lfdr } } if(any(c("bonferroni","bonf") %in% tolower(addResults))) out$bonf <- if(is.matrix(out$p.value)) { apply(out$p.value, 2, stats::p.adjust, meth="bonferroni")} else stats::p.adjust(out$p.value, meth="bonferroni") } if("nonMod" %in% addResults) { leLev <- length(levels(grp)) grX <- lapply(2:leLev, function(x) which(grp==levels(grp)[x])) grX[2:leLev] <- grX[1:(length(levels(grp)) -1)] grX[[1]] <- which(grp==levels(grp)[1]) names(grX) <- levels(grp) altHyp <- testOrientation if(altHyp=="=") altHyp <- "two.sided" comp <- triCoord(leLev) out$nonMod.p <- apply(comp,1,function(y) apply(dat, 1, function(x) stats::t.test(x[which(grp==levels(grp)[y[1]])], x[which(grp==levels(grp)[y[2]])], alternative=altHyp)$p.value) ) colnames(out$nonMod.p) <- compNa if(any(c("FDR","BH") %in% toupper(addResults))) { if(length(dim(out$nonMod.p))==2) { out$nonMod.FDR <- apply(out$nonMod.p, 2, stats::p.adjust, method="BH") colnames(out$nonMod.FDR) <- compNa } else out$nonMod.FDR <- stats::p.adjust(out$nonMod.p, method="BH") } if(any("BY" %in% toupper(addResults))) { if(length(dim(out$nonMod.p))==2) { out$nonMod.BY <- apply(out$nonMod.p, 2, stats::p.adjust, method="BY") colnames(out$nonMod.BY) <- compNa } else out$nonMod.BY <- stats::p.adjust(out$nonMod.p, method="BY") } if(any("lfdr" %in% tolower(addResults))) { if(length(dim(out$nonMod.p))==2) { out$nonMod.lfdr <- apply(out$nonMod.p, 2, pVal2lfdr) colnames(out$nonMod.lfdr) <- compNa } else out$nonMod.lfdr <- pVal2lfdr(out$nonMod.p) } if(any(c("qval","qvalue") %in% tolower(addResults))) { out$nonMod.qVal <- if(length(dim(out$nonMod.p))==2) try(apply(out$nonMod.p, 2, qvalue::qvalue), silent=TRUE) else try(qvalue::qvalue(out$nonMod.p), silent=TRUE) if(inherits(out$nonMod.qVal, "try-error")) { if(!silent) message(fxNa," Problem with pi0 estimation (non-shrinked p-values) for qValue, setting pi0=1 like BH-FDR") out$nonMod.qVal <- if(length(dim(out$nonMod.p))==2) apply(out$nonMod.p, 2, qvalue::qvalue,pi0=1, lfdr.out=TRUE) else qvalue::qvalue(out$nonMod.p,pi0=1, lfdr.out=TRUE) } if(length(dim(out$nonMod.p))==2) colnames(out$nonMod.qVal) <- compNa } if(any(c("bonferroni","bonf") %in% tolower(addResults))) { if(length(dim(out$nonMod.p))==2) { out$nonMod.bonf <- apply(out$nonMod.p, 2, stats::p.adjust, method="bonferroni") colnames(out$nonMod.bonf) <- compNa } else out$nonMod.lfdr <- stats::p.adjust(out$nonMod.p, method="bonferroni") } } out } }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/moderTestXgrp.R
#' Multiple replacement of entire character elements in simple vector, matrix or data.frame #' #' This functions allows multiple types of replacements of entire character elements in simple vector, matrix or data.frame. #' In addtion, the result may be optionally directly transformed to logical or numeric #' #' @param mat (character vector, matrix or data.frame) main data #' @param repl (matrix or list) tells what to replace by what: If matrix the 1st oolumn will be considered as 'old' and the 2nd as 'replaceBy'; if named list, the names of the list-elements will be consdered as 'replaceBy' #' @param convTo (character) optional conversion of content to 'numeric' or 'logical' #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns an object of same dimension as input (with replaced content) #' @seealso \code{\link[base]{grep}} #' @examples #' x1 <- c("ab","bc","cd","efg","ghj") #' multiCharReplace(x1, cbind(old=c("bc","efg"), new=c("BBCC","EF"))) #' #' x2 <- c("High","n/a","High","High","Low") #' multiCharReplace(x2, cbind(old=c("n/a","Low","High"), new=c(NA,FALSE,TRUE)),convTo="logical") #' #' # works also to replace numeric content : #' x3 <- matrix(11:16, ncol=2) #' multiCharReplace(x3, cbind(12:13,112:113)) #' @export multiCharReplace <- function(mat, repl, convTo=NULL, silent=FALSE, debug=TRUE, callFrom=NULL) { ## multiple replacement of entire character elements in simple vector, matrix or data.frame ## repl .. matrix with 2 colums for old and new or list where list-names design new fxNa <- .composeCallName(callFrom, newNa="multiCharReplace") if(length(mat) <1 || (is.list(mat) && !is.data.frame(mat))) stop("Invalid argument 'mat'; must be simple vector, matrix or data.frame of length >0") if(is.data.frame(mat)) mat <- as.matrix(mat) if(is.numeric(mat) && length(convTo) <1) convTo <- "numeric" if(all(length(dim(repl)) ==2, dim(repl) > 0:1)) { ## 'repl' is matrix with 2 cols for(i in 1:nrow(repl)) {ch <- which(mat==repl[i,1]); if(length(ch) >0) mat[ch] <- repl[i,2]} } else if(is.list(repl) && length(repl) >0 && !is.null(names(repl))) { ## 'repl' is named list for(i in 1:length(repl)) { ch <- which(mat %in% repl[[i]]) if(length(ch) >0) mat[ch] <- names(repl)[i]} } msg <- "Unable to convert to " if(length(convTo)==1) { if("numeric" %in% convTo && !is.numeric(mat)) { tmp <- try(as.numeric(mat), silent=TRUE) if(inherits(tmp, "try-error")) {mat <- if(length(dim(mat)) <2) tmp else matrix(tmp, ncol=ncol(mat), dimnames=dimnames(mat)) } else if(!silent) message(fxNa,msg,"numeric") } else if("logical" %in% convTo & !is.logical(mat)) { tmp <- try(as.logical(mat), silent=TRUE) if(!inherits(tmp, "try-error")) {mat <- if(length(dim(mat)) <2) tmp else matrix(tmp, ncol=ncol(mat), dimnames=dimnames(mat)) } else if(!silent) message(fxNa,msg,"logical") }} mat }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/multiCharReplace.R
#' Simple Multi-to-Multi Matching of (Concatenated) Terms #' #' This function allows convenient matching of multi-to-multi relationships between two objects/vectors. #' It was designed for finding common elements in multiple to multiple matching situations (eg when comparing \code{c("aa; bb", "cc")} to \code{c("bb; ab","dd")}, #' ie to find 'bb' as matching between both objects). #' #' @param x (vector or list) first object to compare; if vector, the (partially) concatenated identifyers (will be split using separator \code{sep}), or list of items to be matched (ie already split) #' @param y (vector or list) second object to compare; if vector, the (partially) concatenated identifyers (will be split using separator \code{sep}), or list of items to be matched (ie already split) #' @param sep (character, length=1) separator used to split concatenated identifyers (if \code{x} or \code{y} is vector) #' @param sep2 (character, length=1) optional separator used when \code{method="matched"} to concatenate all indexes of \code{y} for column \code{y.allInd} #' @param method (character) mode of operation: 'asIndex' to return index of y (those hwo have matches) with names of x (which x are the correpsonding match) #' @param silent (logical) suppress messages #' @param debug (logical) display additional messages for debugging #' @param callFrom (character) allow easier tracking of message(s) produced #' #' @details #' \code{method='byX'} .. returns data.frame with view oriented towards entries of \code{x}: character column \code{x} for entire content of \code{x}; integer column \code{x.Ind} for index of \code{x}; #' character column \code{TagBest} for most frequent matching isolated tag/ID; integer column \code{y.IndBest} index of most frequent matching \code{y}; #' character column \code{y.IndAll} index for all \code{y} matching any of the tags; #' character column \code{y.Match} for entire content of best matching \code{y}; #' character column \code{y.Adj} for \code{y} adjusted to best matching \code{y} for easier subsequent perfect matching. #' #' \code{method=c("byX","filter")} .. combinded argument to keep only lines with any matches #' #' \code{method='byTag'} .. returns matrix (of integers) from view of isolated tags from \code{x} (a separate line for each tag from \code{x} matching to \code{y}); #' #' \code{method=c("byTag","filter")} ..if combined as arguments, this will return a data.frame for all unique tags with any matches between \code{x} and \code{y}, with #' additional colunms \code{x.AllInd} for all matching \code{x}-indexes, \code{y.IndBest} best matching \code{y} index; \code{x.n} for number of different \code{x} conatining this tag; #' \code{y.AllInd} for all matching \code{y}-indexes #' #' \code{method='adjustXtoY'} .. returns vector with \code{x} adjusted to \code{y}, ie those elements of \code{x} matching are replace by the exact corresponding term of \code{y}. #' #' \code{method=NULL} .. If no term matching the options shown above is given, another version of 'asIndex' is returned, but indexes to \code{y} _after_ spliting by \code{sep}. #' Again, this method can be filtered by using \code{method="filter"} to focus on the best matches to \code{x}. #' #' @return matrix, data.frame or list with matching results depending on \code{method} chosen #' @seealso \code{\link[base]{match}}; \code{\link[base]{strsplit}} #' #' @examples #' aa <- c("m","k", "j; aa", "m; aa; bb; o; ee", "n; dd; cc", "aa", "cc") #' bb <- c("dd; r", "aa", "ee; bb; q; cc", "p; cc") #' (match1 <- multiMatch(aa, bb, method=NULL)) # match bb to aa #' (match2 <- multiMatch(aa, bb, method="byX")) # match bb to aa #' (match3 <- multiMatch(aa, bb, method="byTag")) # match bb to aa #' (match4 <- multiMatch(aa, bb, method=c("byTag","filter"))) # match bb to aa #' #' @export multiMatch <- function(x, y, sep="; ", sep2=NULL, method="byX", silent=FALSE, debug=FALSE, callFrom=NULL) { ## for finding common in multiple to multiple matching (eg c("aa; bb", "cc") vs c("bb; ab","dd")) ## tells which x (names of output) was found matching (at least by 1 subunit) to which (part of) y, names of y tell which x (index) ## note: multiple matches are ignored (only 1st match reported) fxNa <- .composeCallName(callFrom, newNa="multiMatch") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE doMa <- TRUE if(length(x) <1) {doMa <- FALSE; if(!silent) message(fxNa,"Argument 'x' is empty, nothing to do !")} if(length(y) <1) {doMa <- FALSE; if(!silent) message(fxNa,"Argument 'y' is empty, nothing to do !")} out <- outF <- NULL if(doMa) { if(is.list(x)) {xL <- x; x <- sapply(x, paste, collapse=sep)} else xL <- strsplit(x, sep) if(is.list(y)) {yL <- y; y <- sapply(y, paste, collapse=sep)} else yL <- strsplit(y, sep) names(xL) <- 1:length(x) yV <- unlist(yL) names(yV) <- rep(1:length(y), sapply(yL, length)) if(length(sep2) !=1) sep2 <- sep if(debug) {message(fxNa," doMa=",doMa," mM1")} ## 'asIndex' .. return list (length matches x) where values indicate index of which y is matched by which elment of x (after split) ## check each x; determine that in 3rd x 'aa' matches to 1st of 1st y; in 4th x 'aa' out <- lapply(xL, function(z) {w <- match(yV, z); v <- !is.na(w); if(any(!v)) { v <- yV[which(v)]; u <- as.integer(names(v)); names(u) <- v; chDu <- duplicated(paste(names(u),u)); if(any(chDu)) u <- u[which(!chDu)]; u } else NULL }) ## filter1 : filter to most frequent (or first of same freq) if(length(grep("^filter",method)) >0 && !"byTag" %in% method) out <- outF <- lapply(out, function(z) if(length(z) >1) z[which(z ==names(which.max(table(z))) )] else z) if(debug) {message(fxNa," method=",method," mM2")} ## by isolated tag/ID if("byTag" %in% method) { nLi <- sapply(out, length); tmp <- rep(nLi,nLi) mat <- cbind(x.Ind=as.integer(names(tmp)), yInd=unlist(out)) rownames(mat) <- as.character(unlist(sapply(out, names))) chNa <- is.na(mat[,2]) if(any(chNa)) mat <- mat[which(!chNa),] mat <- mat[order(rownames(mat), mat[,1]),] if(length(grep("^filter", method)) >0) { xV <- unlist(xL) tmX <- tapply(mat[,1], rownames(mat), function(z) c(IndBest=z[which.max(z)], n=length(unique(z)), allInd=paste(unique(z), collapse=sep2))) tmY <- tapply(mat[,2], rownames(mat), function(z) c(IndBest=z[which.max(z)], n=length(unique(z)), allInd=paste(unique(z), collapse=sep2))) tmp <- cbind(matrix(unlist(tmX), nrow=length(tmX), byrow=TRUE), matrix(unlist(tmY), nrow=length(tmY), byrow=TRUE)) dimnames(tmp) <- list(sort(unique(rownames(mat))), paste(rep(c("x","y"), each=3),rep(c("IndBest","n","AllInd"),2), sep=".")) mat <- data.frame(x.IndBest=as.integer(tmp[,1]), x.n=as.integer(tmp[,2]), x.AllInd=tmp[,3], y.IndBest=as.integer(tmp[,4]), x.n=as.integer(tmp[,5]), y.AllInd=tmp[,6]) } out <- mat } if(debug) {message(fxNa," mM3")} if("byX" %in% method) { df1 <- data.frame(x=x,x.Ind=1:length(x), TagBest=NA, y.IndBest=NA, y.IndAll=NA, y.Match=NA, y.Adj=NA) nLi <- sapply(out,length) df1[which(nLi >0),"y.IndAll"] <- sapply(out[which(nLi >0)], function(z) paste(z, collapse=sep2)) ## for IndBest outF <- if(length(outF) <1 | any(sapply(outF,length) >1)) lapply(out, function(z) if(length(z) >1) z[which( z ==names(which.max(table(z))) )][1] else z[1]) else outF df1[which(nLi >0),"y.IndBest"] <- as.integer(sapply(outF[which(nLi >0)], function(z) paste(z, collapse=sep2))) df1[which(nLi >0),"TagBest"] <- naOmit(sapply(outF, function(z) names(z)[1])) df1[which(nLi >0),"y.Match"] <- y[df1[which(nLi >0),"y.IndBest"]] df1[which(nLi >0),"y.Adj"] <- df1[which(nLi >0),"x"] if(length(grep("^filter", method)) >0) df1 <- df1[which(!is.na(df1[,"TagBest"])),] out <- df1 } if(is.list(out) && length(grep("^filter", method)) >0) out <- out[which(sapply(out,length) >0)] } out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/multiMatch.R
#' Number of fragments after cut at specific character(s) #' #' \code{nFragments0} tells the number of fragments/entry when cutting after 'cutAt' #' @param protSeq (character) text to be cut #' @param cutAt (integer) position to cut #' @return numeric vector with number of fragments for each entry 'protSeq' (names are 'protSeq') #' @seealso more elaborate \code{{nFragments}}; \code{\link{cutAtMultSites}} #' @examples #' tmp <- "MSVSRTMEDSCELDLVYVTERIIAVSFPSTANEENFRSNLREVAQMLKSKHGGNYLLFNLSERRPDITKLHAKVLEFGWPDLHTPALEKI" #' nFragments0(c(tmp,"ojioRij"),c("R","K")) #' @export nFragments0 <- function(protSeq,cutAt) {sapply(protSeq,function(x) length(cutAtMultSites(x,cutAt)))} #' Number of fragments after cut at specific character(s) within size-range #' #' \code{nFragments} determines number of fragments /entry within range of 'sizeRa' (numeric,length=2) when cutting after 'cutAt' #' @param protSeq (character) text to be cut #' @param cutAt (character) position to cut #' @param sizeRa (numeric,length=2) min and max size to consider #' @return numeric vector with number of fragments for each entry 'protSeq' (names are 'protSeq') #' @seealso \code{\link{cutAtMultSites}}, simple version \code{{nFragments0}} (no size-range) #' @examples #' tmp <- "MSVSREDSCELDLVYVTERIIAVSFPSTANEENFRSNLREVAQMLKSKHGGNYLLFNLSERRPDITKLHAKVLEFGWPDLHTPALEKI" #' nFragments(c(tmp,"ojioRij"),c("R","K"),c(4,31)) #' #' @export nFragments <- function(protSeq,cutAt,sizeRa) { # number of fragments /entry within range of 'sizeRa' (numeric,length=2) when cutting after 'cutAt' if(length(naOmit(unique(sizeRa))) <2) stop(" 'sizeRa' should be numeric of length=2") if(length(cutAt) <0) rep(1,length(protSeq)) else { sapply(protSeq,function(x) {y <- cutAtMultSites(x,cutAt) sum(nchar(y) > min(sizeRa,na.rm=TRUE) & nchar(y) < max(sizeRa,na.rm=TRUE),na.rm=TRUE)})}}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/nFragments.R
#' Count number of non-numeric characters #' #' \code{nNonNumChar} counts number of non-numeric characters. #' Made for positive non-scientific values (eg won't count neg-sign, neither Euro comma ',') #' @param txt character vector to be treated #' @return This function returns a numeric vector with numer of non-numeric characters (ie not '.' or 0-9)) #' @seealso \code{\link[base]{nchar}} #' @examples #' nNonNumChar("a1b "); sapply(c("aa","12ab","a1b2","12","0.5"), nNonNumChar) #' @export nNonNumChar <- function(txt) {txt <- as.character(txt) sum(!sapply(1:nchar(txt), function(x) substr(txt, x, x) %in% c(".",0:9))) } #' Extract number(s) before capital character #' #' This function aims to extract number(s) before capital character #' #' @param x character vector to be treated #' @return This function returns a numeric vector #' @seealso \code{\link[base]{grep}}, \code{\link[base]{nchar}} #' @examples #' .extrNumHeadingCap(" 1B ") #' @export .extrNumHeadingCap <- function(x){ ## extract number(s) before capital character tmp <- substr(x, regexpr("[[:digit:]]+[[:upper:]]",x), nchar(x)) as.numeric(substr(tmp, 0, regexpr("[[:upper:]]",tmp) -1)) } #' Extract numbers before separator followed by alphabetic character #' #' This function aims to extract number(s) before separator followed by alphabetic character (return named numeric vector, NAs when no numeric part found) #' #' @param x character vector to be treated #' @param sep (character) separator #' @return This function returns a numeric vector #' @seealso \code{\link[base]{nchar}} #' @examples #' .extrNumHeadingSepChar(" 1B ") #' @export .extrNumHeadingSepChar <- function(x, sep="_"){ ## extract number(s) before separator followed by alphabetic character (return named numeric vector, NAs when no numeric part found) tmp <- substr(x, 1, attributes(regexpr(paste("[[:digit:]]+",sep,"[[:alpha:]]",sep=""),x))[[1]] -2) out <- as.numeric(tmp) if(!is.null(names(x))) names(out) <- names(x) out } #' Set lowest value to given value #' #' This function aims to set lowest value of x to value 'setTo' #' #' @param x (numeric) main vector to be treated #' @param setTo (numeric) replacement value #' @return This function returns a numeric vector #' @seealso \code{\link[base]{nchar}} #' @examples #' .setLowestTo(9:4, 6) #' @export .setLowestTo <- function(x, setTo) { ## set lowest value of x to value 'setTo' mi <- min(x[which(is.finite(x))], na.rm=TRUE); x[which(x==mi)] <- setTo; x}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/nNonNumChar.R
#' Fast na.omit #' #' \code{naOmit} removes NAs from input vector. This function has no slot for removed elements while \code{na.omit} does so. #' Resulting objects from \code{naOmit} are smaller in size and subsequent execution (on large vectors) is faster (in particular if many NAs get encountered). #' Note : Behaves differently to \code{na.omit} with input other than plain vectors. Will not work with data.frames ! #' @param x (vector or matrix) input #' @return vector without NAs (matrix input will be transformed to vector). Returns NULL if input consists only of NAs. #' @seealso \code{\link[stats]{na.fail}}, \code{na.omit} #' @examples #' aA <- c(11:13,NA,10,NA); #' naOmit(aA) #' @export naOmit <- function(x) {chNa <- is.na(x); if(all(chNa)) NULL else x[which(!chNa)]}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/naOmit.R
#' Transform matrix to non-ambiguous matrix (in respect to given column) #' #' \code{nonAmbiguousMat} makes values of matrix 'mat' in col 'byCol' unique. #' @param mat numeric or character matrix (or data.frame), column specified by 'byCol' must be/will be used as.numeric, 1st column of 'mat' will be considered like index & used for adding prefix 'nameMod' (unless byCol=1, then 2nd col will be used) #' @param byCol (character or integer-index) column by which ambiguousity will be tested #' @param uniqOnly (logical) if =TRUE return unique only, if =FALSE return unique and single representative of non-unique values (with '' added to name), selection of representative of repeated: first (of sorted) or middle if >2 instances #' @param asList (logical) return result as list #' @param nameMod (character) prefix added to 1st column of 'mat' (expect 'by') for indicating non-unique/ambiguous values #' @param callFrom (character) allow easier tracking of message(s) produced #' @return sorted non-ambigous numeric vector (or list if 'asList'=TRUE and 'uniqOnly'=FALSE) #' @seealso for non-numeric use \code{\link{firstOfRepeated}} - but 1000x much slower !; \code{\link{get1stOfRepeatedByCol}} #' @examples #' set.seed(2017); mat2 <- matrix(c(1:100,round(rnorm(200),2)),ncol=3, #' dimnames=list(1:100,LETTERS[1:3])); #' head(mat2U <- nonAmbiguousMat(mat2,by="B",na="_",uniqO=FALSE),n=15) #' head(get1stOfRepeatedByCol(mat2,sortB="B",sortS="B")) #' @export nonAmbiguousMat <- function(mat,byCol,uniqOnly=FALSE,asList=FALSE,nameMod="amb_",callFrom=NULL) { fxNa <- .composeCallName(callFrom,newNa="nonAmbiguousMat") if(is.character(byCol)) byCol <- naOmit(match(byCol,colnames(mat))) else { # transform 'byCol' to index using match if(is.factor(byCol)) byCol <- as.numeric(as.character(byCol))} msg <- "Invalid 'byCol': Argument 'byCol' allows selecting one column of numeric data from 'mat', either as column-name or index" if(length(byCol) <1) stop(msg) else if(length(byCol) >1) {byCol <- byCol[1]; message(msg)} mat <- mat[order(as.numeric(mat[,byCol]),decreasing=FALSE),] y <- convToNum(mat[,byCol],remove=NULL,sciIncl=TRUE,callFrom=fxNa) ab <- which(diff(y)==0) onlySingleLast <- FALSE if(length(ab) <1) return(if(asList) list(unique=mat) else mat) else { if(onlySingleLast) { ac <- diff(ab) ac <- ab[c(which(ac >1),if(ac[length(ac)] >1) length(ab) else NULL)]} # not yet used: only single (last) instance of repeated nrName <- if(is.null(rownames(mat))) rownames(mat) else mat[,if(byCol==1) 2 else 1] nrName[c(ab,ab+1)] <- paste(nameMod,nrName[c(ab,ab+1)],sep="") if(is.null(rownames(mat))) mat[,if(byCol==1) 2 else 1] <- nrName else rownames(mat) <- nrName out <- if(uniqOnly | asList) mat[-1*unique(sort(c(ab,ab+1))),] else NULL out <- if(asList) {if(uniqOnly) list(unique=out) else list(unique=out,ambig=mat[ab,])} else {if(uniqOnly) out else mat[-ab,]} out } }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/nonAmbiguousMat.R
#' make numeric vector non-ambiguous (ie unique) #' #' \code{nonAmbiguousNum} makes (named) values of numeric vector 'x' unique. #' Note: for non-numeric use \code{\link{firstOfRepeated}} - but 1000x slower ! #' Return sorted non-ambigous numeric vector (or list if 'asList'=TRUE and 'uniqOnly'=FASLSE) #' @param x (numeric) main input #' @param uniqOnly (logical) if=TRUE return unique only, if =FALSE return unique and single representative of non-unique values (with '' added to name), selection of representative of repeated: first (of sorted) or middle if >2 instances #' @param asList (logical) return list #' @param nameMod (character) text to add in case on ambiguous values, default="amb_" #' @param callFrom (character) allow easier tracking of message(s) produced #' @return sorted non-ambigous numeric vector (or list if 'asList'=TRUE and 'uniqOnly'=FALSE) #' @seealso \code{\link{firstOfRepeated}} for non-numeric use (much slower !!!), \code{\link[base]{duplicated}} #' @examples #' set.seed(2017); aa <- round(rnorm(100),2); names(aa) <- 1:length(aa) #' str(nonAmbiguousNum(aa)) #' str(nonAmbiguousNum(aa,uniq=FALSE,asLi=TRUE)) #' @export nonAmbiguousNum <- function(x,uniqOnly=FALSE,asList=FALSE,nameMod="amb_",callFrom=NULL) { fxNa <- .composeCallName(callFrom,newNa="nonAmbiguousNum") y <- sort(x) ab <- which(diff(y)==0) if(length(ab) <1) return(if(asList) list(unique=x) else x) else { ac <- diff(ab) ac <- ab[c(which(ac >1),if(ac[length(ac)] >1) length(ab) else NULL)] # index : single instance of repeated red <- y[ac] names(red) <- paste(nameMod,names(red),sep="") out <- y[-1*unique(sort(c(ab,ab+1)))] if(!uniqOnly) out <- if(asList) list(unique=out,ambig=red) else c(out,red) out} }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/nonAmbiguousNum.R
#' Non-redundant lines of matrix #' #' \code{nonRedundLines} reduces complexity of matrix (or data.frame) if multiple consectuive (!) lines with same values. #' Return matrix (or data.frame) without repeated lines (keep 1st occurance) #' @param dat (matrix or data.frame) main input #' @param callFrom (character) allow easier tracking of message(s) produced #' @return matrix (or data.frame) without repeated lines (keep 1st occurance).. #' @seealso \code{\link{firstLineOfDat}}, \code{\link{firstOfRepLines}}, \code{\link{findRepeated}}, \code{\link{firstOfRepeated}}, \code{\link{get1stOfRepeatedByCol}}, \code{\link{combineRedBasedOnCol}}, \code{\link{correctToUnique}} #' @examples #' mat2 <- matrix(rep(c(1,1:3,3,1),2),ncol=2,dimnames=list(letters[1:6],LETTERS[1:2])) #' nonRedundLines(mat2) #' @export nonRedundLines <- function(dat,callFrom=NULL){ fxNa <- .composeCallName(callFrom,newNa="nonRedundLines") msg <- c(fxNa," expecting matrix or data.frame with >1 lines and >= 1 column(s)") if(length(dim(dat)) <2) stop(msg) if(any(nrow(dat)<2, ncol(dat) <1)) stop(msg) if(is.null(rownames(dat))) rownames(dat) <- 1:nrow(dat) exclLi <- which(rowSums(dat[-nrow(dat),] == dat[-1,]) ==ncol(dat)) +1 out <- if(length(exclLi) >0) dat[-exclLi,] else dat if(length(dim(out)) <2) out <- matrix(out,ncol=ncol(dat), dimnames=list(rownames(dat)[-1*exclLi],colnames(dat))) out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/nonRedundLines.R
#' Filter for unique elements #' #' \code{nonredDataFrame} filters 'x' (list of char-vectors or char-vector) for elements unique (to 'ref' or if NULL to all 'x') and of character length. #' May be used for different 'accession' for same pep sequence (same 'peptide_id'). #' Note : made for treating data.frames, may be slightly slower than matrix equivalent #' @param dataFr (data.frame) main inpput #' @param useCol (character,length=2) comlumn names of 'dataFr' to use : 1st value designates where redundant values should be gathered; 2nd value designes column of which information should be concatenated #' @param sepCollapse (character) conatenation symbol #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a data.frame of filtered (fewer lines) with additional 2 columns 'nSamePep' (number of redundant entries) and 'concID' (concatenated content) #' @seealso \code{\link{combineRedBasedOnCol}}, \code{\link{correctToUnique}}, \code{\link[base]{unique}} #' @examples #' 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")) #' @export nonredDataFrame <- function(dataFr, useCol=c(pepID="peptide_id", protID="accession", seq="sequence",mod="modifications"), sepCollapse="//", callFrom=NULL) { fxNa <- .composeCallName(callFrom,newNa="nonredDataFrame") chColNa <- useCol %in% colnames(dataFr) if(any(!chColNa)) message(" TROUBLE AHEAD : can't find ",pasteC(useCol[which(!chColNa)])) if(!is.data.frame(dataFr)) dataFr <- as.data.frame(dataFr,stringsAsFactors=FALSE) i <- which(colnames(dataFr)==useCol[1]); dataFr[,i] <- as.character(dataFr[,i]) i <- which(colnames(dataFr)==useCol[2]); dataFr[,i] <- as.character(dataFr[,i]) dataFr <- cbind(dataFr, nSamePep=1, concID="") class(dataFr[,ncol(dataFr)-1]) <- "integer" class(dataFr[,ncol(dataFr)]) <- "character" dataFr[,ncol(dataFr)] <- as.character(dataFr[,useCol[2]]) dupL <- duplicated(dataFr[,useCol[1]], fromLast=TRUE) # search in col with petide_id if(any(dupL)) { dupB <- duplicated(dataFr[,useCol[1]], fromLast=FALSE) firOfRep <- which(dupL & !dupB) anyDup <- which(dupL | dupB) out <- matrix(unlist(tapply(dataFr[anyDup,useCol[2]],dataFr[anyDup,useCol[1]], function(x) c(length(x),paste(x,collapse=sepCollapse)))), ncol=2, byrow=TRUE, dimnames=list(dataFr[firOfRep,useCol[1]],c("n","protIDs"))) dataFr <- dataFr[-1*which(dupB),] # remove lines of mult repeated replLi <- match(rownames(out),as.character(dataFr[,useCol[1]]) ) dataFr[match(rownames(out),as.character(dataFr[,useCol[1]]) ),ncol(dataFr)-(1:0)] <- out class(dataFr[,ncol(dataFr)-1]) <- "integer" } dataFr }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/nonredDataFrame.R
#' Normalize data in various modes #' #' Generic normalization of 'dat' (by columns), multiple methods may be applied. #' The choice of normalization procedures must be done with care, plotting the data before and after normalization #' may be critical to understandig the initial data structure and the effect of the procedure applied. #' Inappropriate methods chosen may render interpretation of (further) results incorrect. #' #' @details #' In most cases of treating 'Omics'-data one works with the hypothesis that there are no global changes in the structure of all data/columns #' Under this htpothesis it is very common to assume the the median (via the argument \code{method}) of all samples (ie columns) should remain constant. #' For examples samples/columns with less signal will be considered as having received 'accidentally' less material (eg due to the imprecision when transfering very small amounts of liquid samples). #' In consequence, a sample having received only 95% of input material is assumed to give only 95% signal intensity of what may have been expected. #' Thus, all measures will be multiplied by 1/0.95 (apr 1.053) to compensate for supposed lack of staring material. #' #' With the analysis of 'Omics'-data it is very common to work with data on log-scale. #' In this case the argument \code{mode} should be set to \code{additive}, since adding a constant factor to log-data corresponds to a multiplicative factor on regular scale #' Please note that (at this point) the methods 'slope', 'exponent', 'slope2Sections' and 'vsn' don't distinguish between additive and proportional modes, but take take the data 'as is' #' (you may look at the original documenation for more details, see \code{\link{exponNormalize}}, \code{\link{adjBy2ptReg}}, \code{\link[vsn]{justvsn}}). #' #' Normalization using \code{method="rowNormalize"} runs \code{\link{rowNormalize}} from this package. #' In this case, the working hypothesis is, that all values in each row are expected to be the same. #' This method could be applied when all series of values (ie columns) are replicate measurements of the same sample. #' THere is also an option for treating sparse data (see argument \code{sparseLim}), which may, hovere, consume much more comptational ressources, #' in particular, when the value \code{nCombin} is low (compared to the number of samples/columns). #' #' Normalization using \code{method="vsn"} runs \code{\link[vsn]{justvsn}} from \href{https://bioconductor.org/packages/release/bioc/html/vsn.html}{vsn} #' (this requires a minimum of 42 rows of input-data and having the Bioconductor package vsn installed). #' Note : Depending on the procedure chosen, the normalized data may appear on a different scale. #' #' @param dat matrix or data.frame of data to get normalized #' @param method (character) may be "mean","median","NULL","none", "trimMean", "rowNormalize", "slope", "exponent", "slope2Sections", "vsn"; When \code{NULL} or 'none' is chosen the input will be returned #' @param refLines (NULL or numeric) allows to consider only specific lines of 'dat' when determining normalization factors (all data will be normalized) #' @param refGrp Only the columns indicated will be used as reference, default all columns (integer or colnames) #' @param mode (character) may be "proportional", "additive"; #' decide if normalizatio factors will be applies as multiplicative (proportional) or additive; for log2-omics data \code{mode="aditive"} is suggested #' @param trimFa (numeric, length=1) additional parameters for trimmed mean #' @param minQuant (numeric) only used with \code{method='rowNormalize'}: optional filter to set all values below given value as \code{NA}; see also \code{\link{rowNormalize}} #' @param sparseLim (integer) only used with \code{method='rowNormalize'}: decide at which min content of \code{NA} values the function should go in sparse-mode; see also \code{\link{rowNormalize}} #' @param nCombin (NULL or integer) only used with \code{method='rowNormalize'}: used only in sparse-mode (ie if content of \code{NA}s higher than content of \code{sparseLim}): #' Number of groups of smller matrixes with this number of columns to be inspected initially; #' low values (small groups have higher chances of more common elements); see also \code{\link{rowNormalize}} #' @param omitNonAlignable (logical) only used with \code{method='rowNormalize'}: allow omitting all columns which can't get aligned due to sparseness; see also \code{\link{rowNormalize}} #' @param maxFact (numeric, length=2) only used with \code{method='rowNormalize'}: max normalization factor; see also \code{\link{rowNormalize}} #' @param quantFa (numeric, length=2) additional parameters for quantiles to use with method='slope' #' @param expFa (numeric, length=1) additional parameters for method='exponent' #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allows easier tracking of messages produced #' @return This function returns a matrix of normalized data (same dimensions as input) #' @seealso \code{\link{rowNormalize}}, \code{\link{exponNormalize}}, \code{\link{adjBy2ptReg}}, \code{\link[vsn]{justvsn}} #' @examples #' 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 #' summary(dat1) #' dat1[c(1:5,50:54,95:100),] #' 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)) #' dat1[c(1:10,91:100),] #' cor(dat1[,3],rowMeans(dat1[,1:2],na.rm=TRUE), use="complete.obs") # high #' cor(dat1[,4],rowMeans(dat1[,1:2],na.rm=TRUE), use="complete.obs") # bad #' cor(dat1[c(1:10,91:100),4],rowMeans(dat1[c(1:10,91:100),1:2],na.rm=TRUE),use="complete.obs") #' cor(dat1[,3],rowMeans(dat1[,1:2],na.rm=TRUE)^ (1/seq(2,5,length.out=100)),use="complete.obs") #' @export normalizeThis <- function(dat, method="mean", refLines=NULL, refGrp=NULL, mode="proportional", trimFa=NULL, minQuant=NULL, sparseLim=0.4, nCombin=3, omitNonAlignable=FALSE, maxFact=10, quantFa=NULL, expFa=NULL, silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="normalizeThis") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(!any(sapply(c("additive","add","a"), identical, mode))) mode <- "proportional" out <- NULL chMe <- is.na(method) if(sum(!chMe) <1) stop(" Argument 'method' seems empty - nothing to do !") method <- if(any(chMe)) naOmit(method)[1] else method[1] if(length(dim(dat)) !=2) stop(" expecting matrix or data.frame with >= 2 rows as 'dat' !") if(!is.matrix(dat)) dat <- as.matrix(dat) if(!is.null(refLines)) if(identical(refLines, 1:nrow(dat))) {refLines <- NULL; if(!silent) message(fxNa," omit redundant 'refLines'")} ## assemble parameters params <- list(refLines=refLines, trimFa=trimFa, useQ=quantFa, useExp=expFa) ## method specific elements if(is.null(refGrp)) { refGrp <- 1:ncol(dat) } else if(min(refGrp) > ncol(dat) | max(refGrp) < 1) stop(fxNa," 'refGrp' should be integer vector indicating which columns to be used as reference") if(debug) {message(fxNa,"Assemble parameters ; nt1 ; using method=",method," mode=",mode," params=",pasteC(unlist(params[-1])))} if(method %in% "trimMean") { params$trimFa <- 0.2 if(length(trimFa) >0) {if(length(trimFa) ==1) params$trimFa <- trimFa else if(!silent) message(fxNa," invalid 'trimFa', use default 0.2")} } if(any(sapply(c("rowNormalize","rowN","row"), identical, method))) { if(debug) message(fxNa," recognized as method='rowNormalize'") params$minQuant <- minQuant params$sparseLim <- sparseLim params$nCombin <- nCombin params$omitNonAlignable <- omitNonAlignable params$maxFact <- maxFact method <- "row" } if(method %in% "slope") { params$useQ <- c(0.2,0.8) if(length(quantFa) >0) {if(length(quantFa)==2) params$useQ <- quantFa else if(!silent) message(fxNa," invalid 'quantFa', use default c(0.2,0.8)")} } if(method %in% "slope2Sections") { if(length(params$useQ) !=1) params$useQ <- list(signif(stats::quantile(dat, c(0.05,0.15), na.rm=TRUE), 3), signif(stats::quantile(dat, c(0.05,0.15), na.rm=TRUE), 3)) } if(any(sapply(c("exponent","expo","exp"), identical, method))) { if(debug) message(fxNa," recognized as method='exponent'") if(length(expFa) <1) { useExp <- c(log(c(10:1)), 30, 10, 3) params$useExp <- sort(unique(c(round(1 /(1 +abs(useExp -useExp[1])), 4), round(1 +abs(useExp -useExp[1]), 3)))) } method <- "exponent" } if("vsn" %in% method & (if(length(refLines) >0) length(refLines) < nrow(dat) else FALSE)) { if(debug) message(fxNa," recognized as method='vsn'") params$refLines <- NULL if(!silent) message(fxNa," ignoring content of 'refLines', since 'vsn' can only normalize considering all data")} if(debug) {message(fxNa,"Ready to start .normalize() ; nt2 ; using method=",method," mode=",mode," params=",pasteC(unlist(params)))} ## main normalization out <- .normalize(dat, method, mode=mode, param=params, silent=silent, debug=debug, callFrom=fxNa) if(inherits(out, "try-error")) { message(fxNa," Could not run normalization by '",method,"' which gave an error (returning unnormalized)"); out <- dat} out } #' Main Normalization function #' #' This function aims to normalize a matrix or data.frame by columns. #' It assumes all checks have been done before calling this function. #' #' @param dat matrix or data.frame of data to get normalized #' @param meth (character) may be "mean","median","NULL","none", "trimMean", "rowNormalize", "slope", "exponent", "slope2Sections", "vsn"; When \code{NULL} or 'none' is chosen the input will be returned #' @param mode (character) may be "proportional", "additive"; #' decide if normalizatio factors will be applies as multiplicative (proportional) or additive; for log2-omics data \code{mode="aditive"} is suggested #' @param param (list) additional parameters #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allows easier tracking of messages produced #' @return This function returns a numeric vector #' @seealso \code{\link{normalizeThis}} #' @examples #' aa <- matrix(1:12, ncol=3) #' .normalize(aa,"median",mode="proportional",param=NULL) #' @export .normalize <- function(dat, meth, mode, param, silent=FALSE, debug=FALSE, callFrom=NULL){ ## 'dat' .. matrix (>1 col, >1 li) to be normalized ## 'meth' .. method ## 'param' .. list with supl parameters (refLines, certain specific for norm methods) fxNa <- ".normalize" mode <- if(identical(mode,"additive")) "Add" else "Prop" # reduce to short name if(identical(meth,"average")) meth <- "mean" asRefL <- (length(param$refLines) < nrow(dat) && !is.null(param$refLines)) datRef <- if(asRefL) {if(length(param$refLines) >1) dat[param$refLines,] else matrix(dat[param$refLines,],nrow=1)} else NULL if("vsn" %in% meth) { chPa <- requireNamespace("vsn", quietly=TRUE) if(!chPa) { meth <- "mean" warning(fxNa, "Package 'vsn' not found ! Please install first from Bioconductor; resetting to default 'mean'") } if(nrow(if(asRefL) datRef else dat) <42) message(callFrom," PROBLEM : Too few lines of data to run 'vsn' ! ")} ## Some methods have not yet been adopted/declined to additive/proportional mode if(meth %in% c("none", "slope", "exponent", "slope2Sections", "vsn")) mode <- NULL meth <- paste0(meth,mode) switch(meth, none=dat, meanAdd= mean(if(asRefL) datRef else dat, na.rm=TRUE) + dat - rep(colMeans(if(asRefL) datRef else dat, na.rm=TRUE), each=nrow(dat)), meanProp= mean(if(asRefL) datRef else dat, na.rm=TRUE) * dat / rep(colMeans(if(asRefL) datRef else dat, na.rm=TRUE), each=nrow(dat)), trimMeanAdd=mean(if(asRefL) datRef else dat, trim=param$trimFa, na.rm=TRUE) + dat - rep(apply( if(asRefL) datRef else dat, 2, mean, trim=param$trimFa, na.rm=TRUE), each=nrow(dat)), trimMeanProp=mean(if(asRefL) datRef else dat, trim=param$trimFa, na.rm=TRUE) * dat / rep(apply( if(asRefL) datRef else dat, 2, mean, trim=param$trimFa, na.rm=TRUE), each=nrow(dat)), medianAdd=stats::median(if(asRefL) datRef else dat, na.rm=TRUE) + dat - rep(apply( if(asRefL) datRef else dat, 2, stats::median, na.rm=TRUE), each=nrow(dat)), medianProp=stats::median(if(asRefL) datRef else dat,na.rm=TRUE) * dat / rep(apply( if(asRefL) datRef else dat, 2, stats::median, na.rm=TRUE), each=nrow(dat)), rowAdd= rowNormalize(dat=dat, method=meth, refLines=param$refLines, refGrp=param$refGrp, proportMode="additive", minQuant=param$minQuant, sparseLim=param$sparseLim, nCombin=param$nCombin, omitNonAlignable=param$omitNonAlignable, maxFact=param$maxFact, silent=silent, debug=debug, callFrom=fxNa), rowProp=rowNormalize(dat=dat, method=meth, refLines=param$refLines, refGrp=param$refGrp, proportMode="proportional", minQuant=param$minQuant, sparseLim=param$sparseLim, nCombin=param$nCombin, omitNonAlignable=param$omitNonAlignable, maxFact=param$maxFact, silent=silent, debug=debug, callFrom=fxNa), slope=.normConstSlope(mat=dat, useQuant=param$useQ, refLines=param$refLines, diagPlot=FALSE), exponent=try(exponNormalize(dat, useExpon=param$useExp, refLines=param$refLines)$datNor, silent=TRUE), slope2Sections=try(adjBy2ptReg(dat, lims=param$useQ, refLines=param$refLines), silent=TRUE), vsn=try(vsn::justvsn(dat), silent=TRUE) ) } #' Normalize columns of 2dim matrix to common linear regression fit #' #' This function aims to normalize columns of 2dim matrix to common linear regression fit within range of 'useQuant' #' #' @param mat matrix or data.frame of data to get normalized #' @param useQuant (numeric) quantiles to use #' @param refLines (NULL or numeric) allows to consider only specific lines of 'dat' when determining normalization factors (all data will be normalized) #' @param diagPlot (logical) draw diagnistic plot #' @param plotLog (character) indicate which axis shousl be diplayed on log-scale, may be 'x', 'xy' or 'y' #' @param datName (character) use as title in diag plot #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allows easier tracking of messages produced #' @return This function returns a numeric vector #' @examples #' aa <- matrix(1:12, ncol=3) #' @seealso \code{\link{normalizeThis}} ##' @export .normConstSlope <- function(mat, useQuant=c(0.2,0.8), refLines=NULL, diagPlot=TRUE, plotLog="", datName=NULL, silent=FALSE, debug=FALSE, callFrom=NULL){ ## normalize columns of 2dim matrix to common linear regression fit within range of 'useQuant' ## returns normalized data (2dim matrix) ## in case of matrixes, data will be normalized by columns, but only the average of all indiv regression-lines will be shown on graph ## 'useQuant' ..defines window of data to be considered for normalizing ## 'refLines' ..lines to use for determining normalization factors ## 'datName' for use as title in diag plot # cat(" mat: "); cat(str(mat),"\n") fxNa <- .composeCallName(callFrom,newNa=".normConstSlope") msg1 <- " 'useQuant' should be vector of two numeric values between 0 & 1" msg2 <- paste(" 'mat' should be matrix with two dimensions. Here it appears as ") if(!is.numeric(mat)) stop(fxNa,msg2,class(mat)," with ",mode(mat)," data of ",length(dim(mat))," dims") if(sum(is.finite(useQuant)) != 2 || length(useQuant) !=2) {message(fxNa,msg1); useQuant=c(0.2,0.8)} if(useQuant[1] < 0 || useQuant[1] > 1) {message(msg1); useQuant=c(0.2,0.8)} if(plotLog %in% c("x","xy")) {matOri <- mat; mat <- log(mat); message(fxNa," ..setting data to log")} quantVal <- apply(mat, 2, stats::quantile, useQuant,na.rm=TRUE) tmp <- apply(mat, 2, function(x) {x <- naOmit(x); x[x >= stats::quantile(x,min(useQuant),na.rm=TRUE) & x <= stats::quantile(x,max(useQuant),na.rm=TRUE)]}) if(!is.list(tmp)) tmp <- as.data.frame(tmp) regr <- sapply(if(length(refLines) < nrow(mat) && !is.null(refLines)) tmp[refLines,] else tmp,.datSlope,toNinX=TRUE) regr[1,] <- regr[1,] + apply(rbind(quantVal[1,],mat), 2, function(x) sum(x[-1] < x[1], na.rm=TRUE)) # correct intercept for no of quantile-omitted data regrM <- rowMeans(regr, na.rm=FALSE) normD <- apply(rbind(regr, mat), 2, function(x) (x[-1*(1:2)] -(regrM[1]-x[1])/x[2]) *x[2]/regrM[2]) if(plotLog %in% c("x","xy")) normD <- exp(normD) if(diagPlot) { msg2 <- paste(fxNa," Unknow argument content ('",plotLog,"') for 'plotLog'; resetting to default no log",sep="") if(length(plotLog) !=1) { message(fxNa,msg2); plotLog <- ""} if(!(plotLog %in% c("","x","y","xy"))) {message(fxNa,msg2); plotLog <- ""} yLab <- "number of values" xLab <- "sorted values" xDat <- sort(normD[which(is.finite(normD[,1])),1]) if(length(refLines) < nrow(mat) && !is.null(refLines)) { chG <- try(graphics::plot(1:sum(is.finite(normD[refLines,1])) ~ sort(normD[which(is.finite(normD[refLines,1])),1]), type="s", main=paste("normalizing ",datName),log=plotLog,col=3,xlab=xLab,ylab=yLab), silent=TRUE) if(inherits(chG, "try-error")) message(fxNa,"UNABLE to draw figure !") else { graphics::points(sort(normD[which(is.finite(normD[-1*refLines,1])),1]), 1:sum(is.finite(normD[-1*refLines,1])), type="s",col=grDevices::grey(0.4))} } else chG <- try(graphics::plot(1:sum(is.finite(normD[,1])) ~ sort(normD[which(is.finite(normD[,1])),1]), type="s",main=paste("normalizing ",datName), log=plotLog,col=3,xlab=xLab,ylab=yLab), silent=TRUE) if(inherits(chG, "try-error")) message(fxNa,"UNABLE to draw figure !") else { for(ii in 2:ncol(normD)) if(length(refLines) < nrow(mat) && !is.null(refLines)) { graphics::points(1:sum(is.finite(normD[refLines,ii]))~ sort(normD[which(is.finite(normD[refLines,ii])),ii]),type="s",col=ii+2) graphics::points(sort(normD[which(is.finite(normD[-1*refLines,ii])),1]), 1:sum(is.finite(normD[-1*refLines,ii])),type="s",col=grDevices::grey(0.4)) } else graphics::points(1:sum(is.finite(normD[,ii]))~ sort(normD[which(is.finite(normD[,ii])),ii]), type="s",col=ii+2) graphics::abline(h=useQuant*sum(!is.na(normD))/ncol(normD), lty=3,col=grDevices::grey(0.6)) if(plotLog %in% c("x","xy")) graphics::curve(log(regrM[1])*(regrM[2]) +regrM[1], lty=2,col=2,add=TRUE) else graphics::abline(regrM[1],regrM[2],lty=2,col=2) } } normD }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/normalizeThis.R
#' Extract pair of numeric values from vector or column-names #' #' This function extracts a pair of numeric values out of a vector or colnames (from a matrix). #' This is useful when pairwise comparisons are concatenated like '10c-100c', return matrix with 'index'=selComp, log2rat and both numeric. #' Additional white space or character text can be removed via the argument \code{stripTxt}. #' Of course, the separator \code{sep} needs to be specified and should not be included to 'stripTxt'. #' #' @param dat (matrix or data.frame) main input #' @param selComp (character) the column index selected #' @param stripTxt (character, max length=2) text to ignore, if NULL heading letter and punctuation characters will be removed; default will remove all letters (and following spaces) #' @param sep (character, length=1) separator between pair of numeric values to extract #' @param columLabel (character) column labels in output #' @param sortByAbsRatio (logical) optional sorting of output by (absolute) log-ratios (most extreme ratios on top) #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of messages produced #' @param debug (logical) additional messages for debugging #' @return This function returns a matrix #' @seealso \code{\link[base]{strsplit}} and help on regex #' @examples #' ## composed column names #' mat1 <- matrix(1:8, nrow=2, dimnames=list(NULL, paste0(1:4,"-",6:9))) #' numPairDeColNames(mat1) #' numPairDeColNames(colnames(mat1)) #' ## works also with simple numeric column names #' mat2 <- matrix(1:8, nrow=2, dimnames=list(NULL, paste0("a",6:9))) #' numPairDeColNames(mat2) #' @export numPairDeColNames <- function(dat, selComp=NULL, stripTxt=NULL, sep="-", columLabel="conc", sortByAbsRatio=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL) { ## extract pair of numeric content of colnames from pairwise comparisons, return matrix with 'index'=selComp, log2rat and both numeric ## dat (matrix or data.frame) testing results (only the colnames will be used) ## selComp (integer) the column index selected ## stripTxt (character) text to be removed, if NULL letter and punctuation characters will be removed; default will remove all letters (and following spaces) ## sep (character) separator (for separating multiple numeric parts out of character-string) ## columLabel (character) used for column labels in output ## sortByAbsRatio (logical) sort output by (absolute) log-ratios fxNa <- .composeCallName(callFrom, newNa="numPartDeColNames") if(length(dim(dat)) >1) dat <- colnames(dat) if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(length(dat) <1) stop("Invalid entry of 'dat'") if(length(selComp) >0) { if(is.numeric(selComp)) dat <- dat[as.integer(selComp)] else { if(any(selComp %in% dat)) dat[selComp] else message(fxNa," invalid entry for 'selComp', ignoring")} } else selComp <- 1:length(dat) if(length(stripTxt) <1) stripTxt <- "[[:alpha:]]+[[:space:]]*[[:alpha:]]*|[[:space:]]+[[:alpha:]]+[[:space:]]*[[:alpha:]]*|[[:space:]]+" chSep <- nchar(sub(stripTxt,"",paste0("A",sep,"B"))) if(chSep !=3) message(fxNa,"PROBLEM ? : 'stripTxt' does REMOVE the separator 'sep' ! Select a different separator or 'stripTxt' strategy to resolve pairwise combinations !") dat <- if(length(stripTxt) >1) sub(stripTxt[2],"",sub(stripTxt[1],"",dat)) else gsub(stripTxt,"",dat) chSep <- grep(sep, dat) if(length(chSep) <1) { if(!silent) message(fxNa,"Could not find any instance of separator 'sep'; (maybe removed with 'stripTxt' ?)") logRat <- try(as.integer(dat), silent=TRUE) # try remove text at start or end if(inherits(logRat, "try-error")) stop(fxNa," Did not succed to extract (single) numeric content") logRat <- cbind(index=selComp, logRat=NA, logRat) colnames(logRat)[3] <- columLabel } else { logRat <- try(as.integer( unlist(strsplit(dat, sep))), silent=TRUE) if(inherits(logRat, "try-error")) stop(fxNa," Did not succed to extract numeric content (by splitting)") logRat <- matrix(logRat, ncol=2, byrow=TRUE, dimnames=list(NULL,paste0(columLabel,1:2))) chRat <- logRat[,1] > logRat[,2] if(any(chRat)) logRat[which(chRat),] <- logRat[which(chRat), 2:1] logRat <- cbind(index=selComp, log2rat=signif(log2(logRat[,2]/logRat[,1]),4), logRat) } if(sortByAbsRatio && nrow(logRat) >1) logRat <- logRat[order(if(length(chSep) <1) logRat[,3] else abs(logRat[,2]), decreasing=TRUE),] logRat }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/numPairDeColNames.R
#' Order Lines of Matrix According to Reference (Character) Vector #' #' @description #' This function orders lines of matrix \code{mat} according to a (character) reference vector \code{ref}. #' To do so, all columns of \code{mat} will be considered to use the first column from left with the best (partial) matching results. #' This function first looks for unambiguous perfect matches, and if not found successive rounds of more elaborte partial matching will be engaged: #' In case of no perfect matches found, grep of \code{ref} on all columns of \code{mat} and/or grep of all columns of \code{mat} on \code{ref} (ie 'reverse grep') will be applied (finally a 'two way grep' approach). #' Until a perfect match is found each element of \code{ref} will be tested on \code{mat} and inversely (for each column) each element of \code{mat} will be tested on \code{ref}. #' The approach with the best number of (unique) matches will be chosen. In case of one-to-many matches, it will be tried to use most complete lines (see also last example). #' #' @param mat (matrix, data.frame) main input of which rows should get re-ordered according to a (character) reference vector \code{ref} #' @param ref (character) reference imposing new order #' @param addRef (logical) add \code{ref} to output as new column #' @param listReturn (logical) allows retrieving more information in form of list #' @param silent (logical) suppress messages #' @param debug (logical) display additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns, depending on \code{listReturn}, either the input-matrix in new order or a list with $mat (the input matrix in new order), $grep (matched matrix) and $col indicating the colum of \code{mat} finally used #' @seealso for basic ordering see \code{\link[base]{match}}; \code{\link{checkGrpOrder}} for testing each line for expected order, \code{\link{checkStrictOrder}} to check for strict (ascending or descending) order #' @examples #' 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))) #' #' @export orderMatrToRef <- function(mat, ref, addRef=TRUE, listReturn=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL) { ## order lines of matrix \code{mat} according to (character) vector \code{ref} ## in case of no perfect matches, grep of \code{ref} on all columns of \code{mat} and/or grep of all columns of \code{mat} on \code{ref} (ie 'reverse grep') will be applied ## find best column for matching mat (matrix) to ref (char vector) via two way grep ## return list $grep (matched matrix), $col best colum ## idea : also use trimRedundText() ? fxNa <- .composeCallName(callFrom, newNa="orderMatrToRef") # was '.compToRef' if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE out <- NULL # initialize ## check for simple solution ch1 <- colSums(matrix(mat %in% ref, ncol=ncol(mat)))==nrow(mat) if(any(ch1)) { out <- list(by="match", colNo=which(ch1), le=rep(1,nrow(mat)), ord=match(ref, mat[,which(ch1)])) out$mat <- mat[out$ord,] } else { ## need to use grep .. leM <- apply(nchar(as.matrix(mat)), 2, stats::median, na.rm=TRUE) # median number of characters per col (mat) leR <- stats::median(nchar(ref), na.rm=TRUE) # median number of characters (ref) ## grep ref in each col of mat gM <- apply(as.matrix(mat), 2, function(x) sapply(ref, grep, x)) # grep each col of mat in ref lM <- sapply(gM, sapply, length) # matrix of counts ## 'reverse' grep in each col of mat in ref gR <- apply(as.matrix(mat), 2, sapply, grep, ref) lR <- if(is.list(gR)) { if(is.list(gR[[1]])) sapply(gR, sapply, length) else sapply(gR, length) } else sapply(gR, length) #if(is.list(lR)) lT <- sapply(gR, sapply, length) else if(length(dim(lR)) <2) lR <- matrix(lR, nrow=1,dimnames=list(NULL, names(lR))) if(is.list(lR)) warning(fxNa, " Trouble ahead, can't make matrix/vector of counts from grep in each col of mat in ref") if(debug) {message(fxNa,"..cTR1"); cTR1 <- list(mat=mat,ref=ref,leM=leM,leR=leR,gM=gM,lM=lM,gR=gR,lR=lR)} ## if(any(lM >0, lR >0)) { # some (perfect or partial) solutions chM1 <- apply(lM, 2, function(x) all(x==1)) chR1 <- apply(lR, 2, function(x) all(x==1)) if(sum(chM1, chR1) >0) { # ideal solution exists (direct matching) if(any(chM1)) { out <- list(by="mat", colNo=which(chM1), le=if(length(dim(lM)) >1) lM[,which(chM1)] else lM[which(chM1)], ord=gM[[which(chM1)]])} else { out <- list(by="ref", colNo=which(chR1), le=if(length(dim(lR)) >1) lR[,which(chR1)] else lR[which(chR1)], ord=gR[[which(chR1)]]) } } else { # less ideal (multiple hits and/or empty) chM1 <- colSums(lM >0) chR1 <- colSums(lR >0) if(any(chM1==nrow(mat), chR1==nrow(mat))) { # multiple hits, no empty, need further refinement if(any(chM1==nrow(mat))) { out <- list(by="ref", colNo=which(chM1==nrow(mat))[1], # solution in M le=if(length(dim(lM)) >1) lM[,which(chM1==nrow(mat))[1]] else lM[which(chM1==nrow(mat))[1]], ord=gM[[which(chM1==nrow(mat))[1]]]) } else if(any(chR1==nrow(mat))) { out <- list(by="mat", colNo=which(chR1==nrow(mat))[1], le=if(length(dim(lR)) >1) lR[,which(chR1==nrow(mat))[1]] else lR[which(chR1==nrow(mat))[1]], ord=gR[[which(chR1==nrow(mat))[1]]])} ## resolve multiple hits in $ord by picking 1st not yet used newGr <- sapply(out$ord, function(x) x[1]) # simply 1st of multiple ## try using other instances of repeated : other cols of mat may contain other information multX <- unique(names(newGr[which(sapply(out$ord, length) >1)])) # names of all multi-hit for(i in 1:length(multX)) newGr[which(names(newGr)==multX[i])] <- out$ord[[multX[i]]] out$ord <- newGr if(debug) message(fxNa," newGr ",pasteC(newGr)) } else {warning(fxNa,"Impossible to find complete solution, returning NULL")} } if(debug) { message(fxNa,"..cTR2"); cTR2 <- list(mat=mat,ref=ref,leM=leM,leR=leR,gM=gM,lM=lM,gR=gR,lR=lR,out=out)} } else warning(fxNa,"Impossible to find any matches, returning NULL") if(length(out) >0) { if(out$by=="mat") out$ord <- order(out$ord) out$mat <- mat[out$ord,] if(!isFALSE(addRef)) out$mat <- if("ref" %in% colnames(out$mat)) cbind(out$mat, ref) else cbind(out$mat, ref=ref) if(isFALSE(listReturn) & length(out) >0) out <- out$mat } } out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/orderMatrToRef.R
#' (re)organize data of (3-dim) array as list of replicates #' #' Organize array of all data ('arrIn', long table) into list of (replicate-)arrays (of similar type/layout) based on dimension number 'byDim' of 'arrIn' (eg 2nd or 3rd dim). #' Argument \code{inspNChar} defines the number of characters to consider, so if the beginning of names is the same they will be separated as list of multiple arrays. #' Default will search for '_' separator or trim from end if not found in the relevant dimnames #' @param arrIn (array) main input #' @param inspNChar (interger) if inspNChar=0 the array-names (2nd dim of 'arrIn') will be cut before last '_' #' @param byDim (integer, length=1) dimension number along which data will be split in separate elements (considering the first inspNChar characters) #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a list of arrays (typically 1st and 2nd dim for specific genes/objects, 3rd for different measures associated with) #' @seealso \code{\link[base]{array}} #' @examples #' arr1 <- array(1:24,dim=c(4,3,2),dimnames=list(c(LETTERS[1:4]), #' paste("col",1:3,sep=""), c("ch1","ch2"))) #' organizeAsListOfRepl(arr1) #' @export organizeAsListOfRepl <- function(arrIn, inspNChar=0, byDim=3, silent=TRUE,debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="organizeAsListOfRepl") if(length(dim(arrIn)) !=3) stop(fxNa,"Expecting data organized as 3 dims, where last dimension should represent different plates") msg <- "Expecting 2nd dim to have names where characters 1 to 6 describe the plate-type- to identify replicates" if(sum(nchar(dimnames(arrIn)[[byDim]]) <1) >1) stop(fxNa,msg) msg <- "Expecting 'byDim' to be single integer between 1 an 3" if(!is.numeric(byDim)) stop(msg) else byDim <- as.integer(byDim)[1] if(byDim <1 || byDim >3) stop(msg) if(length(inspNChar) != ncol(arrIn)) inspNChar <- rep(inspNChar,3)[1:ncol(arrIn)] chNch <- inspNChar <1 if(any(chNch)) inspNChar[which(chNch)] <- as.integer(gregexpr("_",dimnames(arrIn)[[byDim]][which(chNch)])) -1 chNch <- inspNChar <0 if(any(inspNChar <1)) inspNChar[which(chNch)] <- nchar(.trimFromEnd(dimnames(arrIn)[[byDim]])[which(chNch)]) if(!silent) message(fxNa," inspect ",inspNChar," characters of ",pasteC(dimnames(arrIn)[[byDim]])) plateTy <- substr(dimnames(arrIn)[[byDim]],1,inspNChar) if(length(unique(plateTy)) ==dim(arrIn)[byDim]) message(fxNa," names of rd dim of 'arrIn' seem all different") replPlaArr <- list() if(!silent) message(fxNa," inspect the following ",length(unique(plateTy))," plate-types : ", paste(utils::head(unique(plateTy),n=20),collapse=" "),if(length(plateTy) >20) " ...") uniPlaTy <- unique(plateTy) if(length(uniPlaTy) >0) for(i in 1:length(uniPlaTy)) { replPlaArr[[i]] <- array(as.numeric(arrIn[,which(plateTy==uniPlaTy[i]),]), dim=c(dim(arrIn)[1],sum(plateTy %in% uniPlaTy[i],na.rm=TRUE),dim(arrIn)[3])) dimnames(replPlaArr[[i]]) <- list(dimnames(arrIn)[[1]],dimnames(arrIn)[[byDim]][which(plateTy==uniPlaTy[i])],dimnames(arrIn)[[3]]) } names(replPlaArr) <- uniPlaTy replPlaArr } #' fuse 2 instances of 3dim arr as mult cols in 3dim array #' #' This function allows fusing 2 instances of 3dim arr as mult cols in 3dim array (ie fuse along 2nd dim, increase cols) #' #' @param arr1 (array) #' @param arr2 (array) #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This functuin returns a numeric vector with numer of non-numeric characters (ie not '.' or 0-9)) #' @seealso \code{\link[base]{array}} #' @examples #' aa <- 11:15 #' @export .fuse2ArrBy2ndDim <- function(arr1,arr2,silent=FALSE, debug=FALSE, callFrom=NULL){ ## fuse 2 instances of 3dim arr as mult cols in 3dim array (ie fuse along 2nd dim, increase cols) fxNa <- .composeCallName(callFrom,newNa=".fuse2ArrBy2ndDim") msg <- "Problem with input : needs to have same number of rows and levels of 3rd dim" if(!identical(dim(arr1)[c(1,3)], dim(arr2)[c(1,3)])) stop(fxNa,msg) array(rbind(matrix(as.numeric(arr1), ncol=dim(arr1)[3]), matrix(as.numeric(arr2),ncol=dim(arr2)[3])), dim=c(dim(arr1)[1], dim(arr1)[2] +dim(arr2)[2], dim(arr1)[3])) }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/organizeAsListOfRepl.R
#' Convert p-values to lfdr #' #' This function takes a numeric vector of p-values and returns a vector of lfdr-values (local false discovery) using #' the package \href{https://CRAN.R-project.org/package=fdrtool}{fdrtool}. #' Multiple testing correction should be performed with caution, short series of p-values typically pose problems for transforming to lfdr. #' The transformation to lfdr values may give warning messages, in this case the resultant lfdr values may be invalid ! #' @param x (numeric) vector of p.values #' @param silent (logical) suppres messages #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a (numeric) vector of lfdr values (or \code{NULL} if data insufficient to run the function 'fdrtool') #' @seealso lfdr from \code{\link[fdrtool]{fdrtool}}, other p-adjustments (multiple test correction, eg FDR) in \code{\link[stats]{p.adjust}} #' @examples #' ## Note that this example is too small for estimating really meaningful fdr values #' ## In consequence, a warning will be issued. #' 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))) #' @export pVal2lfdr <- function(x, silent=TRUE, callFrom=NULL) { ## take vector of p-values and return vector of lfdr-values fxNa <- .composeCallName(callFrom, newNa="pVal2lfdr") if(!isTRUE(silent)) silent <- FALSE if(!requireNamespace("fdrtool", quietly = TRUE)) { warning("package 'fdrtool' not found ! Please install from CRAN ... (returning NULL)") return(NULL) } else { if(sum(is.na(x)) >0 & !silent) message(fxNa," omitting ",sum(is.na(x))," NAs !") z <- as.numeric(naOmit(x)) z <- try(fdrtool::fdrtool(z, statistic="pvalue", plot=FALSE, verbose=!silent)$lfdr, silent=TRUE) if(inherits(z, "try-error")) { message(fxNa," FAILED to calulate lfdr ! Check how to use package 'fdrtool' (data too small ?)") return(NULL) } else { z <- as.numeric(z) lfdr <- rep(NA, length(x)) lfdr[!is.na(x)] <- z # for returning NA at place of initial NAs if(!is.null(names(x))) names(lfdr) <- names(x) lfdr }}}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/pVal2lfdr.R
#' Simple Package Download Statistics from CRAN #' #' This function allows accessing the most recent counts of package downloads availabale on http://www.datasciencemeta.com/rpackages, #' obtaining rank quantiles and to compare (multiple) given packages to the bulk data, optionally a plot can be drawn. #' #' @details #' Detailed articles on this subject have been published on R-Hub (https://blog.r-hub.io/2020/05/11/packagerank-intro/) and on #' R-bloggers (https://www.r-bloggers.com/2020/10/a-cran-downloads-experiment/). #' The task of checking the number of downloads for a given package has also been addressed by several other packages (eg dlstats, cranlogs, adjustedcranlogs). #' #' This function only allows accessing counts as listed on the website of \code{www.datasciencemeta.com} which get updated dayly. #' Please note, that reading all lines from the website may take a few seconds !! #' To get a better understanding of the counts read, reference quantiles for download-counts get added by default (see argument \code{refQuant}). #' The (optional) figure can be drawn in linear scale (default, with minor zoom to lower number of counts) or in log (necessary for proper display of the entire range of counts), by setting the argument \code{log="y"}. #' #' The number of downloads counted by RStudio may not be a perfect measure for the actual usage/popularity of a given package, #' the articles cited above discuss this in more detail. #' For example, multiple downloads from the same IP or subsequent downloads of multiple (older) versions of the same package seem to get counted, too. #' #' @param queryPackages (character or integer) package names of interest, if \code{integer}, n random packages will be picked by random #' @param countUrl (character) the url where the dayly counts ara available #' @param refQuant (numeric) add reference quantile values to output matrix #' @param figure (logical) decide of figure should be printed #' @param log (character) set count-axis of figure to linear or log-scale (by setting \code{log="y"}) #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of messages produced #' @param debug (logical) additional messages for debugging #' @return This function retuns a matrix with download counts (or \code{NULL} if the web-site can't be accessed or the query-packages are not found there) #' @seealso packages \href{https://CRAN.R-project.org/package=cranlogs}{cranlogs} and \href{https://CRAN.R-project.org/package=packageRank}{packageRank} #' @examples #' ## Let's try a microscopic test-file (NOT representative for true up to date counts !!) #' pack1 <- c("cif", "bcv", "FinCovRegularization", "wrMisc", "wrProteo") #' testFi <- file.path(system.file("extdata", package="wrMisc"), "rpackagesMicro.html") #' packageDownloadStat(pack1, countUrl=testFi, log="y", figure=FALSE) #' ## For real online counting simply drop the argument countUrl #' #' @export packageDownloadStat <- function(queryPackages=c("wrMisc","wrProteo","cif","bcv","FinCovRegularization"), countUrl="http://www.datasciencemeta.com/rpackages", refQuant=(1:10)/10, figure=TRUE, log="", silent=FALSE, callFrom=NULL, debug=FALSE) { ## get rank & downloads for all 10% tiles as well as queryPackages ## return matrix with 1st line as rank and 2nd as n.dowloads, if inclQuant=TRUE 12th col - end for queryPackages fxNa <- .composeCallName(callFrom, newNa="packageDownloadStat") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE inclQuant <- length(refQuant) >0 chPa <- length(naOmit(queryPackages)) >0 && all(is.character(queryPackages) | is.numeric(queryPackages)) datOK <- FALSE txt <- paNa <- paRa <- nDownl <- NULL # intialize (just in case) if(chPa) { if(length(countUrl) <1) countUrl <- "http://www.datasciencemeta.com/rpackages" txt <- try(readLines(countUrl, warn=FALSE), silent=TRUE) if(inherits(txt, "try-error") || length(txt) <2) { Sys.sleep(30) message(fxNa,"First attempt reading data failed, try again after 30 sec ..") txt <- try(readLines(countUrl, warn=FALSE), silent=TRUE) if(inherits(txt, "try-error") || length(txt) <2) { txt <- try(readLines(countUrl, warn=FALSE, n=9000), silent=TRUE) if(!inherits(txt, "try-error")) { message(fxNa," Failed to read entire data-set, but succeeded to read first 9000 lines. Your package(s) of interest may not be included in this list") } } } datOK <- !inherits(txt, "try-error") && length(txt) >1 ## start exploiting if(datOK) { ## check argument refQuant if(any(length(refQuant) < 1, identical(refQuant,NA), isFALSE(refQuant))) {refQuant <- 1; inclQuant <- FALSE} # minimal setting if(inclQuant && length(txt) <900) { inclQuant <- FALSE if(!silent) message(fxNa,"Too few data for adding reference centile values/packages") } if(!is.numeric(refQuant)) refQuant <- (1:10)/10 chNa <- is.na(refQuant) if(any(chNa)) { if(all(chNa)) { refQuant <- (1:10)/10 } else { refQuant <- refQuant[which(!chNa)] if(!silent) message(fxNa,"Removing ",sum(refQuant)," invalid reference quantile entries (must be 0 > x >= 1)") } } if(debug) {message("pds1"); pds1 <- list(txt=txt,queryPackages=queryPackages,chPa=chPa,chNa=chNa)} ## start parsing page iniIn <- grep("<tbody>", txt)[1] +1 # position 54 +1 endIn <- grep("</tbody>", txt)[1] -1 # position 143044 -1 datOK <- length(iniIn)==1 && length(endIn)==1 if(datOK) datOK <- (endIn -iniIn+1) %% 7 == 0 && all(grepl("<td>[[:digit:]]+</td>", txt[iniIn +1 +c(0,7)])) && all(grepl("<td>[0-9,]+</td>", txt[iniIn +3 +c(0,7)])) # check if series of 7 and if 1st & 2nd line line contain rank as 1st, counts as 3rd } else datOK <- FALSE if(datOK) { tab <- matrix(txt[iniIn:endIn], byrow=TRUE, ncol=7)[,c(2:4)] paNa <- sub("[[:print:]]+https://cran.r-project.org/web/packages/", "", sub("/index.html.+", "", tab[,2])) nDownl <- try(as.integer(gsub(",", "", sub(" +<td>", "", sub("</td> *", "", tab[,3])))), silent=TRUE) paRa <- try(as.integer(sub(" +<td>", "", sub("</td> *", "", tab[,1]))), silent=TRUE) if(any(sapply(list(nDownl,paRa), inherits, "try-error"), length(paNa) !=length(nDownl))) datOK <- FALSE } else if(!silent) message(fxNa,"Unable to read data (format of data not recognized or maybe the server is not responding)") } else if(!silent) message(fxNa,"Invalid 'queryPackages'") if(any(c(length(txt), length(paNa), length(paRa)) <1)) datOK <- FALSE if(datOK) { ## assemble; verify 'queryPackages' ta2 <- data.frame(name=paNa, rank=paRa, downloads=nDownl) ta2[order(ta2$rank),] # order (just in case) if(debug) {message("pds2"); pds2 <- list(txt=txt,ta2=ta2,tab=tab,queryPackages=queryPackages,chPa=chPa,chNa=chNa,iniIn=iniIn,endIn=endIn, paNa=paNa, nDownl=nDownl,paRa=paRa,datOK=datOK)} if(is.numeric(queryPackages)) queryPackages <- paNa[sample(1:nrow(tab), as.integer(abs(queryPackages[1])), replace=FALSE)] # random pick if numeric ## search query chPa <- match(queryPackages, ta2$name) if(any(is.na(chPa))) { if(all(is.na(chPa))) { warning(fxNa,"NONE of queryPackages found; returning NULL"); datOK <- FALSE } else { queryPackages <- naOmit(queryPackages) ta2 <- data.frame(name=paNa, rank=paRa, downloads=nDownl) # update ta2[order(ta2$rank),] # update order (just in case) } } if(debug) {message("pds3"); pds3 <- list()} } else if(!silent) message(fxNa,"Unable to understand information from '",countUrl,"'") if(datOK) { ## add centile (& plot graph) maxPa <- max(ta2$rank, na.rm=TRUE) out <- ta2[chPa,] out$centile <- round(100*out$rank/maxPa,1) if(debug) {message("pds4"); pds4 <- list(out=out,txt=txt,tab=tab,ta2=ta2,queryPackages=queryPackages,maxPa=maxPa,chPa=chPa)} if(isTRUE(figure)){ if(!identical(log,"y")) log <- "" yMa <- min(ta2$downloads[round(nrow(ta2)*0.05)], ta2$downloads[1]*0.15) suppressWarnings(graphics::plot(downloads ~rank, ta2, las=2, ylim=if(identical(log,"y")) c(100,nDownl[1]) else c(1,yMa), type="l", cex.axis=0.8, xaxs="i", yaxs="i", xlab="Rank",ylab="Number of Downloads", main="CRAN Packages Downloads", log=log)) graphics::abline(v=pretty(c(rep(100,5), maxPa)), col="grey75", lty=2) graphics::abline(h=if(identical(log,"y")) 10^(1:7) else 1:5*20000, col="grey75", lty=2) if(FALSE) graphics::points(ta2$rank[chPa], ta2$downloads[chPa], col=2) arrBo <- if(identical(log, "y")) 1.04 *ta2$downloads[chPa] else yMa/150 +1.03* ta2$downloads[chPa] arrUp <- if(identical(log, "y")) 2.2* ta2$downloads[chPa] else arrBo +yMa/18 graphics::arrows(x0=ta2$rank[chPa], y0=arrUp, x1=ta2$rank[chPa], y1=arrBo, col=2, length=0.11, lwd=1.8) # ok graphics::text(ta2$rank[chPa], arrUp*1.03, labels=ta2$name[chPa], col=2,las=1,cex=1,srt=90,adj=0) date1 <- sub(" .+","",sub(".+Last updated: ","",txt[grep("Last updated",txt)])) if(grepl("https://",countUrl)) graphics::mtext(paste("as of ",date1," "), cex=0.9, adj=1) } if(debug) {message("pds5"); pds5 <- list(out=out,txt=txt,tab=tab,ta2=ta2,queryPackages=queryPackages,chPa=chPa,chNa=chNa,iniIn=iniIn,endIn=endIn, paNa=paNa, nDownl=nDownl,paRa=paRa,datOK=datOK)} if(inclQuant) { ## add quantile (reference-)values if(nrow(ta2) <1000) warning(fxNa,"Too few data ! Very imprecise estimation of reference centile ...") refQuan2 <- round(maxPa * refQuant) refInd <- round(nrow(ta2) *refQuant) supl <- ta2$downloads[refInd] names(supl) <- paste0("cent_",100*round(refQuant,3)) out <- rbind(out, data.frame(name=ta2$name[refInd], rank=ta2$rank[refInd], downloads=supl, centile=100*round(refQuant,3))) out <- out[order(out$rank, decreasing=FALSE),] } out } }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/packageDownloadStat.R
#' Convert Pairs of Node-Names to Non-Oriented Propensity Matrix #' #' @description #' Numerous network query tools produce a listing of pairs of nodes (with one pair of nodes per line). #' Using this function such a \code{matrix} (or \code{data.frame}) can be combined to this more comprehensive view as propensity-matrix. #' #' @details #' Note, this has been primarily developed for undirected interaction networks, the resulting propensity-matrix does not show any orientation any more. #' In a number of applications (eg in protein-protein interaction networks, PPI) the resulting matrix may be rather sparse. #' #' @param mat (matrix) main input, matrix of interaction partners with each line as a separate pair of nodes; #' the first two columns should contain identifiers of the nodes #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns matrix or data.frame #' @seealso uses typically input from \code{\link{filterNetw}} #' @examples #' pairs3L <- matrix(LETTERS[c(1,3,3, 2,2,1)], ncol=2) # loop of 3 #' (netw13pr <- pairsAsPropensMatr(pairs3L)) # as prop matr #' #' @export pairsAsPropensMatr <- function(mat, silent=FALSE, debug=FALSE, callFrom=NULL) { ## convert pairs of node-names (non-oriented) to propensity matrix ## sparse matrix solution fxNa <- .composeCallName(callFrom, newNa="pairsAsPropensMatr") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(!is.matrix(mat)) mat <- try(as.matrix(mat), silent=TRUE) msg <- " 'mat'; must be matrix or data.frame with min 1 line and 2 col" if(inherits(mat, "try-error")) stop("Invalid input in",msg) if(any(length(dim(mat)) !=2, dim(mat) < 1:2)) stop("Invalid argument",msg) nodeNa <- sort(unique(as.character(mat[,1:2]))) nodeIM <- matrix(match(as.character(mat[,1:2]), nodeNa), ncol=2) # as matrix di <- matrix(0, nrow=length(nodeNa), ncol=length(nodeNa)) for(i in 1:ncol(di)) { j <- which(nodeIM[,1]==i) if(length(j) >0) { di[i,nodeIM[j,2]] <- di[i,nodeIM[j,2]] +1 di[nodeIM[j,2],i] <- di[nodeIM[j,2],i] +1 } } dimnames(di) <- list(seq(nrow(di)), seq(nrow(di))) di }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/pairsAsPropensMatr.R
#' Partial unlist of lists of lists #' #' \code{partUnlist} does partial unlist for treating list of lists : New (returned) list has one level less of hierarchy #' (Highest level list will be appended). In case of conflicting (non-null) listnames a prefix will be added. #' Behaviour different to \code{\link[base]{unlist}} when unlisting list of matrixes. #' @param lst (list) main input, list to be partially unlisted #' @param sep (character, length=1) separator for names #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a list with partially reduced nested structure #' @seealso \code{\link[base]{unlist}}, \code{\link{asSepList}} #' @examples #' partUnlist(list(list(a=11:12,b=21:24), list(c=101:101,d=201:204))) #' li4 <- list(c=1:3, M2=matrix(1:4,ncol=2), L3=list(L1=11:12, M3=matrix(21:26,ncol=2))) #' partUnlist(li4) #' unlist(li4, rec=FALSE) #' @export partUnlist <- function(lst, sep="_", silent=FALSE, debug=FALSE, callFrom=NULL) { fxNa <- .composeCallName(callFrom, newNa="partUnlist") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE notL <- !sapply(lst, inherits, "list") if(debug) message(fxNa," pU1") if(all(notL)) { if(!silent) message(fxNa,"Input is not list of lists, nothing to do") return(lst) } else { ## lst is list of list(s) out <- if(any(notL)) lst[which(notL)] else list() # the non-list elements for(i in which(!notL)) { iniLe <- length(out) newNa <- names(lst[[i]]) if(any(nchar(newNa) >0)) { newNa <- if(any(newNa %in% names(out))) paste(names(lst)[i], newNa, sep=sep) else newNa} out[length(out) +1:length(lst[[i]])] <- lst[[i]] if(any(nchar(newNa) >0)) names(out)[iniLe + 1:length(lst[[i]])] <- newNa } out }}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/partUnlist.R
#' Partial distance matrix (focus on closest) #' #' \code{partialDist} calculates distance matrix like \code{dist} for 1- or 2-dim data, but only partially, ie only cases of small distances. #' This function was made for treating very large data-sets where only very close distances to a given point need to be found, #' it allows to overcome memory-problems with larger data (and faster execution with > 50 rows of 'dat'). #' #' @param dat (matrix of numeric values) main input #' @param groups (factor) to split using \code{cut} or specific custom grouping (length of dat) #' @param overLap (logical) if TRUE make groups overlapping by 1 value (ie maintain some context-information) #' @param method 'character' name of method passed to \code{dist} #' @param silent (logical) suppress messages #' @param debug (logical) display additional messages for debugging #' @param callFrom (character) allow easier tracking of message(s) produced #' @return This function returns a matrix with partial distances (not of class 'dist' object) #' @seealso \code{\link[stats]{dist}} #' @examples #' set.seed(2016); mat3 <- matrix(runif(300),nr=30) #' round(dist(mat3), 1) #' round(partialDist(mat3, gr=3), 1) #' @export partialDist <- function(dat, groups, overLap=TRUE, method="euclidean", silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom,newNa="partialDist") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE dim1 <- length(dim(dat)) <2 msg <- "names of 'dat' must be unique !" if(dim1) { if(is.null(names(dat))) names(dat) <- 1:length(dat) if(length(unique(names(dat))) < length(dat)) stop(msg) dis <- matrix(nrow=length(dat),ncol=length(dat)) # prepare for output } else { if(is.null(rownames(dat))) rownames(dat) <- paste("li",1:nrow(dat),sep="") if(length(unique(rownames(dat))) < nrow(dat)) stop(" row",msg) dis <- matrix(nrow=nrow(dat),ncol=nrow(dat)) # prepare for output } if(debug) {message(fxNa," length(groups) ",length(groups), " pD1")} if(length(groups)==1 && is.numeric(groups)) { if(dim1) { dat <- sort(dat) daCu <- cut(dat,groups) } else { # (2dim) sorting too complicated ? tmp <- apply(dat, 2, function(x) as.numeric(cut(x, groups))) daCu <- factor(paste(tmp[,1],tmp[,2],sep="_")) } } else daCu <- groups ## check for orphan-groups & fuse if(any(table(daCu) <2) && !overLap) message(fxNa,sum(table(daCu) <2)," orphan groups (n=1) in grouping ! (overLap=TRUE suggested)") dimnames(dis) <- if(dim1) list(names(dat), names(dat)) else list(rownames(dat),rownames(dat)) datL <- list() if(debug) {message(fxNa," pD2")} if(overLap) { for(i in 1:length(unique(daCu))) { tmp <- which(daCu==levels(daCu)[i]) tmp <- sort(c(tmp, range(tmp) +c(-1,1))) if(tmp[1] <1) tmp <- tmp[-1] if(max(tmp) > nrow(dis)) tmp <- tmp[which(tmp <= nrow(dis))] datL[[i]] <- if(dim1) dat[tmp] else dat[tmp,] } ## could check if some groups are now all redundant -> adjust datL & useNo } else { if(dim1) datL <- split(dat, daCu) else { useSep <- "_" # make sure this sep doesn't appear in rownames ! !! tmp <- apply(dat, 1, paste, collapse=useSep) names(tmp) <- rownames(dat) datL <- split(tmp, daCu) datL <- lapply(datL, function(x) { y <- matrix(as.numeric(unlist(strsplit(x,useSep))), ncol=ncol(dat)) rownames(y) <- names(x); y}) } } if(debug) {message(fxNa," pD3")} for(i in 1:length(datL)) { useLi <- if(dim1) match(names(datL[[i]]), names(dat)) else match(rownames(datL[[i]]), rownames(dat)) dis[useLi,useLi] <- as.matrix(stats::dist(datL[[i]], method=method)) } dis } #' Raise all values close to lowest value #' #' This function aims to raise all values close to lowest value to end up as at value of 'raiseTo'. #' This is done independently for each col of mat. #' This function sets all data to common raiseTo (which is min among all cols) #' @param mat (matrix of numeric values) main input #' @param raiseTo (numeric) #' @param minFa (numeric) minimum factor #' @param silent (logical) suppress messages #' @param debug (logical) display additional messages for debugging #' @param callFrom (character) allow easier tracking of message(s) produced #' @return This function returns a numeric vector with numer of non-numeric characters (ie not '.' or 0-9)) #' @seealso \code{\link[base]{nchar}} #' @examples #' aa <- 11:15 #' @export .raiseColLowest <- function(mat, raiseTo=NULL, minFa=0.1, silent=FALSE, debug=FALSE, callFrom=NULL){ ## independently for each col of mat : raise all values close to lowest value to end up as at value of 'raiseTo' ## select all values within range of 'minFa' to determined min (eg 0.1 select until min+10%ofMin) ## this version sets all data to common raiseTo (which is min among all cols) fxNa <- .composeCallName(callFrom, newNa=".raiseColLowest") colMin <- apply(as.matrix(mat), 2, min, na.rm=TRUE) if(is.null(raiseTo)) { raiseTo <- apply(mat, 2, function(x) { y <- sort(unique(signif(x,3))) y[which(y > min(y, na.rm=TRUE) +0.1* abs(min(y, na.rm=TRUE))) [1]] }) raiseTo <- min(raiseTo, na.rm=TRUE) if(!silent) message(fxNa," 'raiseTo' was set to ",raiseTo)} if(length(raiseTo) >1) raiseTo <- min(raiseTo, na.rm=TRUE) raiseF <- matrix(rep(raiseTo -colMin, each=nrow(mat)), nrow=nrow(mat)) raiseF[mat > raiseTo + minFa*abs(raiseTo)] <- 0 out <- mat + raiseF out } #' Find overlap instances among range of values in lines #' #' This function aims to find overlap instances among range of values in lines of 'x' (typically give just min & max) #' #' #' @param x (matrix of numeric values or all-numeric data.frame) main input #' @param rmRedund (logical) report overlaps only in 1st instance (will show up twice otherwise) #' @param callFrom (character) allow easier tracking of message(s) produced #' @return This function returns a matrix with line for each overlap found, cols 'refLi' (line no), 'targLi' (line no), 'targCol' (col no) #' @seealso \code{\link[base]{nchar}} #' @examples #' aa <- 11:15 #' @export .findBorderOverlaps <- function(x, rmRedund=FALSE, callFrom=NULL){ ## find overlap instances among range of values in lines of 'x' (typically give just min & max) ## 'x' .. matrix (or all-numeric data.frame), inspect by lines for potential overlap ## 'rmRedund' .. report overlaps only in 1st instance (will show up twice otherwise) ## return matrix with line for each overlap found, cols 'refLi' (line no), 'targLi' (line no), 'targCol' (col no) fxNa <- .composeCallName(callFrom, newNa=".findBorderOverlaps") if(any(is.na(x))) { message(fxNa," NAs detected, remove all lines with NAs only") x <- x[which(rowSums(!is.na(x)) ==ncol(x)),] if(any(is.na(x))) { NaLi <- which(rowSums(is.na(x)) >0) x[NaLi,] <- apply(x[NaLi], 1, min)}} tmp <- matrix(NA, nrow=nrow(x), ncol=ncol(x)*(nrow(x)-1)) for(i in 1:nrow(x)) { # check each line of x against everything else te <- as.numeric(t(x[-i,])) tmp[i,] <- max(x[i,]) > te && te > min(x[i,]) } curLi <- 1 out <- matrix(nrow=sum(tmp), ncol=3, dimnames=list(NULL,c("refLi","targLi","targCol"))) for(i in which(rowSums(tmp) >0)) { # extract corresponding line & col info ti <- which(tmp[i,]) if(length(ti) >0) { to <- cbind(ref=rep(i,length(ti)), li=(1:nrow(x))[-i][ti %/% ncol(x)+ ti %% ncol(x)], col=ncol(x)- ti %% ncol(x)) if(rmRedund && curLi >1) {to <- to[which(!(to[,2] %in% out[,1] & to[,1] %in% out[,2])),] if(length(to) >0) { if(!is.matrix(to)) to <- matrix(to, ncol=3) out[curLi:(curLi +nrow(to)-1),] <- to } } else out[curLi:(curLi +nrow(to)-1),] <- to curLi <- curLi +length(ti) } } out <- out[which(rowSums(is.na(out)) <2),] out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/partialDist.R
#' Advanced paste-collapse #' #' This function is a variant of \code{\link[base]{paste}} for convenient use of paste-collapse and separation of last element to paste (via 'lastCol'). #' This function was mode for more human like enumeriating in output and messages. #' If multiple arguments are given without names they will all be concatenated, if they contain names lazy evaluation for names will be tried #' (with preference to longest match to argument names). #' Note that some special characters (like backslash) may need to be protetected when used with 'collapse' or 'quoteC'. #' Returns character vector of length 1 (everything pasted together) #' @param ... (character) main input to be collapsed #' @param collapse (character,length=1) element to use for collapsing #' @param lastCol (character) text to use before last item enumerated element #' @param quoteC character to use for citing with quotations (default "") #' @return This function returns a character vector of truncated versions of intpup \code{txt} #' @keywords character #' @seealso \code{\link[base]{paste}} for basic paste #' @examples #' pasteC(1:4) #' @export pasteC <- function(..., collapse=", ", lastCol=" and ", quoteC=""){ inp <- list(...) chArgNa <- c("collapse","lastCol","quoteC") chNa0 <- lapply(chArgNa, function(x) rev(substring(x, 1, 2:nchar(x)))) chNa <- lapply(chNa0, function(x) stats::na.omit(match(x, names(inp)))[1]) # find location of match to longest variant of argument name if(any(!is.na(chNa[[1]]))) {collapse <- inp[[chNa[[1]]]]; inp <- inp[-chNa[[1]]]} if(any(!is.na(chNa[[2]]))) {lastCol <- inp[[chNa[[2]]]]; inp <- inp[-chNa[[2]]]} if(any(!is.na(chNa[[3]]))) {quoteC <- inp[[chNa[[3]]]]; inp <- inp[-chNa[[3]]]} .paQ <- function(x,quo) sapply(x, function(y) paste0(quo, y, quo)) if(nchar(quoteC) >0) inp <- lapply(inp, .paQ, quoteC) if(length(unlist(inp)) >1) { out <- if(length(inp) >1) paste(unlist(inp[-length(inp)]), collapse=collapse) else NULL tmp <- inp[[length(inp)]] tmp <- list(tmp[-length(tmp)], tmp[length(tmp)]) out <- paste0(paste(c(out, tmp[[1]]), collapse=collapse), lastCol, tmp[[2]]) } else out <- as.character(unlist(inp)) out } #' Cut string to get all variants from given start with min and max length #' #' This function allows truncating character vector to all variants from given start, with min and optonal max length #' Used to evaluate argument calls without giving full length of argument #' #' @param txt (character) main input, may be length >1 #' @param startFr (interger) where to start #' @param minLe (interger) minimum length of output #' @param maxLe (interger) maximum length of output #' @param reverse (logical) return longest text-fragments at beginning of vector #' @return This function returns a character vector #' @seealso used in \code{\link{pasteC}}; \code{\link[base]{substr}} #' @examples #' .cutStr("abcdefg", minLe=2) #' @export .cutStr <- function(txt, startFr=1, minLe=1, maxLe=NULL, reverse=TRUE){ maxChar <- max(nchar(txt), na.rm=TRUE) if(length(startFr) >1) {startFr <- startFr[1]} if(startFr <1) startFr <- 1 if(length(minLe) >1) {minLe <- minLe[1]} if(length(maxLe) >0) if(any(is.na(maxLe))) maxLe <- NULL if(length(maxLe) >0) maxChar <- min(startFr +maxLe -1, maxChar) minStop <- startFr + minLe -1 out <- if(maxChar - startFr +1 >= minLe && minLe <= minStop) unique(substring(txt, startFr, rep((minStop):maxChar, each=length(txt)))) else NULL nChar <- nchar(out) >= minLe if(any(!nChar)) out <- out[which(nChar)] if(isTRUE(reverse) && length(out) >1) out <- rev(out) out } #' Cut string to get all variants from given start with min length, depreciated #' #' This function is depreciated, please use \code{/cutStr} instead ! #' This function allows truncating character vector to all variants from given start, with min and optonal max length #' Used to evaluate argument calls without giving full length of argument #' #' @param txt (character) main input, may be length >1 #' @param startFr (interger) where to start #' @param minLe (interger) minimum length of output #' @param reverse (logical) return longest text-fragments at beginning of vector #' @return This function returns a character vector #' @seealso \code{\link{pasteC}}; \code{\link[base]{substr}} #' @examples #' .seqCutStr("abcdefg", minLe=2) #' @export .seqCutStr <- function(txt, startFr=1, minLe=1, reverse=TRUE){ .Deprecated(new=".cutStr", package="wrMisc", msg="The function .seqCutStr() has been deprecated and replaced by .cutStr()") fxNa <- ".seqCutStr" maxChar <- max(nchar(txt), na.rm=TRUE) message(fxNa, "Depreciated function, please use .cutStr() instead (also from package wrMisc)") if(length(startFr) >1) {startFr <- startFr[1]} out <- unique(substring(txt, 1, rep(max(1, startFr):maxChar, each=length(txt)))) # get all variants from start of min 3 to max 6 letters (substr() will give only 1st) nChar <- nchar(out) >= minLe if(any(!nChar)) out <- out[which(nChar)] if(isTRUE(reverse) && length(out) >1) out <- rev(out) out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/pasteC.R
#' Filter lines of matrix for max number of NAs #' #' This function produces a logical matrix to be used as filter for lines of 'dat' for sufficient presence of non-\code{NA} values (ie limit number of NAs per line). #' Filter abundance/expression data for min number and/or ratio of non-\code{NA} values in at east 1 of multiple groups. #' This type of procedure is common in proteomics and tanscriptomics, where a \code{NA} can many times be assocoaued with quantitation below detetction limit. #' #' @param dat matrix or data.frame (abundance or expression-values which may contain some \code{NA}s). #' @param grp factor of min 2 levels describing which column of 'dat' belongs to which group (levels 1 & 2 will be used) #' @param maxGrpMiss (numeric) at least 1 group has not more than this number of NAs (otherwise marke line as bad) #' @param ratMaxNA (numeric) at least 1 group reaches this content of non-\code{NA} values #' @param minVal (default NULL or numeric), any value below will be treated like \code{NA} #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return logical matrix (with separate col for each pairwise combination of 'grp' levels) indicating if line of 'dat' acceptable based on \code{NA}s (and values minVal) #' @seealso \code{\link{presenceGrpFilt}}, there are also other packages totaly dedicated to filtering on CRAN and Bioconductor #' @examples #' mat <- matrix(rep(8,150), ncol=15, dimnames=list(NULL, #' paste0(rep(LETTERS[4:2],each=6),1:6)[c(1:5,7:16)])) #' mat[lower.tri(mat)] <- NA #' mat[,15] <- NA #' mat[c(2:3,9),14:15] <- NA #' mat[c(1,10),13:15] <- NA #' mat #' presenceFilt(mat ,rep(LETTERS[4:2], c(5,6,4))) #' presenceFilt(mat, rep(1:2,c(9,6))) #' #' # one more example #' 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) #' @export presenceFilt <- function(dat, grp, maxGrpMiss=1, ratMaxNA=0.8, minVal=NULL, silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="presenceFilt") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE msg <- "Expecting (2dim) numeric matrix or data.frame with >1 columns and >1 rows" if(length(dim(dat)) !=2) stop(msg) if(ncol(dat) <2) stop(msg) if(is.data.frame(dat)) dat <- as.matrix(dat) nGrp <- table(grp) nGrp <- nGrp[order(unique(grp))] if(length(nGrp) <2) stop(" too few levels (",length(nGrp),") in 'grp' !") if(length(maxGrpMiss) !=length(nGrp)) { if(length(maxGrpMiss)==1) maxGrpMiss <- rep(maxGrpMiss, length(nGrp)) else { if(length(maxGrpMiss) < nGrp) {message(fxNa,"Length of 'maxGrpMiss' too short")} else maxGrpMiss <- maxGrpMiss[1:length(nGrp)]}} ## main if(length(minVal)==1 && is.numeric(minVal)) dat[dat <minVal] <- NA nNa <- matrix(unlist(by(t(dat), grp, function(x) colSums(is.na(x)))), nrow=nrow(dat))[,order(unique(grp))] # no of NAs per group & line ch <- maxGrpMiss > round(nGrp *ratMaxNA) if(any(ch)) {maxGrpMiss[which(ch)] <- round(nGrp*ratMaxNA)[ch] if(!silent) message(fxNa," correcting 'maxGrpMiss' for group(s) ",pasteC(names(nGrp)[ch]), " due to ratMaxNA=",ratMaxNA)} sufVa <- nNa <= matrix(rep(maxGrpMiss, each=nrow(dat)), nrow=nrow(dat)) combin <- triCoord(length(nGrp)) out <- apply(combin, 1, function(x) sufVa[,x[1]] | sufVa[,x[2]]) outNa <- matrix(names(nGrp)[as.numeric(combin)], ncol=2) colnames(out) <- paste(outNa[,1], outNa[,2], sep="-") out } #' Return position of 'di' (numeric vector) which is most excentric (distant to 0), starts with NAs as most excentric #' #' This function aims to return position of 'di' (numeric vector) which is most excentric (distant to 0), starts with NAs as most excentric #' It is used for identifying/removing (potential) outliers. #' Note : this fx doesn't consider reference distrubutions, even with "perfect data" 'nMost' points will ba tagged ! #' #' #' @param di (numeric) main input #' @param nMost (integer) #' @return This function returns a integer/numeric vector (indicating index) #' @seealso use in \code{\link{presenceFilt}}; \code{\link[base]{diff}} #' @examples #' .offCenter(11:14) #' @export .offCenter <- function(di, nMost=1) { ## return position of 'di' (numeric vector) which is most excentric (distant to 0), starts with NAs as most excentric ## used for identifying/removing (potential) outliers ## note : this fx doesn't consider reference distrubutions, even with "perfect data" 'nMost' points will ba tagged ! if(length(di) <1 || length(nMost) <1) stop(" 'di' or 'nMost' seem to be missing") if(nMost <1) stop(" 'nMost' should be single numeric integer >0") out <- if(sum(is.na(di) >0)) naOmit(which(is.na(di))[1:nMost]) else NULL if(length(out) < nMost) { nMost <- nMost - length(out) out <- c(out, which(rank(-1*di, ties.method="random") <= nMost)) } out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/presenceFilt.R
#' Filter for each group of columns for sufficient data as non-NA #' #' The aim of this function is to filter for each group of columns for sufficient data as non-NA. #' #' #' @details #' This function allows to identify lines with an \code{NA}-content above the threshold \code{presThr} per group as defined by the levels of factor \code{grp}. #' With different types of projects/questions different threshold \code{presThr} levels may be useful. #' For example, if one would like to keep the degree of threshold \code{presThr}s per group rather low, one could use a value of 0.75 (ie >= 75% values non-NA. #' #' #' #' @param dat matrix or data.frame (abundance or expression-values which may contain some \code{NA}s). #' @param grp factor of min 2 levels describing which column of 'dat' belongs to which group (levels 1 & 2 will be used) #' @param presThr (numeric) min ratio of non- \code{NA} values (per group) for returning a given line & group as \code{TRUE} #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of messages produced #' @return logical matrix (with on column for each level of \code{grp}) #' @seealso \code{\link{presenceFilt}}, there are also other packages totaly dedicated to filtering on CRAN and Bioconductor #' @examples #' mat <- matrix(NA, nrow=11, ncol=6) #' mat[lower.tri(mat)] <- 1 #' mat <- cbind(mat, mat[,1:4]) #' colnames(mat) <- c(paste0("re",1:6), paste0("x",1:4)) #' mat[6:8,7:10] <- mat[1:3,7:10] # ref #' mat[9:11,1:6] <- mat[2:4,1:6] #' #' ## accept 1 NA out of 4, 2 NA out of 6 (ie certainly present) #' (filt0a <- presenceGrpFilt(mat, rep(1:2, c(6,4)), pres=0.66)) #' ## accept 2 NA out of 4, 2 NA out of 6 (ie min 50% present) #' (filt0b <- presenceGrpFilt(mat, rep(1:2, c(6,4)), pres=0.5)) #' ## accept 3 NA out of 4, 4 NA out of 6 (ie possibly present) #' (filt0c <- presenceGrpFilt(mat, rep(1:2, c(6,4)), pres=0.19)) #' #' @export presenceGrpFilt <- function(dat, grp, presThr=0.75, silent=FALSE, callFrom=NULL) { ## dat(matrix or data.frame) ## filter for each group of columns for sufficient data as non-NA fxNa <- .composeCallName(callFrom, newNa="presenceGrpFilt") if(length(grp) != ncol(dat)) stop("Number of columns of 'dat' (",ncol(dat),") does NOT match length of 'grp' (",length(grp),") !") if(presThr >1) { presThr <- 1; if(!silent) message(fxNa, "Argument 'presThr' may not be higher tan 1 (ie 100%), correcting")} ## construct unique group-names to use chDu <- duplicated(grp, fromLast=FALSE) grpU <- if(any(chDu)) as.character(grp)[which(!chDu)] else as.character(grp) ## main filter out <- matrix(nrow=nrow(dat), ncol=length(grpU), dimnames=list(rownames(dat), grpU)) for(i in 1:length(grpU)) { useCol <- which(grp ==grpU[i]) out[,i] <- if(length(useCol) >0) {if(length(useCol) ==1) !is.na(dat[,useCol]) else rowSums(!is.na(dat[,useCol]))/length(useCol) >= presThr} else FALSE } out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/presenceGrpFilt.R
#' Protect Special Characters #' #' Some characters do have a special meaning when used with regular expressions. #' This concerns characters like a point, parinthesis, backslash etc. #' Thus, when using \code{grep} or any related command, shuch special characters must get protected in order to get considered as they are. #' #' #' #' #' #' @param x character vector to be prepared for use in regular expressions #' @param prot (character) collection of characters that need to be protected #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a modified character vector #' @examples #' aa <- c("abc","abcde","ab.c","ab.c.e","ab*c","ab\\d") #' grepl("b.", aa) # all TRUE #' grepl("b\\.", aa) # manual prootection #' grepl(protectSpecChar("b."), aa) #' @export protectSpecChar <- function(x, prot=c(".","\\","|","(",")","[","{","^","$","*","+","?"), silent=TRUE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="protectSpecChar") if(!isTRUE(silent)) silent <- FALSE chSp <- matrix(sapply(prot, function(x) grepl(paste0("\\",x),x)), ncol=length(prot)) ## special treatment for '\\' if("\\" %in% prot & any(grepl("\\\\",x))) {x <- gsub("\\\\","\\\\\\\\",x); prot <- prot[-which(prot %in% "\\")]} ## main protecting of sec chars if(any(chSp)) { z <- if(length(x) >1) which(colSums(chSp) >0) else which(chSp) for(i in z) { if(!silent) message(fxNa," i=",i," at ",pasteC(which(chSp[,i]))," to ",pasteC(x[which(chSp[,i])]) ) x[which(chSp[,i])] <- gsub(paste0("\\",prot[i]), paste0("\\\\",prot[i]), x[which(chSp[,i])]) } } x }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/protectSpecChar.R
#' Distance of categorical data (Jaccard, Rand and adjusted Rand index) #' #' \code{randIndFx} calculates distance of categorical data (as Rand Index, Adjusted Rand Index or Jaccard Index). #' Note: uses/requires package \href{https://CRAN.R-project.org/package=flexclust}{flexclust} #' Methods so far available (via flexclust): "ARI" .. adjusted Rand Index, "RI" .. Rand index, "J" .. Jaccard, "FM" .. Fowlkes-Mallows. #' @param ma (matrix) main input for distance calulation #' @param method (character) name of distance method (eg "ARI","RI","J","FM") #' @param adjSense (logical) allows introducing correlation/anticorrelation (interprete neg distance results as anti) #' @param silent (logical) suppres messages #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a distance matrix #' @seealso \code{comPart} in \code{\link[flexclust]{randIndex}} #' @examples #' set.seed(2016); tab2 <- matrix(sample(1:2, size=42, replace=TRUE), ncol=7) #' if(requireNamespace("flexclust")) { flexclust::comPart(tab2[1,], tab2[2,]) #' flexclust::comPart(tab2[1,], tab2[3,]) #' flexclust::comPart(tab2[1,], tab2[4,]) } #' ## via randIndFx(): #' randIndFx(tab2, adjSense=FALSE) #' cor(t(tab2)) #' randIndFx(tab2, adjSense=TRUE) #' @export randIndFx <- function(ma, method="ARI", adjSense=TRUE, silent=FALSE, callFrom=NULL){ ## calculate distance for categorical data (using Rand Index, Adjusted Rand Index or Jaccard Index) ## method : "ARI" .. adjusted Rand Index, "RI" .. Rand index, "J" .. Jaccard, "FM" .. Fowlkes-Mallows ## 'adjSense' allows introducing corretaltion/anticorrelation (interprete neg distance results as anti) ## uses package flexclust ## wr 29jan15, cor 23mar16 ## require(flexclust) fxNa <- .composeCallName(callFrom, newNa="randIndFx") if(!isTRUE(silent)) silent <- FALSE if(!requireNamespace("flexclust", quietly=TRUE)) { warning("Package 'flexclust' not found ! Please install first from CRAN") } else { if(!is.matrix(ma) & !silent) message(fxNa," Caution : data-frames with factors may cause problems !!") if(is.logical(ma)) stop(fxNa,"Expecting matrix with integer values") maCo <- matrix(1:nrow(ma), ncol=nrow(ma), nrow=nrow(ma)) maCo <- cbind(x=maCo[upper.tri(maCo)], y=t(maCo)[upper.tri(maCo)]) maCo <- maCo[order(maCo[,1], maCo[,2]),] # need proper order for upper.tri di <- try(apply(maCo, 1, function(x) flexclust::comPart(ma[x[1],],ma[x[2],], type=method)), silent=TRUE) if(inherits(di, "try-error")) message(fxNa,"Problem running flexclust::comPart ! (package might not be installed) class ",class(di)," mode ",mode(di)," ",di) out <- matrix(NA, nrow=nrow(ma), ncol=nrow(ma), dimnames=list(rownames(ma),colnames(ma))) out[upper.tri(out)] <- rev(di) # not used any more by as.dist() out[lower.tri(out)] <- di if(adjSense){ out <- .scaleXY(out, minim=0, maxim=max(out,na.rm=TRUE)) # re-scale from 0 to max mi <- min(out, na.rm=TRUE) maX <- max(out, na.rm=TRUE) if(mi <0) out <- (out -mi)*maX/(maX -mi) orient <- try(stats::cor(t(ma)) >0) if("try-error" %in% class(orient)) { out <- NA warning(fxNa," PROBLEM with calulating cor(), returning 0 ") } else out <- as.matrix(out)*(-1 +2*orient) } stats::as.dist(out) }}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/randIndFx.R
#' Contingenty tables for fit of ranking #' #' Count the number of instances where the corresponding columns of 'dat' have a value matching the group number as specified by 'grp'. #' Counting will be performed/repeated independently for each line of 'dat'. #' Returns array (1st dim is rows of dat, 2nd is unique(grp), 3rd dim is ok/bad), these results may be tested using eg \code{\link[stats]{fisher.test}}. #' This function was made for prearing to test the ranking of multiple features (lines in 'mat') including replicates (levels of 'grp'). #' #' @param dat (matrix or data.frame of integer values) ranking of multiple features (lines), equal ranks may occur #' @param grp (integer) expected ranking #' @return array (1st dim is rows of dat, 2nd is unique(grp), 3rd dim is ok/bad) #' @seealso \code{\link[stats]{lm}} #' @examples #' # Let's create a matrix with ranks (equal ranks do occur) #' ma0 <- matrix(rep(1:3,each=6), ncol=6, dimnames=list( #' c("li1","li2","ref"), letters[1:6])) #' ma0[1,6] <- 1 # create item not matching correctly #' ma0[2,] <- c(3:1,2,1,3) # create items not matching correctly #' gr0 <- gl(3,2) # the expected ranking (as duplicates) #' (count0 <- rankToContigTab(ma0,gr0)) #' cTab <- t(apply(count0, c(1,3) ,sum)) #' # Now we can compare the ranking of line1 to ref ... #' fisher.test(cTab[,c(3,1)]) # test li1 against ref #' fisher.test(cTab[,c(3,2)]) # test li2 against ref #' @export rankToContigTab <- function(dat,grp) { ## It is supposed that the columns of dat can be cut in multiple groups according to (sorted) grp ## Then the number of instances where the corresponding columns of dat have a value matching the group number is counted ## returns array (1st dim is rows of dat, 2nd is unique(grp), 3rd dim is ok/bad) grUnq <- unique(grp) chSo <- sort(grUnq)==grUnq if(length(dim(dat)) <2) dat <- matrix(as.numeric(dat),nrow=1,dimnames=list(NULL,names(dat))) if(any(!chSo)) { message("need to re-sort groups !") newOrd <- order(grp) oldRa <- rank(grp) # for setting back in old order dat <- dat[,newOrd] grp <- grp[newOrd] grUnq <- unique(grp) } else newOrd <- NULL lims <- sapply(grUnq,function(x) range(which(grp==x))) out <- array(dim=c(nrow(dat),length(grUnq),2),dimnames=list(rownames(dat),grUnq,c("ok","bad"))) for(i in 1:length(grUnq)) { z <- dat[,lims[1,i]:lims[2,i]] out[,i,] <- if(nrow(z) >1) cbind(ok=rowSums(z ==i,na.rm=TRUE),bad=rowSums(z !=i,na.rm=TRUE)) else c(ok=sum(z ==i,na.rm=TRUE),bad=sum(z !=i,na.rm=TRUE)) } out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rankToContigTab.R
#' Calculate all ratios between x and y #' #' This function calculates all possible pairwise ratios between all individual calues of x and y, or samples up to a maximum number of combinations. #' #' @param x (numeric) vector, numerator for constructing rations #' @param y (numeric) vector, denominator for constructing rations #' @param maxLim (integer) allows reducing complexity by drawing for very long x or y #' @param isLog (logical) adjust ratio calculation to log-data #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @examples #' set.seed(2014); ra1 <- c(rnorm(9,2,1),runif(8,1,2)) #' 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]))) #' @export ratioAllComb <- function(x, y, maxLim=1e4, isLog=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="ratioAllComb") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE namesXY <- c(deparse(substitute(x)), deparse(substitute(y))) if(!is.numeric(x)) x <- try(if(is.factor(x)) as.numeric(as.character(x)) else as.numeric(x), silent=TRUE) if(!is.numeric(y)) y <- try(if(is.factor(y)) as.numeric(as.character(y)) else as.numeric(y), silent=TRUE) msg <- " 'x' and 'y' must be numeric and length >0. Can't convert !" if(inherits(x, "try-error")) stop(fxNa,msg,namesXY[1]," to numeric") if(inherits(y, "try-error")) stop(fxNa,msg,namesXY[2]," to numeric") if(length(x) > maxLim){ if(!silent) message(fxNa,"Reducing x from to ",length(x)," to user-selectend length ",maxLim) x <- sample(x, size=maxLim, replace=FALSE) } if(length(y) > maxLim){ if(!silent) message(fxNa,"Reducing y from to ",length(y)," to user-selectend length ",maxLim) y <- sample(y, size=maxLim, replace=FALSE) } if(!silent) {nMax <- prod(length(x), length(y)) if(nMax > 1e8) message(fxNa,"Calculations may take long time ! (",signif(nMax,4)," combinations !)")} rat <- if(isLog) rep(x, each=length(y)) -rep(y, length(x)) else rep(x,each=length(y))/rep(y,length(x)) rat } #' Bring most extreme to center #' #' This function aims to bring most extreme value to center #' #' @param aa (numeric) main input #' @param ctr (numeric) 'control' #' @param ctrFa (numeric <1) modulate amplitude of effect #' @return This function returns an adjusted numeric vector #' @seealso \code{\link[stats]{dist}} #' @examples #' .bringToCtr(11:14, 9) #' @export .bringToCtr <- function(aa, ctr, ctrFa=0.75){ ## bring most extreme value of 'aa' (numeric vector) closer to 'ctr' ## 'ctrFa' .. (numeric <1) modulate amplitude of effect ## return adjusted numeric vector di <- abs(aa-ctr) sel <- which(di ==max(di,na.rm=TRUE)) aa[sel] <- ctr +max(di[if(length(aa) <3) which.min(di) else order(di)[length(aa) -1]], ctrFa*sum(di, na.rm=TRUE))*(((aa -ctr)/di)[sel])/sum(!is.na(di)) aa } #' Get series of values after last discontinuity #' #' This function aims to get series of values after last discontinuity #' #' @param x (numeric) main input #' @param getFrom (character) #' @return This function returns a numeric vector of reduced length #' @seealso \code{\link[stats]{dist}} #' @examples #' .breakInSer(c(11:14,16:18)) #' @export .breakInSer <- function(x, getFrom="last") { ## get series of values after last discontinuity ## 'x' as vector of numeric values ## 'getFrom' to decide if to extract from beginning or form from end (default) diffPos <- which(diff(x) >1) extrFrom <- if(length(diffPos) >0) {if(getFrom=="last") max(diffPos) +1 else min(diffPos) } else if(getFrom=="last") 1 else length(x) extrTo <- if(getFrom=="last") length(x) else 1 x[sort(extrFrom:extrTo)] } #' Remove columns indicated by col-number #' #' This function aims to remove columns indicated by col-number #' #' @param matr (matrix or data.frame) main input #' @param rmCol (integer) column index for removing #' @return This function returns an matrix or data.frame #' @seealso \code{\link[stats]{dist}} #' @examples #' aa <- matrix(1:6, ncol=3) #' .removeCol(aa, 2) #' @export .removeCol <- function(matr, rmCol) { ## remove columns indicated by col-number ## verifies that dimnames don't get lost and that output is not converted to simple vector (if 1 col remains) if(is.null(dim(matr))) stop(" expecting matrix or data.frame") if(length(rmCol) >0) { if(max(rmCol) > ncol(matr)) stop(" 'rmCol' must not be higher than nuber of columns of 'matr'") iniDimNa <- dimnames(matr) matr <- matr[,-1*rmCol] if(is.null(dim(matr))) matr <- matrix(matr, ncol=1, dimnames=list(iniDimNa[[1]], iniDimNa[[2]][-1*rmCol])) } matr } #' Reorganize array by reducing dimension 'byDim' (similar to stack() for data-frames) #' #' This function aims to reorganize an array by reducing dimension 'byDim' (similar to stack() for data-frames) #' It returns an array/matrix of 1 dimension less than 'arr', 1st dim has more lines (names as paste with '_') #' #' @param arr (array) main input #' @param byDim (integer) #' @return This function returns an array/matrix of 1 dimension less than 'arr', 1st dim has more lines (names as paste with '_') #' @seealso \code{\link[stats]{dist}} #' @examples #' (arr1 <- array(11:37, dim=c(3,3,3))) #' .stackArray(arr1, 3) #' @export .stackArray <- function(arr, byDim=3){ ## reorganize array by reducing dimension 'byDim' (similar to stack() for data-frames) ## returns array/matrix of 1 dimension less than 'arr', 1st dim has more lines (names as paste with '_') if(byDim > length(dim(arr))) stop(" 'byDim' should indicate the dimension-number to be supressed") dimNa <- dimnames(arr) useDi <- (1:length(dimNa))[-1*byDim] arr <- apply(arr,byDim,function(x) x) dimnames(arr) <- list(paste(rep(dimNa[[useDi[1]]], length(dimNa[[useDi[2]]])), rep(dimNa[[useDi[2]]], each=length(dimNa[[useDi[1]]])), sep="_"), dimNa[[byDim]]) arr } #' Check argument for Location of legend #' #' This function allows checking an argument for Location of legend, #' if value provided not found as valid, it returns 'defLoc #' #' @param legLoc (character) main input #' @param defLoc (character) #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a character vector designing the potential location of legend #' @seealso \code{\link[graphics]{legend}} #' @examples #' .checkLegendLoc("abc") #' @export .checkLegendLoc <- function(legLoc, defLoc="topright", silent=FALSE, debug=FALSE, callFrom=NULL){ ## check argument for Location of legend ## if value provided not found as valid, use 'defLoc' fxNa <- .composeCallName(callFrom, newNa=".checkLegendLoc") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(is.null(legLoc)) legLoc <- defLoc if(!is.character(legLoc) || length(legLoc) >1) legLoc <- defLoc if(!(tolower(legLoc) %in% c("topleft","topright", "top","bottomright", "bottomleft", "bottom", "left","right","center"))) { legLoc <- defLoc if(!silent) message(fxNa,"Can't interpret value of 'legLoc', setting to default '",defLoc,"'") } tolower(legLoc) } #' Avoid duplicating items between 'curNa' and 'newNa' by incrementing digits after 'extPref' (in newNa) #' #' This function aims to avoid duplicating items between 'curNa' and 'newNa' by incrementing digits after 'extPref' (in newNa) #' #' @param newNa (character) main input 1 #' @param curNa (character) main input 2 #' @param extPref (character) extension #' @return This function returns the corrected input vector \code{newNa} #' @seealso \code{\link[base]{duplicated}} #' @examples #' .corDuplItemsByIncrem(letters[1:6], letters[8:4]) #' @export .corDuplItemsByIncrem <- function(newNa, curNa, extPref="_s") { ## avoid duplicating items between 'curNa' and 'newNa' by incrementing digits after 'extPref' (in newNa) ## 'newNa' .. character vector for new names (to be adjusted/corrected) ## 'curNa' .. character vector for references of names ## cannot handle NAs ! ## return corrected 'newNa' (character vector) chSear <- unlist(regexec(paste0(extPref,"[[:digit:]]+$"), newNa)) # for finding extension at very end if(all(chSear==-1)) corExt <- newNa else { tt <- chSea2 <- unlist(regexec(paste0(extPref,"[[:digit:]]"),newNa)) # for finding extension at first of mult occurance whS <- which(chSear >0) tt[tt==-1] <- nchar(newNa)[tt==-1] +1 newExt <- cbind(bas=substr(newNa, 1, tt -1),ext=substr(newNa, tt +2, nchar(newNa))) chSear <- unlist(regexec(paste0(extPref,"[[:digit:]]+$"),curNa)) # for finding extension at very end chSea2 <- unlist(regexec(paste0(extPref,"[[:digit:]]"),curNa)) # for finding extension at first of mult occurance whS <- which(chSear >0) curExt <- cbind(bas=substr(curNa[whS], 1, chSea2[whS] -1), ext=substr(curNa[whS],chSear[whS]+2,nchar(curNa)[whS])) curMax <- tapply(as.numeric(curExt[,2]), curExt[,1], max) for(i in 1:length(curMax)) { uu <- which(newExt[,1]==names(curMax)[i]) newExt[uu,2] <- 1+ curMax[i]:(curMax[i] +length(uu) -1) } corExt <- paste(newExt[,1], newExt[,2], sep=extPref) if(any(newExt[,2]=="")) corExt[which(newExt[,2]=="")] <- newExt[which(newExt[,2]==""),1] } corExt }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/ratioAllComb.R
#' Convert ratio to ppm #' #' This function transforms ratio 'x' to ppm (parts per million). #' If 'y' not given (or different length as 'x'), then 'x' is assumed as ratio otherise rations are constructed as x/y is used lateron. #' Does additional checking : negative values not expected - will be made absolute ! #' #' @param x (numeric) main input #' @param y (numeric) optional value to construct ratios (x/y). If NULL (or different length as 'x'), then 'x' will be considered as ratio. #' @param nSign (numeric) number of significan digits #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a numeric vector of ppm values #' @seealso \code{\link{XYToDiffPpm}} for ppm of difference as used in mass spectrometrie #' @examples #' set.seed(2017); aa <- c(1.000001,0.999999,1+rnorm(10,0,0.001)) #' cbind(x=aa,ppm=ratioToPpm(aa,nSign=4)) #' @export ratioToPpm <- function(x, y=NULL, nSign=NULL, silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="ratioToPpm") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(any(is.na(x))) {if(!silent) message(fxNa," 'x' contains ",sum(is.na(x))," out of ",length(x)," NA alike, omit !"); x <- naOmit(x)} if(length(y) >0) if(any(is.na(y))) {if(!silent) message(fxNa," 'y' contains ",sum(is.na(y))," NA alike, omit !"); y <- naOmit(y)} if(length(y) >1 && length(x) != length(x)) { if(!silent) message(fxNa,"Length of 'y' (",length(y),") not corresponding to 'x' (",length(x),"), ignore 'y'") y <- NULL} if(length(y) == length(x) || length(y) ==1) { # get ration of x / Y if(any(y==0, na.rm=TRUE) && !silent) message(fxNa,"Division by 0 !") x <- x/y } if(any(x <0)) {if(!silent) message(fxNa,"Ngative values not possible"); x <- abs(x)} whNeg <- which(x <1) x[whNeg] <- 1/x[whNeg] x <- 1e6*(1-x) x[-1*whNeg] <- abs(x[-1*whNeg]) if(length(nSign) >0) signif(x, as.numeric(nSign)) else x }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/ratioToPpm.R
#' Read batch of csv-files #' #' This function was designed to read screening data split in parts (with common structure) and saved to multiple files, #' to extract the numeric columns and to compile all (numeric) data to a single array (or list). Some screening platforms save results while progressing #' through a pile of microtiter-plates separately. The organization of the resultant files is structured through file-names and all files have exactely the same organization of lines and columns/ #' European or US-formatted csv files can be read, if argument \code{fileFormat} is \code{NULL} both types will be tested, otherwise it allows to specify a given format. #' The presence of headers (to be used as column-names) may be tested using \code{checkFormat}. #' #' @param fileNames (character) names of files to be read, if \code{NULL} all files fitting 'fileFormat' #' @param path (character) where files should be read (folders should be written in R-style) #' @param fileFormat (character) may be \code{NULL} (both US and European formats will be tried), 'Eur' or 'US' #' @param checkFormat (logical) if \code{TRUE}: check header, remove empty columns, 1st line if all empmty, set output format for each file to matrix, if rownames are increasing integeres try to use 2nd of 'columns' as rownames #' @param returnArray (logical) allows switching from array to list-output #' @param columns (NULL or character) column-headers to be extracted (if specified), 2nd value may be comlumn with rownames (if rownames are encountered as increasing rownames) #' @param excludeFiles (character) names of files to exclude (only used when reading all files of given directory) #' @param simpleNames (logical) allows truncating names (from beginning) to get to variable part (using .trimFromStart()), but keeping 'minNamesLe' #' @param minNamesLe (interger) min length of column-names if simpleNames=TRUE #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allows easier tracking of messages produced #' @return This function returns an array (or list if \code{returnArray=FALSE}) of all numeric data read (numerical columns only) from individual files #' @seealso \code{\link[utils]{read.table}}, \code{\link{writeCsv}}, \code{\link{readXlsxBatch}} #' @examples #' 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) #' ## batch reading of all csv files in specified path : #' datAll2 <- readCsvBatch(fileNames=NULL, path=path1, silent=TRUE) #' @export readCsvBatch <- function(fileNames=NULL, path=".", fileFormat="Eur", checkFormat=TRUE, returnArray=TRUE, columns=c("Plate","Well","StainA"), excludeFiles="All infected plates", simpleNames=TRUE, minNamesLe=4, silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="readCsvBatch") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE HeaderInData <- if(is.null(columns)) FALSE else TRUE if(length(path) >0) { chPath <- dir.exists(path) if(!chPath) {path <- "." message(fxNa," Cannot find path '",path,"' ! ... Setting to default='.'")} } else path <- "." if(is.null(fileNames)) { # read batch of files fileNames <- file.path(path, dir(path=path, pattern="\\.csv$")) if(length(fileNames) <1) message(fxNa,"Could not find ANY suitable files !!") else { if(!silent) message(fxNa,"Batch mode: Found ",length(fileNames)," files to extract (eg ",pasteC(utils::head(fileNames,3),quoteC="'"),")")} } else { # read explicit set of files if(length(path) >0) { chPath <- grep(paste0("^",path), fileNames) # check if path already given with filenames if(length(chPath) <1) fileNames <- file.path(path,fileNames)} checkFi <- file.exists(fileNames) if(any(!checkFi)) { if(!silent) message(fxNa,"Could not find ",sum(!checkFi)," files (eg ",pasteC(utils::head(fileNames[which(!checkFi)],3),quoteC="'"),")") fileNames <- fileNames[which(checkFi)] } if(length(fileNames) >0) { ## treat files to exclude checkFi <- if(!is.null(excludeFiles)) grepl(excludeFiles, fileNames) else rep(FALSE, length(fileNames)) if(any(!checkFi)) if(!silent) message(fxNa,"Based on 'excludeFiles': excluding ",sum(checkFi)," files (out of ",length(fileNames),")") fileNames <- fileNames[which(!checkFi)]} } ## check if US or European format if(length(fileNames) >0) { if(!silent) message(fxNa," ready to start reading ",length(fileNames)," files; expecting header(s) : ", HeaderInData) tmp1 <- if(!identical(fileFormat,"Eur")) try(utils::read.csv(fileNames[1], header=HeaderInData, stringsAsFactors=FALSE), silent=TRUE) else NULL tmp2 <- if(!identical(fileFormat,"US")) try(utils::read.csv2(fileNames[1], header=HeaderInData, stringsAsFactors=FALSE), silent=TRUE) else NULL cheF <- c(inherits(tmp1, "try-error"), inherits(tmp2, "try-error")) if(debug) message(fxNa,"Done with inital try of reading files") if(all(cheF)) { fileNames <- NULL stop(fxNa,"\n Problem with file format, can't read 1st file neither as European nor US-type CSV !!") } else { chDim <- prod(dim(tmp1)) > prod(dim(tmp2)) datDim <- if(chDim) dim(tmp1) else dim(tmp2) if(!silent) message(fxNa,"csv-format used ",if(chDim) "'US'" else "'Europe'"," with ",datDim[1]," lines & ",datDim[2]," cols") } } ## main reading if(length(fileNames) >0) { datL <- list() arrNames <- if(isTRUE(simpleNames)) .trimFromStart(fileNames, minNchar=minNamesLe) else fileNames if(debug) message(fxNa,"ready for main reading of ",pasteC(utils::head(fileNames))) for(i in 1:length(fileNames)) { if(!silent) message(fxNa," ..reading file ",fileNames[i]) curFileNa <- fileNames[i] tmp <- if(chDim) { utils::read.csv(curFileNa, header=HeaderInData, stringsAsFactors=FALSE) } else utils::read.csv2(curFileNa, header=HeaderInData, stringsAsFactors=FALSE) if(isTRUE(checkFormat)) { tmp <- .inspectHeader(tmp, headNames=columns, silent=i !=1 | silent, callFrom=fxNa) tmp <- .removeEmptyCol(tmp, fromBackOnly=FALSE, silent=i !=1 | silent, callFrom=fxNa) } if(i ==1) { # (re)define new format based on 1st file after format-checking (ie remove empty cols, extract col of well-names,...) datDim <- dim(tmp) dat <- if(isTRUE(returnArray)) array(NA, dim=c(datDim[1],length(fileNames),datDim[2])) else NULL } if(!returnArray) datL[[i]] <- as.matrix(tmp) else { if(identical(dim(tmp),datDim)) dat[,i,] <- as.matrix(tmp) else { message(fxNa, i,"th file ",fileNames[i]," seems not to have format consistent with prev files (",dim(tmp)[1]," lines & ",dim(tmp)[2]," rows)") } } } if(sum(nchar(arrNames) <1) >0) { if(!silent) message(fxNa,"Some arrays seem to have no plate-name specified from within data, using file-names") arrNames <- substr(fileNames[i],1,nchar(fileNames[i])-4)} if(returnArray) { dimnames(dat) <- list(rownames(tmp), arrNames, colnames(tmp)) } else { dat <- datL if(length(fileNames) !=length(dat)) message(fxNa," Problem ? Got ",length(fileNames)," fileNames BUT ",length(dat)," list-elements !") names(dat) <- substr(fileNames,1,nchar(fileNames)-4) if(isTRUE(simpleNames)) names(dat) <- .trimFromStart(names(dat), minNchar=minNamesLe) } dat } else NULL } #' Inspect 'matr' and check if 1st line can be used/converted as header #' #' This function inspects 'matr' and check if 1st line can be used/converted as header. #' If colnames of 'matr' are either NULL or 'V1',etc the 1st row will be tested if it contains any of the elements (if not, 1st line won't be used as new colnames) #' If 'numericCheck'=TRUE, all columns will be tested if they can be converted to numeric #' #' @param matr (matrix or data.frame) main input to be instected #' @param headNames (character) column-names t look for #' @param numericCheck (logical) allows reducing complexity by drawing for very long x or y #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a matrix vector or data.frame similar to input #' @seealso \code{\link[utils]{head}} for looking at first few lines #' @examples #' ma1 <- matrix(letters[1:6], ncol=3, dimnames=list(NULL,c("ab","Plate","Well"))) #' .inspectHeader(ma1) #' #' @export .inspectHeader <- function(matr, headNames=c("Plate","Well","StainA"), numericCheck=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL){ ## inspect 'matr' and check if 1st line can be used/converted as header ## if colnames of 'matr' are either NULL or 'V1',etc the 1st row will be tested if it contains any of the elements (if not, 1st line won't be used as new colnames) ## if'numericCheck'=TRUE, all columns will be tested if they can be converted to numeric extr1stLine <- TRUE fxNa <- .composeCallName(callFrom, newNa=".inspectHeader") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE msg <- character() if(!is.null(colnames(matr))) {if(identical(colnames(matr), paste0("V",1:ncol(matr)))) extr1stLine <- FALSE} if(extr1stLine & sum(tolower(headNames) %in% tolower(as.matrix(matr[1,]))) <1) extr1stLine <- FALSE if(extr1stLine) { chNewNa <- length(matr[1,]) ==length(unique(matr[1,])) if(!chNewNa && !silent) message(fxNa,"Transferring text to now column-names, but they are not unique !") matr <- as.data.frame(matr) colnames(matr) <- matr[1,] matr <- matr[-1,] } if(numericCheck) { ## try to locate 1st column that can be used as rownames (before removing text-content of non-nuleric columns) rowNa <- rownames(matr) if(is.null(rowNa) || identical(rowNa,as.character(1:nrow(matr)))) { chUniq <- apply(matr, 2, function(x) length(unique(x)) ==length(x)) if(any(chUniq)) rowNa <- matr[,which(chUniq)[1]] } ## extract numerical values only (text will be converted to NA) matr <- apply(matr, 2, convToNum, spaceRemove=TRUE, convert=c(NA,"allChar"), remove=NULL,sciIncl=TRUE,euroStyle=TRUE,callFrom=fxNa,silent=silent) rownames(matr) <- rowNa } matr }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/readCsvBatch.R
#' Batch reading of Tabulated Text-Files #' #' @description #' This function allows batch reading of multiple tabulated text files n batch. #' The files can be designed specifically, or, alternatively all files from a given directory can be read. #' If package \href{https://CRAN.R-project.org/package=data.table}{data.table} is available, faster reading of files will be performed using the function \code{\link[data.table]{fread}}. #' #' @details #' If you want to provide a flexible pattern of ffile-names, this has to be done before calling this usntion, eg using \code{grep} to provide an explicit collection of flles. #' However, it is possible to read different files from different locations/directories, the length of \code{path} must match the length of \code{query} #' #' @param query (character) vector of file-names to be read, if \code{"."} all files will be read (no matter what their extension might be) #' @param path (character) path for reading files, if \code{NULL} or \code{NA} the current directory will be used #' @param dec (character, length=1) decimals to use, will be passed to \code{\link[data.table]{fread}} or \code{\link[utils]{read.delim}} #' @param header (character, length=1) path for reading files, if \code{NULL} or \code{NA} the current directory will be used, will be passed to \code{\link[data.table]{fread}} or \code{\link[utils]{read.delim}} #' @param strip.white (logical, length=1) Strips leading and trailing whitespaces of unquoted fields, will be passed to \code{\link[data.table]{fread}} or \code{\link[utils]{read.delim}} #' @param blank.lines.skip (logical, length=1) If \code{TRUE} blank lines in the input are ignored. will be passed to \code{\link[data.table]{fread}} or \code{\link[utils]{read.delim}} #' @param fill (logical, length=1) If \code{TRUE} then in case the rows have unequal length, blank fields are implicitly filled, will be passed to \code{\link[data.table]{fread}} or \code{\link[utils]{read.delim}} #' @param filtCol (integer, length=1) which columns should be used for filtering, if \code{NULL} or \code{NA} all data will be returned #' @param filterAsInf (logical, length=1) filter as inferior or equal (\code{TRUE}) or superior or equal threshold \code{filtVal} #' @param filtVal (numeric, length=1) which numeric threshold should be used for filtering, if \code{NULL} or \code{NA} all data will be returned #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of messages produced #' @param debug (logical) display additional messages for debugging #' @return This function returns a list of data.frames #' @seealso \code{\link[data.table]{fread}}, \code{\link[utils]{read.delim}}, for reading batch of csv files : \code{\link{readCsvBatch}} #' @examples #' path1 <- system.file("extdata", package="wrMisc") #' fiNa <- c("a1.txt","a2.txt") #' allTxt <- readTabulatedBatch(fiNa, path1) #' str(allTxt) #' #' @export readTabulatedBatch <- function(query, path=NULL, dec=".", header="auto", strip.white=FALSE, blank.lines.skip=TRUE, fill=FALSE, filtCol=2, filterAsInf=TRUE, filtVal=5000, silent=FALSE, callFrom=NULL, debug=FALSE) { ## read tabulated data from local download fxNa <- .composeCallName(callFrom, newNa="readTabulatedBatch") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE ## check for packages reqPa <- c("utils","wrMisc","data.table") chPa <- sapply(reqPa, requireNamespace, quietly=TRUE) if(any(!chPa[1:2])) stop("Package(s) '",paste(reqPa[which(!chPa)], collapse="','"),"' not found ! Please install first from CRAN") if(!chPa[2]) message(fxNa, "NOTE : package 'data.table' for fast reading of files absent, please consider installing from CRAN for faster reading") ## check path & file as valid entries msg <- "Invalid entry for 'query'" if(length(query) <1) {warning(fxNa,msg," Setting to '.'"); query <- "." } else { chNa <- is.na(query) if(all(chNa)) stop("All queries are NA !!") else if(any(chNa)) { if(!silent) message(fxNa,"Removing ",sum(chNa)," queries at NA-status") query <- query[which(!is.na(chNa))] if(length(path) >1 && length(path)==length(query)) path <- path[which(!is.na(chNa))] }} ## check & remove entries without any characters chChar <- nchar(query) >0 if(debug) {message(fxNa,"rt1")} if(all(!chChar)) stop(msg) else if(any(!chChar)) { query <- query[which(chChar)] if(length(path) >1 && length(path)==length(query)) path <- path[which(chChar)]} ## check & remove entries with NA if(length(path) >0) { chNaPa <- is.na(path) if(any(chNaPa)) { path <- path[which(!chNaPa)] if(length(query) >1 && length(query)==length(path)) query <- query[which(!chNaPa)] } } if(debug) {message(fxNa,"rt2")} ## combine file & path, main testing if existing if(length(path) >1 && length(path) != length(query)) { path <- NULL if(!silent) message(fxNa,"Length of entries for 'path' not matching length of queries ! Ignoring 'path'")} if(identical(".", query)) { if(debug) message(fxNa,"Reading all files from dir selected") chPath <- if(length(path) ==1) { if(is.na(path)) FALSE else dir.exists(path)} else FALSE query <- list.files(if(chPath) path=path else ".") if(debug) {message(fxNa,"rt3a")} fiPa <- if(chPath) file.path(path, query) else query } else { if(debug) {message(fxNa,"rt3b Reading specific files selected")} chPath <- if(length(path) ==1 || length(path) == length(query)) { if(any(is.na(path))) FALSE else all(dir.exists(path))} else FALSE fiPa <- if(chPath) file.path(path, query) else query chfiPa <- file.exists(fiPa) if(all(!chfiPa)) warning(msg,"Can't find ANY of the files !") else { if(any(!chfiPa)) { if(!silent) message(fxNa," removing ",sum(!chfiPa)," out of ",length(fiPa), " non-existing queries/files") query <- query[which(chfiPa)] fiPa <- fiPa[which(chfiPa)]} } } if(debug) {message(fxNa,"rt4"); rt4 <- list(fiPa=fiPa,query=query,chPa=chPa,filtCol=filtCol,filtVal=filtVal,strip.white=strip.white,blank.lines.skip=blank.lines.skip,fill=fill)} ## main reading of files (& integrated filtering) if(debug) message(fxNa,"Ready to start reading ",length(fiPa)," files using ",if(chPa[3]) "data.table::fread()" else "utils::read.delim()") if(length(fiPa) >0) { if(length(filtCol) ==1) {if(is.na(filtCol)) filtCol <- NULL } else filtCol <- NULL if(length(filtVal) ==1) {if(is.na(filtVal) || !is.numeric(filtVal)) { filtVal <- NULL; if(debug) message(fxNa,"Invalid 'filtVal'")}} else filtVal <- NULL if(identical(header,"auto") & !chPa[3]) header <- FALSE if(!isFALSE(filterAsInf)) filterAsInf <- TRUE if(debug) {message(fxNa,"rt5")} datLi <- lapply(fiPa, function(x) { y <- if(chPa[3]) {as.data.frame(data.table::fread(x, sep="\t", dec=dec, header=header,strip.white=strip.white, blank.lines.skip=blank.lines.skip,fill=fill)) } else utils::read.delim(file=x, dec=dec, header=header, strip.white=strip.white, blank.lines.skip=blank.lines.skip, fill=fill) if(length(filtCol)==1) { if(ncol(y) < filtCol) filtCol <- NULL else if(!is.numeric(y[,filtCol])) filtCol <- NULL} if(length(filtVal)==1 && length(filtCol) ==1) y <- y[which( if(filterAsInf) y[,filtCol] <= filtVal else y[,filtCol] >= filtVal),] y }) names(datLi) <- query datLi }}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/readTabulatedBatch.R
#' Read tabular content of files with variable number of columns #' #' Reading the content of files where the number of separators (eg tabulation) is variable poses problems with traditional methods for reding files, like \code{\link[utils]{read.table}}. #' This function reads each line independently and then parses all separators therein. The first line is assumed to be column-headers. #' Finally, all data will be returned in a matrix adopted to the line with most separators and if the number of column-headers is insufficient, new (unique) column-headers will be generated. #' Thus, the lines may contain different number of elements, empty elements (ie tabular fields) will always get added to right of data read #' and their content will be as defined by argument \code{emptyFields} (default \code{NA}). #' #' Note, this functions assumes one line of header and at least one line of data ! #' Note, for numeric data the comma is assumed to be US-Style (as '.'). #' Note, that it is assumed, that any missing fields for the complete tabular view are missing on the right (ie at the end of line) ! #' #' @param fiName (character) file-name #' @param path (character) optional path #' @param sep (character) separator (between columns) #' @param header (logical) indicating whether the file contains the names of the variables as its first line. #' @param emptyFields (\code{NA} or character) missing headers will be replaced by the content of 'emptyFields', if \code{NA} the last column-name will be re-used and a counter added #' @param refCo (integer) for custom choice of column to be used as row-names (default will use 1st text-column) #' @param supNa (character) base for constructing name for columns wo names (+counter starting at 2), default column-name to left of 1st col wo colname #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a matrix (character or numeric) #' @seealso for regular 'complete' data \code{\link[utils]{read.table}} #' @examples #' path1 <- system.file("extdata",package="wrMisc") #' fiNa <- "Names1.tsv" #' datAll <- readVarColumns(fiName=file.path(path1,fiNa)) #' str(datAll) #' @export readVarColumns <- function(fiName, path=NULL, sep="\t", header=TRUE, emptyFields=NA, refCo=NULL, supNa=NULL, silent=FALSE, callFrom=NULL) { ## slightly slower function for reading variable tabular content of files: This function allows reading variable number of elements per line (via parsing each line separately). ## read content of file using separator 'sep'; 1st line is expectd to caintain some headers, missing headers will be replaced by the content of 'emptyFields' ## 'emptyFields' (NA or character) content of fields ## 'refCo' (integer) for custom choice of column to be used as row-names (default will use 1st text-column) ## 'supNa' (character) base for constructing name for columns wo names (+counter starting at 2), default column-name to left of 1st col wo colname fxNa <- .composeCallName(callFrom, newNa="readVarColumns") fiName <- if(length(path) >0) {if(nchar(path) >0) file.path(path, fiName) else fiName} else fiName if(!file.exists(fiName)) { dataOK <- FALSE warning(" PROBLEM : Can't find file '",fiName,"'") } else { dataOK <- TRUE if(length(header) !=1) header <- FALSE if(!is.logical(header)) { dataOK <- FALSE warning(fxNa,"Invalid command: argument 'header' should be logical and of length=1")} } if(dataOK) { out <- try(scan(fiName, what="character", sep="\n"), silent=TRUE) if(inherits(out, "try-error")) { dataOK <- FALSE warning(fxNa,"Did NOT succeed reading file '",fiName,"'")}} if(dataOK) { ## parse each line since file does/may contain variable number of columns and/or (many) columns wo colnames out <- strsplit(out, sep) maxCo <- max(sapply(out, length)) out <- t(sapply(out, function(x,maxC) {if(length(x)==maxC) x else {z <- rep("",maxC); z[1:length(x)] <- x; z}}, maxC=maxCo)) supPep <- which(out[1,] =="") if(length(supNa) !=1) { supNa0 <- min(supPep, na.rm=TRUE) supNa <- if(supNa0 >1) out[1, min(supPep, na.rm=TRUE) -1] else ((1:ncol(out))[-supPep])[1]} out[1, supPep] <- paste(supNa, 1 +1:length(supPep),sep="_") if(nrow(out) <2) { dataOK <- FALSE warning(" PROBLEM : data seem to be empty (header only ?)")} } if(dataOK) { ## extract row- and col-names, prepare for separating numeric from text testNum <- function(x) all(grepl("(^([0-9]+)|(^[+-][0-9]+)|(^\\.[0-9]+))((\\.[0-9]+)?)(([eE][+-]?[0-9]+)?)$", x)) numCol <- apply(out[-1,], 2, testNum) if(length(refCo) !=1) {refCo <- min(which(!numCol)) if(isFALSE(silent)) message(fxNa," setting 'refCo' to '",out[1,refCo],"'")} # dupNa <- duplicated(out[1,]) ## integrate colnames and rownames ... useLi <- if(header) 2:nrow(out) else 1:nrow(out) colNa <- if(header) {if(any(dupNa)) correctToUnique(out[1,], callFrom=fxNa) else out[1,]} else NULL dupNa <- duplicated(out[useLi,refCo]) rowNa <- if(any(dupNa)) correctToUnique(out[useLi,refCo], callFrom=fxNa) else out[useLi,refCo] if(header) out <- out[-1,] if(length(dim(out)) <2) out <- matrix(out, nrow=1, dimnames=list(rowNa, names(out))) else dimnames(out) <- list(rowNa,colNa) out } }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/readVarColumns.R
#' Read Batch of Excel xlsx-Files #' #' \code{readXlsxBatch} reads data out of multiple xlsx files, the sheet indicated by 'sheetInd' will be considered. #' All files must have the same organization of data, as this is typically the case when high-throughput measurements are automatically saved while experiments progress. #' In particular, the first file read is used to structure the output. #' #' @details #' By default all columns with text-content may be eliminated to keep the numeric part only, which may then get organized to a 3-dim numeric array #' (where the additional files will be used as 2nd dimension and multiple columns per file shown as 3rd dimension). #' #' NOTE : (starting from version wrMisc-1.5.5) requires packages \href{https://CRAN.R-project.org/package=readxl}{readxl} and #' \href{https://CRAN.R-project.org/package=Rcpp}{Rcpp} being installed ! #' (This allows much faster and memory efficient processing than previous use of package '\code{xlsx}') #' #' @param fileNames (character) provide either explicit list of file-names to be read or leave \code{NULL} for reading all files ending with 'xlsx' in path specified with argument \code{path} #' @param path (character) there may be a different path for each file #' @param fileExtension (character) extension of files (default='\code{xlsx}') #' @param excludeFiles (character) names of files to exclude (only used when reading all files of given directory) #' @param sheetInd (character or integer) specify which sheet to extract (as exact name of sheed or sheet-number, eg \code{sheetInd=2} will extract always the 2nd sheet (no matter the name); if given as sheet-name but nor present in file an empty list-elements wil be returned #' @param checkFormat (logical) if \code{TRUE}: check header, remove empty columns, if rownames are increasing integeres it will searh for fisrt column with different entries to use as rownames #' @param returnArray (logical) allows switching from array to list-output #' @param columns (NULL or character) column-headers to be extracted (if specified, otherwise all columns will be extracted) #' @param simpleNames (integer), if \code{NULL} all characters of fileNames will be maintained, otherwise allows truncating names (from beginning) to get to variable part (using .trimFromStart()), but keeping at least the number of charcters indicated by this argument #' @param silent (logical) suppress messages #' @param callFrom (character) allows easier tracking of messages produced #' @return This function returns a list of data.frames #' @seealso \code{\link[readxl]{read_excel}}; for simple reading of (older) xls-files under 32-bit R one may also see the package \href{https://CRAN.R-project.org/package=RODBC}{RODBC} #' @examples #' path1 <- system.file("extdata", package="wrMisc") #' fiNa <- c("pl01_1.xlsx","pl01_2.xlsx","pl02_1.xlsx","pl02_2.xlsx") #' datAll <- readXlsxBatch(fiNa, path1) #' str(datAll) #' ## Now let's read all xlsx files of directory #' datAll2 <- readXlsxBatch(path=path1, silent=TRUE) #' identical(datAll, datAll2) #' @export readXlsxBatch <- function(fileNames=NULL, path=".", fileExtension="xlsx", excludeFiles=NULL, sheetInd=1, checkFormat=TRUE, returnArray=TRUE, columns=c("Plate","Well","StainA"), simpleNames=3, silent=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="readXlsxBatch") packages <- c("readxl", "Rcpp") checkPkg <- function(pkg) requireNamespace(pkg, quietly=TRUE) checkPkgs <- sapply(packages, checkPkg) if(!isTRUE(silent)) silent <- FALSE if(!isFALSE(returnArray)) returnArray <- TRUE if(any(!checkPkgs)) { out <- NULL warning(fxNa,"package 'readxl' and/or 'Rcpp' not found ! Please install first from CRAN") } else { ## prepare if(is.null(path)) path <- "." chPath <- dir.exists(path) if(!chPath) {message(fxNa,"Cannot find path '",path,"' ! ... Setting to default='.'")} if(is.null(fileNames)) { ## automatic reading of all files in directory fileNames <- dir(path=path,pattern=paste0(fileExtension,"$")) if(length(fileNames) <1) message(fxNa,"Could not find ANY suitable files !!") else { if(silent) message(fxNa," found ",length(fileNames)," files to extract (eg ",pasteC(utils::head(fileNames,3),quoteC="'"),")")} useFi <- file.path(path,fileNames) } else { ## reading of specfied files in directory douPath <- grep(path,fileNames) useFi <- if(length(douPath) <1) file.path(path, fileNames) else fileNames checkFi <- file.exists(useFi) if(sum(!checkFi) >0) { if(silent) message(fxNa,"Could not find ",sum(!checkFi)," files out of ",length(useFi), " (eg ",pasteC(utils::head(fileNames[which(!checkFi)],3),quoteC="'"),")") useFi <- fileNames[which(checkFi)] fileNames <- fileNames[which(checkFi)] }} ## files to omit from reading, ie exclude checkFi <- if(!is.null(excludeFiles)) grep(excludeFiles, fileNames) else NULL if(!any("try-error" %in% checkFi)) useFi <- NULL if(length(checkFi) >0) { if(silent) message(fxNa,"Based on 'excludeFiles': excluding ",length(checkFi)," files (out of ",length(fileNames),")") useFi <- useFi[-1*checkFi] fileNames <- fileNames[-1*checkFi] } ## main reading outL <- list() if(length(useFi) >0) { for(i in 1:length(useFi)) { sheets <- try(readxl::excel_sheets(useFi[i])) if("try-error" %in% class(sheets)) { sheetInd <- NULL warning(fxNa,"Unable to read '",fileNames[i],"' Check if you have sufficient rights to open the file !?!") } else { ## inspect for sheet to load if(is.numeric(sheetInd)) { sheetInd <- as.integer(sheetInd) if(length(sheets) < sheetInd | sheetInd <1) { sheetInd <- NULL }} else sheetInd <- naOmit(match(sheetInd,sheets)) if(silent & length(sheetInd) <1) message(fxNa,"Unable to read '",fileNames[i],"', the sheet '",sheetInd, "' was not found (existing: ",pasteC(sheets,quoteC="'"),")") } if(silent & length(sheetInd) >1) message(fxNa,"Only '",sheets[sheetInd],"', ie first match of 'sheetInd' will be read !") ## read xls and xlsx tmp <- if(length(sheetInd)==1) readxl::read_excel(useFi[i], sheet=sheets[sheetInd]) else NULL # may also use readxl::read_xlsx if(length(tmp) >0) { outL[[i]] <- as.data.frame(tmp) if(isTRUE(checkFormat)) { ## display messages only for first file (others are presumed to repeat...) silent2 <- isTRUE(silent) | i !=1 outL[[i]] <- .inspectHeader(outL[[i]], headNames=columns,silent=silent2, callFrom=fxNa) outL[[i]] <- .removeEmptyCol(outL[[i]], fromBackOnly=FALSE,silent=silent2, callFrom=fxNa) } ## for case array-output : define object out with dimensions based on 1st file if(i ==1) { # (re)define new format based on 1st file after format-checking (ie remove empty cols, extract col of well-names,...) outDim <- dim(outL[[i]]) out <- if(returnArray) array(NA, dim=c(outDim[1],length(fileNames),outDim[2]), dimnames=list(rownames(outL[[i]]), basename(fileNames),colnames(outL[[i]]))) else NULL } ## for case array-output : fill directly into object out if(returnArray) outL[[i]] <- as.matrix(outL[[i]]) else { if(identical(dim(outL[[i]]),outDim)) out[,i,] <- as.matrix(outL[[i]]) else { message(fxNa," Omit ",i,"th file ''",fileNames[i],"': format (",dim(outL[[i]])[1]," rows & ",dim(outL[[i]])[2]," cols) NOT consistent with previous files - omitting") } } } } names(outL) <- fileNames if(returnArray) { ## refine column-names in array chColNa <- length(unique(colnames(out)))==1 arrNames <- if(chColNa) paste(colnames(out),sub("\\.xlsx$","",if(length(simpleNames) >1) .trimFromStart(fileNames, minNchar=simpleNames, callFrom=fxNa) else fileNames),sep=".") else colnames(out) } else { out <- outL ## refine names in list-output if(length(fileNames) !=length(out)) message(fxNa," Problem ? Got ",length(fileNames)," fileNames BUT ",length(out)," list-elements !") names(out) <- substr(basename(fileNames), 1, nchar(basename(fileNames)) -4) # remove extesions if(simpleNames) names(out) <- if(length(simpleNames) >1) .trimFromStart(fileNames, minNchar=simpleNames, callFrom=fxNa) else fileNames } } else out <- NULL } out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/readXlsxBatch.R
#' Reduce table by aggregating smaller groups #' #' \code{reduceTable} treats/reduces results from \code{\link[base]{table}} to 'nGrp' groups, #' optional indiv resolution of 'separFirst' (numeric or NULL). #' Mainly made for reducing the number of classes for betters plots with \code{\link[graphics]{pie}} #' #' @param tab output of \code{\link[base]{table}} #' @param separFirst (integer or NULL) optinal separartion of n 'separFirst' groups (value <2 or NULL #' will priviledge more uniform size of groups, higher values will cause small inital and larger tailing groups) #' @param nGrp (integer) number of groups expected #' @return This function returns a numeric vector with number of counts and class-borders as names (like table). #' @seealso \code{\link[base]{table}} #' @examples #' set.seed(2018); dat <- sample(11:60,200,repl=TRUE) #' pie(table(dat)) #' pie(reduceTable(table(dat), sep=NULL)) #' pie(reduceTable(table(dat), sep=NULL), init.angle=90, #' clockwise=TRUE, col=rainbow(20)[1:15], cex=0.8) #' @export reduceTable <- function(tab, separFirst=4, nGrp=15) { if(!inherits(tab, "table")) message(" Note: Expecting class 'table' for argument 'tab' for proper functioning !!") cuSu <- cumsum(tab) if(length(separFirst) >0) {ch <- grep("^[[:digit:]]$", separFirst[1]) separFirst <- if(length(ch)==1) as.numeric(separFirst[1]) else NULL} if(length(separFirst) >0) { nGrp <- nGrp -separFirst +1 if(nGrp <1) message("correcting nGrp -> 1 ") else message(" nGrp=",nGrp) if(nGrp <1) nGrp <- 1 cu <- as.numeric(cut(cuSu,nGrp)) +separFirst -1 cu[1:separFirst] <- 1:separFirst } else cu <- as.numeric(cut(cuSu, nGrp)) ## idea : modify to to priviledge round numbers (of names(tab)) out <- tapply(tab, cu, sum) names(out) <- tapply(as.numeric(names(tab)), cu, function(x) if(length(x) >1) paste(range(x),collapse="-") else x) out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/reduceTable.R
#' Rescaling according to reference data using linear regression. #' #' \code{regrBy1or2point} does rescaling: linear transform simple vector 'inDat' that (mean of) elements of names cited in 'refLst' will end up as values 'regrTo'. #' Regress single vector according to 'refLst' (describing names of inDat). #' If 'refLst' contains 2 groups, the 1st group will be set to the 1st value of 'regrTo' (and the 2nd group of 'refLst' to the 2nd 'regtTo') #' @param inDat matrix or data.frame #' @param refLst list of names existing in inDat (one group of names for each value in 'regrTo'), to be transformed in values precised in 'regTo'; if no matches to names of 'inDat' found, the 2 lowest and/or highest highest values will be chosen #' @param regrTo (numeric,length=2) range (at scale 0-1) of target-values for mean of elements cited in 'refLst' #' @param silent (logical) suppress messages #' @param callFrom (character) allows easier tracking of message(s) produced #' @return normalized matrix #' @seealso \code{\link{adjBy2ptReg}}, \code{\link{regrMultBy1or2point}} #' @examples #' set.seed(2016); dat1 <- 1:50 +(1:50)*round(runif(50),1) #' names(dat1) <- 1:length(dat1) #' reg1 <- regrBy1or2point(dat1,refLst=c("2","49")) #' plot(reg1,dat1) #' @export regrBy1or2point <- function(inDat,refLst,regrTo=c(1,0.5),silent=FALSE,callFrom=NULL){ fxNa <- .composeCallName(callFrom,newNa="regrBy1or2point") if(length(names(inDat)) <0) { names(inDat) <- 1:length(inDat) message(fxNa," no (valid) names found in 'inDat', making default numbering")} chLst <- sapply(refLst,function(x) !all(x %in% names(inDat))) if(any(chLst)) { if(chLst[1]) refLst[[1]] <- names(inDat)[order(inDat)][1:2] if(chLst[2]) refLst[[2]] <- names(inDat)[order(inDat)][length(inDat):(length(inDat)-1)] if(!silent) message(fxNa," no (valid) names found in 'refLst', choosing noth most extreme values")} checkEntr <- .checkRegrArguments(inDat,refLst,regrTo) refLst <- checkEntr$refLst regrTo <- checkEntr$regrTo tmp <- sapply(refLst,function(x) inDat[x]) contrAve <- if(is.matrix(tmp)) colMeans(tmp) else sapply(tmp,mean,na.rm=TRUE) normFact <- if(length(refLst) ==1) (regrTo[1]/contrAve[1]) else (regrTo[2]-regrTo[1])/(contrAve[2]-contrAve[1]) normFact <- c(k=normFact, d= if(length(refLst) ==1) 0 else regrTo[1] -normFact*contrAve[1]) inDat*normFact[1] + normFact[2] }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/regrBy1or2point.R
#' Rescaling of multiple data-sets according to reference data using regression #' #' \code{regrMultBy1or2point} regresses each col of matrix according to 'refLst'(describing rownames of inDat). #' If 'refLst' conatins 2 groups, the 1st group will be set to the 1st value of 'regrTo' (and the 2nd group of 'refLst' to the 2nd 'regtTo') #' #' @param inDat matrix or data.frame #' @param refLst list of names existing in inDat (one group of names for each value in 'regrTo'), to be transformed in values precised in 'regTo'; if no matches to names of 'inDat' found, the 2 lowest and/or highest highest values will be chosen #' @param regrTo (numeric,length=2) range (at scale 0-1) of target-values for mean of elements cited in 'refLst' #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of message(s) produced #' @return normalized matrix #' @seealso \code{\link{adjBy2ptReg}}, \code{\link{regrBy1or2point}} #' @examples #' set.seed(2016); dat2 <- round(cbind(1:50 +(1:50)*runif(50),2.2*(1:50) +rnorm(50,0,3)),1) #' rownames(dat2) <- 1:nrow(dat2) #' reg1 <- regrBy1or2point(dat2[,1],refLst=list(as.character(5:7),as.character(44:45))) #' reg2 <- regrMultBy1or2point(dat2,refLst=list(as.character(5:7),as.character(44:45))) #' plot(dat2[,1],reg2[,1]) #' identical(reg1,reg2[,1]) #' identical(dat2[,1],reg2[,1]) #' @export regrMultBy1or2point <- function(inDat,refLst,regrTo=c(1,0.5),silent=FALSE,callFrom=NULL){ fxNa <- .composeCallName(callFrom,newNa="regrMultBy1or2point") checkEntr <- .checkRegrArguments(inDat,refLst,regrTo) refLst <- checkEntr$refLst; regrTo <- checkEntr$regrTo contrAve <- sapply(lapply(refLst,function(x) as.matrix(inDat[x,])),colMeans,na.rm=TRUE) if(is.null(dim(contrAve))) contrAve <- matrix(contrAve,ncol=length(contrAve)) normFact <- if(length(refLst) ==1) (regrTo[1]/contrAve[,1]) else (regrTo[2]-regrTo[1])/(contrAve[,2]-contrAve[,1]) normFact <- cbind(k=normFact, d= if(length(refLst) ==1) rep(0,ncol(inDat)) else regrTo[1]-normFact*contrAve[,1]) matrix(rep(normFact[,1],each=nrow(inDat)),nrow=nrow(inDat))*inDat + matrix(rep(normFact[,2],each=nrow(inDat)),nrow=nrow(inDat)) }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/regrMultBy1or2point.R
#' Rename columns #' #' This function renames columns of 'refMatr' using 2-column matrix (or data.frame) indicating old and new names (for replacement). #' #' @param refMatr matrix (or data.frame) where column-names should be changed #' @param newName (matrix of character) giving correspondence of old to new names (number of lines must match number of columns of 'refMatr') #' @param silent (logical) suppres messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allows easier tracking of messages produced #' @return This function returns a matrix (or data.frame) with renamed columns #' @examples #' ma <- matrix(1:8,ncol=4,dimnames=list(1:2,LETTERS[1:4])) #' replBy1 <- cbind(new=c("dd","bb","z_"),old=c("D","B","zz")) #' replBy2 <- matrix(c("D","B","zz","dd","bb","z_"),ncol=2) #' replBy3 <- matrix(c("X","Y","zz","xx","yy","z_"),ncol=2) #' renameColumns(ma,replBy1) #' renameColumns(ma,replBy2) #' renameColumns(ma,replBy3) #' @export renameColumns <- function(refMatr, newName, silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="renameColumns") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(length(dim(refMatr)) <2) stop("Expecting matrix or data.frame") msg <- "Expecting matrix with 2 cols ('old','new')" if(length(dim(newName)) !=2) stop(msg) else if(ncol(newName) <2) stop(msg) if(is.null(colnames(newName))) { colNe <- 1:2 } else { colNe <- match(c("old","new"),colnames(newName)) if(debug) message(fxNa," colNe ini ",colNe) if(is.na(colNe[1])) colNe[1] <- (1:ncol(newName))[if(is.na(colNe[2])) -2 else -1*colNe[2]][1] if(is.na(colNe[2])) colNe[2] <- (1:ncol(newName))[-1*colNe[1]][1] } newName <- newName[,colNe] replLi <- naOmit(match(colnames(refMatr), newName[,1])) if(length(replLi) <1) { if(!silent) message(fxNa,"No names matching for replacing dat, nothing to do !") } else { colnames(refMatr)[match(newName[replLi,1], colnames(refMatr))] <- newName[replLi,2] } refMatr } #' Remove all columns where all data are not finite #' #' This function aims to remove all columns where all data are not finite #' #' #' @param dat (matrix or data.frame) main input #' @param msgStart (character) #' @param silent (logical) suppres messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allows easier tracking of messages produced #' @return This function returns a corrected matrix or data.frame #' @seealso \code{\link{renameColumns}}; \code{\link[base]{is.finite}} #' @examples #' ma1 <- matrix(c(1:5, Inf), ncol=2) #' .keepFiniteCol(ma1) #' #' @export .keepFiniteCol <- function(dat, msgStart=NULL, silent=FALSE, debug=FALSE, callFrom=NULL){ ## remove all columns where all data are not finite fxNa <- .composeCallName(callFrom, newNa=".keepFiniteCol") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE tmp <- colSums(is.finite(dat)) if(any(tmp <1)) { if(!silent) message(fxNa," removing ",sum(tmp <1)," columns without valid (finite) numbers") chC <- tmp >0 dat <- if(sum(chC) ==1) matrix(dat[,which(chC)], ncol=1, dimnames=list(rownames(dat),colnames(dat[chC]))) else dat[,which(chC)]} dat } #' Search for (empty) columns conaining only entries defined in 'searchFields' and remove such columns #' #' This function aims to search for (empty) columns conaining only entries defined in 'searchFields' and remove such columns. #' If 'fromBackOnly' =TRUE .. only tailing empty columns will be removed (other columns with "empty" entries in middle will be kept). #' If ''=TRUE columns containing all NAs will be excluded as well #' This function will also remove columns containing (exculsively) mixtures of the various 'searchFields'. #' #' @param dat (matrix or data.frame) main input #' @param fromBackOnly (logical) #' @param searchFields (character) #' @param silent (logical) suppres messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allows easier tracking of messages produced #' @return This function returns a corrected matrix or data.frame #' @seealso \code{\link{renameColumns}}; \code{\link[base]{is.finite}} #' @examples #' ma1 <- matrix(c(1:5, NA), ncol=2) #' .removeEmptyCol(ma1) #' @export .removeEmptyCol <- function(dat, fromBackOnly=TRUE, searchFields=c(""," ","NA.",NA), silent=FALSE, debug=FALSE, callFrom=NULL){ ## search for (empty) columns conaining only entries defined in 'searchFields' and remove such columns ## if 'fromBackOnly' =TRUE .. only tailing empty columns will be removed (other columns with "empty" entries in middle will be kept) ## if ''=TRUE columns containing all NAs will be excluded as well ## will also remove columns containing (exculsively) mixtures of the various 'searchFields' fxNa <- .composeCallName(callFrom,newNa=".removeEmptyCol") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(length(dim(dat)) <1) dat <- matrix(dat,ncol=1,dimnames=list(names(dat),NULL)) iniDimNa <- dimnames(dat) isEmpty <- which(apply(dat, 2, function(x) sum(x %in% searchFields) ==length(x))) if(fromBackOnly && length(isEmpty) >0) { isEmpty <- if(max(isEmpty) != ncol(dat)) NULL else { if(length(isEmpty) >1) .breakInSer(isEmpty) else isEmpty } } if(length(isEmpty) >1) { dat <- .removeCol(dat,isEmpty) if(!silent) message(fxNa,"Columns no ",paste(isEmpty,collapse=", ")," were considered empty and removed") } dat }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/renameColumns.R
#' Reorganize matrix according to clustering-output #' #' Reorganize input matrix as sorted by cluster numbers (and geometric mean) according to vector with cluster names, and index for sorting per cluster and per geometric mean. #' In case \code{mat} is an array, the 3rd dimension will be considered as 'column' with arguments \code{useColumn} ( and \code{cluNo}, if it designs a 'column' of mat). #' #' #' @param mat (matrix or data.frame) main input #' @param cluNo (positive integer, length to match nrow(dat) initial cluster numbers for each line of 'mat' (obtained by separate clustering or other segmentation) or may desinn column of \code{mat} to use as cluster-numbers #' @param useColumn (character or integer) the columns to use from \code{mat} as main data (default will use all, exept \code{cluCol} and/or \code{meanCol} if they design columns)) #' @param meanCol (character or integer) alternative summarizing data for intra-cluster sorting (instead of geometric mean) #' @param addInfo (logical) allows adding of columns 'index', 'geoMean' and 'cluNo' (or array if \code{FALSE}) #' @param retList (logical) return as list of matrixes (or array if \code{FALSE}) #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of messages produced #' @param debug (logical) additional messages for debugging #' @return This function returns a list or array (as 2- or 3 dim) with possible number of occurances for each of the 3 elements in nMax. Read results vertical : out[[1]] or out[,,1] .. (multiplicative) table for 1st element of nMax; out[,,2] .. for 2nd #' @seealso pairwise combinations \code{\link[utils]{combn}}, clustering \code{\link[stats]{kmeans}} #' @examples #' dat1 <- matrix(round(runif(24),2), ncol=3, dimnames=list(NULL,letters[1:3])) #' clu <- stats::kmeans(dat1, 5)$cluster #' reorgByCluNo(dat1, clu) #' #' dat2 <- cbind(dat1, clu=clu) #' reorgByCluNo(dat2, "clu") #' @export reorgByCluNo <- function(mat, cluNo, useColumn=NULL, meanCol=NULL, addInfo=TRUE, retList=FALSE, silent=FALSE, callFrom=NULL, debug=FALSE) { ## reorganize input matrix as sorted by cluster numbers (and geometric mean) according to vector with cluster names, and index for sorting per cluster and per geometric mean fxNa <- .composeCallName(callFrom, newNa="reorgByCluNo") iniCla <- inherits(mat, "data.frame") chDim <- dim(mat) dataOK <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(!isTRUE(silent)) silent <- FALSE if(length(chDim) >1) if(all(chDim >1)) dataOK <- TRUE ## extract cluNo if(dataOK & length(cluNo)==1) { cluN <- if(is.character(cluNo)) which(dimnames(mat)[[length(chDim)]]==cluNo) else cluNo if(length(chDim) ==3) { cluNo <- mat[,1,cluN]; mat <- mat[,,-cluN] } else { cluNo <- mat[,cluN]; mat <- mat[,-cluN] } } if(dataOK) if(length(cluNo) != nrow(mat)) dataOK <- FALSE ## extract meanCol if(dataOK & length(meanCol)==1) { meanC <- if(is.character(meanCol)) which(dimnames(mat)[[length(chDim)]]==meanCol) else meanCol if(length(chDim) ==3) { meanCol <- mat[,1,meanC]; mat <- mat[,,-meanC] } else { meanCol <- mat[,meanC]; mat <- mat[,-meanC] } } if(dataOK & length(meanCol) >0) {if(length(meanCol) != nrow(mat)) dataOK <- FALSE } if(debug) {message(fxNa,"rbc1")} ## main if(dataOK){ if(length(useColumn) <1) useColumn <- 1:ncol(mat) mat1 <- if(length(chDim) ==3) mat[,,useColumn] else mat[,useColumn] if(length(dim(mat1)) <1) mat1 <- matrix(mat1, ncol=1, dimnames=list(rownames(mat1), colnames(mat)[useColumn])) nClu <- length(unique(naOmit(cluNo))) if(!isFALSE(addInfo)) { ## construct geometric mean for sorting (if not provided externally) geoMe <- if(length(meanCol)==nrow(mat)) meanCol else apply(mat1, 1, function(x) prod(x,na.rm=TRUE)^(1/sum(!is.na(x)))) if(length(dim(geoMe)) >1) geoM <- rowMeans(geoMe, na.rm=TRUE) if(debug) {message(fxNa,"rbc2")} ## assemble main data mat1 <- cbind(mat1, index=1:nrow(mat), geoMean=geoMe) ## 1: split in list, determine clu median, overall score & sort clusters cluL <- by(mat1, cluNo, as.matrix) clTab <- table(cluNo) if(length(clTab) < max(cluNo) & !silent) message(fxNa," Note: Some cluster-names seem to be absent (no-consecutive numbers for names) !") ## need to correct when single occurance if(any(clTab ==1)) for(i in which(clTab ==1)) cluL[[i]] <- matrix(cluL[[i]], nrow=1, dimnames=list(rownames(mat1)[which(cluNo==i)], colnames(mat1))) if(debug) {message(fxNa,"rbc3")} ## sort intra cluL <- lapply(cluL, function(x) if(nrow(x) >1) x[order(x[,ncol(x)], decreasing=TRUE),] else x) ## sort inter cluL <- cluL[order(sapply(cluL, function(x) stats::median(x[,ncol(x)], na.rm=TRUE)), decreasing=TRUE)] names(cluL) <- 1:length(cluL) nByClu <- sapply(cluL, nrow) } else { fOrg <- if(is.data.frame(mat1)) as.data.frame else as.matrix cluL <- by(mat1, cluNo, fOrg) } if(debug) {message(fxNa,"rbc4"); rbc4 <- list(mat=mat,cluNo=cluNo,cluL=cluL,nByClu=nByClu,clTab=clTab,geoMe=geoMe,nClu=nClu)} if(isTRUE(retList)) { out <- cluL for(i in 1:nClu) out[[i]] <- if(!isFALSE(addInfo)) cbind(out[[i]][,-1], cluNo=i) else out[[i]][,-1] if(iniCla) out <- lapply(out, convMatr2df, addIniNa=FALSE, silent=silent, callFrom=fxNa) } else { if(debug) {message(fxNa,"rbc5")} out <- lrbind(cluL, silent=silent, callFrom=fxNa) if(!isFALSE(addInfo)) out <- cbind(out, cluNo=rep(1:nClu, nByClu)) } } else {out <- NULL; if(!silent) message(fxNa," invalid input, returning NULL")} out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/reorgByCluNo.R
#' Replace NAs by low values #' #' With several screening techniques used in hight-throughput biology values at/below detection limit are returned as \code{NA}. #' However, the resultant \code{NA}-values may be difficult to analyse properly, simply ignoring \code{NA}-values mat not be a good choice. #' When (technical) replicate measurements are available, one can look for cases where one gave an \code{NA} while the other did not #' with the aim of investigating such 'NA-neighbours'. #' \code{replNAbyLow} locates and replaces \code{NA} values by (random) values from same line & same group 'grp'. #' The origin of NAs should be predominantly absence of measure (quantitation) due to signal below limit of detection #' and not saturation at upper detection limit or other technical problems. #' Note, this approach may be not optimal if the number of NA-neighbours is very low. #' Replacamet is done -depending on agrument 'unif'- by Gaussian random model based on neighbour values (within same group), #' using their means and sd, or a uniform random model (min and max of neighbour values) . #' Then numeric matrix (same dim as 'x') with \code{NA} replaced is returned. #' #' @param x (numeric matrix or data.frame) main input #' @param grp (factor) to organize replicate columns of (x) #' @param quant (numeric) quantile form 'neighbour' values to use as upper limit for random values #' @param signific number of signif digits for random values #' @param unif (logical) toggle between uniform and Gaussian random values #' @param absOnly (logical) if TRUE, make negative NA-replacment values positive as absolute values #' @param seed (integer) for use with set.seed for reproducible output #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of message(s) produced #' @return numeric matrix (same dim as 'x') with \code{NA} replaced #' @seealso \code{\link{naOmit}}, \code{\link[stats]{na.fail}} #' @examples #' dat <- matrix(round(rnorm(30),2),ncol=6); grD <- gl(2,3) #' dat[sort(sample(1:30,9,repl=FALSE))] <- NA #' dat; replNAbyLow(dat,gr=grD) #' @export replNAbyLow <- function(x,grp,quant=0.8,signific=3,unif=TRUE,absOnly=FALSE,seed=NULL,silent=FALSE,callFrom=NULL){ fxNa <- .composeCallName(callFrom,newNa="replNAbyLow") if(length(dim(x))<2) stop("expecting matrix or data.frameas 'x'") if(is.data.frame(x)) x <- as.matrix(x) if(length(grp) != ncol(x)) stop(" 'grp' does NOT match number of columns in 'x'") nNA <- sum(is.na(x)) if(nNA >0){ lowVa <- unlist(apply(x,1,.extrNAneighb,grp)) # all low values with NA in same grp if(length(lowVa) <1) { lowVa <- sort(as.numeric(x))[1:round(sqrt(length(x)))] if(!silent) message(fxNa,"no values within lines of NA groups, use all observations")} lowVa <- lowVa[which(lowVa < stats::quantile(lowVa,quant))] nEstim <- ceiling(nNA*1.2)+5 if(!silent) message(fxNa,"random model as ",if(unif) c("uniform ",signif(min(lowVa),signific)," to ", signif(max(lowVa),signific)) else c("Gaussian mean=",signif(mean(lowVa),signific),sd=signif(stats::sd(lowVa),signific))) if(!is.null(seed)) {if(is.numeric(seed)) set.seed(round(seed[1])) else message(fxNa,"ignoring invalid 'seed'")} raVa <- if(unif) signif(stats::rnorm(nEstim,mean(lowVa),stats::sd(lowVa)),digits=signific) else { signif(stats::runif(nEstim,min(lowVa),max(lowVa)),digits=signific)} if(absOnly & any(raVa <0)) {message(fxNa," force ",sum(raVa <0)," to positive"); raVa <- abs(raVa)} tmp <- unique(raVa) raVa <- if(length(tmp) > nNA) unique(raVa)[1:nNA] else raVa[1:nNA] # avoid identical values x[which(is.na(x))] <- raVa } x }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/replNAbyLow.R
#' CV of replicate plates (list of matrixes) #' #' \code{replPlateCV} gets CVs of replicates from list of 2 or 3-dim arrays (where 2nd dim is replicates, 3rd dim may be channel). #' Note : all list-elements of must MUST have SAME dimensions ! #' When treating data from microtiter plates (eg 8x12) data are typically spread over multiple plates, ie initial matrixes that are the organized into arrays. #' Returns matrix or array (1st dim is intraplate-position, 2nd .. plate-group/type, 3rd .. channels) #' @param lst list of matrixes : suppose lines are independent elements, colums are replicates of the 1st column. All matrixes must have same dimensions #' @param callFrom (character) allows easier tracking of messages produced #' @return matrix or array (1st dim is intraplate-position, 2nd .. plate-group/type, 3rd .. channels) #' @seealso \code{\link{rowCVs}}, @seealso \code{\link{arrayCV}} #' @examples #' set.seed(2016); ra1 <- matrix(rnorm(3*96),nrow=8) #' pla1 <- list(ra1[,1:12],ra1[,13:24],ra1[,25:36]) #' replPlateCV(pla1) #' arrL1 <- list(a=array(as.numeric(ra1)[1:192],dim=c(8,12,2)), #' b=array(as.numeric(ra1)[97:288],dim=c(8,12,2))) #' replPlateCV(arrL1) #' @export replPlateCV <- function(lst,callFrom=NULL) { fxNa <- .composeCallName(callFrom,newNa="replPlateCV") chDim <- sapply(lst,dim) msg <- "ALL list-elements of must MUST have SAME dimensions" if(is.matrix(chDim)) {if(any(apply(chDim,1,function(x) length(unique(x))>1))) stop(msg)} else stop(msg) if(length(dim(lst[[1]])) >2){ out <- matrix(sapply(lst,arrayCV),nrow=nrow(lst[[1]])) tmp <- 1:(ncol(out)/2) out <- out[,c((2*tmp-1),2*tmp)] out <- array(out,dim=c(nrow(lst[[1]]),length(lst),dim(lst[[1]])[3]),dimnames=list( rownames(lst[[1]]),names(lst),dimnames(lst[[1]])[[3]])) } else { out <- matrix(sapply(lst,arrayCV),nrow=nrow(lst[[1]]), dimnames=list( rownames(lst[[1]]),names(lst))) } out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/replPlateCV.R
#' Search and Select Groups of Replicates #' #' This function was designed for mining annotation information organized in multiple columns to identify the (potential) grouping of multiple samples, ie to determine factor levels. #' The argument \code{method} allows further finetuning if high or low number of groups should be preferred, if multiple columns may be combined, or to choose a particular custom column for desiganting factor levels. #' #' #' @details #' Statistical tests require specifying which samples should be considered as replicates of whom. #' In some cases, like the Sdrf-format, automatic mining of such annotation to indentify an experiment's underlying structure of replicates #' may be challanging, since the key information may not always be found in the same column. #' For this reason this function allows inspecting all columns of a matrix of data.frame to identify which colmns may serve describing groups of replicates. #' #' The argument \code{exclNoRepl=TRUE} allows excluding all columns with different content for each line (like line-numbers), ie information without any replicates. #' It is set by default to \code{TRUE} to exclude such columns, since statistical tests usually do require some replicates. #' #' When using as \code{method="combAll"}, there is risk all lines (samples) will be be considered different and no replicates remain. #' To avoid this situation the argument can be set to \code{method="combNonOrth"}. #' Using this mode it will be checked if adding more columns will lead to complete loss of replicates, and -if so- concerned columns omitted. #' #' #' #' @param x (matrix or data.frame) the annotation to inspect; each column is supposed to describe another set of annoation/metadata for the rows of \code{x} (min 1 row and 1 column), #' @param method (character, length=1) the procedure to choose column(s) with properties of information, may be \code{highest} or \code{max} (max number of levels) #' \code{lowest} or \code{min} (min number of levels), \code{median} (median of all options for number of levels), #' \code{combAll} (combine all columns of \code{x}) or \code{combNonOrth} (combine only non-orthogonal columns of \code{x}, to avoid avoid n lines with n levels); #' lazy evluation of the argument is possible #' @param sep (character) separator used when a method combining multiple columns (eg combAll, combNonOrth) is chosen (should not appear anywhere in \code{x}) #' @param exclNoRepl (logical) decide whether columns with all values different (ie no replicates or max divergency) should be excluded #' @param trimNames (logical) optional trimming of names in \code{x} by removing redundant heading and tailing text #' @param includeOther (logical) include $allCols with pattern of (all) other columns #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a list with $col (column index relativ to \code{x}), $lev (abstract labels of level), #' $meth (note of method finally used) and $allCols with general replicate structure of all columns of \code{x} #' @seealso \code{\link[base]{duplicated}}, uses \code{\link{trimRedundText}} #' @examples #' ## 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") #' replicateStructure(strX, method=3, includeOther=TRUE) # custom choice of 3rd column #' #' #' #' @export replicateStructure <- function(x, method="median", sep="__", exclNoRepl=TRUE, trimNames=FALSE, includeOther=FALSE, silent=FALSE, callFrom=NULL, debug=FALSE) { ## fxNa <- .composeCallName(callFrom, newNa="replicateStructure") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE out <- ou3 <- str1 <- NULL # initialize datOK <- all(length(x) >0 & length(dim(x)) >0) if(debug) message(fxNa,"ini datOK ",datOK) ## check for unique colnames if(datOK) { chMe <- TRUE if(length(method) <1) { chMe <- FALSE; method <- "median"} else if(length(method) >1) method <- method[1] if(is.na(method)) { chMe <- FALSE; method <- "median" } if(!chMe && !silent) message(fxNa, "Invalid entry for 'method', setting to default, ie 'median'") iniColNa <- colnames(x) chColN <- duplicated(colnames(x), fromLast=FALSE) if(any(chColN)) { if(!silent) message(fxNa,"Need to correct redundant colnames !!!")} } else if(!silent) message(fxNa,"Invalid entry for 'x' .. should be matrix or data.frame (min 1 row, 1 column) .. returning NULL") ## single available/given .. shortcut if(datOK) { if(any(dim(x) ==1)) { datOK <- FALSE if(debug) message(fxNa,"Single column or single line available/relevant .. shortcut") if(nrow(x) ==1) { out <- list(col=1, lev=1, meth="single row") if(!silent) message(fxNa,"Note : Only single line with levels, ie single group wo any replicates") } else { nn <- match(as.character(x), unique(as.character(x))) names(nn) <- if(ncol(x)==1) x[,1] else x[1,] coln <- 1 names(coln) <- colnames(x) out <- list(col=coln, lev=nn, meth="single informative") } } } ## check argument 'method' : check for costom choice of column if(datOK && length(out) <1 && grepl("^[[:digit:]]+$", method)) { colNo <- as.integer(method) out <- list(col=colNo, lev=match(x[,colNo], unique(x[,colNo])), meth="custom column") } if(debug) {message(fxNa,"fd0"); fd0 <- list(x=x,method=method,sep=sep,exclNoRepl=exclNoRepl,datOK=datOK,out=out)} ## check argument 'method' if(datOK && length(out) <1) { methOpt <- c("highest","lowest","min","median","combAll","combNonOrth") msg <- c(" 'method' should designate one of the following options ",pasteC(methOpt,quoteC="'"),"; setting to default") if(identical(method,"min")) method <- "lowest" if(identical(method,"max")) method <- "highest" if(length(method) <1) { method <- "median" warning(fxNa,"Argument 'method' seems empty !",msg)} chNa <- is.na(method) if(any(chNa)) { method <- "median" warning(fxNa,"Argument 'method' may not contain NA !",msg)} if(length(method) >1) { method <- method[1] if(!silent) message(fxNa,"Argument 'method' should be of length=1, using first")} chMeth <- pmatch(method, methOpt) chMe2 <- any(is.na(chMeth)) if(chMe2) { method <- "median"; chMeth <- 3 warning(fxNa,"Unable to match argument 'method' to any of the options ",pasteC(methOpt,quoteC="'"),msg)} method <- methOpt[chMeth] ## check separator if(length(sep) != 1) { sep <- "__" warning(fxNa," Argument 'sep' must be character and of length =1; resetting to default")} if(nchar(sep) <1) { sep <- "__" warning(fxNa," Argument sep=\"\" may lead to incorrect comparisons, resetting to default")} chSep <- grep(sep, x) if(length(chSep) >0) warning(fxNa," BEWARE, the annotation data do contain ",length(chSep)," instances of '", sep,"' ! The results of combined searches may be incorrect. Please consider using a different separator") ## if(debug) {message(fxNa,"fd1"); fd1 <- list(x=x,ou3=ou3,method=method,sep=sep,exclNoRepl=exclNoRepl,datOK=datOK,out=out)} ## utility functions chStru <- function(y, debug) { # check duplication structure of vector dup <- duplicated(y) out <- -1 if(sum(dup) <1) out <- if(isTRUE(exclNoRepl)) 0 else 1:length(y) # all unique if(sum(dup) == length(y) -1) out <- 1 # all duplic if(any(out < 0)) out <- match(y, unique(y)) if(debug) message(fxNa," -> chStru : ",pasteC(out)) out } fMin <- function(y, ref=y) { coln <- which.min(apply(y, 2, max, na.rm=TRUE)); if(debug) {message(fxNa," -> fMin colnames y", colnames(y),"\n"); fMi <- list(y=y,coln=coln, ref=ref)} refn <- if(identical(y, ref)) coln else which(colnames(y)[coln]==colnames(ref)) nn <- y[,coln]; names(nn) <- ref[,refn]; names(refn) <- colnames(y)[coln] list(col=refn, lev=nn, meth="single min col")} fMax <- function(y, ref=y) { coln <- which.max(apply(y, 2, max, na.rm=TRUE)); if(debug) {message(fxNa," -> fMax colnames y", colnames(y),"\n"); fMa <- list(y=y,coln=coln, ref=ref)} refn <- if(identical(y, ref)) coln else which(colnames(y)[coln]==colnames(ref)) nn <- y[,coln]; names(nn) <- ref[,refn]; names(refn) <- colnames(y)[coln] list(col=refn, lev=nn, meth="single max col")} fMed <- function(y, ref=y) { zz <- apply(y, 2, max, na.rm=TRUE); coln <- which(zz==stats::median(if((ncol(y) %% 2) ==0) c(zz[1],zz) else zz))[1]; if(debug) {message(fxNa," -> fMed colnames y", colnames(y),"\n"); fMe <- list(y=y,zz=zz,coln=coln, ref=ref)} refn <- if(identical(y, ref)) coln else which(colnames(y)[coln]==colnames(ref)) names(refn) <- colnames(y)[coln] nn <- y[,coln]; names(nn) <- ref[,refn] list(col=refn, lev=nn, meth="single median col")} fCombAll <- function(y, ref=y) { # uses debug refn <- if(identical(y, ref)) 1:ncol(y) else match(colnames(y), colnames(ref)) names(refn) <- colnames(y) tm <- if(ncol(y)==2) paste(y[,1],y[,2]) else apply(y, 1, paste, collapse=" "); nn <- match(tm, unique(tm)) if(debug) {message(fxNa," -> fCombAll"); fComb <- list(y=y,ref=ref,refn=refn,tm=tm,nn=nn)} names(nn) <- if(ncol(y)==1) ref[,refn] else apply(ref[,refn], 1, paste0, collapse="_") list(col=refn, lev=nn, meth="comb all col") } fComNonOrth <- function(y, oup="min", ref=y) { if(debug) message(fxNa," -> fComNonOrth") tm <- if(ncol(y)==2) as.matrix(paste(y[,1], y[,2])) else { if(ncol(y)==3) cbind(paste(y[,1],y[,2]), paste(y[,1],y[,3])) else apply(y[,-1], 2, paste,y[,1])} # pairwise groups/combin st2 <- as.matrix(apply(tm, 2, function(z) match(z, unique(z)))) # levels of pairwise combin colnames(st2) <- paste(colnames(y)[1], colnames(y)[2:ncol(y)], sep=sep) maxL <- apply(st2, 2, max) if(debug) {message(fxNa," -> fComNonOrt"); fComNonOrt <- list(y=y,oup=oup,tm=tm, st2=st2,maxL=maxL,x=x)} if(any(maxL ==nrow(y))) {useCo <- which(maxL < nrow(y)); st2 <- matrix(st2[,useCo], ncol=length(useCo), dimnames=list(rownames(st2), colnames(st2)[useCo]))} if(length(st2) >0) { if(TRUE) {maxP <- which.max(apply(st2, 2, max)); coln <- which(colnames(y) %in% unlist(strsplit(names(maxP), split=sep))) refn <- if(identical(y, ref)) coln else match(colnames(y)[coln], colnames(ref)) names(refn) <- colnames(y)[coln] nn <- st2[,maxP]; names(nn) <- if(length(refn)==1) ref[,refn] else { if(length(refn)==2) paste(ref[,refn[1]],ref[,refn[2]],sep="_") else apply(ref[,refn], 1, paste0, collapse="_")} out <- list(col=refn, lev=nn, meth="combNonOrth col" )} } else out <- fMax(y) out } ## get generalized pattern of replicates str1 <- apply(x, 2, chStru, debug=debug) chStr <- if(is.matrix(str1)) rep(nrow(str1) <nrow(x), ncol(x)) else {sapply(str1, length) < nrow(x)} ## develop more to recuperate replicates after enumerarators ? if(debug) {message(fxNa,"fd2"); fd2 <- list(x=x,method=method,ou3=ou3,str1=str1,sep=sep,exclNoRepl=exclNoRepl,datOK=datOK)} if(all(chStr)) { if(exclNoRepl) { if(debug) message(fxNa,"None of the columns have any replicates, setting exclNoRepl=FALSE") exclNoRepl <- FALSE str1 <- apply(x, 2, chStru, debug=debug) chStr <- sapply(str1, length) < nrow(x) } else warning(fxNa,"Can't find replicates for any of the columns !! ") } if(debug) {message(fxNa,"fd3"); fd3 <- list(x=x,method=method,ou3=ou3,str1=str1,sep=sep,exclNoRepl=exclNoRepl,datOK=datOK,chStr=chStr)} ## had removing all replicated instances, but this will create list if str1 is matrix with uneven number of replicates per column ! if(length(dim(str1)) <1 & any(chStr, na.rm=TRUE) & !all(chStr, na.rm=TRUE)) str1 <- str1[which(!chStr)] if(is.list(str1)) str1 <- as.matrix(as.data.frame(str1)) if(length(dim(str1)) <2 & length(str1) >0) str1 <- matrix(unlist(str1), ncol=ncol(x), dimnames=dimnames(x)) if(debug) {message(fxNa,"fd4"); fd4 <- list(x=x,method=method,ou3=ou3,str1=str1,sep=sep,exclNoRepl=exclNoRepl,datOK=datOK,chStr=chStr)} if(!isTRUE(exclNoRepl)) { ## check if single col at max levels may serve as shortcut chMax <- sapply(str1, max, na.rm=TRUE) ==nrow(x) if(any(chMax)) { datOK <- FALSE coln <- which.min(chMax) names(coln) <- colnames(str1)[coln] nn <- 1:nrow(x) names(nn) <- str1[,coln] out <- list(col=coln, lev=nn, meth="(shortcut, first) single col at max divergence", allCols=str1) } } } if(datOK && length(str1) >0) { ## remove non-useful, obtain matrix of indexes if(is.list(str1)) { chLe <- sapply(str1, length) if(any(chLe) <2) if(sum(duplicated(chLe[which(chLe >1)])) == sum(chLe >1) -1) { ou3 <- as.matrix(as.data.frame(str1[which(chLe >1)])) # all remaining of same length } else { ou3 <- NULL; message(fxNa,"Trouble ahead ? Different length when trying to extract patterns") # } } else { ou3 <- if(length(dim(str1)) >1) str1 else NULL } if(length(ou3) >0) { # now look for replicates of these patterns (paste-collapse series internal) & remove redundant columns (keep 1st instance from left) tm2 <- apply(ou3, 2, paste0, collapse="") chDu <- duplicated(tm2, fromLast=FALSE) if(any(chDu)) {tm2 <- tm2[which(!chDu)]; ou3 <- matrix(ou3[,which(!chDu)], nrow=nrow(x), dimnames=list(NULL,colnames(ou3)[which(!chDu)]))} if(debug) {message(fxNa,"fd5 .."); fd5 <- list(x=x,method=method,out=out,ou3=ou3,tm2=tm2,str1=str1,chDu=chDu,sep=sep,exclNoRepl=exclNoRepl)} out <- if(ncol(ou3) <2) { if(debug) message(fxNa," single column for choice ..") co <- which(colnames(x) ==colnames(ou3)) names(co) <- colnames(ou3) nn <- as.integer(ou3) names(nn) <- x[,co] list(col=co, lev=nn, meth="single informative col") } else switch(method, ## return column index highest =fMax(ou3, ref=x), lowest =fMin(ou3, ref=x), median =fMed(ou3, ref=x), combAll=fCombAll(ou3, ref=x), combNonOrth=fComNonOrth(ou3, ref=x) ) } if(debug) {message(fxNa,"fd6"); fd6 <- list(x=x,method=method,out=out,ou3=ou3,tm2=tm2,str1=str1,chDu=chDu,sep=sep,exclNoRepl=exclNoRepl)} } ## optional include all patterns if(datOK && length(out) >0 && isTRUE(includeOther) && !"allCols" %in% names(out)) out$allCols <- apply(x, 2, function(y) match(y, unique(y))) ## optional trim names to ou3$lev if(datOK && length(out) >0 && isTRUE(trimNames)) names(out$lev) <- trimRedundText(names(out$lev), spaceElim=TRUE, silent=silent, callFrom=fxNa, debug=debug) out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/replicateStructure.R
#' Remove lines of matrix redundant /duplicated for 1st and 2nd column #' #' \code{rmDupl2colMatr} removes lines of matrix that are redundant /duplicated for 1st and 2nd column (irrespective of content of their columns). #' The first occurance of redundant /duplicated elements is kept. #' #' @param mat (matrix or data.frame) main input #' @param useCol (integer, length=2) columns to consider/use when looking for duplicated entries #' @return matrix with duplictaed lines removed #' @seealso \code{\link[base]{unlist}} #' @examples #' mat <- matrix(1:12,ncol=3) #' mat[3,1:2] <- mat[1,1:2] #' rmDupl2colMatr(mat) #' @export rmDupl2colMatr <- function(mat,useCol=c(1,2)) { ## remove entries with same value in 1st & 2nd col of mat msg <- " 'mat' should be matrix with at least 2 columns" if(length(dim(mat)) <2) stop(msg) else if(ncol(mat) <2) stop(msg) tx <- paste(mat[,useCol[1]],mat[,useCol[2]],sep="_") dup <- duplicated(tx,fromLast=FALSE) if(any(dup)) {if(sum(!dup)==1) matrix(mat[which(!dup),],dimnames=list(rownames(mat)[which(!dup)],colnames(mat))) else mat[which(!dup),]} else mat }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rmDupl2colMatr.R
#' Remove or rename enumerator tag/name (or remove entire enumerator) from tailing enumerators #' #' @description #' This function allows indentifying, removing or renaming enumerator tag/name (or remove entire enumerator) from tailing enumerators (eg 'abc_No1' to 'abc_1'). #' A panel of potential candidates as combination of separator-symbols and separtor text/words will be tested to find if one matches all data. #' In case the main input is a matrix, all columns will be tested independently to find the first column where one specific combination of separator-symbols and separtor text/words is found. #' Several options exist for the output, the combination of separator-symbols and separtor text/words may be included, too. #' #' @details #' Please note, that checking a variety of different separator text-word and separator-symbols may give an important number of combinations to check. #' In particular, when automatic trimming of separator text-words is added (eg \code{incl="trim2"}), the complexity of associated searches increases quickly. #' Thus, with large data-sets restricting the content of the arguments \code{nameEnum}, \code{sepEnum} and (in particular) \code{newSep} to the most probable terms/options #' is suggested to help reducing demands on memory and CPU. #' #' In case the input \code{dat} is a matrix and multiple different numerator-types are found, only the first colum (from the left) will be treated. #' If you which to remove/subsitute mutiple types of enumerators the function \code{rmEnumeratorName} must be run independently, see last example below. #' #' @param dat (character vecor or matrix) main input #' @param nameEnum (character) potential enumerator-names #' @param sepEnum (character) potential separators for enumerator-names #' @param newSep (character) potential enumerator-names #' @param incl (character) options to include further variants of the enumerator-names, use \code{"rmEnum"} for completely removing enumerator tag/name and digits #' for differentr options of trimming names/tags from \code{nameEnum} one may use \code{anyCase}, \code{trim3} (trimming down to max 3 letters), #' \code{trim2} (trimming to max 2 letters) or \code{trim1} (trimming down to single letter); #' \code{trim0} works like \code{trim1} but also includes ' ', ie no enumerator tag/name in front of the digit(s) #' @param silent (logical) suppress messages #' @param debug (logical) display additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a corrected vector (or matrix), or a list if \code{incl="rmEnumL"} containing $dat (corrected data), #' $pattern (the combination of separator-symbols and separtor text/words found), and if input is matrix $column (which column of the input was identified and treated) #' @seealso when the exact pattern is known \code{\link[base]{grep}} and \code{sub} may allow direct manipulations much faster #' @examples #' xx <- c("hg_Re1","hjRe2_Re2","hk-Re3_Re33") #' rmEnumeratorName(xx) #' rmEnumeratorName(xx, newSep="--") #' rmEnumeratorName(xx, incl="anyCase") #' #' xy <- cbind(a=11:13, b=c("11#11","2_No2","333_samp333"), c=xx) #' rmEnumeratorName(xy) #' rmEnumeratorName(xy,incl=c("anyCase","trim2","rmEnumL")) #' #' xz <- cbind(a=11:13, b=c("23#11","4#2","567#333"), c=xx) #' apply(xz, 2, rmEnumeratorName, sepEnum=c("","_"), newSep="_", silent=TRUE) #' #' @export rmEnumeratorName <- function(dat, nameEnum=c("Number","No","#","Replicate","Sample"), sepEnum=c(" ","-","_"), newSep="", incl=c("anyCase","trim2"), silent=FALSE, debug=FALSE, callFrom=NULL) { ## remove or rename enumerator tag/name (or remove entire enumerator) from tailing enumerators (eg 'abc_No1' to 'abc_1'), only if found present in all instances ## dat (character voector or matrix) ## return character vector of same length as initial ## return-options : 1) repl/no EnumName 2) wo any enum, no digits 3) both fxNa <- .composeCallName(callFrom, newNa="rmEnumeratorName") if(isTRUE(debug)) silent <- FALSE if(!isTRUE(silent)) silent <- FALSE out <- dat datOK <- length(dat) >0 if(datOK) { ch1 <- if(length(dim(dat)) >0) colSums(!matrix(grepl("..[[:digit:]]+$", as.matrix(dat)), ncol=ncol(dat))) <1 else all(grepl("..[[:digit:]]+$", as.character(dat))) datOK <- any(ch1, na.rm=TRUE) useCol <- if(length(dim(dat)) >0) which(ch1) else NULL } if(length(nameEnum) >0) { nameEnum <- naOmit(nameEnum)} if(length(nameEnum) <1) { nameEnum <- c("Number","Replicate") if(!silent) message(fxNa,"Empty or Invalid entry for 'sepEnum', setting to default") } if(length(sepEnum) >0) { sepEnum <- naOmit(sepEnum) chDu <- duplicated(nameEnum) if(any(chDu)) nameEnum <- nameEnum[which(!chDu)] } if(length(sepEnum) <1) { sepEnum <- c(" ","-","_") if(!silent) message(fxNa,"Empty or Invalid entry for 'sepEnum', setting to default") } if(length(incl) <1) incl <- NA if(length(newSep) >0) { newSep <- naOmit(newSep)[1]} if(length(newSep) <1) { newSep <- "" if(!silent) message(fxNa,"Empty or Invalid entry for 'newSep', setting to default") } if(datOK) { ## prepare enumerator-patterns to test chDu <- duplicated(nameEnum) if(any(chDu)) nameEnum <- nameEnum[which(!chDu)] if("anyCase" %in% incl) nameEnum <- unique(c(nameEnum, tolower(nameEnum), toupper(nameEnum))) if("trim3" %in% incl) {tmp <- 3:max(nchar(nameEnum)); nameEnum <- unique(substring(rep(nameEnum, each=length(tmp)), 1, rep(3:max(nchar(nameEnum)), length(nameEnum)))) } else { if("trim2" %in% incl) {tmp <- 2:max(nchar(nameEnum)); nameEnum <- unique(substring(rep(nameEnum, each=length(tmp)), 1, rep(2:max(nchar(nameEnum)), length(nameEnum)))) } else { if("trim1" %in% incl || "trim0" %in% incl) {tmp <- 1:max(nchar(nameEnum)); nameEnum <- unique(substring(rep(nameEnum, each=length(tmp)), 1, rep(1:max(nchar(nameEnum)), length(nameEnum)))) }}} if("trim0" %in% incl) {nameEnum <- unique(c(nameEnum, "")) sepEnum <- unique(c(sepEnum, ""))} chDu <- duplicated(sepEnum) if(any(chDu)) sepEnum <- sepEnum[which(!chDu)] nameEnum <- paste0(rep(sepEnum, length(nameEnum)), rep(nameEnum, each=length(sepEnum)),"[[:digit:]]+$") if(debug) message(fxNa,"Ready to test ",length(nameEnum)," types of enumerators") ## main if(length(nameEnum) >1) nameEnum <- nameEnum[order(nchar(nameEnum), decreasing=TRUE)] # sort to prefer using longest version chEnum <- if(length(dim(dat)) ==2) apply(dat[,useCol], 2, function(y) sapply(nameEnum, function(x) all(grepl(x, y)))) else { sapply(nameEnum, function(x) all(grepl(x, dat)))} if(debug) {message(fxNa,"rEN0 .."); rEN0 <- list(dat=dat,out=out,nameEnum=nameEnum,newSep=newSep,sepEnum=sepEnum,chEnum=chEnum,newSep=newSep)} if(any(chEnum)) { nameEnumInd <- which(chEnum, arr.ind=length(dim(dat)) ==2) # each hit in new line if(debug) {message(fxNa,"rEN1 .."); rEN1 <- list(dat=dat,out=out,nameEnum=nameEnum,nameEnumInd=nameEnumInd,chEnum=chEnum,newSep=newSep)} if(length(dim(dat)) >0) { ## input is matrix usePat <- rownames(nameEnumInd)[1] # the (1st) pattern matching all input nameEnumInd <- nameEnumInd[1,] enu2 <- sub(usePat,"", dat[,useCol[nameEnumInd[2]]]) # wo nameEnumerator curSep <- sepEnum[1+ ((nameEnumInd[1] -1) %/% length(sepEnum))] if(debug) {message(fxNa,"rEN2"); rEN2 <- list()} out[,useCol[nameEnumInd[2]]] <- if(length(grep("^rmEnum", incl)) >0) enu2 else { paste0(enu2, if(length(newSep)==1) newSep else curSep, substr(dat[,useCol[nameEnumInd[2]]], nchar(enu2) +nchar(usePat) -12, max(nchar(dat[,useCol[nameEnumInd[2]]]))))} if(debug && any(grepl(".L$", incl))) message("Matched matrix via column '",useCol[nameEnumInd[2]],"'") if(any(grepl(".L$", incl))) out <- list(dat=out, column=useCol[nameEnumInd[2]], pattern=substr(usePat, 1, nchar(usePat) -13)) # optinal return as list including info which col was modified } else { ## input is vector if(length(nameEnumInd) >1) nameEnumInd <- nameEnumInd[1] usePat <- names(nameEnumInd) maxNch <- max(nchar(dat), na.rm=TRUE) enu2 <- sub(names(nameEnumInd),"", dat) # wo nameEnumerator curSep <- sepEnum[1+ ((nameEnumInd -1) %/% length(sepEnum))] if(length(grep("^rmEnum", incl)) >0) out <- enu2 else { out <- if(length(grep("^rmEnum", incl)) >0) enu2 else { paste0(enu2, if(length(newSep)==1) newSep else curSep, substr(dat, nchar(enu2) +nchar(usePat) -12, maxNch)) } } if("all" %in% incl) out <- cbind(ini=dat, new=out) if(debug && any(grepl(".L$", incl))) message(fxNa,"Matched vector") if(any(grepl(".L$", incl))) out <- list(dat=out, pattern=substr(usePat, 1, nchar(usePat) -13)) # optinal return as list including info which col was modified } } else if(!silent) message(fxNa,"No conistent enumerator+digit combination found; nothing to do ..") } else if(!silent) message(fxNa,"Invalid or empty input; nothing to do ..") out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rmEnumeratorName.R
#' Normal random number generation with close fit to expected mean and sd #' #' This function allows creating a vector of random values similar to \code{rnorm}, but resulting value get recorrected to fit to expected mean and sd. #' When the number of random values to generate is low, the mean and sd of the resultant values may deviate from the expected mean and sd when using the standard \code{rnorm} function. #' In such cases the function \code{rnormW} helps getting much closer to the expected mean and sd. #' #' @details #' For making result reproducible, a seed for generating random numbers can be set via the argument \code{seed}. #' However, with \code{n=2} the resulting values are 'fixed' since no random component is possible at n <3. #' #' @param n (integer, length=1) number of observations. If \code{length(n) > 1}, the length is taken to be the number required. #' @param mean (numeric, length=1) expected mean #' @param sd (numeric, length=1) expected sd #' @param seed (integer, length=1) seed for generating random numbers #' @param digits (integer, length=1 or \code{NULL}) number of significant digits for output, set to \code{NULL} to get all digits #' @param silent (logical) suppress messages #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a numeric vector of random values #' @seealso \code{\link[stats]{Normal}} #' @examples #' x1 <- (11:16)[-5] #' mean(x1); sd(x1) #' ## the standard way #' ra1 <- rnorm(n=length(x1), mean=mean(x1), sd=sd(x1)) #' ## typically the random values deviate (slightly) from expected mean and sd #' mean(ra1) -mean(x1) #' sd(ra1) -sd(x1) #' ## 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 #' @export rnormW <- function(n, mean=0, sd=1, seed=NULL, digits=8, silent=FALSE, callFrom=NULL) { ## reconstitute orginal values based on summary fxNa <- .composeCallName(callFrom, newNa="rnormW") if(!isTRUE(silent)) silent <- FALSE if(length(n) <1 | !is.numeric(n)) { out <- NULL; if(!silent) message(fxNa,"invalid 'n', returning NULL") } else { if(length(n) >1) n <- length(n) msg <- c("argument '","' must be positive numeric and of length=1") if(!is.numeric(mean)) mean <- try(as.numeric(mean)) if(length(mean) != 1 | inherits(mean, "try-error")) stop(msg[1],"mean",msg[2]) if(!is.numeric(sd)) sd <- try(as.numeric(sd)) ## main if(n==1) {out <- mean if(isFALSE(silent) & is.finite(sd)) message(fxNa,"Ignoring 'sd' since n=1") } else if(length(sd) != 1 | inherits(sd, "try-error")) stop(msg[1],"sd",msg[2]) if(n==2) out <- mean + c(-1,1)*sd/sqrt(2) if(n >2) { if(length(seed) ==1) try(set.seed(seed), silent=TRUE) out <- if(length(digits)==1 & is.finite(digits)) signif(stats::rnorm(n=n, mean=mean, sd=sd), digits) else stats::rnorm(n=n, mean=mean, sd=sd) out <- out - mean(out) # set meant to 0 out <- mean + out*sd/sd(out) # adjust sd and reset mean }} out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rnormW.R
#' rowCVs #' #' This function returns CV for values in each row (using speed optimized standard deviation). #' Note : NaN values get replaced by NA. #' @param dat (numeric) matix #' @param autoconvert (NULL or character) allows converting simple vectors in matrix of 1 row (autoconvert="row") #' @return This function returns a (numeric) vector with CVs for each row of 'dat' #' @seealso \code{\link[base]{colSums}}, \code{\link{rowGrpCV}}, \code{\link{rowSds}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200) +rep(1:10,20)),ncol=10) #' head(rowCVs(dat1)) #' @export rowCVs <- function(dat, autoconvert=NULL) { msg <- "Data should be matrix or data.frame with at least 2 columns !" if(is.data.frame(dat)) dat <- as.matrix(dat) if(is.null(ncol(dat))) { if(identical(autoconvert,"row")) dat <- matrix(dat,nrow=1)} if(is.null(ncol(dat))) stop(msg) else if(ncol(dat) < 2) stop(msg) out <- rowSds(dat)/base::rowMeans(dat,na.rm=TRUE) out[which(is.nan(out))] <- NA out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rowCVs.R
#' Row group CV #' #' This function calculates CVs for matrix with multiple groups of data, ie one CV for each group of data. #' Groups are specified as columns of 'x' in 'grp' (so length of grp should match number of columns of 'x', NAs are allowed) #' @param x numeric matrix where relplicates are organized into separate columns #' @param grp (factor) defining which columns should be grouped (considered as replicates) #' @param means (numeric) alternative values instead of means by .rowGrpMeans() #' @param listOutp (logical) if TRUE, provide output as list with $CV, $mean and $n #' @return This function returns a matrix of CV values #' @seealso \code{\link{rowCVs}}, \code{\link{arrayCV}}, \code{\link{replPlateCV}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)),ncol=10) #' head(rowGrpCV(dat1, gr=gl(4,3,labels=LETTERS[1:4])[2:11])) #' @export rowGrpCV <- function(x, grp, means=NULL, listOutp=FALSE){ if(!is.matrix(x) && !is.data.frame(x)) stop(" 'x' should be data.frame or matrix") if(length(dim(x)) !=2) stop(" 'x' should be data.frame or matrix of 2 dimensions") if(length(grp) != ncol(x)) stop(" 'grp' should be of length of number of cols in 'x'") if(length(grp) <1 || all(is.na(grp))) stop(" 'grp' appears to be empty or all NAs") if(!is.factor(grp)) grp <- as.factor(grp) if(is.null(means)) means <- .rowGrpMeans(x, grp) ## main out <- .rowGrpCV(x, grp, means) if(listOutp) out <- list(CV=out, mean=means, n=summary(grp)) out } #' row group CV (main) #' #' This function calculates CVs for matrix with multiple groups of data, ie one CV for each group of data. #' #' @param x numeric matrix where relplicates are organized into separate columns #' @param grp (factor) defining which columns should be grouped (considered as replicates) #' @param means (numeric) alternative values instead of means by .rowGrpMeans() #' @return This function returns a matrix of CV values #' @seealso \code{\link{rowGrpCV}}, \code{\link{rowCVs}}, \code{\link{arrayCV}}, \code{\link{replPlateCV}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)),ncol=10) #' grp1 <- gl(4,3,labels=LETTERS[1:4])[2:11] #' head(.rowGrpCV(dat1, grp1, .rowGrpMeans(dat1, grp1))) #' @export .rowGrpCV <- function(x, grp, means){ .rowGrpSds(x, grp)/means }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rowGrpCV.R
#' rowMeans with destinction of groups (of columns, eg groups of replicates) #' #' \code{rowGrpMeans} calculates column-means for matrix with multiple groups of data, ie similar to rowMeans but one mean for each group of data. #' Groups are specified as columns of 'x' in 'grp' (so length of grp should match number of columns of 'x', NAs are allowed). #' #' @param x matrix or data.frame #' @param grp (character or factor) defining which columns should be grouped (considered as replicates) #' @param na.rm (logical) a logical value indicating whether \code{NA}-values should be stripped before the computation proceeds. #' @return matrix with mean values #' @seealso \code{\link{rowSds}}, \code{\link[base]{colSums}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200) +rep(1:10,20)), ncol=10) #' head(rowGrpMeans(dat1, gr=gl(4, 3, labels=LETTERS[1:4])[2:11])) #' @export rowGrpMeans <- function(x, grp, na.rm=TRUE){ if(!is.matrix(x) && !is.data.frame(x)) stop(" 'x' should be data.frame or matrix") if(length(dim(x)) !=2) stop(" 'x' should be data.frame or matrix of 2 dimensions") if(length(grp) != ncol(x)) stop(" 'grp' should be of length of number of cols in 'x'") if(length(grp) <1 || all(is.na(grp))) stop(" 'grp' appears to be empty or all NAs") if(!is.factor(grp)) grp <- as.factor(grp) if(!is.matrix(x)) x <- matrix(as.matrix(x), nrow=nrow(x), dimnames=if(length(dim(x)) >1) dimnames(x) else list(names(x),NULL)) if(length(na.rm) !=1 || !is.logical(na.rm)) na.rm <- TRUE ## main out <- .rowGrpMeans(x, grp, na.rm=na.rm) chNan <- is.nan(out) if(any(chNan)) out[which(chNan)] <- NA out } #' row group mean (main) #' #' This function calculates CVs for matrix with multiple groups of data, ie one CV for each group of data. #' #' @param x numeric matrix where relplicates are organized into separate columns #' @param grp (factor) defining which columns should be grouped (considered as replicates) #' @param na.replVa (numeric) value to replace \code{NA} values #' @param na.rm (logical) remove all \code{NA} values #' @return This function returns a matrix of mean values per row and group of replicates #' @seealso \code{\link{rowGrpCV}}, \code{\link{rowCVs}}, \code{\link{arrayCV}}, \code{\link{replPlateCV}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)),ncol=10) #' grp1 <- gl(4,3,labels=LETTERS[1:4])[2:11] #' head(.rowGrpMeans(dat1, grp1)) #' @export .rowGrpMeans <- function(x, grp, na.replVa=NULL, na.rm=TRUE){ ## determine means of rows conditional as (multiple) groups ## NAs (eg from counting data) can be replaced by specified value 'na.replVa', eg 0) ## 'grp' expected as factor !! if(!is.null(na.replVa)) x[is.na(x)] <- na.replVa grNa <- unique(naOmit(as.character(grp))) out <- matrix(nrow=nrow(x), ncol=length(grNa), dimnames=list(rownames(x),grNa)) for(i in 1:length(grNa)) { useC <- which(as.character(grp)==grNa[i]) out[,i] <- if(length(useC) >1) base::rowMeans(x[,useC], na.rm=na.rm) else x[,useC] } out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rowGrpMeans.R
#' Count number of NAs per row and group of columns #' #' This functions allows easy counting the number of NAs per row in data organized in multiple sub-groups as columns. #' #' #' @param mat (matrix of data.frame) data to count the number of \code{NA}s #' @param grp (character or factor) defining which columns should be grouped (considered as replicates) #' @return matrix with number of \code{NA}s per group #' @seealso \code{\link{rowGrpMeans}}, \code{\link{rowSds}}, \code{\link[base]{colSums}} #' @examples #' mat2 <- c(22.2, 22.5, 22.2, 22.2, 21.5, 22.0, 22.1, 21.7, 21.5, 22, 22.2, 22.7, #' NA, NA, NA, NA, NA, NA, NA, 21.2, NA, NA, NA, NA, #' NA, 22.6, 23.2, 23.2, 22.4, 22.8, 22.8, NA, 23.3, 23.2, NA, 23.7, #' NA, 23.0, 23.1, 23.0, 23.2, 23.2, NA, 23.3, NA, NA, 23.3, 23.8) #' mat2 <- matrix(mat2, ncol=12, byrow=TRUE) #' gr4 <- gl(3, 4, labels=LETTERS[1:3]) #' # overal number of NAs per row #' rowSums(is.na(mat2)) #' # number of NAs per row and group #' rowGrpNA(mat2, gr4) #' @export rowGrpNA <- function(mat, grp) { ## get number of NAs per line & group of replicates if(any(length(dim(mat)) !=2, dim(mat) < 1)) stop("Invalid argument 'mat'; must be matrix (or data.frame) with min 1 line and 1 column") if(length(grp) != ncol(mat)) stop("Length of 'grp' and number of columns of 'mat' do not match !") if(is.data.frame(mat)) mat <- as.matrix(mat) gr1 <- naOmit(unique(grp)) nNA <- matrix(nrow=nrow(mat), ncol=length(gr1), dimnames=list(NULL, gr1)) for(i in 1:length(gr1)) { nNA[,i] <- rowSums(is.na(matrix(mat[,which(grp==gr1[i])], nrow=nrow(mat)) )) } nNA }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rowGrpNA.R
#' Per line and per group sd-values #' #' \code{rowGrpSds} calculate Sd (standard-deviation) for matrix with multiple groups of data, ie one sd for each group of data. #' Groups are specified as columns of 'x' in 'grp' (so length of grp should match number of columns of 'x', NAs are allowed). #' @param x matrix where relplicates are organized into seprate columns #' @param grp (character or factor) defining which columns should be grouped (considered as replicates) #' @return This function returns a matrix of sd values #' @seealso \code{\link{rowGrpMeans}}, \code{\link{rowCVs}}, \code{\link{rowSEMs}},\code{\link[stats]{sd}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200) +rep(1:10,20)), ncol=10) #' head(rowGrpSds(dat1, gr=gl(4,3,labels=LETTERS[1:4])[2:11])) #' @export rowGrpSds <- function(x, grp){ ## return Sd for within-row subgroup of data 'x' (matrix or data.frame) if(is.null(ncol(x))) stop("Data should be matrix or data.frame with multiple columns !") else { if(ncol(x) < 2) stop("Data should be matrix or data.frame with at least 2 columns !")} if(length(grp) != ncol(x)) stop("Length of (factor) 'grp' and number of cols in 'x' don't match !") .rowGrpSds(x, grp) } #' row group sd (main) #' #' This function calculates sd for matrix with multiple groups of data, ie one sd for each group of data. #' #' @param x numeric matrix where relplicates are organized into separate columns #' @param grp (factor) defining which columns should be grouped (considered as replicates) #' @return This function returns a matrix of sd values per row and group of replicates #' @seealso \code{\link{rowGrpCV}}, \code{\link{rowCVs}}, \code{\link{arrayCV}}, \code{\link{replPlateCV}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)),ncol=10) #' grp1 <- gl(4,3,labels=LETTERS[1:4])[2:11] #' head(.rowGrpSds(dat1, grp1)) #' @export .rowGrpSds <- function(x, grp){ ## return (entire col of) NA if only single col for spec group grpM <- unique(naOmit(as.character(grp))) out <- matrix(nrow=nrow(x), ncol=length(grpM), dimnames=list(rownames(x),grpM)) for(i in 1:length(grpM)) { useC <- which(grp==unique(naOmit(grp))[i]) out[,i] <- if(length(useC) >1) rowSds(x[,useC]) else NA } out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rowGrpSds.R
#' rowSums with destinction of groups (of columns, eg groups of replicates) #' #' This function calculates row-sums for matrix with multiple groups of data, ie similar to \code{rowSums} but one summed value for each line and group of data. #' Groups are specified as columns of 'x' in 'grp' (so length of grp should match number of columns of 'x', NAs are allowed). #' #' @param x matrix or data.frame #' @param grp (character or factor) defining which columns should be grouped (considered as replicates) #' @param na.rm (logical) a logical value indicating whether \code{NA}-values should be stripped before the computation proceeds. #' @return This function a matrix with row/group sum values #' @seealso \code{\link{rowGrpMeans}}, \code{\link{rowGrpSds}}, \code{\link{rowSds}}, \code{\link[base]{colSums}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200) +rep(1:10,20)), ncol=10) #' head(rowGrpMeans(dat1, gr=gl(4, 3, labels=LETTERS[1:4])[2:11])) #' @export rowGrpSums <- function(x, grp, na.rm=TRUE){ if(!is.matrix(x) && !is.data.frame(x)) stop(" 'x' should be data.frame or matrix") if(length(dim(x)) !=2) stop(" 'x' should be data.frame or matrix of 2 dimensions") if(length(grp) != ncol(x)) stop(" 'grp' should be of length of number of cols in 'x'") if(length(grp) <1 || sum(is.na(grp)) == length(grp)) stop(" 'grp' appears to be empty or all NAs") if(!is.factor(grp)) grp <- as.factor(grp) if(!is.matrix(x)) x <- matrix(as.matrix(x), nrow=nrow(x), dimnames=if(length(dim(x)) >1) dimnames(x) else list(names(x),NULL)) if(length(na.rm) !=1 || !is.logical(na.rm)) na.rm <- TRUE ## main out <- .rowGrpSums(x, grp, na.rm=na.rm) chNan <- is.nan(out) if(any(chNan)) out[which(chNan)] <- NA out } #' row group rowSums per group (main) #' #' This function calculates row-sums for matrix with multiple groups of data, with multiple groups of data, ie one sd for each group of data. #' #' @param x numeric matrix where relplicates are organized into separate columns #' @param grp (factor) defining which columns should be grouped (considered as replicates) #' @param na.replVa (numeric) value to replace \code{NA} values #' @param na.rm (logical) remove all \code{NA} values #' @return This function returns a matrix of row-sums for matrix with multiple groups of data #' @seealso \code{\link{rowGrpCV}}, \code{\link{rowCVs}}, \code{\link{arrayCV}}, \code{\link{replPlateCV}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)),ncol=10) #' grp1 <- gl(4,3,labels=LETTERS[1:4])[2:11] #' head(.rowGrpSums(dat1, grp1)) #' @export .rowGrpSums <- function(x, grp, na.replVa=NULL, na.rm=TRUE){ ## determine sums of rows conditional as (multiple) groups ## NAs (eg from counting data) can be replaced by specified value 'na.replVa', eg 0) ## 'grp' expected as factor !! if(!is.null(na.replVa)) x[is.na(x)] <- na.replVa grNa <- unique(naOmit(as.character(grp))) out <- matrix(nrow=nrow(x), ncol=length(grNa), dimnames=list(rownames(x),grNa)) for(i in 1:length(grNa)) { useC <- which(as.character(grp) ==grNa[i]) out[,i] <- if(length(useC) >1) base::rowSums(x[,useC], na.rm=na.rm) else x[,useC] } out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rowGrpSums.R
#' sd of median for each row by bootstrap #' #' \code{rowMedSds} determines the stand error (sd) of the median for each row by bootstraping each row of 'dat'. #' Note: requires package \href{https://CRAN.R-project.org/package=boot}{boot} #' #' @param dat (numeric) matix, main input #' @param nBoot (integer) number if iterations for bootstrap #' @return This functions returns a (numeric) vector with estimated standard errors #' @seealso \code{\link[boot]{boot}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)), ncol=10) #' rowMedSds(dat1) ; plot(rowSds(dat1), rowMedSds(dat1)) #' @export rowMedSds <- function(dat, nBoot=99) { msg <- "'dat' should be matrix or data.frame with " if(is.null(ncol(dat))) stop(msg,"multiple columns !") else if(ncol(dat) < 2) stop(msg,"at least 2 columns !") if(!requireNamespace("boot", quietly=TRUE)) { warning("Package 'boot' not found ! Please install first from CRAN") } else { median.fun <- function(dat,indices) stats::median(dat[indices],na.rm=TRUE) out <- try(apply(dat,1,function(x) stats::sd(boot::boot(data=x, statistic=median.fun, R=nBoot)$t))) if(inherits(out, "try-error")) stop("Did not succeed in running boot()") out }}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rowMedSds.R
#' Row Normalize #' #' This function was designed for normalizing data that is supposed to be particularly similar, like a collection of technical replicates. #' Thus, initially for each row an independent normalization factor is calculated and the median or mean across all factors will be finally applied to the data. #' This function has a special mode of operation with higher content of \code{NA} values (which may pose problems with other normalization approaches). #' If the \code{NA}-content is higher than the threshold set in \code{sparseLim}, #' a special procedure for sparse data will be applied (iteratively trating subsets of \code{nCombin} columns that will be combined in a later step). #' #' @details #' Arguments were kept similar with function \code{normalizeThis} as much as possible. #' In most cases data get normalized by proportional factors. In case of log2-data (very common in omics-data) normalizing by an additive factor is equivalent to a proportional factor. #' #' This function has a special mode of operation for sparse data (ie containing a high content of \code{NA} values). #' 0-values by themselves will be primarily considered as true measurment outcomes and not as missing. #' However, by using the argument \code{minQuant} all values below a given threshold will be set as \code{NA} and this may possibly trigger the sparse mode of normalizing. #' #' Note : Using a small value of \code{nCombin} will give the highest chances of finding sufficient complete combination of columns with sparse data. #' However, this will also increase (very much) the computational efforts and time required to produce an output. #' #' When using default proportional mode a potential division by 0 could occur, when the initial normalization factor turns out as 0. #' In this case a small value (default the maximum value of \code{dat} / 10 will be added to all data before normalizing. #' If this also creates 0-vales in the data this factor will be multiplied by 0.03. #' #' @param dat matrix or data.frame of data to get normalized #' @param method (character) may be "mean","median" (plus "NULL","none"); When NULL or 'none' is chosen the input will be returned as is #' @param refLines (NULL or numeric) allows to consider only specific lines of 'dat' when determining normalization factors (all data will be normalized) #' @param refGrp (integer) Only the columns indicated will be used as reference, default all columns (integer or colnames) #' @param proportMode (logical) decide if normalization should be done by multiplicative or additive factor #' @param minQuant (numeric) optional filter to set all values below given value as \code{NA} #' @param sparseLim (integer) decide at which min content of \code{NA} values the function should go in sparse-mode #' @param nCombin (NULL or integer) used only in sparse-mode (ie if content of \code{NA}s higher than content of \code{sparseLim}): Number of groups of smller matrixes with this number of columns to be inspected initailly; #' low values (small groups have higher chances of more common elements) #' @param omitNonAlignable (logical) allow omitting all columns which can't get aligned due to sparseness #' @param maxFact (numeric, length=2) max normalization factor #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) This function allows easier tracking of messages produced #' @return This function returns a matrix of normalized data #' @seealso \code{\link{exponNormalize}}, \code{\link{adjBy2ptReg}}, \code{\link[vsn]{justvsn}} #' @examples #' ## sparse matrix normalization #' set.seed(2); AA <- matrix(rbinom(110,10,0.05), nrow=10) #' AA[,4:5] <- AA[,4:5] *rep(4:3, each=nrow(AA)) #' AA[2,c(2,6,7)] <- 1; AA[3,8] <- 1; #' #' (AA1 <- rowNormalize(AA)) #' (AA2 <- rowNormalize(AA, minQuant=1)) # set all 0 as NAs #' (AA3 <- rowNormalize(AA, refLines=1:6, omitNonAlignable=FALSE, minQuant=1)) #' #' #' @export rowNormalize <- function(dat, method="median", refLines=NULL, refGrp=NULL, proportMode=TRUE, minQuant=NULL, sparseLim=0.4, nCombin=3, omitNonAlignable=FALSE, maxFact=10, silent=FALSE, debug=FALSE, callFrom=NULL) { ## integrate to normalizeThis ? ## method (character) normalization method applied to slection of complete lines from subsets of \code{nCombin} columns, sent to with normalizeThis() ## however, if less than 25 common lines found "average" normalization will be used ## proportMode (logical) .. switch between normalizing by multiplicative (proportional) or additive factor ## minQuant (numeric) .. intensity threshold; all values below will be considered as missing (ie \code{NA}) ## sparseLim (numeric) .. the max ratio of content of \code{NA}s in data for regular normalization, if content of \code{NA}s is higher an iterative approch using subsets of content of \code{nCombin} columns will be used ## omitNonAlignable (logical) .. decide if columns which can't be 'connected' to the rest (due to missing common measures) will be added without proper normalization or rather omitted ## minQuant (numeric) .. intensity threshold; all values below will be considered as missing (ie \code{NA}) ## maxFact (numeric) .. max normalization factor (values higher will be set to threshold) ## nCombin (integer) .. (only if content of \code{NA}s higher than content of \code{sparseLim}) groups of smller matrixes with this number of columns to be inspected initailly; low values (small groups have higher chances of more common elements) ## ## This function was designed for normalizing rows of sparse matrixes. 'dat' is supposed to represent equivalent (eg replicate measures) of the same series of individuals/elements, ## However, numerous values may be missing ie \code{NA}. Thus, it may occur frequently that a given element has not all measures, ie lines containing some \code{NA} values. ## In consequence, chances of finding lines without any \code{NA} are higher when initially fewer columns (argument \code{nCombin}) are normalized first and then combined with other sets of comumns in an iterative way. fxNa <- .composeCallName(callFrom, newNa="rowNormalize") ## proportional mode : need to add small value to avoid divBy0 ! if(any(length(dim(dat)) !=2, dim(dat) < 2:1)) stop("Invalid argument 'dat'; must be matrix or data.frame with min 2 lines and 1 col") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE sep <- "_" # separator used internally with column-numbers maxFact=10 if(is.data.frame(dat)) dat <- as.matrix(dat) iniColNa <- colnames(dat) colnames(dat) <- 1:ncol(dat) if(length(refLines) <1) refLines <- 1:nrow(dat) else if(any(refLines > nrow(dat) | refLines < 1)) { if(!silent) message(fxNa,"Note: 'refLines' designs (some) lines not present in data, ignoring..") refLines <- refLines[which(refLines <= nrow(dat) & refLines >0)] } if(length(refGrp) >0) refGrp <- refGrp[which(refGrp %in% 1:ncol(dat))] if(length(refGrp) <1) refGrp <- 1:ncol(dat) if(length(minQuant)==1 && is.numeric(minQuant)) if(!is.na(minQuant)) {chMin <- dat < minQuant if(any(chMin)) dat[which(chMin)] <- NA } if(debug) {message(fxNa," srn0")} refVal <- if(sum(!is.na(dat[refLines, refGrp])) >10) stats::median(dat[refLines, refGrp], na.rm=TRUE) else mean(dat[refLines, refGrp], na.rm=TRUE) if(refVal==0) refVal <- 1 if(debug) {message(fxNa," srn0b \n")} ## may be better/faster to random-shuffle column-order of combOfN ? (allow reaching last quicker) chNa <- sum(is.na(dat[refLines,])) / length(dat[refLines,]) # ratio of NAs if(debug) message(fxNa," Data contain ",round(100*chNa/length(dat),2),"% NA, using partial/iterative approach for sparse data") if(chNa > sparseLim) { if(ncol(dat) <= 9 ) { combOfN <- utils::combn(ncol(dat), nCombin) # the combinations (all, ie max 126) .. colnames(combOfN) <- apply(combOfN, 2, paste0, collapse="_") } else { ## shortcut for larger data-sets, consecutive sligtly overlapping segments will be considered overLap <- 2 nSeg <- floor(ncol(dat)/(nCombin -overLap)) staSto <- cbind(sta=(0:nSeg)*(nCombin -overLap) +1, sto=(1:(nSeg+1))*(nCombin -overLap) +overLap) chStaSto <- staSto[,2] > ncol(dat) if(any(chStaSto)) staSto[which(chStaSto),] <- rep(ncol(dat) -c((nCombin-1), 0), each=sum(chStaSto)) combOfN <- apply(staSto, 1, function(x) x[1]:x[2]) if( TRUE) { ## large data-sets : complete by few additional cross-references suplGrpFac <- round(log2(ncol(dat))) ## used for extending consecutive splits by additional non-consecutive sets : split into x subgroups for shuffeling tsart-sites stepW <- c(floor(nCombin/2), ceiling(nCombin/2)) tmp <- suplGrpFac*(1:(floor(ncol(dat)/suplGrpFac))) combOfN <- cbind(combOfN, sapply(tmp, function(x) c(1:stepW[1], x:(x +stepW[2] -1))), c(1:stepW[1], ncol(dat) -(stepW[2] -1):0) ) if(suplGrpFac >2) for(i in 2:suplGrpFac) combOfN <- cbind(combOfN, sapply(tmp, function(x) c(tmp[i] -1 + 1:stepW[1], x:(x +stepW[2] -1)))) combOfN <- apply(combOfN, 2, sort) combOfN <- cbind(combOfN, ncol(dat) -((nCombin -1):0) ) ## now filter away replicated/redundant combinations or combinations with intra-repeats (of specific cols) or combiantions suggesting col-numbers out of bound chDu <- duplicated(apply(combOfN, 2, function(x) paste0(sort(x), collapse=sep))) | apply(combOfN, 2, function(x) any(duplicated(x))) | apply(combOfN, 2, max) > ncol(dat) if(any(chDu)) combOfN <- if(sum(!chDu) >1) combOfN[,-which(chDu)] else as.matrix(combOfN[,-which(chDu)]) if(debug) {message("srn1"); srn1 <- list(dat=dat,combOfN=combOfN,nSeg=nSeg,sparseLim=sparseLim,refLines=refLines,refGrp=refGrp,refVal=refVal,method=method,proportMode=proportMode,sparseLim=sparseLim,nCombin=nCombin)} } } ## sort dat ?? comUse <- apply(combOfN[,], 2, function(x) which(rowSums(is.na(dat[refLines,x])) == 0) ) # index of valid/complete lines (no NA) per set of nCombin cols if(!is.list(comUse)) comUse <- as.list(as.data.frame(comUse)) chLe <- sapply(comUse, length) if(any(chLe >0, na.rm=TRUE)) { ## filter to subsets of complete lines combOfN <- combOfN[,which(chLe >0)] comUse <- if(is.matrix(comUse)) as.list(as.data.frame(comUse[,which(chLe >0)])) else comUse[which(chLe >0)] } else { warning("No complete lines found !! Try reducing 'nCombin' ...")} ## check for coverage chC <- !(1:ncol(dat) %in% sort(unique(as.integer(combOfN)))) if(any(chC, na.rm=TRUE)) { ## search for add'l columns complementing existing choice suplC <- if(sum(chC)==1) as.matrix(.complCols(which(chC), dat, nCombin)) else sapply(which(chC),.complCols, dat, nCombin) if(length(suplC) >0) { ## attach, remove duplicates & update comUse combOfN <- cbind(combOfN, suplC) chDu <- duplicated(apply(combOfN, 2, function(x) paste0(sort(x), collapse=sep))) if(any(chDu)) combOfN <- if(sum(!chDu) >1) combOfN[,-which(chDu)] else as.matrix(combOfN[,-which(chDu)]) comUse <- apply(combOfN, 2, function(x) which(rowSums(is.na(dat[refLines,x])) == 0) ) } # index of valid/complete lines (no NA) per set of nCombin cols} } ## if(debug) {message("rn2"); rn2 <- list(dat=dat,combOfN=combOfN,comUse=comUse,nSeg=nSeg,sparseLim=sparseLim,refLines=refLines,refGrp=refGrp,refVal=refVal,method=method,proportMode=proportMode,sparseLim=sparseLim,nCombin=nCombin)} fact <- .rowNormFact(dat=dat, combOfN=combOfN,comUse=comUse, method=method, refLi=refLines, refGrp=refGrp, proportMode=proportMode, minQuant=minQuant, maxFact=10, omitNonAlignable=omitNonAlignable, silent=silent, debug=debug, callFrom=fxNa) if(debug) {message("rn3")} ## final rendering if(debug) {message(fxNa," final rendering srnG")} out <- dat / rep(fact, each=nrow(dat)) } else { if(debug) { message(fxNa,"This data/selection contains only few or no NAs, no need for iterative sparse alignment .. srn9a") } ch1 <- colSums(!is.na(dat[refLines,])) ## proportional mode : .rowNorm() adds small value to avoid divBy0 ! if(any(ch1 ==0) && length(refLines) < nrow(dat) && omitNonAlignable && !silent) message(fxNa,"Note : ",sum(ch1 ==0)," columns are all NA when using ",length(refLines)," refLines, resuting columns will be retured as NaN") out <- .rowNorm(dat, refLines, method, proportMode) chNaN <- is.nan(out) if(any(chNaN)) if(!omitNonAlignable) { out[which(chNaN)] <- dat[which(chNaN)] if(!silent) message(fxNa,"Note : ",sum(ch1 ==0)," columns are all NA when using ",length(refLines)," refLines, resulting columns are retured as WITHOUT ANY normalization") } else if(!silent) message(fxNa,"Note : ",sum(ch1 ==0)," columns are all NA when using ",length(refLines)," refLines, resulting columns are retured as NaN") } if(length(iniColNa) >0) colnames(out) <- iniColNa out } #' Search (complementing) columns for best coverage of non-NA data for rowNormalization (main) #' #' This function was designed to complete the selection of columns of sparse matrix 'dat' with sets of 'nCombin' columns at complete 'coverage' #' Context : In sparse matrix 'dat' search subsets of columns with some rows as complete (no NA). #' #' @param x (integer, length=1) column number for with other columns to combine & give (some) complete non-NA lines are seeked #' @param dat (matrix) .. init data, smay be parse matrix with numerous NA #' @param nCombin (integer) .. number of columns used to make complete subset #' @return This function returns a matrix of column-indexes complementing (nCombin rows) #' @seealso \code{\link{rowNormalize}} #' @examples #' .complCols(3, dat=matrix(c(NA,12:17,NA,19),ncol=3), nCombin=3) #' @export .complCols <- function(x, dat, nCombin) { ## search (complementing) columns for best coverage of non-NA data for rowNormalization ## Context : In sparse matrix 'dat' search subsets of columns with some rows as complete (no NA). ## This function was designed to complete the selection of columns of sparse matrix 'dat' with sets of 'nCombin' columns at complete 'coverage' ## x (integer) .. column number for with other columns to combine & give (some) complete non-NA lines are seeked ## dat (matrix) .. init data, smay be parse matrix with numerous NA ## nCombin(integer) .. number of columns used to make complete subset ## returns matrix of column-indexes complementing (nCombin rows) if(any(length(dim(dat)) !=2, dim(dat) < 1:2)) stop("Invalid argument 'dat'; must be matrix or data.frame with min 1 line and 2 cols") if(is.null(colnames(dat))) colnames(dat) <- 1:ncol(dat) # colnames are essential ! msg <- "x must be integer to design column number of 'dat'" if(length(x) <0) stop(msg) else { if(is.character(x)) x <- which(colnames(x) %in% x) if(length(x) >1) x <- x[1] if(x > ncol(dat) || x < 1) stop(msg) } ## main z3 <- !is.na(dat[which(!is.na(dat[,x])), -x]) # remaining cols: !is.na of extract of lines to consider (based on incomplete col) z4 <- if(is.matrix(z3)) apply(z3, 1, which) else which(z3) if(!is.list(z4)) z4 <- as.list(as.data.frame(z4)) chLe <- sapply(z4, length) chLe <- chLe > nCombin -2 if(any(!chLe)) z4 <- z4[which(chLe)] if(length(z4) >0) { if(length(z4) >1) { c(as.integer(names(sort(table(unlist(z4)), decreasing=TRUE))) [1:(nCombin -1)], x) } else c(z4[[1]][1:(nCombin -1)], x)} else NULL } #' Obtain normalization factor (main) #' #' This function was designed to obtain normalization factors. #' #' @param dat (matrix) .. init data, smay be parse matrix with numerous NA #' @param combOfN (matrix) .. # matrix of index for all sub-groups (assumed as sorted) #' @param comUse (list) .. index of complete lines for each col of combOfN #' @param method (character) may be "mean","median" (plus "NULL","none"); When NULL or 'none' is chosen the input will be returned as is #' @param refLi (NULL or numeric) allows to consider only specific lines of 'dat' when determining normalization factors (all data will be normalized) #' @param refGrp (integer) Only the columns indicated will be used as reference, default all columns (integer or colnames) #' @param proportMode (logical) decide if normalization should be done by multiplicative or additive factor #' @param minQuant (numeric) optional filter to set all values below given value as \code{NA} #' @param maxFact (numeric, length=2) max normalization factor #' @param omitNonAlignable (logical) allow omitting all columns which can't get aligned due to sparseness #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) This function allows easier tracking of messages produced #' @return This function returns a matrix of column-indexes complementing (nCombin rows) #' @seealso \code{\link{rowNormalize}} #' @examples #' ma1 <- matrix(11:41, ncol=3) #' @export .rowNormFact <- function(dat, combOfN, comUse, method="median", refLi=NULL, refGrp=NULL, proportMode=TRUE, minQuant=NULL, maxFact=10, omitNonAlignable=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL) { ## obtain normalization factor ## combOfN (matrix) .. # matrix of index for all sub-groups (assumed as sorted) ## comUse (list) .. index of complete lines for each col of combOfN fxNa <- .composeCallName(callFrom, newNa=".rowNormFact") outL <- list() outFa <- matrix(nrow=ncol(combOfN), ncol=ncol(dat), dimnames=list(1:ncol(combOfN), 1:ncol(dat))) conti <- list() if(debug) message(callFrom, "..start loop") for(i in 1:ncol(combOfN)) { if(length(comUse[[i]]) >0) { # has sufficent valid data .. check with refLi refLiX <- if(length(refLi) >0) comUse[[i]][which(comUse[[i]] %in% refLi)] else comUse[[i]] if(length(refLiX) <1) {comUse[[i]] <- NA; if(debug) message(fxNa,"No valid lines remain when considering 'refLi' (of columns ",pasteC(utils::head(combOfN[,i])),"), loop no ",i," !!")} } if(length(comUse[[i]]) >0 && sum(is.na(comUse[[i]]))==0) { # has sufficent valid data .. tm2 <- if(length(refLiX ==1)) dat[refLiX,combOfN[,i]]/mean(dat[refLiX,combOfN[,i]], na.rm=TRUE) else .rowNorm(dat[,combOfN[,i]], method=if(length(comUse[[i]]) < 25) "mean" else method, refLi=refLiX, proportMode=proportMode, retFact=TRUE, callFrom=fxNa, silent=silent) if(debug && length(dim(tm2)) >1) message(fxNa,"Strange, tm2 is matrix and NOT vector !!") outFa[i, combOfN[,i]] <- if(length(dim(tm2)) >1) tm2[1,] else tm2 ## construct 'contigs' if(length(conti) <1) { conti <- list(conti1=matrix(combOfN[,i], nrow=1, dimnames=list(paste0("li",i),NULL))) # initiate 1st } else { tm4 <- unlist(lapply(conti, function(x) sum(combOfN[,i] %in% x))) # how many hits in which contig if(any(tm4 >0)) { if(sum(tm4 >0) ==1) { conti[[which(tm4 >0)]] <- rbind(conti[[which(tm4 >0)]], combOfN[,i]) # (simplest case) add to (single) existing contig rownames(conti[[which(tm4 >0)]])[nrow(conti[[which(tm4 >0)]])] <- paste0("li",i) } else { maxC <- which.max(tm4) # first align to contig with most common elements conti[[maxC]] <- rbind(conti[[maxC]], combOfN[,i]) # history rownames(conti[[maxC]])[nrow(conti[[maxC]])] <- paste0("li",i) if(debug) message(fxNa,"Adding contig no ",maxC," to main chunk") supC <- tm4[-maxC] conti[[maxC]] <- rbind(conti[[maxC]], conti[[supC]][nrow(conti[[supC]]):1,]) # add reversed other contig conti <- conti[-supC] } } else { if(debug) message(fxNa," i=",i," starting new contig..") conti[[length(conti) +1]] <- matrix(combOfN[,i], nrow=1, dimnames=list(paste0("li",i),NULL)) names(conti)[length(conti)] <- paste0("conti",length(conti)) } # add/start new contig } } if(debug) {message(fxNa," ..end loop",i," out of ",ncol(combOfN)); rnf2b <- list(dat=dat,combOfN=combOfN,comUse=comUse,method=method,outFa=outFa,conti=conti,i=i)} } if(debug) {message(fxNa," start 2nd part rnf3")} ## now need to adjust factors row by row (if any overlap) if(length(conti) >1) conti <- conti[order(sapply(conti, nrow), decreasing=TRUE)] ## assume sorted conti, ie 1st element of conti has most data liNo <- as.integer(sub("^li","", rownames(conti[[1]]))) # needed for outFa if(ncol(combOfN) >1) for(i in 2:nrow(conti[[1]])) { ## loop over all lines of contig (after 2nd), ie over all combinations of subsets of columns, to adjst normalization factor if(i ==2) { # 2nd line, ie only single preceeding line to adjust to ovLa <- conti[[1]][i, which(conti[[1]][i,] %in% conti[[1]][i -1,])] refPo <- conti[[1]][i -1, which(conti[[1]][i -1,] %in% conti[[1]][i,])] # needed ?? tm2 <- (outFa[liNo[i],][ovLa]) / (outFa[liNo[i -1],][ovLa]) if(length(tm2) >1) tm2 <- if("median" %in% method & length(tm2) > 5) stats::median(tm2, na.rm=TRUE) else mean(tm2, na.rm=TRUE) if(debug) message(fxNa," outFa[1,]", pasteC(round(outFa[1,],2))," add li 2.. tm2 ",pasteC(round(tm2,2))," correct li2 to ", pasteC(round(outFa[i,] / tm2,2))) outFa[i,] <- outFa[i,] / tm2 } else { if(debug) message(fxNa," outFa li=",i-2," ",pasteC(round(outFa[i-2,],2)),"\n li=",i-1," ",pasteC(round(outFa[i-1,],2)),"\n li=",i," ",pasteC(round(outFa[i,],2))) ovLa <- apply(conti[[1]][1:(i-1),], 1, function(x) x %in% conti[[1]][i,]) # overlap of prev contigs to current i refPo <- apply(conti[[1]][1:(i-1),], 1, function(x) conti[[1]][i,] %in% x) # overlap of current i to prev contigs tm2 <- list() for(j in 1:ncol(ovLa)) if(any(ovLa[,j], na.rm=TRUE)) { tm2[[j]] <- outFa[liNo[i], conti[[1]][i,][refPo[,j]]] / outFa[liNo[i], conti[[1]][i,][which(ovLa[,j])]] if(is.null(names(tm2[[j]]))) names(tm2[[j]]) <- conti[[1]][j,][which(ovLa[,j])] } tm2 <- tm2[sapply(tm2, length) >0] fact <- tapply(unlist(tm2), names(unlist(tm2)), function(x) if(length(x) > 5 & "median" %in% method) stats::median(x) else mean(x)) # summarize over all lines matching up to i (keep factors for cols separate) fact <- if(length(fact) > 5 && "median" %in% method) stats::median(fact) else mean(fact) chFa <- rbind(fact > maxFact , fact < 1/maxFact) if(any(chFa, na.rm=TRUE)) {if(any(chFa[1,])) fact[which(chFa[1,])] <- maxFact; if(any(chFa[2,])) fact[which(chFa[2,])] <- 1/maxFact } outFa[liNo[i],] <- outFa[liNo[i],] / fact if(debug) { message(fxNa,"Done with loop ",i," rnf3b")} } } ## (future ?) fuse multiple contigs (if necessary) ## compress to single norm-factor per column finFa <- apply(outFa, 2, function(x) if(sum(!is.na(x)) > 5 && "median" %in% method) stats::median(x, na.rm=TRUE) else mean(x, na.rm=TRUE)) if(debug) message("rnf4"); rnf4 <- list(finFa=finFa,dat=dat,combOfN=combOfN,comUse=comUse,method=method,outFa=outFa,conti=conti,ovLa=ovLa,refPo=refPo,i=i,outFa=outFa,tm2=tm2,fact=fact,maxFact=maxFact) if(length(conti) >1) { chCo <- unlist(conti[-1]) ch2 <- !chCo %in% conti[[1]] if(any(ch2)) { if(omitNonAlignable) finFa[chCo[which(ch2)]] <- NA if(!silent) message(fxNa,"Note: ",sum(ch2)," columns (no ",if(sum(ch2) <7) pasteC(chCo[which(ch2)]) else paste0(paste0(utils::head(chCo[which(ch2)]), collapse=", ")," ..."), ") can't get aligned !", if(omitNonAlignable)" Setting respective norm-factors to NA") } } finFa } #' Row-normalization procedure on matrix or data.frame 'dat' #' #' This function was performs a row-normalization procedure on matrix or data.frame 'dat' #' #' @param dat (matrix) .. init data, smay be parse matrix with numerous NA #' @param refLi (NULL or numeric) allows to consider only specific lines of 'dat' when determining normalization factors (all data will be normalized) #' @param method (character) may be "mean","median" (plus "NULL","none"); When NULL or 'none' is chosen the input will be returned as is #' @param proportMode (logical) decide if normalization should be done by multiplicative or additive factor #' @param maxFact (numeric, length=2) max normalization factor #' @param fact0val (integer) #' @param retFact (logical) #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) This function allows easier tracking of messages produced #' @return This function returns a matrix of normalized data same dimensions as 'dat' #' @seealso \code{\link{rowNormalize}} #' @examples #' .rowNorm(matrix(11:31, ncol=3), refLi=1, method="mean", proportMode=TRUE) #' @export .rowNorm <- function(dat, refLi, method, proportMode, maxFact=10, fact0val=10, retFact=FALSE, callFrom=NULL, debug=FALSE, silent=FALSE) { ## row-normalization procedure on matrix or data.frame 'dat' ## return matrix of same dimensions as 'dat' ## note : problem with values=0 in proportional mode (div/0) => replace 0 values by maxAbsVal/fact0val (proportMode only, nor replacement needed in additive mode) ## maxFact .. max normalization factor ## should be resistant to low degree of NAs suplVa <- NULL if(proportMode && any(dat==0, na.rm=TRUE)) {suplVa <- max(abs(dat), na.rm=TRUE)/fact0val; while(any((-1*suplVa) %in% dat, na.rm=TRUE)) suplVa <- suplVa*0.02; dat <- dat + suplVa } # substitute 0 by value 10000x smaller than smallest pos value if(length(dim(dat)) <2) dat <- matrix(dat, nrow=1, dimnames=list(NULL, names(dat))) rowMe <- if("median" %in% method & length(refLi) >10) { # per row mean or median (for each line of refLi) if(length(refLi) >1) apply(dat[refLi,], 1, stats::median, na.rm=TRUE) else stats::median(dat[refLi,], na.rm=TRUE) } else { if(length(refLi) >1) rowMeans(dat[refLi,], na.rm=TRUE) else mean(dat[refLi,], na.rm=TRUE)} corFa <- if(proportMode) dat[refLi,]/ rep(rowMe, ncol(dat)) else dat[refLi,] -rep(rowMe, ncol(dat)) # cor-factors if(length(dim(corFa)) >1) corFa <- if("median" %in% method && length(refLi) >10) apply(corFa, 2, stats::median, na.rm=TRUE) else colMeans(corFa, na.rm=TRUE) # per column cor-factor if(retFact) corFa else { corFa <- rep(corFa, each=nrow(dat)) if(proportMode) dat / corFa else dat - corFa } }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rowNormalize.R
#' SEM for each row #' #' This function speed optimized SEM (standard error of the mean) for each row. #' The function takes a matrix or data.frame and treats each row as set of data for SEM; NAs are ignored from data. #' Note: NaN instances will be transformed to NA #' @param dat matrix or data.frame #' @return This function returns a numeric vector with SEM values #' @seealso \code{\link{rowSds}}, \code{\link{colSds}}, \code{\link[base]{colSums}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)),ncol=10) #' head(rowSEMs(dat1)) #' @export rowSEMs <- function(dat) { if(is.null(ncol(dat))) stop("Data should be matrix or data.frame with multiple columns !") else if(ncol(dat) < 2) { stop("Data should be matrix or data.frame with at least 2 columns !")} out <- sqrt(rowSums(matrix(as.numeric(!is.na(dat)),ncol=ncol(dat))*((dat) - rowMeans(dat, na.rm=TRUE))^2,na.rm=TRUE)/(rowSums(!is.na(dat)) -1)) / sqrt(rowSums(!is.na(dat))) out[is.nan(out)] <- NA out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rowSEMs.R
#' sd for each row (fast execution) #' #' This function is speed optimized sd per line (takes matrix or data.frame and treats each line as set of data for sd, )equiv to using \code{apply}. #' NAs are ignored from data unless entire line NA). Speed improvements may be seen at more than 100 lines. #' Note: NaN instances will be transformed to NA #' @param dat matrix (or data.frame) with numeric values (may contain NAs) #' @return numeric vector of sd values #' @seealso \code{\link[stats]{sd}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)),ncol=10) #' rowSds(dat1) #' @export rowSds <- function(dat) { msg <- "'dat' should be matrix or data.frame with " if(is.null(ncol(dat))) stop(msg,"multiple columns !") else if(ncol(dat) < 2) stop(msg,"at least 2 columns !") if(is.data.frame(dat)) dat <- as.matrix(dat) allRowsNA <- rowSums(!is.na(dat)) <1 out <- sqrt(rowSums(matrix(as.numeric(!is.na(dat)),ncol=ncol(dat))*((dat) - rowMeans(dat,na.rm=TRUE))^2,na.rm=TRUE)/(rowSums(!is.na(dat))-1)) chNan <- is.nan(out) if(any(chNan)) out[which(chNan)] <- NA if(any(allRowsNA)) out[which(allRowsNA)] <- NA out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/rowSds.R
#' Locate Sample Index From Index or Name Of Pair-Wise Comparisons in list or MArrayLM-Object #' #' When multiple series of data are tested simultaneaously (eg using \code{moderTestXgrp}), multiple pairwise comparisons get performed. #' This function helps locating the samples, ie mean-columns, corresponding to a specific pairwise comparison. #' #' @details #' As main input one gives a list or MArrayLM-object containing testing results contain the pairwise comparisons #' and a specific comparison indicated by \code{useComp} to get located in the element of mean-columns (\code{lstMeans}) among all pairwise comparisons. #' #' @param MArrayObj (list or MArray-object) main input #' @param useComp (character or integer) index or name of pairwise-comparison to be addressed #' @param groupSep (character, length=1) separator for paitr of names #' @param lstMeans (character, length=1) the list element containing the individual sample names, typically the matrix containing the replicate-mean values for each type of sample, the column-names get used #' @param lstP (character, length=1) the list element containing all pairwise comparisons performed, the column-names get used #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @seealso \code{\link{moderTestXgrp}}, this function gets used eg in \code{\link[wrGraph]{MAplotW}} or \code{\link[wrGraph]{VolcanoPlotW}} #' @return This fuction returns a numeric vector (length=2) with index indicating the columns of (replicate) mean-values corresponding to the comparison specified in \code{useComp} #' @examples #' 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=""))) #' test8 <- moderTestXgrp(t8, grp) #' head(test8$p.value) # all pairwise comparisons available #' if(requireNamespace("limma", quietly=TRUE)) { # need limma installed... #' sampNoDeMArrayLM(test8,1) #' head(test8$means[,sampNoDeMArrayLM(test8,1)]) #' head(test8$means[,sampNoDeMArrayLM(test8,"C-D")]) } #' #' @export sampNoDeMArrayLM <- function(MArrayObj, useComp, groupSep="-", lstMeans="means",lstP=c("BH","FDR","p.value"), silent=FALSE, debug=FALSE, callFrom=NULL) { ## locate sample index from index or name of pair-wise comparisons in list or MArrayLM-object fxNa <- .composeCallName(callFrom, newNa="sampNoDeMArrayLM") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE errMsg <- c("Argument 'MArrayObj' is ","empty","doesn't contain the list-element needed ('",lstMeans,"') !") if(length(MArrayObj) <1) stop(errMsg[1:2]) if(length(MArrayObj[[lstMeans]]) <1) stop(errMsg[-2]) if(length(colnames(MArrayObj[[lstMeans]])) <1) stop("Problem with 'MArrayObj$lstMeans' (does not contain matrix of means)") if(ncol(MArrayObj[[lstMeans]])==2) { # only 2 mean-values, no other choice, don't need to try matching anything if(!identical(as.character(useComp),"1") & !silent) message(fxNa,"Only 2 columns of mean-values available, can't interpret properly 'useComp=",useComp,"'") out <- 1:2 } else { if(length(lstP) <0) stop(" 'lstP' is empty !") chP <- lstP %in% names(MArrayObj) if(any(chP) & length(lstP) >0) lstP <- lstP[which(chP)[1]] if(length(colnames(MArrayObj[[lstP]])) <1) stop("Problem with 'MArrayObj' (can't find names of comparisons in '",lstP,"')") ## convert/locate names to index if(is.character(useComp) & length(grep("[[:alpha:]]",useComp)) >0) useComp <- naOmit(match(useComp, colnames(MArrayObj[[lstP]]) )) if(length(useComp) <1) stop("Argument 'useComp' is empty or can't locate in comparison-names") ## main out <- if(ncol(MArrayObj[[lstP]])==2 & colnames(MArrayObj[[lstP]])[1] =="(Intercept)") 1:2 else { matchSampToPairw(grpNa=colnames(MArrayObj[[lstMeans]]), pairwNa=colnames(MArrayObj[[lstP]])[useComp], sep=groupSep, silent=silent, callFrom=fxNa)} if(length(useComp)==1) out <- as.integer(out)} out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/sampNoDeMArrayLM.R
#' Scale data to given minimum and maxiumum #' #' This is a convenient way to scale data to given minimum and maxiumum without full standarization, ie without deviding by the sd. #' #' @param x (numeric) vector to rescacle #' @param min (numeric) minimum value in output #' @param max (numeric) maximum value in output #' @return vector of rescaled data (in dimensions as input) #' @seealso \code{\link[base]{scale}} #' @examples #' dat <- matrix(2*round(runif(100),2), ncol=4) #' range(dat) #' dat1 <- scaleXY(dat, 1,100) #' range(dat1) #' summary(dat1) #' #' ## scale for each column individually #' dat2 <- apply(dat, 2, scaleXY, 1, 100) #' range(dat2) #' summary(dat2) #' @export scaleXY <- function(x, min=0, max=1) { ## adjust values to range form min to max y <- .scale01(x) y*(max-min) + min} #' Scale between 0 and 1 (main) #' #' This function rescales between 0 and 1 #' #' @param x numeric vector to be re-scalded #' @return This function returns a numeric vector of same length with re-scaled values #' @seealso \code{\link{scaleXY}} , \code{\link[base]{scale}} #' @examples #' .scale01(11:15) #' @export .scale01 <- function(x){low <- min(x, na.rm=TRUE); (x - low)/(max(x, na.rm=TRUE) - low)} ## adjust values to range form 0 to 1 #' Scale between min and max value (main) #' #' This function rescales between user-defined min and max values #' #' @param x numeric vector to be re-scalded #' @param minim (numeric) minimum value for resultant vactor #' @param maxim (numeric) minimum value for resultant vactor #' @return This function returns a matrix of CV values #' @seealso \code{\link{scaleXY}} , \code{\link[base]{scale}} #' @examples #' .scaleXY(11:15, min=1, max=100) #' @export .scaleXY <- function(x, minim=2, maxim=3) { ## adjust values to range form min to max y <- .scale01(x) y*(maxim-minim) +minim}
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/scaleXY.R
#' Search duplicated data over multiple columns, ie pairs of data #' #' \code{searchDataPairs} searches matrix for columns of similar data, ie 'duplicate' values in separate columns or very similar columns if \code{realDupsOnly=FALSE}. #' Initial distance measures will be normalized either to diagonale (\code{normRange=TRUE)} of 'window' or to the real max distance observed (equal or less than diagonale). #' Return data.frame with names for sample-pair, percent of identical values (100 for complete identical pair) and relative (Euclidean) distance (ie max dist observed =1.0). #' Note, that low distance values do not necessarily imply correlating data. #' #' @param dat matrix or data.frame (main input) #' @param disThr (numeric) threshold to decide when to report similar data (applied on normalized distances, low val fewer reported), applied on normalized distances (norm to diagonale of all data for best relative 'unbiased' view) #' @param byColumn (logical) rotates main input by 90 degrees (using \code{\link[base]{t}}), thus allows to read by rows instead of by columns #' @param normRange (logical) normize each columns separately if \code{TRUE} #' @param altNa (character, default \code{NULL}) vector with alternative names (for display) #' @param realDupsOnly (logical) if \code{TRUE} will consider equal values only, otherwise will also consider very close values (based on argument \code{disThr}) #' @param silent (logical) suppres messages #' @param callFrom (character) allows easier tracking of messages produced #' @return This function returns a data.frame with names of sample-pairs, percent of identical values (100 for complete identical pair) and rel (Euclidean) distance (ie max dist observed =1.0) #' @seealso \code{\link[base]{duplicated}} #' @examples #' mat <- round(matrix(c(11:40,runif(20)+12,11:19,17,runif(20)+18,11:20), nrow=10), 1) #' colnames(mat) <- 1:9 #' searchDataPairs(mat,disThr=0.05) #' @export searchDataPairs <- function(dat, disThr=0.01, byColumn=TRUE, normRange=TRUE, altNa=NULL, realDupsOnly=TRUE, silent=FALSE, callFrom=NULL) { fxNa <- .composeCallName(callFrom, newNa="searchDataPairs") if(!isTRUE(silent)) silent <- FALSE if(byColumn) dat <- t(dat) if(!is.null(altNa)){ msg <- "invalid content of argument 'altNa' (should be non-redudant vector of length of number of columns of 'dat'" if(length(altNa) != ncol(dat)) {altNa <- NULL; if(!silent) message(fxNa,msg)} if(length(altNa) > length(unique(dat))) {altNa <- NULL; if(!silent) message(fxNa,msg)} } if(!is.null(altNa)) rownames(dat) <- altNa else { if(is.null(rownames(dat))) rownames(dat) <- 1:nrow(dat) } ma0 <- matrix(1:nrow(dat), nrow=nrow(dat), ncol=nrow(dat)) diCoor <- cbind(li=ma0[lower.tri(ma0)], co=t(ma0)[lower.tri(ma0)]) di <- stats::dist(dat) diNor <- if(normRange) stats::dist(apply(dat, 2, range)) else max(di,na.rm=TRUE) di <- di/diNor chk <- diCoor[which(di < disThr),] if(!is.matrix(chk)) chk <- matrix(chk, ncol=2) chN <- if(nrow(chk) <1) matrix(nrow=0, ncol=4, dimnames=list(NULL,c("samp1","samp2","pcIdent","relDist"))) else { data.frame(samp1=rownames(dat)[chk[,2]], samp2=rownames(dat)[chk[,1]], pcIdent=round(100*apply(chk, 1, function(x) sum(dat[x[1],]==dat[x[2],],na.rm=TRUE)/ncol(dat)),1), relDist=signif(as.numeric(di)[which(di < disThr)],4))} if(nrow(chN) >0 && realDupsOnly) chN <- chN[chN$pcIdent ==100,] chN }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/searchDataPairs.R
#' Search points forming lines at given slope #' #' \code{searchLinesAtGivenSlope} searchs among set of points (2-dim) those forming line(s) with user-defined slope ('coeff'), #' ie search optimal (slope-) offset parameter(s) for (regression) line(s) with given slope ('coef'). #' Note: larger data-sets : segment residuals to 'coeff' & select most homogenous #' #' @param dat matrix or data.frame, main input #' @param coeff (numeric) slope to consider #' @param filtExtr (integer) lower & upper quantile values, remove points with extreme deviation to offset=0, (if single value: everything up to or after will be used) #' @param minMaxDistThr (logical) optional minumum and maximum distance threshold #' @param lmCompare (logical) add'l fitting of linear regression to best results, return offset AND slope based on lm fit #' @param indexPoints (logical) return results as list with element 'index' specifying retained points #' @param displHist (logical) display histogram of residues #' @param displScat (logical) display (simple) scatter plot #' @param bestCluByDistRat (logical) initial selection of decent clusters based on ratio overallDist/averNeighbDist (or by CV & cor) #' @param neighbDiLim (numeric) additional threshold for (trimmed mean) neighbour-distance #' @param silent (logical) suppress messages #' @param debug (logical) for bug-tracking: more/enhanced messages #' @param callFrom (character) allow easier tracking of messages produced #' @seealso \code{\link[stats]{lm}} #' @return This functions returns a matrix of line-characteristics (or if indexPoints is \code{TRUE} then list (line-characteristics & index & lm-results) #' @examples #' set.seed(2016); ra1 <- runif(300) #' dat1 <- cbind(x=round(c(1:100+ra1[1:100]/5,4*ra1[1:50]),1), #' y=round(c(1:100+ra1[101:200]/5, 4*ra1[101:150]), 1)) #' (li1 <- searchLinesAtGivenSlope(dat1, coeff=1)) #' @export searchLinesAtGivenSlope <- function(dat, coeff=1.5, filtExtr=c(0,1), minMaxDistThr=NULL, lmCompare=TRUE, indexPoints=TRUE, displHist=FALSE, displScat=FALSE, bestCluByDistRat=TRUE, neighbDiLim=NULL, silent=FALSE, debug=FALSE, callFrom=NULL) { fxNa <- .composeCallName(callFrom, newNa="searchLinesAtGivenSlope") opar <- list(mfrow=graphics::par("mfrow"), mfcol=graphics::par("mfcol")) on.exit(graphics::par(opar$mfrow)) on.exit(graphics::par(opar$mfcol)) if(isTRUE(debug)) silent <- FALSE if(!isTRUE(silent)) silent <- FALSE if(isTRUE(lmCompare)) { if(!requireNamespace("MASS", quietly=TRUE)) warning(fxNa,"Package 'MASS' not found ! Please install first from CRAN \n setting 'lmCompare' to FALSE") lmCompare <- FALSE } else lmCompare <- FALSE minNPoints <- 8 ## min no of points to be included in primary selection of groups/clusters cvThr <- c(0.06,0.09) ## threshold for 1st flitering of clustering results argNa <- deparse(substitute(dat)) coeff <- convToNum(coeff, spaceRemove=TRUE, convert=c(NA,"sparseChar"), remove=NULL, euroStyle=TRUE, sciIncl=TRUE, callFrom=fxNa) if(length(coeff) <1) stop(" 'coeff' should be numeric of length 1") else coeff <- coeff[1] offS <- offS0 <- dat[,2] - coeff*dat[,1] if(!isTRUE(silent)) silent <- FALSE if(!isTRUE(debug)) debug <- FALSE if(debug) silent <- FALSE if(identical(filtExtr, c(0,1))) filtExtr <- NULL if(is.numeric(filtExtr)) { ## remove extreme points (needed for all appoaches ??) if(length(filtExtr) !=2) filtExtr <- sort(c(filtExtr, if(filtExtr[1] <0.5) 1 else 0)[1:2]) offSL <- stats::quantile(offS, filtExtr, na.rm=TRUE) # filt1 <- which(offS > offSL[1] & offS < offSL[2]) } else filt1 <- 1:nrow(dat) # filt1 : index for which lines of 'dat' are actually condsidered .. ## exclude lines containing any NA if(sum(is.na(dat[,1:2]) >0)) { exclu <- which(rowSums(is.na(dat[,1:2])) >0) filt1 <- filt1[-1*which(filt1 %in% exclu)] } filt0 <- (1:nrow(dat))[-1*filt1] # opposite of filt1, ie index numbers of points(lines of dat) excluded ## main : segment - if data sufficiently large bestPart <- if(length(filt1) >60 ) { .insp1dimByClustering(offS[filt1], automClu=TRUE, cluChar=TRUE, silent=TRUE, callFrom=fxNa) } else list(cluster=rep(1,length(filt1)), cluChar=matrix(c(length(filt1), stats::median(offS[filt1]), abs(stats::sd(offS[filt1]))/mean(offS[filt1])), nrow=1, dimnames=list(1,c("n","center","centerCV")))) if(!silent & length(filt1) >50) message(fxNa,"Data (",nrow(dat), " lines) segemented in ",nrow(bestPart$cluChar)," cluster(s)") ## note : cluster-names MUST be numeric-like !! (no letters !) ## now add info from 2 dim data ## note : problem with using cor: small clusters have tendency for high cor ... ## choose base on 'refVa' (1-cor) x (centerCV)/ sqrt(n) ... lower =better cluTab <- table(bestPart$cluster) disIni <- as.list(rep(NA,length(cluTab))) extrPtDis <- rep(NA,length(cluTab)) for(j in as.numeric(names(cluTab))[which(cluTab > max(2,minNPoints))]) { cluLi <- which(bestPart$cluster==j) disIni[[j]] <- .neigbDis(dat[filt1[cluLi],1:2], asSum=FALSE) tmp <- dat[filt1[cluLi[order(rowMeans(dat[filt1[cluLi],1:2], na.rm=TRUE))]], 1:2] extrPtDis[j] <- sqrt(sum((tmp[1,] -tmp[length(cluLi)])^2 )) } if(debug) message(fxNa," ",sum(!is.na(extrPtDis))," out of ",length(extrPtDis)," distances calultated") xyCor <- as.numeric(unlist(by(dat[filt1,1:2], bestPart$cluster, function(x) stats::cor(x[,1],x[,2]) ))) offSclu <- cbind(bestPart$cluChar, cor=xyCor) offSclu <- cbind(offSclu, refVa=(1-abs(offSclu[,"cor"]))*offSclu[,"centerCV"]/sqrt(offSclu[,"n"])) ## <<== refVa offSclu <- cbind(offSclu, meanNeigbDi=sapply(disIni,mean,na.rm=TRUE,trim=0.2), maxSpread=extrPtDis) if(debug) message(fxNa," 'offSclu' columns: ",paste(colnames(offSclu),collapse=" ")) ## now refine best clusters (either by ratio overallSpread/meanNeighbDist, or by CV & cor) if(bestCluByDistRat && sum(cluTab >minNPoints) >1) { refRat <- mean(offSclu[,"meanNeigbDi"]/offSclu[,"maxSpread"], trim=0.2, na.rm=TRUE) refCluNo <- which(offSclu[,"meanNeigbDi"]/offSclu[,"maxSpread"] < refRat & offSclu[,"n"] >=minNPoints) if(length(refCluNo) <1) { message(fxNa,"Cannot find decent clusters with 'bestCluByDistRat' ") } } else { refCluNo <- which(offSclu[,"refVa"] < stats::median(offSclu[,"refVa"],na.rm=TRUE) && abs(offSclu[,"cor"]) > 0.95 && offSclu[,"centerCV"] < cvThr[1] & offSclu[,"n"] >=minNPoints) if(length(refCluNo) <1) { refCluNo <- which(offSclu[,"refVa"] < stats::median(offSclu[,"refVa"],na.rm=TRUE) && abs(offSclu[,"cor"]) > 0.92 && offSclu[,"centerCV"] < cvThr[2] & offSclu[,"n"] >=minNPoints) } } if(debug) message(fxNa," select clusters ",if(length(refCluNo) >0) paste(refCluNo,collapse=" ") else "(none)"," for refining") if(length(refCluNo) >0) { for(j in refCluNo) { newCluNo <- max(bestPart$cluster) +1 ## this part may be further improved (.keepCenter1d may remove too much = split good clusters) tmp <- .keepCenter1d(offS[filt1[which(bestPart$cluster==j)]], core="veryhigh", keepOnly=FALSE, displPlot=FALSE, silent=silent, callFrom=fxNa) # want display of hist-refinement? if(!silent) message(fxNa,"Split clu no ",j," in main (n=",length(tmp$keep),") and fragm clu ", newCluNo," (n=",length(tmp$drop),")") bestPart$cluster[which(bestPart$cluster==j)[tmp$drop]] <- newCluNo } if(debug) message(" now at ",newCluNo," groups/clusters") cluN <- bestPart$cluster offSclu <- cbind(n=table(cluN), center=tapply(offS[filt1], cluN, mean, na.rm=TRUE), centerSd=tapply(offS[filt1], cluN, stats::sd, na.rm=TRUE)) ## set cor to 0 if cor can't get caluclated due to indentical values in one of the colums xyCor <- as.numeric(unlist(by(dat[filt1,1:2],cluN,function(x) {if(length(unique(x[,1])) >1 && length(unique(x[,2])) >1) stats::cor(x[,1],x[,2]) else 0} ))) refVa <- (1 -abs(xyCor)) *offSclu[,"centerSd"]/ (offSclu[,"center"] *sqrt(offSclu[,"n"])) offSclu <- cbind(offSclu ,centerCV=abs(offSclu[,"centerSd"]/offSclu[,"center"]), cor=xyCor, refVa=refVa) if(debug) message(fxNa," updated xyCor,offSclu ...") } if(length(refCluNo) <1) { ## nothing found so far, rather choose big cluster with cor > 50% if(debug) message(fxNa," nothing found so far, rather choose big cluster with cor > 50%") tmp3 <- which(offSclu[,"n"] >3) if(nrow(offSclu) ==1){ refCluNo <- 1 } else { # single cluster (no choice) if(length(tmp3) <2) refCluNo <- which.max(offSclu[,"n"]) else { # all clusters smaller <4, choose largest tmp <- offSclu[which(offSclu[,"n"] >3),] # or select amongst clusters >3 if(length(dim(tmp)) >1){ tmp2 <- which(abs(tmp[,"cor"]) >= stats::median(abs(tmp[,"cor"]), na.rm=TRUE)) tmp <- log(tmp[tmp2,"n"])/20 + tmp[tmp2,"cor"] -10*tmp[tmp2,"centerCV"] # compromise betw n,cor & centerCV refCluNo <- as.numeric(names(tmp2)[which.max(tmp2)]) } else refCluNo <- which(offSclu[,"n"] >3) } } if(!silent) message(fxNa,"Cannot easily identify clusters for refining, use (large & decent cor) clu: ",refCluNo) } ## get characteristics (of best clusters) (no need to refresh refCluNo, OK) ## add parameter for checking if points are compact : sort, sum of each dist.to.neighb neigbDist <- rep(NA, nrow(offSclu)) for(j in which(offSclu[,"n"] >1)) { neigbDist[j] <- mean(.neigbDis(dat[filt1[which(bestPart$cluster==j)],1:2], asSum=FALSE), trim=0.1, na.rm=TRUE)} # 10% each trimmed mean(dist) offSclu <- cbind(offSclu,neigbDist=neigbDist) ## return matrix 'offT' with line-characteristics (for selected/best) or list (line-characteristics & index) reportLi <- unique(c(refCluNo, which(offSclu[,"n"] > min(4,minNPoints)))) offT <- matrix(nrow=length(reportLi), ncol=10, dimnames=list(reportLi, c("n","medOffS","CVoffS","r","neigbDist", "CIlo","CIhi","CIov","grade","grade2"))) for(j in reportLi){ sel <- which(bestPart$cluster==j) CI <- sort(stats::t.test(offS[filt1[sel]])$conf.int) offT[as.character(j),] <- c(n=length(sel), medOffS=stats::median(offS[filt1[sel]]), CVoffS=abs(stats::sd(offS[filt1[sel]])/mean(offS[filt1[sel]])), r=stats::cor(dat[filt1[sel],1],dat[filt1[sel],2]), neigbDist=.neigbDis(dat[filt1[which(bestPart$cluster==j)],1:2])/sum(bestPart$cluster==j), CIlo=CI[1], CIhi=CI[2], CIov=NA, grade=NA, grade2=NA) } offT[,"grade"] <- signif(log(offT[,"n"])/15 + offT[,"r"] -10*offT[,"CVoffS"],3) # 'grade' .. consider n,r & CVoffS; higher..better if(debug) message(fxNa," offT created, columns ",paste(colnames(offT),collapse=" ")) refCluSel <- which(refCluNo %in% rownames(offT)[which(offT[,"neigbDist"] <= neighbDiLim)]) if(!is.null(neighbDiLim) & length(refCluSel) >0) refCluNo <- refCluNo[refCluSel] ## rank2 : rank of 'grade' among top-hits ('refCluNo'), here with 1 for highest=best 'grade' offT[match(refCluNo, rownames(offT)),"grade2"] <- (nrow(offT) +1 -rank(offT[,"grade"]))[match(refCluNo, rownames(offT))] if(indexPoints) { if(length(filt0) >0) bestPart$cluster[filt0] <- NA out <- list(offS=offT, clus=bestPart$cluster, index=lapply(refCluNo, function(x) which(bestPart$cluster==x))) } else out <- offT ## compare to lm fit if(debug) message(fxNa," ..ready to refine ",length(refCluNo)," groups by lm (conserve = ",is.list(out),")") if(lmCompare) {for(i in 1:length(refCluNo)) { j <- refCluNo[i] dat2 <- as.data.frame(matrix(dat[filt1[which(bestPart$cluster==j)],1:2], ncol=2)) colnames(dat2) <- c("slope","B") # LETTERS[1:2] tryLm <- try(MASS::rlm(B ~ slope, data=dat2)) if(debug) message(" ..i=",i," used ",c("MASS::rlm","stats::lm")[1 +as.numeric(inherits(tryLm, "try-error") )]) if(inherits(tryLm, "try-error")) { if(!silent) message(" group ",refCluNo[i],": problem making robust regression (from package MASS), trying regular regression instead") tryLm <- try(stats::lm(B ~ slope, data=dat2)) } out$lm[[i]] <- tryLm # needed for lmFilter() if(i==1) out$lmSum <- matrix(NA, nrow=length(refCluNo), ncol=6, dimnames=list(refCluNo, c("(Intercept)","slope","pInterc","pSlope","residSE","Rsqu"))) if(inherits(tryLm, "try-error")) message(" Problem making regression on group",refCluNo[i],"") else if(is.list(out)) { tmp <- if(inherits(tryLm, "rlm")) { c(2*stats::pt(-abs(stats::coef(summary(tryLm))[,3]), df=length(stats::residuals(tryLm))-1), stats::cor(tryLm$qr$qr[,1], tryLm$qr$qr[,2])^2) } else c(stats::coef(summary(tryLm))[,4], summary(tryLm)$adj.r.squared) if(any(tmp[1:2] ==0, na.rm=TRUE)) tmp[which(tmp[1:2]==0)] <- 1e-320 # avoid p=0 ... out$lmSum[i,] <- c(stats::coef(tryLm), tmp[1:2], summary(tryLm)$sigma,tmp[3]) } } names(out$lm) <- refCluNo } useColPa <- if(nrow(offT) <8) 2:nrow(offT) else grDevices::rainbow(1.2*nrow(offT))[1+(1:nrow(offT))] useCol <- useColPa[out$clus] ## plot histogram of residues if(displHist) { if(displScat) if(all(graphics::par()$mfrow <2)) {graphics::layout(matrix(1:2, ncol=2)) ; message(" adjusting layout for 2 images")} cluBor <- matrix(unlist(by(offS,bestPart$cluster,range)), byrow=TRUE, ncol=2) his <- try(graphics::hist(offS, breaks="FD", main="hist of residuals to given slope"), silent=TRUE) if(inherits(his, "try-error")) message(fxNa,"UNABLE to plot histogram figure !") else { graphics::mtext(paste(nrow(cluBor),"(best) clusters shown as grey/color boxes according to mean neighbour-point distance"),cex=0.8) yPos <- c(-0.03*max(his$counts),-0.005*max(his$counts)) tmp <- unique(as.numeric(cluBor)) graphics::rect(min(cluBor[,1]), mean(yPos), max(cluBor[,2]), yPos[2],col=grDevices::grey(0.95), border=grDevices::grey(0.7)) graphics::segments(tmp,mean(yPos), tmp, yPos[2],col=grDevices::grey(0.7)) graphics::rect(cluBor[refCluNo,1], yPos[1], cluBor[refCluNo,2], yPos[2], col=useColPa,border=useColPa[refCluNo]) } } ## plot of dat if(displScat) { if(debug) message(fxNa," ..displScat=",displScat) grpChar1 <- offT[,"neigbDist"] names(grpChar1) <- rownames(offT) # names gets lost when just 1 line in offT tit <- paste("identification of linear groups with slope ",signif(coeff,3)) if(!all(unique(bestPart$cluster) %in% rownames(offT))) { cluNa <- data.frame(clu=unique(bestPart$cluster), xx=NA, stringsAsFactors=FALSE) tmp <- data.frame(clu=rownames(offT), offT, stringsAsFactors=FALSE) tmp <- merge(tmp, cluNa, by="clu", all=TRUE) grpChar1 <- tmp[,"neigbDist"] names(grpChar1) <- tmp[,"clu"] } if(debug) message(fxNa,"Class dat ",class(dat)," class grpNo ",class(bestPart$cluster)," class grpChar ",class(grpChar1), " class grpHighl ",class(rownames(offT))," class datNa ",class(argNa)) useClu <- which.max(offT[,"n"]) useLi <- which(bestPart$cluster==useClu) if(debug) message(fxNa," len useLi",length(useLi)," useCol ",useCol) chG <- try(graphics::plot(dat[,1], dat[,2], main=tit, pch=21, bg=useCol, xlab=colnames(dat)[1], ylab=colnames(dat)[2]), silent=TRUE) if(inherits(chG, "try-error")) message(fxNa,"UNABLE to plot scatter figure !") else { graphics::legend("topleft",paste0("clu ",rownames(offT)," ,n=",offT[,1]), text.col=1, pch=21, col=1, pt.bg=useColPa,cex=0.8,xjust=0.5,yjust=0.5)} # as points } out } #' Calculate residues of (2-dim) linear model 'lMod'-prediction of/for 'dat' #' #' This function calculates residues of (2-dim) linear model 'lMod'-prediction of/for 'dat' (using 2nd col of 'useCol' ) #' (indexing in 'dat', matrix or data.frame with min 2 cols), using 1st col of 'useCol' as 'x'. #' It may be used for comparing/identifying data close to regression (eg re-finding data on autoregression line in FT-ICR) #' #' @param dat matrix or data.frame, main input #' @param lMod linear model, only used to extract coefficients offset & slope #' @param regTy (character) type of regression model #' @param useCol (integer) columns to use #' @return This function returns a numeric vector of residues (for each line of dat) #' @seealso \code{\link{searchLinesAtGivenSlope}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)),ncol=10) #' @export .predRes <- function(dat, lMod, regTy="lin", useCol=1:2){ ## calculate residues of (2-dim) linear model 'lMod'-prediction of/for 'dat' (using 2nd col of 'useCol' ) ## (indexing in 'dat', matrix or data.frame with min 2 cols), using 1st col of 'useCol' as 'x' ## used for comparing/identifying data close to regression (eg re-finding data on autoregression line in FT-ICR) ## 'lMod' .. linear model, only used to extract coefficients offset & slope ## used with column useCol[1] and then column useCol[2] subtracted ## return numeric vector of residues (for each line of dat) dat <- dat[,useCol] lMod <- stats::coef(lMod) ## lin: y~ x +d+err; inv: y~ 1/x+d+err; res: y~ (x-y)+; nor: y~ x/y+; resY: y-x~ x+; norRes: y~ (x-y)/y+; norResY: (y-x)/x~ x+; sqNorRes: y ~ (x-y)/(y*y)+; sqNorResY: (y-x)/(x*x)~ x+ switch(regTy, # lMod[2] ... slope !! lin = lMod[2]*dat[,1] +lMod[1] -dat[,2], inv = lMod[2]/dat[,1] +lMod[1] -dat[,2], res = lMod[2]*(dat[,1] -dat[,2]) +lMod[1] -dat[,2], nor = lMod[2]*dat[,1]/dat[,2] +lMod[1] -dat[,2], resY = lMod[2]*dat[,1] +lMod[1] -(dat[,2] -dat[,1]), norY = lMod[2]*dat[,1] +lMod[1] -dat[,2]/dat[,1], norRes = lMod[2]*(dat[,1] -dat[,2])/dat[,2] +lMod[1] -dat[,2], norResY = lMod[2]*dat[,1] +lMod[1] -(dat[,2] -dat[,1])/dat[,1], sqNorRes = lMod[2]*(dat[,1] -dat[,2])/dat[,2]^2 +lMod[1] -dat[,2], sqNorResY = lMod[2]*dat[,1] +lMod[1] -(dat[,2] -dat[,1])/dat[,1]^2, other=NULL) } #' Compare 'dat' to confindence interval of linare model 'lMod' (eg from lm()) #' #' This function allows to compare 'dat' to confindence interval of linare model 'lMod' (eg from lm()) #' #' @param dat matrix or data.frame, main input #' @param lMod linear model, only used to extract coefficients offset & slope #' @param level (numeric) alpha threshold for linear model #' @return This function returns a logical vector for each value in 2nd col of 'dat' if INSIDE confid interval #' @seealso \code{\link{searchLinesAtGivenSlope}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)),ncol=10) #' @export .checkLmConfInt <- function(dat, lMod, level=0.95){ ## compare 'dat' to confindence interval of linare model 'lMod' (eg from lm()) ## suppose (y-x)~x (ie 2nd col estimated by 1st col) : formula(lMod) ## return logical vector for each value in 2nd col of 'dat' if INSIDE confid interval ## could be improved by more steps betw various values of confint(lMod,level=level), ## so far too stringent (nothing within confint range) ## or use predict() and exploit pVal formPat <- sub("","", stats::formula(lMod)[3]) # inspect formula if (y-x)~x chResForm <- stats::formula(lMod)[2] == paste0("(",formPat," - ",sub(" 1"," 2",formPat),")()") mod <- cbind(main=stats::coef(lMod)[2]*dat[,1] +stats::coef(lMod)[1], up1=stats::confint(lMod,level=level)[2,1]*dat[,1] +stats::confint(lMod,level=level)[1,1], up2=stats::confint(lMod,level=level)[2,1]*dat[,1] +stats::confint(lMod,level=level)[1,2], lo1=stats::confint(lMod,level=level)[2,2]*dat[,1] +stats::confint(lMod,level=level)[1,2], lo2=stats::confint(lMod,level=level)[2,2]*dat[,1] +stats::confint(lMod,level=level)[1,1]) moRa <- t(apply(mod, 1, range)) out <- if(chResForm) dat[,2] -dat[,1] >= moRa[,1] & dat[,2] -dat[,1] <= moRa[,2] else NULL out } #' Segment (1-dim vector) 'dat' into clusters #' #' This function allows aegmenting (1-dim vector) 'dat' into clusters. #' If 'automClu=TRUE ..' first try automatic clustering, if too few clusters, run km with length(dat)^0.3 clusters #' This function requires the package NbClust to be installed. #' #' @param dat matrix or data.frame, main input #' @param automClu (logical) run atomatic clustering #' @param cluChar (logical) to display cluster characteristics #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns clustering (class index) or (if 'cluChar'=TRUE) list with clustering and cluster-characteristics #' @seealso \code{\link{searchLinesAtGivenSlope}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)),ncol=10) #' @export .insp1dimByClustering <- function(dat, automClu=TRUE, cluChar=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL){ ## Segment (1-dim vector) 'dat' into clusters ## if 'automClu=TRUE ..' first try automatic clustering, if too few clusters, run km with length(dat)^0.3 clusters ## 'cluChar' .. to display cluster characteristics ## return clustering (class index) or (if 'cluChar'=TRUE) list with clustering and cluster-characteristics ## require(NbClust) fxNa <- .composeCallName(callFrom, newNa=".insp1dimByClustering") if(!isFALSE(automClu)) automClu <- TRUE if(!isFALSE(cluChar)) cluChar <- TRUE out <- NULL if(automClu) { if(!requireNamespace("NbClust", quietly=TRUE)) { message(fxNa,"Package 'NbClust' not found ! Please install first from CRAN \n setting 'automClu'=FALSE for using kmeans()") automClu <- FALSE } } if(automClu) { cluAut <- try(NbClust::NbClust(dat, method="average", index="ccc"),silent=TRUE) # cluster only best = smallest dist if(inherits(cluAut, "try-error")) { warning(fxNa,"Failed to run NbClust::NbClust(); ignoring 'automClu'") automClu <- FALSE } if(automClu) { out <- cluAut$Best.partition if(length(table(out)) < ceiling(length(dat)^0.16)) { if(!silent) message(" Automatic clustering proposed only ",length(table(out))," clusters -> impose ",ceiling(length(dat)^0.3)) automClu <- FALSE } } # insufficient number of clusters -> run kmeans if(!automClu) { nClu <- ceiling(length(dat)^0.4) kMe <- stats::kmeans(dat, centers=nClu, iter.max=9) out <- kMe$cluster } if(cluChar) { ctrClu <- tapply(dat, out, mean, na.rm=TRUE) sdClu <- tapply(dat, out, stats::sd, na.rm=TRUE) out <- list(cluster=out, cluChar=cbind(n=table(out), center=ctrClu, centerSd=sdClu, centerCV=abs(sdClu/ctrClu))) } } out } #' Refine/filter 'dat1' (1dim dataset, eg cluster) with aim of keeping center of data #' #' This function allows to refine/filter 'dat1' (1dim dataset, eg cluster) with aim of keeping center of data. #' It is done based on most freq class of histogramm keep/filter data if 'core' (% of volume) are within 'core' (%) range #' #' @param dat1 simple numeric vector #' @param core numeric vactor (betw 0 and 1) for fraction of data to keep; if null trimmedMean/max hist occurance will be used, limited within 30-70 perent; may also be 'high' or 'low' for forcing low (20-60percent) or high (75-99) percent of data to retain #' @param keepOnly (logical) #' @param displPlot (logical) show plot of hist & boundaries #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns the index of values retained or if 'keepOnly' return list with 'keep' index and 'drop' index #' @seealso \code{\link{searchLinesAtGivenSlope}} #' @examples #' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)),ncol=10) #' @export .keepCenter1d <- function(dat1, core=NULL, keepOnly=TRUE, displPlot=FALSE, silent=TRUE, debug=FALSE, callFrom=NULL) { ## refine/filter 'dat1' (1dim dataset, eg cluster) with aim of keeping center of data ## based on most freq class of histogramm keep/filter data if 'core' (% of volume) are within 'core' (%) range ## or adopt to non-symmetric if most freq class is close to either end of distribution ## 'dat1 .. simple numeric vector ## 'core' .. numeric vactor (betw 0 and 1) for fraction of data to keep ## if null trimmedMean/max hist occurance will be used, limited within 30-70% ## may also be 'high' or 'low' for forcing low (20-60%) or high (75-99) % of data to retain ## 'displPlot' .. show plot of hist & boundaries ## not efficient if center very homogenous and very few values quite off !! ## return index of values retained or if 'keepOnly' return list with 'keep' index and 'drop' index fxNa <- .composeCallName(callFrom, newNa=".keepCenter1d") lim4cor <- c(0.3,0.7) if(identical(core, "high")) { lim4cor <- c(0.75,0.99) # upper & lower limits for automatic determination of 'core' (ie % of values to keep) core <- NULL } if(identical(core, "low")) { lim4cor <- c(0.2,0.6) # upper & lower limits for automatic determination of 'core' (ie % of values to keep) core <- NULL } dat1 <- signif(naOmit(dat1), 5) if(length(unique(dat1)) ==1) { if(!silent) message(fxNa,"All (slightly rounded) values identical ! (keep all)") out <- 1:length(dat1) return(if(keepOnly) out else list(keep=out, drop=NULL)) } else { his1 <- graphics::hist(dat1, breaks="FD", plot=FALSE) maxPo <- which(his1$counts==max(his1$counts, na.rm=TRUE)) # position of peak(s), ie mode based on hist maxVa <- if(length(maxPo)==1) his1$mids[maxPo] else sum(his1$mids[maxPo])/length(maxPo) if(length(maxPo) >1) { if(any(diff(maxPo)) >1) { if(!silent) message(fxNa," (multiple) non-neighbour peaks in hist") maxVa <- maxPo[round(stats::median(maxPo))] } } ## refine 'mode' in double resolution in +- 2 hist-classes range refWi <- 2.5*(his1$mids[2] -his1$mids[1]) useBr <- seq(maxVa -refWi, maxVa +refWi, length.out=11) tab <- table(cut(dat1[dat1 > maxVa -refWi & dat1 < maxVa +refWi], breaks=useBr)) useP <- which(tab==max(tab)) if(length(useP) >1) useP <- if(length(useP) %% 2 >0) stats::median(useP) else stats::median(useP[-1]) maxVa <- ((useBr[-1] +useBr[-length(useBr)])/2)[useP] # refined histogram 'mode' maxQu <- sum(dat1 <= maxVa)/length(dat1) # quantile of mode ## note: effort to find mode ('maxVa') using computeMode() from BBmisc was not at all satisfying ... ## note: fully tested against NAs ## automatic bandwidth ('core'=NULL) : based on ration max histogram class height / trimmed mean of heights if(is.null(core)) { core <- round(10*mean(his1$counts, trim=0.25)/his1$counts[which.max(his1$counts)], 3) # sharp peak ->low ratio, small core fraction if(!silent) message(fxNa,"Proposed value for core ",core," trim mean ", signif(mean(his1$counts, trim=0.25), 3)," max ",signif(his1$counts[which.max(his1$counts)], 3)) core <- round(sort(c(lim4cor, core))[2],3) } # keep proposed 'core' within limits .chSD <- function(x,y) {med <- stats::median(x,na.rm=TRUE); which(x > med -y*stats::sd(x,na.rm=TRUE) & x < med +y*stats::sd(x,na.rm=TRUE))} if(identical(core,"veryhigh")) { core <- 0.9 # must have some value for later use .. out <- .chSD(dat1, y=1) if(length(out) < length(dat1)*core) {out <- .chSD(dat1, y=1.5) } if(length(out) < length(dat1)*core) {out <- .chSD(dat1, y=2) } useQu <- c(sum(dat1 > min(dat1[out]) ,na.rm=TRUE), sum(dat1 > max(dat1[out]), na.rm=TRUE))/length(dat1) quaVa <- signif(stats::quantile(dat1, useQu), 4) } else { centrQu <- which(abs(dat1 -maxVa) ==min(abs(dat1 -maxVa))) useQu <- maxQu +c(-1,1)*core/2 # boundaries of range around mode if(core/2 > min(maxQu,1 -maxQu)) { useQu <- if(useQu[1] <0) c(0,core) else c(1 -core,1)} quaVa <- signif(stats::quantile(dat1, useQu), 4) ## examine boders if assymetric (but not due to fact of touching range of data), if too assym bring most far closer offSe <- abs(quaVa -maxVa) offSe <- offSe > 1.3*sum(offSe)/length(offSe) if(any(offSe) && !(any(useQu %in% c(0,1)))) { quaVa <- .bringToCtr(quaVa, maxVa) useQu[which(offSe)] <- sum(dat1 >= quaVa[which(offSe)])/length(dat1) } quaVa <- signif(quaVa,4) if(any(offSe) && !(any(useQu %in% c(0,1))) && !silent) message(fxNa, " ..new modified borders ",paste(quaVa,collapse=" ")) # result not ideal ? out <- which(dat1 >= quaVa[1] & dat1 <= quaVa[2]) } if(length(out) > length(dat1)*core & !silent) message(fxNa,"Keep ", round(length(out) -length(dat1)*core)," more elements than ",round(100*core),"%") if(displPlot) { chG <- try(graphics::plot(his1, col=grDevices::grey(0.8),border=grDevices::grey(0.7)), silent=TRUE) if(inherits(chG, "try-error")) message(fxNa,"UNABLE to draw plot !") else { graphics::mtext(paste("n=",length(dat1)), cex=0.8) graphics::abline(v=sort(c(quaVa,maxVa)), lty=c(2,1,2), col=grDevices::grey(0.4))}} if(!keepOnly) out <- list(keep=out, drop=(1:length(dat1))[-out], limits=useQu) out } }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/searchLinesAtGivenSlope.R
#' Simple figure showing line from start- to end-sites of edges (or fragments) defined by their start- and end-sites #' #' \code{simpleFragFig} draws figure showing start- and end-sites of edges (or fragments) #' #' @param frag (matrix) 2 columns defining begin- and end-sites (as interger values) #' @param fullSize (integer) optional max size used for figure (x-axis) #' @param sortByHead (logical) sort by begin-sites (if \code{TRUE}) or sort by end-sites #' @param useTit (character) custom title #' @param useCol (character) specify colors, if numeric vector will be onsidered as score values #' @param displNa (character) display names of edges (figure may get crowded) #' @param useCex (numeric) expansion factor, see also \code{\link[graphics]{par}} #' @return matrix with mean values #' @seealso \code{\link{buildTree}}, \code{\link{countSameStartEnd}}, \code{\link{contribToContigPerFrag}}, #' @examples #' frag2 <- cbind(beg=c(2,3,7,13,13,15,7,9,7, 3,7,5,7,3),end=c(6,12,8,18,20,20,19,12,12, 4,12,7,12,4)) #' rownames(frag2) <- c("A","E","B","C","D","F","H","G","I", "J","K","L","M","N") #' simpleFragFig(frag2,fullSize=21,sortByHead=TRUE) #' buildTree(frag2) #' @export simpleFragFig <- function(frag,fullSize=NULL,sortByHead=TRUE,useTit=NULL,useCol=NULL,displNa=TRUE,useCex=0.7){ useColumn <- c(1,2) opar <- list(yaxt=graphics::par("yaxt")) on.exit(graphics::par(opar)) fra <- frag[,useColumn] if("score" %in% colnames(fra)) useCol <- fra[,"score"] tmp <- table(as.numeric(fra)) lin <- sort(unique(names(tmp)[which(tmp > stats::median(tmp,na.rm=TRUE))])) ra <- range(as.numeric(fra),na.rm=TRUE) if(is.null(fullSize)) fullSize <- ra[2] if(is.numeric(useCol) & length(useCol)==nrow(fra)) { scoreV <- useCol col1 <- grDevices::rgb(red=c(179,131,135,203,253,244,255),green=c(170,204,221,211,174,109,0),blue=c(215,248,164,78,97,67,0),maxColorValue=255) # pale purple, pale blue, 2x pale green, 2x orange to red useCol <- col1[as.numeric(cut(useCol,length(col1)))][] } else scoreV <- NULL formDig <- function(x) sprintf(paste("%0",nchar(as.character(round(ra[2]))),"d",sep=""),x) reSort <- if(sortByHead) sort.list(paste(formDig(fra[,1]),formDig(fra[,2]))) else sort.list(paste(formDig(fra[,2]),formDig(fra[,1])),decreasing=TRUE) fra <- fra[reSort,] if(length(useCol) >1) useCol <- useCol[reSort] if(is.null(useCol)) useCol <- grDevices::grey(0.8) labOff <- round(ra[2]/40,1) graphics::par(yaxt="n") graphics::plot(c(1,fullSize),c(1,nrow(fra)),type="n",main=useTit,xlab="fragment location",ylab="",las=1) if(length(lin) >0) graphics::abline(v=lin,lty=2,col=grDevices::grey(0.7)) graphics::segments(x0=fra[,1],y0=1:nrow(fra),x1=fra[,2],y1=1:nrow(fra),lty=1,lwd=4,col=useCol) if(!is.null(rownames(fra)) & displNa) graphics::text(fra[,1]-labOff,1:nrow(fra),rownames(fra),cex=useCex) if(length(useCol) >1) { grpMean <- paste(">", signif(seq(min(scoreV),max(scoreV),length.out=2*length(col1)+1)[2*(1:length(col1))-1],3)) graphics::legend("bottomright",legend=grpMean,text.col="black",fill=col1,cex=0.8,xjust=0.5,yjust=0.5) } }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/simpleFragFig.R
#' 2-factorial Anova on single line of data #' #' This function runs 2-factorial Anova on a single line of data (using \code{\link[stats]{aov}} from package \code{stats}) #' using a model with two factors (without factor-interaction) and extracts the correpsonding p-value. #' #' @param dat numeric vector #' @param fac1 (character or factor) vector describing grouping elements of dat for first factor, must be of same langth as fac2 #' @param fac2 (character or factor) vector describing grouping elements of dat for second factor, must be of same langth as fac1 #' @param inclInteraction (logical) decide if factor-interactions (eg synergy) should be included to model #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns the (uncorrected) p for factor 'Pr(>F)' (see \code{\link[stats]{aov}}) #' @seealso \code{\link[stats]{aov}}, \code{\link[stats]{anova}}; for repeated tests using the package \href{https://bioconductor.org/packages/release/bioc/html/limma.html}{limma} including \code{\link[limma]{lmFit}} and \code{eBayes} see \code{\link{test2factLimma}} #' @examples #' set.seed(2012); dat <- round(runif(8),1) #' singleLineAnova(dat, gl(2,4),rep(1:2,4)) #' @export singleLineAnova <- function(dat, fac1, fac2, inclInteraction=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL){ fxNa <- .composeCallName(callFrom, newNa="singleLineAnova") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(debug) message(fxNa,"sLA1") if(!identical(length(fac1),length(fac2))) stop("Arguments 'fac1' & 'fac2' should be of same length !") tmp <- data.frame(dat=as.numeric(dat), fac1=fac1, fac2=fac2) tmp.aov <- if(inclInteraction) stats::aov(dat ~ fac1 + fac2 + fac1:fac2, data=tmp) else { stats::aov(dat ~ fac1 + fac2, data=tmp)} tmp <- stats::anova(tmp.aov)[["Pr(>F)"]] tmp[-1*length(tmp)] }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/singleLineAnova.R
#' Sort matrix by two categorical and one integer columns #' #' This function sorts matrix 'mat' subsequently by categorical and numerical columns of 'mat', #' ie lines with identical values for categor are sorted by numeric value. #' @param mat matrix (or data.frame) from which by 2 columns will be selected for sorting #' @param categCol (integer or character) which columns of 'mat' to be used as categorical columns #' @param numCol (integer or character) which column of 'mat' to be used as integer columns #' @param findNeighb (logical) if 'findNeighb' neighbour cols according to 'numCol' will be identified as groups & marked in new col 'neiGr', orphans marked as NA #' @param decreasing (logical) order of sort #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a sorted matrix (same dimensions as 'mat') #' @examples #' mat <- cbind(aa=letters[c(3,rep(7:8,3:4),4,4:6,7)],bb=LETTERS[rep(1:5,c(1,3,4,4,1))], #' nu=c(23:21,23,21,22,18:12)) #' mat[c(3:5,1:2,6:9,13:10),] #' sortBy2CategorAnd1IntCol(mat,cate=c("bb","aa"),num="nu",findN=FALSE,decr=TRUE) #' sortBy2CategorAnd1IntCol(mat,cate=c("bb","aa"),num="nu",findN=TRUE,decr=FALSE) #' @export sortBy2CategorAnd1IntCol <- function(mat, categCol, numCol, findNeighb=TRUE, decreasing=FALSE, silent=FALSE, debug=FALSE,callFrom=NULL) { fxNa <- .composeCallName(callFrom,newNa="sortBy2CategorAnd1IntCol") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(length(dim(mat)) <2) stop("'mat' should be matrix (or data.frame) with >2 cols and >1 line") if(length(numCol) <1) stop("'numCol' invalid") else if(length(numCol) >1) numCol <- numCol[1] if(is.numeric(numCol)) { numCol <- as.integer(numCol) if(numCol <1 || numCol >ncol(mat)) stop("'numCol' out of range of 'mat'") } else if(numCol %in% colnames(mat)) numCol <- match(numCol,colnames(mat)) else stop("cCan't find 'numCol' in colnames of 'mat'") dimIni <- dim(mat) ## main num <- as.numeric(mat[,numCol[1]]) mat <- mat[sort.list(num,decreasing=decreasing),] mat <- mat[sort.list(if(length(categCol)==2) paste(mat[,categCol[1]],mat[,categCol[2]]) else mat[,categCol[1]],decreasing=decreasing),] # combined sort for categor if(findNeighb){ num <- as.numeric(mat[,numCol[1]]) if(length(categCol)==2) { tmp <- paste(mat[,categCol[1]],mat[,categCol[2]]) isNei <- tmp[-1]==tmp[-nrow(mat)] } else isNei <- mat[-1,categCol[1]]==mat[-nrow(mat),categCol[1]] isNei <- c(FALSE,isNei) & c(0,num[-1] -num[-nrow(mat)])== (if(decreasing) -1 else 1) gr <- cumsum(!isNei) dup <- (duplicated(gr, fromLast=TRUE) | duplicated(gr, fromLast=FALSE)) if(any(!dup)) gr[which(!dup)] <- NA mat <- cbind(mat[,1:dimIni[2]],neiGr=gr) } mat }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/sortBy2CategorAnd1intCol.R
#' Make a list of common occurances sorted by number of repeats #' #' The aim of this function is to count the number of occurances of words when comaring separate vectors (\code{x}, \code{y} and \code{z}) or from a list (given as \code{x}) #' and to give an output sorted by their frequency. #' The output lists the various values/words by their frequency, the names of the resulting list-elements indicate number of times the values/words were found repeated. #' #' @details #' #' In order to compare the frquency of values/words between separate vectors or vectors within a list, it is necessary that these have been made unique before calling this function or using \code{filterIntraRep=TRUE}. #' #' In case the input is given as list (in \code{x}), there is no restriction to the number of vectors to be compared. #' With very long lists, however, the computational effort incerases (like it does when using \code{table}) #' #' @param x (list, character or integer) main input, if list, arguments \code{y} and \code{z} will not be used #' @param y (character or integer) supplemental vector to comare with \code{x} #' @param z (character or integer) supplemental vector to comare with \code{x} #' @param filterIntraRep (logical) allow making vectors \code{x}, \code{y} and \code{z} unique before comparing (defaults to \code{TRUE}) #' @param silent (logical) suppress messages #' @param debug (logical) additional messages for debugging #' @param callFrom (character) allow easier tracking of messages produced #' @return This function returns a list sorted by number of occurances. The names of the list indicate the number of repeats. #' @seealso \code{\link[base]{table}}, \code{\link[wrMisc]{replicateStructure}} #' @examples #' sortByNRepeated(x=LETTERS[1:11], y=LETTERS[3:13], z=LETTERS[6:12]) #' sortByNRepeated(x=LETTERS[1:11], y=LETTERS[c(3:13,5:4)], z=LETTERS[6:12]) #' #' @export sortByNRepeated <- function(x, y=NULL, z=NULL, filterIntraRep=TRUE, silent=TRUE, debug=FALSE, callFrom=NULL) { ## move to wrMisc with combineAsN() ## make list of common occurances sorted by number of repeats based on list of character-entries/words (eg peptide sequ) or up to 3 separate character vectors ## the name of output indicates number onf times all elements of the vector are repeated ## for 4 sets of data provide 'x' in form of list conatining all data fxNa <- .composeCallName(callFrom, newNa="sortByNRepeated") if(!isTRUE(silent)) silent <- FALSE if(isTRUE(debug)) silent <- FALSE else debug <- FALSE if(length(x) >1 && is.list(x)) { if(length(y) >0) x[length(x) +1] <- unlist(y) if(length(z) >0) x[length(x) +1] <- unlist(z) } else {x <- list(x=x, y=y, z=z); rm(y,z)} chLe <- sapply(x, length) >0 if(debug) { message(fxNa,"sBYN1 list-elements >0 ",pasteC(chLe))} ## remove empty list-elements if(!all(!chLe) && any(!chLe)) { x <- x[which(chLe)] if(debug) message(fxNa,"Removing ",sum(!chLe)," empty entries (out of ",length(x),")") chLe <- sapply(x, length) >0 } if(debug) {message(fxNa,"sBYN2 length of list-elements >0 ",pasteC(sapply(x,length))) } if(length(x) <2) { if(!silent) message(fxNa,"Only ",length(x)," set(s) of data provided", if(length(x) <1 | filterIntraRep)" nothing to do !") if(length(x) ==1) { ## simple case : single vector to treat chDu <- duplicated(x[[1]]) if(any(chDu) & filterIntraRep) x[[1]] <- unique(naOmit(x[[1]])) out2 <- table(table(x[[1]])) out <- rep(0, max(as.integer(names(out2)))) out[match(as.integer(names(out2)), 1:max(as.integer(names(out2))) )] <- out2 if(length(out) >1) { out <- c(out[1:3], min2=sum(out[2:3],na.rm=TRUE), any=sum(out), if(length(out) >3) out[4:length(out)]) } else out <- c(out,0,0,0,out) out <- array(c(out, rep(NA, length(out)*3)), dim=c(length(out),1,4), dimnames=list( c("sing","doub","trip","min2","any", if(length(out) >5) paste0("x",4:(length(out) +2))), names(x[[1]]), c("n","sem","CI","sd")) ) } else out <- NULL } else { ## check/remove for internal repeats if(filterIntraRep) { chDu <- lapply(x, duplicated) chDu2 <- sapply(chDu, any) if(any(chDu2)) { if(debug) message(fxNa,sum(chDu2)," list elements contain (intra-) duplicated elements, need to remove for correct inter-comparison") for(i in which(chDu2)) x[[i]] <- x[[i]][which(!chDu[[i]])] } } if(debug) {message(fxNa,"sBYN3 length of list-elements ",pasteC(sapply(x,length))) } ## sort according to level of duplication x <- table(unlist(x, use.names=FALSE)) ta2 <- table(x) out <- sapply(names(ta2), function(y) names(x)[which(x==as.integer(y))]) } out }
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/sortByNRepeated.R