content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
#' Get predicted data from fitted GAMs across period of observation, every day
#'
#' Get predicted data from fitted GAMs across period of observation, every day
#'
#' @inheritParams anlz_prd
#'
#' @return a \code{data.frame} with predictions
#' @export
#'
#' @concept analyze
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl') %>%
#' filter(yr > 2015)
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#' anlz_prdday(mod)
anlz_prdday <- function(mod) {
# get daily predictions, differs from anlz_prd
rng <- mod$model$cont_year %>%
range(na.rm = T) %>%
lubridate::date_decimal() %>%
as.Date
data <- seq.Date(lubridate::floor_date(rng[1], 'year'), lubridate::ceiling_date(rng[2], 'year'), by = 'days') %>%
tibble::tibble(date = .) %>%
dplyr::mutate(
doy = lubridate::yday(date),
cont_year = lubridate::decimal_date(date),
yr = lubridate::year(date)
)
prd <- predict(mod, newdata = data)
out <- data.frame(data, value = prd, trans = mod$trans, stringsAsFactors = F) %>%
anlz_backtrans()
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/anlz_prdday.R
|
#' Get prediction matrix for a fitted GAM
#'
#' Get prediction matrix for a fitted GAM
#'
#' @param mod input model object as returned by \code{\link{anlz_gam}}
#' @param doystr numeric indicating start Julian day for extracting averages
#' @param doyend numeric indicating ending Julian day for extracting averages
#' @param avemat logical indicating if the prediction matrix is to be passed to \code{anlz_metseason} (default) or \code{anlz_avgseason}
#'
#' @return a \code{data.frame} with predictors to use with the fitted GAM
#' @export
#'
#' @details Used internally by \code{\link{anlz_metseason}}, not to be used by itself
#'
#' @concept analyze
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl') %>%
#' filter(yr > 2015)
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#' anlz_prdmatrix(mod, doystr = 90, doyend = 180)
anlz_prdmatrix <- function(mod, doystr = 1, doyend = 364, avemat = FALSE){
# create uniform matrix if metric is average
if(avemat){
# date range
dtrng <- range(mod$model$cont_year, na.rm = T) %>%
lubridate::date_decimal() %>%
as.Date
# number of days in season subset
numDays <- doyend - doystr + 1
# prediction data, daily time step, subset by doystr, doyend
out <- data.frame(date = seq.Date(dtrng[1], dtrng[2], by = 'day')) %>%
dplyr::mutate(
yr = lubridate::year(date),
doy = lubridate::yday(date),
cont_year = lubridate::decimal_date(date)
) %>%
dplyr::filter(doy >= doystr & doy <= doyend) %>%
dplyr::group_by(yr) %>%
dplyr::mutate(
dayCounts = dplyr::n()
) %>%
dplyr::ungroup() %>%
dplyr::filter(dayCounts == numDays) %>%
dplyr::select(-dayCounts)
}
# create exact matrix if not average
if(!avemat){
# date range
dtrng <- range(mod$model$cont_year, na.rm = T) %>%
lubridate::date_decimal() %>%
as.Date %>%
lubridate::year(.)
dtrng <- c(as.Date(doystr - 1, origin = paste0(dtrng[1], '-01-01')), as.Date(doyend -1, origin = paste0(dtrng[2], '-01-01')))
# prediction data, daily time step, subset by doystr, doyend
out <- data.frame(date = seq.Date(dtrng[1], dtrng[2], by = 'day')) %>%
dplyr::mutate(
yr = lubridate::year(date),
doy = lubridate::yday(date),
cont_year = lubridate::decimal_date(date)
) %>%
dplyr::filter(doy >= doystr & doy <= doyend)
}
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/anlz_prdmatrix.R
|
#' Format p-values for show functions
#'
#' @param x numeric input p-value
#'
#' @return p-value formatted as a text string, one of \code{p < 0.001}, \code{'p < 0.01'}, \code{p < 0.05}, or \code{ns} for not significant
#' @export
#'
#' @concept analyze
#'
#' @examples
#' anlz_pvalformat(0.05)
anlz_pvalformat <- function(x){
sig_cats <- c('p < 0.001', 'p < 0.01', 'p < 0.05', 'ns')
sig_vals <- c(-Inf, 0.001, 0.01, 0.05, Inf)
out <- cut(x, breaks = sig_vals, labels = sig_cats, right = FALSE)
out <- as.character(out)
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/anlz_pvalformat.R
|
#' Return summary statistics for smoothers of GAMs
#'
#' Return summary statistics for smoothers of GAMs
#'
#' @param mod input model object as returned by \code{\link{anlz_gam}}
#'
#' @return a \code{data.frame} with summary statistics for smoothers in each GAM
#' @export
#'
#' @details Results show the individual effects of the modelled components of each model as the estimated degrees of freedom (\code{edf}), the reference degrees of freedom (\code{Ref.df}), the test statistic (\code{F}), and significance of the component (\code{p-value}). The significance of the component is in part based on the difference between \code{edf} and \code{Ref.df}.
#'
#' @concept analyze
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl')
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#' anlz_smooth(mod)
anlz_smooth <- function(mod) {
out <- summary(mod)$s.table %>%
data.frame %>%
tibble::rownames_to_column('smoother')
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/anlz_smooth.R
|
#' Estimate seasonal rates of change based on average estimates for multiple window widths
#'
#' Estimate seasonal rates of change based on average estimates for multiple window widths
#'
#' @param mod input model object as returned by \code{\link{anlz_gam}}
#' @param doystr numeric indicating start Julian day for extracting averages
#' @param doyend numeric indicating ending Julian day for extracting averages
#' @param justify chr string indicating the justification for the trend window
#' @param win numeric vector indicating number of years to use for the trend window
#'
#' @return A data frame of slope estimates and p-values for each year
#' @export
#'
#' @concept analyze
#'
#' @details This function is a wrapper to \code{\link{anlz_trndseason}} to loop across values in \code{win}, using \code{useave = TRUE} for quicker calculation of average seasonal metrics. It does not work with any other seasonal metric calculations.
#'
#' @family analyze
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl') %>%
#' filter(yr > 2015)
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#' anlz_sumtrndseason(mod, doystr = 90, doyend = 180, justify = 'center', win = 2:3)
anlz_sumtrndseason <- function(mod, doystr = 1, doyend = 364, justify = c('center', 'left', 'right'), win = 5:15){
justify <- match.arg(justify)
tmp <- NULL
for(i in win){
res <- anlz_trndseason(mod, metfun = mean, doystr = doystr, doyend = doyend, justify = justify, win = i, useave = T)
res$win <- i
tmp <- rbind(tmp, res)
}
out <- tmp %>%
dplyr::select(yr, yrcoef, pval, win)
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/anlz_sumtrndseason.R
|
#' Transform response variable
#'
#' Transform response variable prior to fitting GAM
#'
#' @param moddat input raw data, one station and paramater
#' @param trans chr string indicating desired type of transformation, one of \code{log10} or \code{ident} (no transformation)
#'
#' @return \code{moddat} with the \code{value} column transformed as indicated
#' @export
#'
#' @concept analyze
#'
#' @family analyze
#'
#' @examples
#' library(dplyr)
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl')
#' anlz_trans(tomod, trans = 'log10')
anlz_trans <- function(moddat, trans = c('log10', 'ident')){
if(length(unique(moddat$param)) > 1)
stop('More than one parameter found in input data')
if(length(unique(moddat$station)) > 1)
stop('More than one station found in input data')
trans <- match.arg(trans)
if(trans == 'log10'){
# deal with values less than or equal to 0
if(any(moddat$value <= 0)){
warning("values <= 0 set to NA for trans = 'log10'")
moddat$value[moddat$value <= 0] <- NA
}
moddat <- moddat %>%
dplyr::mutate(
value = log10(value)
)
}
moddat <- moddat %>%
dplyr::mutate(
trans = trans
)
return(moddat)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/anlz_trans.R
|
#' Estimate rates of change based on seasonal metrics
#'
#' Estimate rates of change based on seasonal metrics
#'
#' @param mod input model object as returned by \code{\link{anlz_gam}}
#' @param metfun function input for metric to calculate, e.g., \code{mean}, \code{var}, \code{max}, etc
#' @param doystr numeric indicating start Julian day for extracting averages
#' @param doyend numeric indicating ending Julian day for extracting averages
#' @param justify chr string indicating the justification for the trend window
#' @param win numeric indicating number of years to use for the trend window, see details
#' @param nsim numeric indicating number of random draws for simulating uncertainty
#' @param useave logical indicating if \code{anlz_avgseason} is used for the seasonal metric calculation
#' @param ... additional arguments passed to \code{metfun}, e.g., \code{na.rm = TRUE)}
#'
#' @return A data frame of slope estimates and p-values for each year
#' @export
#'
#' @concept analyze
#'
#' @details Trends are based on the slope of the fitted linear trend within the window, where the linear trend is estimated using a meta-analysis regression model (from \code{\link{anlz_mixmeta}}) for the seasonal metrics (from \code{\link{anlz_metseason}}).
#'
#' Note that for left and right windows, the exact number of years in \code{win} is used. For example, a left-centered window for 1990 of ten years will include exactly ten years from 1990, 1991, ... , 1999. The same applies to a right-centered window, e.g., for 1990 it would include 1981, 1982, ..., 1990 (if those years have data). However, for a centered window, picking an even number of years for the window width will create a slightly off-centered window because it is impossible to center on an even number of years. For example, if \code{win = 8} and \code{justify = 'center'}, the estimate for 2000 will be centered on 1997 to 2004 (three years left, four years right, eight years total). Centering for window widths with an odd number of years will always create a symmetrical window, i.e., if \code{win = 7} and \code{justify = 'center'}, the estimate for 2000 will be centered on 1997 and 2003 (three years left, three years right, seven years total).
#'
#' @family analyze
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl') %>%
#' filter(yr > 2015)
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#' anlz_trndseason(mod, doystr = 90, doyend = 180, justify = 'center', win = 4)
anlz_trndseason <- function(mod, metfun = mean, doystr = 1, doyend = 364, justify = c('center', 'left', 'right'), win = 5, nsim = 1e4, useave = FALSE, ...){
justify <- match.arg(justify)
# check if metfun input is mean
chk <- identical(deparse(metfun), deparse(mean))
# make sure user wants average and useave
if(!chk & useave)
stop('Specify metfun = mean if useave = T')
# estimate metrics
if(useave)
metseason <- anlz_avgseason(mod, doystr = doystr, doyend = doyend)
if(!useave)
metseason <- anlz_metseason(mod, metfun, doystr = doystr, doyend = doyend, nsim = nsim, ...)
tmp <- tibble::tibble(metseason)
tmp$yrcoef <- NaN
tmp$pval <- NaN
# iterate through years to get trend
for(i in seq_along(tmp$yr)){
yr <- tmp$yr[i]
if(justify == 'left')
mixmet <- anlz_mixmeta(tmp, yrstr = yr, yrend = yr + win - 1)
if(justify == 'right')
mixmet <- anlz_mixmeta(tmp, yrstr = yr - win + 1, yrend = yr)
if(justify == 'center'){
yrstr <- floor(yr - win / 2) + 1
yrend <- floor(yr + win / 2)
mixmet <- anlz_mixmeta(tmp, yrstr = yrstr, yrend = yrend)
}
if(inherits(mixmet, 'logical'))
next
# get slope
slope <- mixmet$coefficients['yr']
slope_lwr <- summary(mixmet)$coefficients[2, 5]
slope_upr <- summary(mixmet)$coefficients[2, 6]
if(mod$trans == 'log10'){
dispersion <- summary(mod)$dispersion
bt_prd <- 10 ^ (predict(mixmet) + log(10) * dispersion / 2)
df <- data.frame(chl = bt_prd, yr = mixmet$model$yr)
apprslope <- lm(chl ~ yr, df) %>% summary %>% coefficients %>% .[2, 1]
tmp[i, 'appr_yrcoef'] <- apprslope
}
tmp[i, 'yrcoef'] <- slope
tmp[i, 'yrcoef_lwr'] <- slope_lwr
tmp[i, 'yrcoef_upr'] <- slope_upr
tmp[i, 'pval'] <- coefficients(summary(mixmet)) %>% data.frame %>% .[2, 4]
}
out <- tmp
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/anlz_trndseason.R
|
globalVariables(c('%>%', '.', 'AIC', 'S', 'annvalue', 'met', 'bl', 'lwr', 'upr', 'cont_year', 'bt_met',
'bt_lwr', 'bt_upr', 'day', 'doy', 'month', 'pval', 'se', 'trans', 'value', 'xmax', 'xmin',
'xval', 'yr', 'yrcoef', 'appr_yrcoef', 'yrcoef_lwr', 'yrcoef_upr', 'dayCounts', 'data',
'psig', 'trnd'))
#' @importFrom stats AIC as.formula coef coefficients lm na.exclude na.omit pt predict qnorm resid sd update
NULL
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/globalVariables.R
|
#' Raw data from San Francisco Estuary (South Bay)
#'
#' Raw data from San Francisco Estuary (South Bay)
#'
#' @format A \code{data.frame} object with 12411 rows and 8 columns
#' \describe{
#' \item{date}{Date}
#' \item{station}{int}
#' \item{param}{chr}
#' \item{value}{num}
#' \item{doy}{num}
#' \item{cont_year}{num}
#' \item{yr}{num}
#' \item{mo}{Ord.factor}
#' }
#' @family utilities
#'
#' @details
#' Data from \code{datprc} object in \url{https://github.com/fawda123/SFbaytrends}
"rawdat"
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/rawdat.R
|
#' Plot period (seasonal) averages from fitted GAM
#'
#' Plot period (seasonal) averages from fitted GAM
#'
#' @param mod input model object as returned by \code{\link{anlz_gam}}
#' @param doystr numeric indicating start Julian day for extracting averages
#' @param doyend numeric indicating ending Julian day for extracting averages
#' @param metfun function input for metric to calculate, e.g., \code{mean}, \code{var}, \code{max}, etc
#' @param yrstr numeric for starting year for trend model, see details
#' @param yrend numeric for ending year for trend model, see details
#' @param yromit optional numeric vector for years to omit from the plot, see details
#' @param ylab chr string for y-axis label
#' @param width numeric for width of error bars
#' @param size numeric for point size
#' @param nsim numeric indicating number of random draws for simulating uncertainty
#' @param useave logical indicating if \code{anlz_avgseason} is used for the seasonal metric calculation
#' @param base_size numeric indicating base font size, passed to \code{\link[ggplot2]{theme_bw}}
#' @param xlim optional numeric vector of length two for x-axis limits
#' @param ylim optional numeric vector of length two for y-axis limits
#' @param ... additional arguments passed to \code{metfun}, e.g., \code{na.rm = TRUE)}
#'
#' @return A \code{\link[ggplot2]{ggplot}} object
#' @export
#'
#' @details
#'
#' Setting \code{yrstr} or \code{yrend} to \code{NULL} will suppress plotting of the trend line for the meta-analysis regression model.
#'
#' The optional \code{omityr} vector can be used to omit years from the plot and trend assessment. This may be preferred if seasonal estimates for a given year have very wide confidence intervals likely due to limited data, which can skew the trend assessments.
#'
#' Set \code{useave = T} to speed up calculations if \code{metfun = mean}. This will use \code{\link{anlz_avgseason}} to estimate the seasonal summary metrics using a non-stochastic equation.
#'
#' @concept show
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl') %>%
#' filter(yr > 2015)
#'
#' mod <- anlz_gam(tomod, trans = 'ident')
#'
#' show_metseason(mod, doystr = 90, doyend = 180, yrstr = 2016, yrend = 2019,
#' ylab = 'Chlorophyll-a (ug/L)')
#'
#' \donttest{
#' # show seasonal metrics without annual trend
#' show_metseason(mod, doystr = 90, doyend = 180, yrstr = NULL, yrend = NULL,
#' ylab = 'Chlorophyll-a (ug/L)')
#'
#' # omit years from the analysis
#' show_metseason(mod, doystr = 90, doyend = 180, yrstr = 2015, yrend = 2019,
#' yromit = 2018, ylab = 'Chlorophyll-a (ug/L)')
#' }
show_metseason <- function(mod, metfun = mean, doystr = 1, doyend = 364, yrstr = 2000, yrend = 2019, yromit = NULL, ylab, width = 0.9, size = 1.5, nsim = 1e4, useave = FALSE, base_size = 11, xlim = NULL, ylim = NULL, ...) {
# check if metfun input is mean
chk <- identical(deparse(metfun), deparse(mean))
# make sure user wants average and useave
if(!chk & useave)
stop('Specify metfun = mean if useave = T')
# estimate metrics
if(useave)
metseason <- anlz_avgseason(mod, doystr = doystr, doyend = doyend)
if(!useave)
metseason <- anlz_metseason(mod, metfun, doystr = doystr, doyend = doyend, nsim = nsim, ...)
# omit years if yromit provided
if(!is.null(yromit))
metseason <- metseason %>%
dplyr::filter(!yr %in% yromit)
# transformation used
trans <- mod$trans
# title
dts <- as.Date(c(doystr, doyend), origin = as.Date("2000-12-31"))
strt <- paste(lubridate::month(dts[1], label = T, abbr = T), lubridate::day(dts[1]))
ends <- paste(lubridate::month(dts[2], label = T, abbr = T), lubridate::day(dts[2]))
func <- as.character(substitute(metfun))
ttl <- paste0('Est. ', func, ' with 95% confidence intervals: ', strt, '-', ends)
# subtitle only if any years missing
subttl <- NULL
# plot objects
toplo1 <- metseason
# plot output
p <- ggplot2::ggplot(data = toplo1, ggplot2::aes(x = yr, y = bt_met)) +
ggplot2::geom_point(colour = 'deepskyblue3', size = size) +
ggplot2::geom_errorbar(ggplot2::aes(ymin = bt_lwr, ymax = bt_upr), colour = 'deepskyblue3', width = width) +
ggplot2::theme_bw(base_size = base_size) +
ggplot2::theme(
axis.title.x = ggplot2::element_blank()
)
# get mixmeta models and plotting results
if(!is.null(yrstr) & !is.null(yrend)){
# get mixmeta models
mixmet <- anlz_mixmeta(metseason, yrstr = yrstr, yrend = yrend, yromit = yromit)
toplo2 <- data.frame(
yr = seq(yrstr, yrend, length = 50)
) %>%
dplyr::mutate(
met = predict(mixmet, newdata = data.frame(yr = yr)),
se = predict(mixmet, newdata = data.frame(yr = yr), se = T)[, 2],
bt_lwr = met - 1.96 * se,
bt_upr = met + 1.96 * se,
bt_met = met
)
# subtitle info
pval <- coefficients(summary(mixmet)) %>% data.frame %>% .[2, 4] %>% anlz_pvalformat()
# backtransform if log10
if(mod$trans == 'log10'){
dispersion <- summary(mod)$dispersion
# backtransform mixmeta predictions
toplo2 <- data.frame(
yr = seq(yrstr, yrend, length = 50)
) %>%
dplyr::mutate(
met = predict(mixmet, newdata = data.frame(yr = yr)),
se = predict(mixmet, newdata = data.frame(yr = yr), se = T)[, 2],
bt_lwr = 10^((met - 1.96 * se) + log(10) * dispersion / 2),
bt_upr = 10^((met + 1.96 * se) + log(10) * dispersion / 2),
bt_met = 10^(met + log(10) * dispersion / 2)
)
# for subtitle
slope <- lm(bt_met ~ yr, toplo2) %>% summary %>% coefficients %>% .[2, 1]
slope <- round(slope, 2)
logslope <- summary(mixmet)$coefficients[2, c(1, 5, 6)]
logslope <- round(logslope, 2)
logslope <- paste0(logslope[1], ' (', logslope[2], ', ', logslope[3], ')')
subttl <- paste0('Trend from ', yrstr, ' to ', yrend, ': approximate slope ', slope, ', log-slope ', logslope, ', ', pval)
}
if(mod$trans == 'ident'){
slope <- summary(mixmet)$coefficients[2, c(1, 5, 6)]
slope <- round(slope, 2)
slope <- paste0(slope[1], ' (', slope[2], ', ', slope[3], ')')
subttl <- paste0('Trend from ', yrstr, ' to ', yrend, ': slope ', slope, ', ', pval)
}
p <- p +
ggplot2::geom_ribbon(data = toplo2, ggplot2::aes(ymin = bt_lwr, ymax = bt_upr), fill = 'pink', alpha = 0.4) +
ggplot2::geom_line(data = toplo2, color = 'pink')
}
p <- p +
ggplot2::labs(
title = ttl,
subtitle = subttl,
y = ylab
) +
ggplot2::coord_cartesian(
xlim = xlim,
ylim = ylim
)
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/show_metseason.R
|
#' Plot seasonal metrics and rates of change
#'
#' Plot seasonal metrics and rates of change
#'
#' @inheritParams anlz_trndseason
#' @param yromit optional numeric vector for years to omit from the plot, see details
#' @param ylab chr string for y-axis label
#' @param width numeric for width of error bars
#' @param size numeric for point size
#' @param nms optional character vector for trend names, see details
#' @param cols optional character vector for point colors, see details
#' @param cmbn logical indicating if the no trend and on estimate colors should be combined, see details
#' @param base_size numeric indicating base font size, passed to \code{\link[ggplot2]{theme_bw}}
#' @param xlim optional numeric vector of length two for x-axis limits
#' @param ylim optional numeric vector of length two for y-axis limits
#'
#' @details
#' The plot is the same as that returned by \code{\link{show_metseason}} with the addition of points for the seasonal metrics colored by the trends estimated from \code{\link{anlz_trndseason}} for the specified window and justification.
#'
#' Four colors are used to define increasing, decreasing, no trend, or no estimate (i.e., too few points for the window). The names and the colors can be changed using the \code{nms} and \code{cols} arguments, respectively. The \code{cmbn} argument can be used to combine the no trend and no estimate colors into one color and label. Although this may be desired for aesthetic reasons, the colors and labels may be misleading with the default names since no trend is shown for points where no estimates were made.
#'
#' @concept show
#'
#' @return A \code{\link[ggplot2]{ggplot}} object
#' @export
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl') %>%
#' filter(yr > 2015)
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#' show_mettrndseason(mod, metfun = mean, doystr = 90, doyend = 180, justify = 'center',
#' win = 4, ylab = 'Chlorophyll-a (ug/L)')
show_mettrndseason <- function(mod, metfun = mean, doystr = 1, doyend = 364, justify = c('center', 'left', 'right'), win = 5, nsim = 1e4, useave = FALSE, yromit = NULL, ylab, width = 0.9, size = 3, nms = NULL, cols = NULL, cmbn = F, base_size = 11, xlim = NULL, ylim = NULL, ...){
# get seasonal metrics and trends
trndseason <- anlz_trndseason(mod = mod, metfun, doystr = doystr, doyend = doyend, justify = justify, win = win, useave = useave)
# handle nms and cols args if not combine (keep no trend and no estimate)
if(!cmbn){
if(is.null(nms)) nms <- c("Increasing", "Decreasing", "No trend", "No estimate")
if(is.null(cols)) cols <- c('tomato1', 'deepskyblue3', 'white', 'darkgrey')
if(length(cols) != 4 | length(nms) != 4)
stop('Four names or colors must be provided')
# plot objects, add column for trend
trndseason <- trndseason %>%
dplyr::mutate(
trnd = dplyr::case_when(
yrcoef > 0 & pval < 0.05 ~ cols[1],
yrcoef < 0 & pval < 0.05 ~ cols[2],
pval >= 0.05 ~ cols[3],
is.na(yrcoef) ~ cols[4]
),
trnd = factor(trnd, levels = cols, labels = nms)
)
}
# handle nms and cols args if combine (combine no trend and no estimate)
if(cmbn){
if(is.null(nms)) nms <- c("Increasing", "Decreasing", "No trend")
if(is.null(cols)) cols <- c('tomato1', 'deepskyblue3', 'white')
if(length(cols) != 3 | length(nms) != 3)
stop('Three names or colors must be provided')
# plot objects, add column for trend
trndseason <- trndseason %>%
dplyr::mutate(
trnd = dplyr::case_when(
yrcoef > 0 & pval < 0.05 ~ cols[1],
yrcoef < 0 & pval < 0.05 ~ cols[2],
pval >= 0.05 | is.na(yrcoef) ~ cols[3]
),
trnd = factor(trnd, levels = cols, labels = nms)
)
}
names(cols) <- nms
# omit years if yromit provided
if(!is.null(yromit))
trndseason <- trndseason %>%
dplyr::filter(!yr %in% yromit)
# title
dts <- as.Date(c(doystr, doyend), origin = as.Date("2000-12-31"))
strt <- paste(lubridate::month(dts[1], label = T, abbr = T), lubridate::day(dts[1]))
ends <- paste(lubridate::month(dts[2], label = T, abbr = T), lubridate::day(dts[2]))
func <- as.character(substitute(metfun))
ttl <- paste0('Est. ', func, ' with 95% confidence intervals: ', strt, '-', ends)
# subtitle for trend window
subttl <- paste0('Points colored by trend for ', win, '-year, ', justify, '-justified window')
toplo <- trndseason
# plot output
p <- ggplot2::ggplot(data = toplo, ggplot2::aes(x = yr, y = bt_met)) +
ggplot2::geom_errorbar(ggplot2::aes(ymin = bt_lwr, ymax = bt_upr), colour = 'black', width = width) +
ggplot2::geom_point(ggplot2::aes(fill = trnd), pch = 21, color = 'black', size = size) +
ggplot2::theme_bw(base_size = base_size) +
ggplot2::scale_fill_manual(values = cols, drop = F) +
ggplot2::theme(
axis.title.x = ggplot2::element_blank(),
legend.position = 'top'
) +
ggplot2::labs(
title = ttl,
subtitle = subttl,
y = ylab,
fill = NULL
) +
ggplot2::coord_cartesian(
xlim = xlim,
ylim = ylim
)
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/show_mettrndseason.R
|
#' Plot percent change trends from GAM results for selected time periods
#'
#' Plot percent change trends from GAM results for selected time periods
#'
#' @inheritParams anlz_perchg
#' @param ylab chr string for y-axis label
#' @param base_size numeric indicating base font size, passed to \code{\link[ggplot2]{theme_bw}}
#' @param xlim optional numeric vector of length two for x-axis limits
#' @param ylim optional numeric vector of length two for y-axis limits
#'
#' @return A \code{\link[ggplot2]{ggplot}} object
#' @export
#'
#' @concept show
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl')
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#'
#' show_perchg(mod, baseyr = 1990, testyr = 2016, ylab = 'Chlorophyll-a (ug/L)')
show_perchg <- function(mod, baseyr, testyr, ylab, base_size = 11, xlim = NULL, ylim = NULL) {
# get change estimates
chg <- anlz_perchg(mod, baseyr = baseyr, testyr = testyr) %>%
dplyr::mutate(pval = anlz_pvalformat(pval)) %>%
dplyr::mutate_if(is.numeric, round, 2)
ttl <- paste0('Base: ', chg$baseval, ', Test: ', chg$testval, ', Change: ', chg$perchg, '%, ', chg$pval)
# get predictions
prds <- anlz_prd(mod)
# get transformation
trans <- unique(prds$trans)
# get raw data from model
tobacktrans <- mod$model %>%
dplyr::mutate(
trans = mod$trans
)
moddat <- anlz_backtrans(tobacktrans) %>%
dplyr::mutate(
date = lubridate::date_decimal(cont_year),
date = as.Date(date)
)
# boundaries for base, test years
trndswn <- prds %>%
dplyr::filter(yr %in% c(baseyr, testyr)) %>%
dplyr::group_by(yr) %>%
dplyr::filter(date %in% range(date)) %>%
dplyr::ungroup() %>%
dplyr::mutate(
xval = ifelse(duplicated(yr), 'xmax', 'xmin'),
bl = dplyr::case_when(
yr %in% baseyr ~ 'baseyr',
yr %in% testyr ~ 'testyr'
)
) %>%
dplyr::select(xval, yr, bl, date) %>%
tidyr::spread(xval, date)
rctmn <- ifelse(trans == 'ident', -Inf, 0)
p <- ggplot2::ggplot() +
ggplot2::geom_rect(data = trndswn, ggplot2::aes(xmin = xmin, xmax = xmax, ymin = rctmn, ymax = Inf, group = yr, fill = bl), alpha = 0.7) +
ggplot2::geom_point(data = moddat, ggplot2::aes(x = date, y = value), size = 0.5) +
ggplot2::geom_line(data = prds, ggplot2::aes(x = date, y = value), size = 0.75, alpha = 0.8) +
ggplot2::theme_bw(base_size = base_size) +
ggplot2::scale_fill_manual(values = c('lightblue', 'lightgreen')) +
ggplot2::theme(
legend.position = 'none',
legend.title = ggplot2::element_blank(),
axis.title.x = ggplot2::element_blank()
) +
ggplot2::labs(
title = ttl,
y = ylab
) +
ggplot2::coord_cartesian(
xlim = xlim,
ylim = ylim
)
if(trans != 'ident')
p <- p + ggplot2::scale_y_log10()
# return(suppressWarnings(print(p))
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/show_perchg.R
|
#' Plot a 3-d surface of predictions
#'
#' Plot a 3-d surface of predictions
#'
#' @inheritParams anlz_prd
#' @param ylab chr string for y-axis label
#'
#' @return a \code{plotly} surface
#' @export
#'
#' @concept show
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl') %>%
#' filter(yr > 2015)
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#'
#' show_prd3d(mod, ylab = 'Chlorophyll-a (ug/L)')
show_prd3d <- function(mod, ylab) {
# get daily predictions, differs from anlz_prd
prds <- anlz_prdday(mod)
toplo <- prds %>%
dplyr::select(-date, -cont_year, -trans) %>%
dplyr::filter(!yr %in% 2018) %>%
tidyr::spread(yr, value) %>%
dplyr::select(-doy) %>%
as.matrix
scene <- list(
aspectmode = 'manual',
aspectratio = list(x = 1, y = 1, z = 0.75),
xaxis = list(title = 'Years from time zero'),
yaxis = list(title = 'Day of year'),
zaxis = list(title = ylab),
roughness = .01,
ambient = 0.9
)
p <- plotly::plot_ly(z = ~toplo, height = 600) %>%
plotly::add_surface(colors = viridisLite::viridis(12)) %>%
plotly::layout(scene = scene)
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/show_prd3d.R
|
#' Plot predictions for GAMs against day of year
#'
#' Plot predictions for GAMs against day of year
#'
#' @param mod input model object as returned by \code{\link{anlz_gam}}
#' @param ylab chr string for y-axis label
#' @param size numeric indicating line size
#' @param alpha numeric from 0 to 1 indicating line transparency
#' @param base_size numeric indicating base font size, passed to \code{\link[ggplot2]{theme_bw}}
#'
#' @return A \code{\link[ggplot2]{ggplot}} object
#' @export
#'
#' @concept show
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl')
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#'
#' show_prddoy(mod, ylab = 'Chlorophyll-a (ug/L)')
show_prddoy <- function(mod, ylab, size = 0.5, alpha = 1, base_size = 11){
# get predictions
prds <- anlz_prd(mod)
# get transformation
trans <- unique(prds$trans)
p <- ggplot2::ggplot(prds, ggplot2::aes(x = doy, group = factor(yr), colour = yr)) +
ggplot2::geom_line(ggplot2::aes(y = value), size = size, alpha = alpha) +
ggplot2::theme_bw(base_size = base_size) +
ggplot2::theme(
legend.position = 'top',
legend.title = ggplot2::element_blank()
) +
ggplot2::scale_color_viridis_c() +
ggplot2::guides(colour = ggplot2::guide_colourbar(barheight = 1, barwidth = 20)) +
ggplot2::labs(
x = "Day of year",
y = ylab
)
if(trans != 'ident')
p <- p + ggplot2::scale_y_log10()
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/show_prddoy.R
|
#' Plot predictions for GAMs over time, by season
#'
#' Plot predictions for GAMs over time, by season
#'
#' @inheritParams show_prdseries
#'
#' @return A \code{\link[ggplot2]{ggplot}} object
#' @export
#'
#' @concept show
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl') %>%
#' filter(yr > 2015)
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#' show_prdseason(mod, ylab = 'Chlorophyll-a (ug/L)')
show_prdseason <- function(mod, ylab, base_size = 11, xlim = NULL, ylim = NULL){
# get daily predictions, differs from anlz_prd
prds <- anlz_prdday(mod)
# get transformation
trans <- unique(prds$trans)
# get raw data from model if not provided
tobacktrans <- mod$model %>%
dplyr::mutate(
trans = mod$trans
)
moddat <- anlz_backtrans(tobacktrans) %>%
dplyr::mutate(
date = lubridate::date_decimal(cont_year),
date = as.Date(date)
)
toplo <- prds %>%
dplyr::mutate(day = lubridate::day(date)) %>%
dplyr::filter(day %in% c(1)) %>%
dplyr::mutate(month = lubridate::month(date, label = T))
# plot
p <- ggplot2::ggplot(toplo, ggplot2::aes(x = date)) +
ggplot2::geom_point(data = moddat, ggplot2::aes(y = value), size = 0.5) +
ggplot2::geom_line(ggplot2::aes(y = value, group = month, colour = month), size = 1, alpha = 0.7) +
ggplot2::theme_bw(base_size = base_size) +
ggplot2::theme(
legend.position = 'top',
axis.title.x = ggplot2::element_blank(),
legend.title = ggplot2::element_blank()
) +
ggplot2::guides(col = ggplot2::guide_legend(nrow = 2)) +
ggplot2::labs(
y = ylab
) +
ggplot2::coord_cartesian(
xlim = xlim,
ylim = ylim
)
if(trans != 'ident')
p <- p + ggplot2::scale_y_log10()
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/show_prdseason.R
|
#' Plot predictions for GAMs over time series
#'
#' Plot predictions for GAMs over time series
#'
#' @param mod input model object as returned by \code{\link{anlz_gam}}
#' @param ylab chr string for y-axis label
#' @param alpha numeric from 0 to 1 indicating line transparency
#' @param base_size numeric indicating base font size, passed to \code{\link[ggplot2]{theme_bw}}
#' @param xlim optional numeric vector of length two for x-axis limits
#' @param ylim optional numeric vector of length two for y-axis limits
#' @param col optional chr string for line color
#'
#' @return A \code{\link[ggplot2]{ggplot}} object
#' @export
#'
#' @concept show
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl')
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#'
#' show_prdseries(mod, ylab = 'Chlorophyll-a (ug/L)')
show_prdseries <- function(mod, ylab, alpha = 0.7, base_size = 11, xlim = NULL, ylim = NULL, col = 'brown'){
# get predictions
prds <- anlz_prd(mod)
# get transformation
trans <- unique(prds$trans)
# raw data
tobacktrans <- mod$model %>%
dplyr::mutate(
trans = mod$trans
)
moddat <- anlz_backtrans(tobacktrans) %>%
dplyr::mutate(
date = lubridate::date_decimal(cont_year),
date = as.Date(date)
)
p <- ggplot2::ggplot(prds, ggplot2::aes(x = date)) +
ggplot2::geom_point(data = moddat, ggplot2::aes(y = value), size = 0.5) +
ggplot2::geom_line(ggplot2::aes(y = value), size = 0.75, alpha = alpha, colour = col) +
# ggplot2::geom_line(ggplot2::aes(y = annvalue), alpha = alpha, colour = 'tomato1') +
ggplot2::theme_bw(base_size = base_size) +
ggplot2::theme(
legend.position = 'top',
legend.title = ggplot2::element_blank(),
axis.title.x = ggplot2::element_blank()
) +
ggplot2::labs(
y = ylab
) +
ggplot2::coord_cartesian(
xlim = xlim,
ylim = ylim
)
if(trans != 'ident')
p <- p + ggplot2::scale_y_log10()
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/show_prdseries.R
|
#' Plot seasonal rates of change based on average estimates for multiple window widths
#'
#' Plot seasonal rates of change based on average estimates for multiple window widths
#'
#' @param mod input model object as returned by \code{\link{anlz_gam}}
#' @param doystr numeric indicating start Julian day for extracting averages
#' @param doyend numeric indicating ending Julian day for extracting averages
#' @param justify chr string indicating the justification for the trend window
#' @param win numeric vector indicating number of years to use for the trend window
#' @param txtsz numeric for size of text labels inside the plot
#' @param cols vector of low/high colors for trends
#' @param base_size numeric indicating base font size, passed to \code{\link[ggplot2]{theme_bw}}
#'
#' @return A \code{\link[ggplot2]{ggplot2}} plot
#' @export
#'
#' @concept show
#'
#' @details This function plots output from \code{\link{anlz_sumtrndseason}}.
#'
#' @family show
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl') %>%
#' filter(yr > 2015)
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#' show_sumtrndseason(mod, doystr = 90, doyend = 180, justify = 'center', win = 2:3)
show_sumtrndseason <- function(mod, doystr = 1, doyend = 364, justify = c('center', 'left', 'right'),
win = 5:15, txtsz = 6, cols = c('lightblue', 'lightgreen'),
base_size = 11){
justify <- match.arg(justify)
sig_cats <- c('**', '*', '')
sig_vals <- c(-Inf, 0.005, 0.05, Inf)
# get ests across all window widths
res <- anlz_sumtrndseason(mod, doystr = doystr, doyend = doyend, justify = justify, win = win)
# seasonal range for title
dts <- as.Date(c(doystr, doyend), origin = as.Date("2000-12-31"))
strt <- paste(lubridate::month(dts[1], label = T, abbr = T), lubridate::day(dts[1]))
ends <- paste(lubridate::month(dts[2], label = T, abbr = T), lubridate::day(dts[2]))
# subtitle
subttl <- paste0('Estimates based on ', justify, ' window')
# legend title, title
legttl <- 'Change/yr'
ttl <- paste0('Annual slopes for seasonal average trends: ', strt, '-', ends)
if(mod$trans == 'log10'){
legttl <- paste0('log-', tolower(legttl))
ttl <- paste0('Annual log-slopes for seasonal average trends: ', strt, '-', ends)
}
toplo <- res %>%
dplyr::mutate(
psig = cut(pval, breaks = sig_vals, labels = sig_cats, right = FALSE),
psig = as.character(psig)
)
p <- ggplot2::ggplot(toplo, ggplot2::aes(x = yr, y = win, fill = yrcoef)) +
ggplot2::geom_tile(color = 'black') +
ggplot2::geom_text(ggplot2::aes(label = psig), size = txtsz) +
ggplot2::scale_x_continuous(expand = c(0, 0)) +
ggplot2::scale_y_continuous(expand = c(0, 0), breaks = win) +
ggplot2::scale_fill_gradient2(low = cols[1], mid = 'white', high = cols[2], midpoint = 0) +
ggplot2::theme_bw(base_size = base_size) +
ggplot2::theme(
legend.position = 'top',
) +
ggplot2::guides(fill = ggplot2::guide_colourbar(barwidth = 10, barheight = 0.5)) +
ggplot2::labs(
fill = legttl,
title = ttl,
subtitle = subttl,
x = NULL,
y = 'Year window',
caption = '* p< 0.05, ** p < 0.005'
)
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/show_sumtrndseason.R
|
#' Plot seasonal rates of change in quarters based on average estimates for multiple window widths
#'
#' Plot seasonal rates of change in quarters based on average estimates for multiple window widths
#'
#' @param mod input model object as returned by \code{\link{anlz_gam}}
#' @param justify chr string indicating the justification for the trend window
#' @param win numeric vector indicating number of years to use for the trend window
#' @param txtsz numeric for size of text labels inside the plot
#' @param cols vector of low/high colors for trends
#' @param base_size numeric indicating base font size, passed to \code{\link[ggplot2]{theme_bw}}
#'
#' @return A \code{\link[ggplot2]{ggplot2}} plot
#' @export
#'
#' @concept show
#'
#' @details This function is similar to \code{\link{show_sumtrndseason}} but results are grouped into seasonal quarters as four separate plots with a combined color scale.
#'
#' @family show
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl') %>%
#' filter(yr > 2015)
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#' show_sumtrndseason2(mod, justify = 'center', win = 2:3)
show_sumtrndseason2 <- function(mod, justify = c('center', 'left', 'right'),
win = 5:15, txtsz = 6, cols = c('lightblue', 'lightgreen'),
base_size = 11){
justify <- match.arg(justify)
sig_cats <- c('**', '*', '')
sig_vals <- c(-Inf, 0.005, 0.05, Inf)
seas <- c('Jan - Mar', 'Apr - Jun', 'Jul - Sep' , 'Oct - Dec')
# get ests across all window widths and quarters
res1 <- anlz_sumtrndseason(mod, doystr = 1, doyend = 90, justify = justify, win = win) %>%
dplyr::mutate(seas = seas[1])
res2 <- anlz_sumtrndseason(mod, doystr = 91, doyend = 181, justify = justify, win = win) %>%
dplyr::mutate(seas = seas[2])
res3 <- anlz_sumtrndseason(mod, doystr = 182, doyend = 273, justify = justify, win = win) %>%
dplyr::mutate(seas = seas[3])
res4 <- anlz_sumtrndseason(mod, doystr = 274, doyend = 365, justify = justify, win = win) %>%
dplyr::mutate(seas = seas[4])
res <- dplyr::bind_rows(res1, res2, res3, res4) %>%
dplyr::mutate(seas = factor(seas, levels = !!seas)) %>%
tidyr::complete(yr, win, seas)
# legend title
legttl <- 'Change/yr'
if(mod$trans == 'log10')
legttl <- paste0('log-', tolower(legttl))
toplo <- res %>%
dplyr::mutate(
psig = cut(pval, breaks = sig_vals, labels = sig_cats, right = FALSE),
psig = as.character(psig)
)
p <- ggplot2::ggplot(toplo, ggplot2::aes(x = yr, y = win, fill = yrcoef)) +
ggplot2::geom_tile(color = 'black') +
ggplot2::geom_text(ggplot2::aes(label = psig), size = txtsz, vjust = 0.5) +
ggplot2::facet_wrap(~seas, ncol = 1) +
ggplot2::scale_x_continuous(expand = c(0, 0)) +
ggplot2::scale_y_continuous(expand = c(0, 0), breaks = win) +
ggplot2::scale_fill_gradient2(low = cols[1], mid = 'white', high = cols[2], midpoint = 0) +
ggplot2::theme_bw(base_size = base_size) +
ggplot2::theme(
legend.position = 'top',
strip.background = ggplot2::element_blank(),
strip.text = ggplot2::element_text(hjust = 0)
) +
ggplot2::guides(fill = ggplot2::guide_colourbar(barwidth = 10, barheight = 0.5)) +
ggplot2::labs(
fill = legttl,
x = NULL,
y = 'Year window',
caption = '* p< 0.05, ** p < 0.005'
)
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/show_sumtrndseason2.R
|
#' Plot rates of change based on seasonal metrics
#'
#' Plot rates of change based on seasonal metrics
#'
#' @inheritParams anlz_trndseason
#' @param type chr string indicating if log slopes are shown (if applicable)
#' @param ylab chr string for y-axis label
#' @param usearrow logical indicating if arrows should be used to indicate significant trend direction
#' @param base_size numeric indicating base font size, passed to \code{\link[ggplot2]{theme_bw}}
#' @param xlim optional numeric vector of length two for x-axis limits
#' @param ylim optional numeric vector of length two for y-axis limits
#'
#' @return A \code{\link[ggplot2]{ggplot}} object
#' @export
#'
#' @concept show
#'
#' @examples
#' library(dplyr)
#'
#' # data to model
#' tomod <- rawdat %>%
#' filter(station %in% 34) %>%
#' filter(param %in% 'chl') %>%
#' filter(yr > 2015)
#'
#' mod <- anlz_gam(tomod, trans = 'log10')
#' show_trndseason(mod, doystr = 90, doyend = 180, justify = 'left', win = 4,
#' ylab = 'Slope Chlorophyll-a (ug/L/yr)')
show_trndseason <- function(mod, metfun = mean, doystr = 1, doyend = 364, type = c('log10', 'approx'),
justify = c('left', 'right', 'center'), win = 5, ylab, nsim = 1e4,
useave = FALSE, usearrow = FALSE, base_size = 11, xlim = NULL, ylim = NULL, ...) {
justify <- match.arg(justify)
type <- match.arg(type)
# get slope trends
trndseason <- anlz_trndseason(mod = mod, metfun = metfun, doystr = doystr, doyend = doyend, justify = justify, win = win, nsim = nsim, useave = useave, ...)
# title
dts <- as.Date(c(doystr, doyend), origin = as.Date("2000-12-31"))
strt <- paste(lubridate::month(dts[1], label = T, abbr = T), lubridate::day(dts[1]))
ends <- paste(lubridate::month(dts[2], label = T, abbr = T), lubridate::day(dts[2]))
# subtitle
subttl <- paste0('Estimates based on ', justify , ' window of ', win, ' years')
# year range
yrrng <- range(trndseason$yr, na.rm = T)
# shape and factor vectors based on usearrow
pshp <- if(usearrow == T) c(21, 24, 25) else c(21, 21)
pfct <- if(usearrow == T) c('ns', 'inc, p < 0.05', 'dec, p < 0.05') else c('ns', 'p < 0.05')
pcol <- if(usearrow == T) c('black', 'tomato1', 'tomato1') else c('black', 'tomato1')
pfil <- if(usearrow == T) c('white', 'tomato1', 'tomato1') else c('white', 'tomato1')
# to plot, no NA
toplo <- trndseason %>%
dplyr::mutate(
pval = dplyr::case_when(
pval < 0.05 & yrcoef > 0 ~ pfct[2],
pval < 0.05 & yrcoef < 0 ~ pfct[3],
T ~ pfct[1]
),
pval = factor(pval, levels = pfct)
) %>%
na.omit()
if(type == 'log10' & mod$trans == 'log10'){
ttl <- paste0('Annual log-slopes (+/- 95%) for seasonal trends: ', strt, '-', ends)
p <- ggplot2::ggplot(data = toplo, ggplot2::aes(x = yr, y = yrcoef, fill = pval)) +
ggplot2::geom_hline(yintercept = 0) +
ggplot2::geom_errorbar(ggplot2::aes(ymin = yrcoef_lwr, ymax = yrcoef_upr, color = pval), width = 0) +
ggplot2::scale_color_manual(values = pcol, drop = FALSE)
}
if(type == 'approx' & mod$trans == 'log10'){
ttl <- paste0('Annual slopes (approximate) for seasonal trends: ', strt, '-', ends)
p <- ggplot2::ggplot(data = toplo, ggplot2::aes(x = yr, y = appr_yrcoef, fill = pval)) +
ggplot2::geom_hline(yintercept = 0) +
ggplot2::labs(
title = ttl,
subtitle = subttl,
y = ylab
)
}
if(mod$trans == 'ident'){
ttl <- paste0('Annual slopes (+/- 95%) for seasonal trends: ', strt, '-', ends)
p <- ggplot2::ggplot(data = toplo, ggplot2::aes(x = yr, y = yrcoef, fill = pval)) +
ggplot2::geom_hline(yintercept = 0) +
ggplot2::geom_errorbar(ggplot2::aes(ymin = yrcoef_lwr, ymax = yrcoef_upr, color = pval), width = 0) +
ggplot2::scale_color_manual(values = pcol, drop = FALSE)
}
p <- p +
ggplot2::geom_point(ggplot2::aes(shape = pval), size = 3) +
ggplot2::scale_fill_manual(values = pfil, drop = FALSE) +
ggplot2::scale_shape_manual(values = pshp, drop = FALSE) +
ggplot2::scale_x_continuous(limits = yrrng) +
ggplot2::theme_bw(base_size = base_size) +
ggplot2::theme(
axis.title.x = ggplot2::element_blank(),
legend.position = 'top',
legend.title = ggplot2::element_blank()
) +
ggplot2::labs(
title = ttl,
subtitle = subttl,
y = ylab
) +
ggplot2::coord_cartesian(
xlim = xlim,
ylim = ylim
)
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/R/show_trndseason.R
|
## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
comment = "#>",
message = F, warning = F,
fig.align = "center",
echo = T
)
library(dplyr)
library(wqtrends)
library(plotly)
library(english)
## -----------------------------------------------------------------------------
head(rawdat)
## -----------------------------------------------------------------------------
tomod <- rawdat %>%
filter(station %in% 34) %>%
filter(param %in% "chl")
mod <- anlz_gam(tomod, trans = "log10")
mod
## -----------------------------------------------------------------------------
anlz_smooth(mod)
anlz_fit(mod)
## ----fig.height = 5, fig.width = 6--------------------------------------------
ylab <- "Chlorophyll-a"
show_prddoy(mod, ylab = ylab)
## ----fig.height = 4, fig.width = 6--------------------------------------------
show_prdseries(mod, ylab = ylab)
## ----fig.height = 4, fig.width = 6--------------------------------------------
show_prdseason(mod, ylab = ylab)
## -----------------------------------------------------------------------------
show_prd3d(mod, ylab = ylab)
## -----------------------------------------------------------------------------
anlz_perchg(mod, baseyr = 2006, testyr = 2017)
## ----fig.height = 4, fig.width = 9--------------------------------------------
show_perchg(mod, baseyr = 2006, testyr = 2017, ylab = "Chlorophyll-a (ug/L)")
## -----------------------------------------------------------------------------
metseason <- anlz_metseason(mod, metfun = max, doystr = 90, doyend = 180, nsim = 100)
metseason
## -----------------------------------------------------------------------------
anlz_mixmeta(metseason, yrstr = 2006, yrend = 2017)
## ----fig.height = 4, fig.width = 9, echo = T----------------------------------
show_metseason(mod, doystr = 90, doyend = 180, yrstr = 2006, yrend = 2017, ylab = "Chlorophyll-a (ug/L)")
## ----fig.height = 4, fig.width = 9, echo = T----------------------------------
show_metseason(mod, doystr = 90, doyend = 180, yrstr = NULL, yrend = NULL, ylab = "Chlorophyll-a (ug/L)")
## ----fig.height = 4, fig.width = 9, echo = T----------------------------------
show_metseason(mod, metfun = max, nsim = 100, doystr = 90, doyend = 180, yrstr = 2006, yrend = 2017, ylab = "Chlorophyll-a (ug/L)")
## -----------------------------------------------------------------------------
trndseason <- anlz_trndseason(mod, doystr = 90, doyend = 180, justify = 'left', win = 5)
head(trndseason)
## ----fig.height = 5, fig.width = 9, echo = T----------------------------------
show_trndseason(mod, doystr = 90, doyend = 180, justify = 'left', win = 5, ylab = 'Chl. change/yr, average')
## ----fig.height = 5, fig.width = 9, echo = T----------------------------------
show_trndseason(mod, metfun = max, nsim = 100, doystr = 90, doyend = 180, justify = 'left', win = 5, ylab = 'Chl. change/yr, maximum')
## ----fig.height = 5, fig.width = 9, echo = T----------------------------------
show_trndseason(mod, metfun = max, nsim = 100, doystr = 90, doyend = 180, justify = 'left', win = 5, ylab = 'Chl. change/yr, maximum', usearrow = T)
## ----fig.height = 7, fig.width = 9, echo = T----------------------------------
show_sumtrndseason(mod, doystr = 90, doyend = 180, justify = 'left', win = 5:15)
## ----fig.height = 5, fig.width = 9, echo = T----------------------------------
show_mettrndseason(mod, metfun = mean, doystr = 90, doyend = 180, ylab = "Chlorophyll-a (ug/L)", win = 5, justify = 'left')
## ----fig.height = 5, fig.width = 9, echo = T----------------------------------
show_mettrndseason(mod, metfun = mean, doystr = 90, doyend = 180, ylab = "Chlorophyll-a (ug/L)", win = 5, justify = 'left', cmbn = T)
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/inst/doc/introduction.R
|
---
title: "Introduction to wqtrends"
author: "Marcus Beck"
date: "`r Sys.Date()`"
output:
rmarkdown::html_vignette:
toc: true
bibliography: refs.bib
vignette: >
%\VignetteIndexEntry{Introduction}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
comment = "#>",
message = F, warning = F,
fig.align = "center",
echo = T
)
library(dplyr)
library(wqtrends)
library(plotly)
library(english)
```
This package can be used to assess water quality trends for long-term monitoring data in estuaries using Generalized Additive Models and mixed-effects meta-analysis [@Wood17; @Sera19]. These models are appropriate for data typically from surface water quality monitoring programs at roughly monthly or biweekly collection intervals, covering at least a decade of observations [e.g., @Cloern16]. Daily or continuous monitoring data covering many years are not appropriate for these methods, due to computational limitations and a goal of the analysis to estimate long-term, continuous trends from irregular or discontinuous sampling.
# Basic usage
The sample dataset `rawdat` is included in the package and is used for the examples below. This dataset includes monthly time series data over ~30 years for nine stations in South Bay, San Francisco Estuary. Data are available for `r english(length(unique(rawdat$param)))` water quality parameters. All data are in long format with one observation per row.
The data are pre-processed to work with the GAM fitting functions included in this package. The columns include date, station number, parameter name, and value for the date. Additional date columns are included that describe the day of year (`doy`), date in decimal time (`cont_year`), year (`yr`), and month (`mo` as character label). These are required for model fitting or use with the analysis/plotting functions.
```{r}
head(rawdat)
```
One GAM model can be fit to the time series data. Each GAM fits additive smoothing functions to describe variation of the response variable (`value`) over time, where time is measured as a continuous number. The basic GAM used by this package is as follows:
* `S`: value ~ s(year, k = *large*)
The `cont_year` vector is measured as a continuous numeric variable for the annual effect (e.g., January 1st, 2000 is 2000.0, July 1st, 2000 is 2000.5, etc.). The function `s()` models `cont_year` as a smoothed, non-linear variable. The optimal amount of smoothing on `cont_year` is determined by cross-validation as implemented in the mgcv package [@Wood17] and an upper theoretical upper limit on the number of knots for `k` should be large enough to allow sufficient flexibility in the smoothing term. The upper limit of `k` was chosen as 12 times the number of years for the input data. If insufficient data are available to fit a model with the specified `k`, the number of knots is decreased until the data can be modelled, e.g., 11 times the number of years, 10 times the number of years, etc.
The `anlz_gam()` function is used to fit the model. First, the raw data are filtered to select only station 34 and the chlorophyll parameter. The model is fit using a log-10 transformation of the response variable. Available transformation options are log-10 (`log10`) or identity (`ident`). The log-10 transformation is used by default if not specified by the user.
```{r}
tomod <- rawdat %>%
filter(station %in% 34) %>%
filter(param %in% "chl")
mod <- anlz_gam(tomod, trans = "log10")
mod
```
All remaining functions use the model results to assess fit, calculate seasonal metrics and trends, and plot results.
The fit can be assessed using `anlz_smooth()` and `anlz_fit()`, where the former assesses the individual smoother functions and the latter assesses overall fit. The `anlz_smooth()` results show the results for the fit to the `cont_year` smoother as the effective degrees of freedom (`edf`), the reference degrees of freedom (`Ref.df`), the test statistic (`F`), and statistical significance (`p-value`). The significance is in part based on the difference between `edf` and `Ref.df`. The `anlz_fit()` results show the overall summary of the model as Akaike Information Criterion (`AIC`), the generalized cross-validation score (`GCV`), and the `R2` values. Lower values for `AIC` and `GCV` and higher values for `R2` indicate better model fit.
```{r}
anlz_smooth(mod)
anlz_fit(mod)
```
The plotting functions show the results in different formats. If appropriate for the response variable, the model predictions are back-transformed and the scales on each plot are shown in log10-scale to preserve the values of the results.
The `show_prddoy()` function shows estimated results by day of year with separate lines for each year.
```{r, fig.height = 5, fig.width = 6}
ylab <- "Chlorophyll-a"
show_prddoy(mod, ylab = ylab)
```
The `show_prdseries()` function shows predictions for the model across the entire time series. Points are the observed data and the lines are the predicted.
```{r, fig.height = 4, fig.width = 6}
show_prdseries(mod, ylab = ylab)
```
The `show_prdseason()` function is similar except that the model predictions are grouped by month. This provides a simple visual depiction of changes by month over time. The trend analysis functions below can be used to statistically test the seasonal changes.
```{r, fig.height = 4, fig.width = 6}
show_prdseason(mod, ylab = ylab)
```
Finally, the `show_prd3d()` function shows a three-dimensional fit of the estimated trends across year and day of year with the z-axis showing the estimates for the response variable.
```{r}
show_prd3d(mod, ylab = ylab)
```
# Trend testing
Statistical tests for evaluating trends are available in this package. These methods are considered "secondary" analyses that use results from a fitted GAM to evaluate trends or changes over time. In particular, significance of changes over time are evaluated using mixed-effect meta-analysis [@Sera19] applied to the GAM results to allow for full propagation of uncertainty between methods. Each test includes a plotting method to view the results.
## Evaluating changes between time periods
The `anlz_perchg()` and `show_perchg()` functions can be used to compare annual averages between two time periods of interest. The functions require base and test year inputs that are used for comparison. More than one year can be entered for the base and test years, e.g., `baseyr = c(1990, 1992, 1993)` vs. `testyr = c(2014, 2015, 2016)`.
```{r}
anlz_perchg(mod, baseyr = 2006, testyr = 2017)
```
To plot the results for one GAM, use the `show_perchg()` function. The plot title summarizes the results.
```{r, fig.height = 4, fig.width = 9}
show_perchg(mod, baseyr = 2006, testyr = 2017, ylab = "Chlorophyll-a (ug/L)")
```
## Evaluating seasonal changes over time
The `anlz_metseason()`, `anlz_mixmeta()`, and `show_metseason()` functions evaluate seasonal metrics (e.g., mean, max, etc.) between years, including an assessment of the trend for selected years using mixed-effects meta-analysis modelling. These functions require inputs for the seasonal ranges to evaluate (`doyend`, `doystr`) and years for assessing the trend in the seasonal averages/metrics (`yrstr`, `yrend`).
The `anlz_metseason()` function estimates the seasonal metrics (including uncertainty as standard error) for results from the GAM fit. The seasonal metric can be any summary function available in R, such as seasonal maxima (`max`), minima (`min`), variance (`var`), or others. The function uses repeated resampling of the GAM model coefficients to simulate multiple time series as an estimate of uncertainty for the summary parameter.
The inputs for `anlz_metseason()` include the seasonal range as day of year using start (`doystr`) and end (`doyend`) days and the `metfun` and `nsim` arguments to specify the summary function and number of simulations, respectively. Here we show the estimate for the maximum chlorophyll in each season, using a relatively low number of simulations. Repeating this function will produce similar but slightly different results because the estimates are stochastic. In practice, a large value for `nsim` should be used to produce accurate results (e.g., `nsim = 1e5`).
```{r}
metseason <- anlz_metseason(mod, metfun = max, doystr = 90, doyend = 180, nsim = 100)
metseason
```
The `anlz_mixmeta()` function uses results from the `anlz_metseason()` to estimate the trend in the seasonal metric over a selected year range. Here, we evaluate the seasonal trend from 2006 to 2017 for the seasonal estimate of the model results above.
```{r}
anlz_mixmeta(metseason, yrstr = 2006, yrend = 2017)
```
The `show_metseason()` function plots the seasonal metrics and trends over time. The `anlz_metseason()` and `anlz_mixmeta()` functions are used internally to get the predictions. The same arguments for these functions are used for `show_metseason`, with the mean as the default metric.
```{r, fig.height = 4, fig.width = 9, echo = T}
show_metseason(mod, doystr = 90, doyend = 180, yrstr = 2006, yrend = 2017, ylab = "Chlorophyll-a (ug/L)")
```
To plot only the seasonal metrics, the regression line showing trends over time can be suppressed by setting one or both of `yrstr` and `yrend` as `NULL`.
```{r, fig.height = 4, fig.width = 9, echo = T}
show_metseason(mod, doystr = 90, doyend = 180, yrstr = NULL, yrend = NULL, ylab = "Chlorophyll-a (ug/L)")
```
Adding an argument for `metfun` to `show_metseason()` will plot results and trends for a metric other than the average. Note the use of `nsim` in this example. In practice, a much higher value should be used (e.g., `nsim = 1e5`)
```{r, fig.height = 4, fig.width = 9, echo = T}
show_metseason(mod, metfun = max, nsim = 100, doystr = 90, doyend = 180, yrstr = 2006, yrend = 2017, ylab = "Chlorophyll-a (ug/L)")
```
The seasonal estimates and mixed-effects meta-analysis regression can be used to estimate the rate of seasonal change across the time series. For any given year and seasonal metric, a trend can be estimated within a specific window (i.e., `yrstr` and `yrend` arguments in `show_metseason()`). This trend can be estimated for every year in the period of record to estimate the rate of change over time for the seasonal estimates.
The `anlz_trndseason()` function estimates the rate of change and the `show_trndseason()` function plots the results. For both, all inputs required for the `anlz_metseason()` function are required, in addition to the desired window width to evaluate for each year (`win`) and the justification for the window as `"left"`, `"right"`, or `"center"` from each year (`justify`).
It's important to note the behavior of the centering for window widths (`win` argument) if choosing even or odd values. For left and right windows, the exact number of years in `win` is used. For example, a left-centered window for 1990 of ten years will include exactly ten years from 1990, 1991, ... , 1999. The same applies to a right-centered window, e.g., for 1990 it would include 1981, 1982, ..., 1990 (if those years have data). However, for a centered window, picking an even number of years for the window width will create a slightly off-centered window because it is impossible to center on an even number of years. For example, if `win = 8` and `justify = 'center'`, the estimate for 2000 will be centered on 1997 to 2004 (three years left, four years right, eight years total). Centering for window widths with an odd number of years will always create a symmetrical window, i.e., if `win = 7` and `justify = 'center'`, the estimate for 2000 will be centered on 1997 and 2003 (three years left, three years right, seven years total).
```{r}
trndseason <- anlz_trndseason(mod, doystr = 90, doyend = 180, justify = 'left', win = 5)
head(trndseason)
```
The `show_trndseason()` function can be used to plot the results directly, one model at a time.
```{r, fig.height = 5, fig.width = 9, echo = T}
show_trndseason(mod, doystr = 90, doyend = 180, justify = 'left', win = 5, ylab = 'Chl. change/yr, average')
```
As before, adding an argument for `metfun` to `show_trndseason()` will plot results and trends for a metric other than the average. Note the use of `nsim` in this example. In practice, a much higher value should be used (e.g., `nsim = 1e5`)
```{r, fig.height = 5, fig.width = 9, echo = T}
show_trndseason(mod, metfun = max, nsim = 100, doystr = 90, doyend = 180, justify = 'left', win = 5, ylab = 'Chl. change/yr, maximum')
```
For additional visual clarity, the significant results in `show_trndseason()` can be shown with different shapes indicating the direction of the trend using `usearrow = T`. This may be useful if the direction of significant trends near the zero line are difficult to determine (not in the below example).
```{r, fig.height = 5, fig.width = 9, echo = T}
show_trndseason(mod, metfun = max, nsim = 100, doystr = 90, doyend = 180, justify = 'left', win = 5, ylab = 'Chl. change/yr, maximum', usearrow = T)
```
The results supplied by `show_trndseason()` can be extended to multiple window widths by stacking the results into a single plot. Below, results for window widths from 5 to 15 years are shown using the `show_sumtrndseason()` function for a selected seasonal range using a left-justified window. This function only works with average seasonal metrics due to long processing times with other metrics. To retrieve the results in tabular form, use `anlz_sumtrndseason()`.
```{r, fig.height = 7, fig.width = 9, echo = T}
show_sumtrndseason(mod, doystr = 90, doyend = 180, justify = 'left', win = 5:15)
```
Lastly, the plots returned by `show_metseason()` and `show_trndseason()` can be combined using the `show_mettrndseason()` function. This plot will show the seasonal metrics from the GAM as in `show_metseason()` with the colors of the points for the seasonal metrics colored by the significance of the moving window trends shown in `show_trndseason()`. The four colors indicate increasing, decreasing, no trend, or no estimate (i.e., too few points for the window). Most of the arguments for `show_metseason()` and `show_trndseason()` apply to `show_mettrndseason()`.
```{r, fig.height = 5, fig.width = 9, echo = T}
show_mettrndseason(mod, metfun = mean, doystr = 90, doyend = 180, ylab = "Chlorophyll-a (ug/L)", win = 5, justify = 'left')
```
Four colors are used to define increasing, decreasing, no trend, or no estimate. The `cmbn` argument can be used to combine the no trend and no estimate colors into one color and label. Although this may be desired for aesthetic reasons, the colors and labels may be misleading with the default names since no trend is shown for points where no estimates were made.
```{r, fig.height = 5, fig.width = 9, echo = T}
show_mettrndseason(mod, metfun = mean, doystr = 90, doyend = 180, ylab = "Chlorophyll-a (ug/L)", win = 5, justify = 'left', cmbn = T)
```
# References
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/inst/doc/introduction.Rmd
|
---
title: "Introduction to wqtrends"
author: "Marcus Beck"
date: "`r Sys.Date()`"
output:
rmarkdown::html_vignette:
toc: true
bibliography: refs.bib
vignette: >
%\VignetteIndexEntry{Introduction}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
comment = "#>",
message = F, warning = F,
fig.align = "center",
echo = T
)
library(dplyr)
library(wqtrends)
library(plotly)
library(english)
```
This package can be used to assess water quality trends for long-term monitoring data in estuaries using Generalized Additive Models and mixed-effects meta-analysis [@Wood17; @Sera19]. These models are appropriate for data typically from surface water quality monitoring programs at roughly monthly or biweekly collection intervals, covering at least a decade of observations [e.g., @Cloern16]. Daily or continuous monitoring data covering many years are not appropriate for these methods, due to computational limitations and a goal of the analysis to estimate long-term, continuous trends from irregular or discontinuous sampling.
# Basic usage
The sample dataset `rawdat` is included in the package and is used for the examples below. This dataset includes monthly time series data over ~30 years for nine stations in South Bay, San Francisco Estuary. Data are available for `r english(length(unique(rawdat$param)))` water quality parameters. All data are in long format with one observation per row.
The data are pre-processed to work with the GAM fitting functions included in this package. The columns include date, station number, parameter name, and value for the date. Additional date columns are included that describe the day of year (`doy`), date in decimal time (`cont_year`), year (`yr`), and month (`mo` as character label). These are required for model fitting or use with the analysis/plotting functions.
```{r}
head(rawdat)
```
One GAM model can be fit to the time series data. Each GAM fits additive smoothing functions to describe variation of the response variable (`value`) over time, where time is measured as a continuous number. The basic GAM used by this package is as follows:
* `S`: value ~ s(year, k = *large*)
The `cont_year` vector is measured as a continuous numeric variable for the annual effect (e.g., January 1st, 2000 is 2000.0, July 1st, 2000 is 2000.5, etc.). The function `s()` models `cont_year` as a smoothed, non-linear variable. The optimal amount of smoothing on `cont_year` is determined by cross-validation as implemented in the mgcv package [@Wood17] and an upper theoretical upper limit on the number of knots for `k` should be large enough to allow sufficient flexibility in the smoothing term. The upper limit of `k` was chosen as 12 times the number of years for the input data. If insufficient data are available to fit a model with the specified `k`, the number of knots is decreased until the data can be modelled, e.g., 11 times the number of years, 10 times the number of years, etc.
The `anlz_gam()` function is used to fit the model. First, the raw data are filtered to select only station 34 and the chlorophyll parameter. The model is fit using a log-10 transformation of the response variable. Available transformation options are log-10 (`log10`) or identity (`ident`). The log-10 transformation is used by default if not specified by the user.
```{r}
tomod <- rawdat %>%
filter(station %in% 34) %>%
filter(param %in% "chl")
mod <- anlz_gam(tomod, trans = "log10")
mod
```
All remaining functions use the model results to assess fit, calculate seasonal metrics and trends, and plot results.
The fit can be assessed using `anlz_smooth()` and `anlz_fit()`, where the former assesses the individual smoother functions and the latter assesses overall fit. The `anlz_smooth()` results show the results for the fit to the `cont_year` smoother as the effective degrees of freedom (`edf`), the reference degrees of freedom (`Ref.df`), the test statistic (`F`), and statistical significance (`p-value`). The significance is in part based on the difference between `edf` and `Ref.df`. The `anlz_fit()` results show the overall summary of the model as Akaike Information Criterion (`AIC`), the generalized cross-validation score (`GCV`), and the `R2` values. Lower values for `AIC` and `GCV` and higher values for `R2` indicate better model fit.
```{r}
anlz_smooth(mod)
anlz_fit(mod)
```
The plotting functions show the results in different formats. If appropriate for the response variable, the model predictions are back-transformed and the scales on each plot are shown in log10-scale to preserve the values of the results.
The `show_prddoy()` function shows estimated results by day of year with separate lines for each year.
```{r, fig.height = 5, fig.width = 6}
ylab <- "Chlorophyll-a"
show_prddoy(mod, ylab = ylab)
```
The `show_prdseries()` function shows predictions for the model across the entire time series. Points are the observed data and the lines are the predicted.
```{r, fig.height = 4, fig.width = 6}
show_prdseries(mod, ylab = ylab)
```
The `show_prdseason()` function is similar except that the model predictions are grouped by month. This provides a simple visual depiction of changes by month over time. The trend analysis functions below can be used to statistically test the seasonal changes.
```{r, fig.height = 4, fig.width = 6}
show_prdseason(mod, ylab = ylab)
```
Finally, the `show_prd3d()` function shows a three-dimensional fit of the estimated trends across year and day of year with the z-axis showing the estimates for the response variable.
```{r}
show_prd3d(mod, ylab = ylab)
```
# Trend testing
Statistical tests for evaluating trends are available in this package. These methods are considered "secondary" analyses that use results from a fitted GAM to evaluate trends or changes over time. In particular, significance of changes over time are evaluated using mixed-effect meta-analysis [@Sera19] applied to the GAM results to allow for full propagation of uncertainty between methods. Each test includes a plotting method to view the results.
## Evaluating changes between time periods
The `anlz_perchg()` and `show_perchg()` functions can be used to compare annual averages between two time periods of interest. The functions require base and test year inputs that are used for comparison. More than one year can be entered for the base and test years, e.g., `baseyr = c(1990, 1992, 1993)` vs. `testyr = c(2014, 2015, 2016)`.
```{r}
anlz_perchg(mod, baseyr = 2006, testyr = 2017)
```
To plot the results for one GAM, use the `show_perchg()` function. The plot title summarizes the results.
```{r, fig.height = 4, fig.width = 9}
show_perchg(mod, baseyr = 2006, testyr = 2017, ylab = "Chlorophyll-a (ug/L)")
```
## Evaluating seasonal changes over time
The `anlz_metseason()`, `anlz_mixmeta()`, and `show_metseason()` functions evaluate seasonal metrics (e.g., mean, max, etc.) between years, including an assessment of the trend for selected years using mixed-effects meta-analysis modelling. These functions require inputs for the seasonal ranges to evaluate (`doyend`, `doystr`) and years for assessing the trend in the seasonal averages/metrics (`yrstr`, `yrend`).
The `anlz_metseason()` function estimates the seasonal metrics (including uncertainty as standard error) for results from the GAM fit. The seasonal metric can be any summary function available in R, such as seasonal maxima (`max`), minima (`min`), variance (`var`), or others. The function uses repeated resampling of the GAM model coefficients to simulate multiple time series as an estimate of uncertainty for the summary parameter.
The inputs for `anlz_metseason()` include the seasonal range as day of year using start (`doystr`) and end (`doyend`) days and the `metfun` and `nsim` arguments to specify the summary function and number of simulations, respectively. Here we show the estimate for the maximum chlorophyll in each season, using a relatively low number of simulations. Repeating this function will produce similar but slightly different results because the estimates are stochastic. In practice, a large value for `nsim` should be used to produce accurate results (e.g., `nsim = 1e5`).
```{r}
metseason <- anlz_metseason(mod, metfun = max, doystr = 90, doyend = 180, nsim = 100)
metseason
```
The `anlz_mixmeta()` function uses results from the `anlz_metseason()` to estimate the trend in the seasonal metric over a selected year range. Here, we evaluate the seasonal trend from 2006 to 2017 for the seasonal estimate of the model results above.
```{r}
anlz_mixmeta(metseason, yrstr = 2006, yrend = 2017)
```
The `show_metseason()` function plots the seasonal metrics and trends over time. The `anlz_metseason()` and `anlz_mixmeta()` functions are used internally to get the predictions. The same arguments for these functions are used for `show_metseason`, with the mean as the default metric.
```{r, fig.height = 4, fig.width = 9, echo = T}
show_metseason(mod, doystr = 90, doyend = 180, yrstr = 2006, yrend = 2017, ylab = "Chlorophyll-a (ug/L)")
```
To plot only the seasonal metrics, the regression line showing trends over time can be suppressed by setting one or both of `yrstr` and `yrend` as `NULL`.
```{r, fig.height = 4, fig.width = 9, echo = T}
show_metseason(mod, doystr = 90, doyend = 180, yrstr = NULL, yrend = NULL, ylab = "Chlorophyll-a (ug/L)")
```
Adding an argument for `metfun` to `show_metseason()` will plot results and trends for a metric other than the average. Note the use of `nsim` in this example. In practice, a much higher value should be used (e.g., `nsim = 1e5`)
```{r, fig.height = 4, fig.width = 9, echo = T}
show_metseason(mod, metfun = max, nsim = 100, doystr = 90, doyend = 180, yrstr = 2006, yrend = 2017, ylab = "Chlorophyll-a (ug/L)")
```
The seasonal estimates and mixed-effects meta-analysis regression can be used to estimate the rate of seasonal change across the time series. For any given year and seasonal metric, a trend can be estimated within a specific window (i.e., `yrstr` and `yrend` arguments in `show_metseason()`). This trend can be estimated for every year in the period of record to estimate the rate of change over time for the seasonal estimates.
The `anlz_trndseason()` function estimates the rate of change and the `show_trndseason()` function plots the results. For both, all inputs required for the `anlz_metseason()` function are required, in addition to the desired window width to evaluate for each year (`win`) and the justification for the window as `"left"`, `"right"`, or `"center"` from each year (`justify`).
It's important to note the behavior of the centering for window widths (`win` argument) if choosing even or odd values. For left and right windows, the exact number of years in `win` is used. For example, a left-centered window for 1990 of ten years will include exactly ten years from 1990, 1991, ... , 1999. The same applies to a right-centered window, e.g., for 1990 it would include 1981, 1982, ..., 1990 (if those years have data). However, for a centered window, picking an even number of years for the window width will create a slightly off-centered window because it is impossible to center on an even number of years. For example, if `win = 8` and `justify = 'center'`, the estimate for 2000 will be centered on 1997 to 2004 (three years left, four years right, eight years total). Centering for window widths with an odd number of years will always create a symmetrical window, i.e., if `win = 7` and `justify = 'center'`, the estimate for 2000 will be centered on 1997 and 2003 (three years left, three years right, seven years total).
```{r}
trndseason <- anlz_trndseason(mod, doystr = 90, doyend = 180, justify = 'left', win = 5)
head(trndseason)
```
The `show_trndseason()` function can be used to plot the results directly, one model at a time.
```{r, fig.height = 5, fig.width = 9, echo = T}
show_trndseason(mod, doystr = 90, doyend = 180, justify = 'left', win = 5, ylab = 'Chl. change/yr, average')
```
As before, adding an argument for `metfun` to `show_trndseason()` will plot results and trends for a metric other than the average. Note the use of `nsim` in this example. In practice, a much higher value should be used (e.g., `nsim = 1e5`)
```{r, fig.height = 5, fig.width = 9, echo = T}
show_trndseason(mod, metfun = max, nsim = 100, doystr = 90, doyend = 180, justify = 'left', win = 5, ylab = 'Chl. change/yr, maximum')
```
For additional visual clarity, the significant results in `show_trndseason()` can be shown with different shapes indicating the direction of the trend using `usearrow = T`. This may be useful if the direction of significant trends near the zero line are difficult to determine (not in the below example).
```{r, fig.height = 5, fig.width = 9, echo = T}
show_trndseason(mod, metfun = max, nsim = 100, doystr = 90, doyend = 180, justify = 'left', win = 5, ylab = 'Chl. change/yr, maximum', usearrow = T)
```
The results supplied by `show_trndseason()` can be extended to multiple window widths by stacking the results into a single plot. Below, results for window widths from 5 to 15 years are shown using the `show_sumtrndseason()` function for a selected seasonal range using a left-justified window. This function only works with average seasonal metrics due to long processing times with other metrics. To retrieve the results in tabular form, use `anlz_sumtrndseason()`.
```{r, fig.height = 7, fig.width = 9, echo = T}
show_sumtrndseason(mod, doystr = 90, doyend = 180, justify = 'left', win = 5:15)
```
Lastly, the plots returned by `show_metseason()` and `show_trndseason()` can be combined using the `show_mettrndseason()` function. This plot will show the seasonal metrics from the GAM as in `show_metseason()` with the colors of the points for the seasonal metrics colored by the significance of the moving window trends shown in `show_trndseason()`. The four colors indicate increasing, decreasing, no trend, or no estimate (i.e., too few points for the window). Most of the arguments for `show_metseason()` and `show_trndseason()` apply to `show_mettrndseason()`.
```{r, fig.height = 5, fig.width = 9, echo = T}
show_mettrndseason(mod, metfun = mean, doystr = 90, doyend = 180, ylab = "Chlorophyll-a (ug/L)", win = 5, justify = 'left')
```
Four colors are used to define increasing, decreasing, no trend, or no estimate. The `cmbn` argument can be used to combine the no trend and no estimate colors into one color and label. Although this may be desired for aesthetic reasons, the colors and labels may be misleading with the default names since no trend is shown for points where no estimates were made.
```{r, fig.height = 5, fig.width = 9, echo = T}
show_mettrndseason(mod, metfun = mean, doystr = 90, doyend = 180, ylab = "Chlorophyll-a (ug/L)", win = 5, justify = 'left', cmbn = T)
```
# References
|
/scratch/gouwar.j/cran-all/cranData/wqtrends/vignettes/introduction.Rmd
|
#' MA-plot (differential intensity versus average intensity)
#'
#' This type of plot for display of relative changes versus (mean) absolute abundance is very common in high-throughput biology, see \href{https://en.wikipedia.org/wiki/MA_plot}{MA-plot}.
#' Basically one compares two independent series of measures (ie gene transcript or protein abundance values) of 2 samples/data-sets or the means of 2 groups of replicates.
#' And the log-fold-change ('Minus'=M) is plotted againts the absolute mean value ('Average'=A).
#' Furthermore, output from statistical testing by \code{\link[wrMisc]{moderTest2grp}} or \code{\link[wrMisc]{moderTestXgrp}} can be directly read to produce MA plots for diagnostic purpose.
#' Please note, that plotting a very high number of points in transparency (eg >10000) may take several seconds.
#'
#' @param Mvalue (numeric, list or MArrayLM-object) main data to plot; if numeric, the content will be used as M-values (and A-values must be provided separateley);
#' if list or MArrayLM-object, it must conatin list-elements named \code{Mvalue} and \code{means} to extract all information needed for plotting
#' @param Avalue (numeric, list or data.frame) if \code{NULL} it is assumed that M-values can be extracted form argument \code{Avalue}
#' @param useComp (integer) choice of one of multiple comparisons present in \code{Mvalue} (if generated using \code{moderTestXgrp()})
#' @param filtFin (matrix or logical) The data may get filtered before plotting: If \code{FALSE} no filtering will get applied; if matrix of \code{TRUE}/\code{FALSE} it will be used as optional custom filter, otherwise (if \code{Mvalue} if an \code{MArrayLM}-object eg from limma) a default filtering based on the \code{filtFin} element will be applied
#' @param ProjNa (character) custom title
#' @param FCthrs (numeric) Fold-Change threshold (display as line) give as Fold-change and NOT log2(FC)
#' @param subTxt (character) custom sub-title
#' @param grayIncrem (logical) if \code{TRUE}, display overlay of points (not exceeding threshold) as increased shades of gray
#' @param col (character) custom color(s) for points of plot (see also \code{\link[graphics]{par}})
#' @param pch (integer) type of symbol(s) to plot (default=16) (see also \code{\link[graphics]{par}})
#' @param compNa depreciated, please use \code{useComp} instead
#' @param batchFig (logical) if \code{TRUE} figure title and axes legends will be kept shorter for display on fewer splace
#' @param cexMa (numeric) font-size of title, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param cexLa (numeric) size of axis-labels, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param limM (numeric, length=2) range of axis M-values
#' @param limA (numeric, length=2) range of axis A-values
#' @param annotColumn (character) column names of annotation to be extracted (only if \code{Mvalue} is \code{MArrayLM}-object containing matrix $annot).
#' The first entry (typically 'SpecType') is used for different symbols in figure, the second (typically 'GeneName') is used as prefered text for annotating the best points (if \code{namesNBest} allows to do so.)
#' @param annColor (character or integer) colors for specific groups of annotation (only if \code{Mvalue} is \code{MArrayLM}-object containing matrix $annot)
#' @param cexPt (numeric) size of points, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param cexSub (numeric) size of subtitle, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param cexTxLab (numeric) size of text-labels for points, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param namesNBest (integer or character, length=1) number of best points to add names in figure; if 'passThr' all points passing FC-filter will be selected;
#' if the initial object \code{Mvalue} contains a list-element called 'annot' the second of the column specified in argument \code{annotColumn} will be used as text
#' @param NbestCol (character or integer) colors for text-labels of best points
#' @param NaSpecTypeAsContam (logical) consider lines/proteins with \code{NA} in Mvalue$annot[,"SpecType"] as contaminants (if a 'SpecType' for contaminants already exits)
#' @param useMar (numeric,length=4) custom margings (see also \code{\link[graphics]{par}})
#' @param returnData (logical) optional returning data.frame with (ID, Mvalue, Avalue, FDRvalue, passFilt)
#' @param callFrom (character) allow easier tracking of messages produced
#' @param silent (logical) suppress messages
#' @param debug (logical) additional messages for debugging
#' @return This function plots an MA-plot (to the current graphical device); if \code{returnData=TRUE}, a data.frame with ($ID, $Mvalue, $Avalue, $FDRvalue, $passFilt) gets returned
#' @seealso (for PCA) \code{\link{plotPCAw}}
#' @examples
#' library(wrMisc)
#' set.seed(2005); mat <- matrix(round(runif(600),2), ncol=6)
#' rownames(mat) <- c(rep(letters[1:25],each=3), letters[2:26])
#' MAplotW(mat[,2] -mat[,1], A=rowMeans(mat))
#' ## assume 2 groups with 3 samples each
#' matMeans <- rowGrpMeans(mat, gr=gl(2,3,labels=LETTERS[3:4]))
#' MAplotW(M=matMeans[,2] -matMeans[,1], A=matMeans)
#' ## assume 2 groups with 3 samples each and run moderated t-test (from package 'limma')
#' tRes <- moderTest2grp(mat, gl(2,3))
#' MAplotW(tRes$Mval, tRes$Amean)
#' MAplotW(M=tRes$Mval, A=tRes$means, FCth=1.3)
#' MAplotW(tRes)
#' MAplotW(tRes, limM=c(-2,2), FCth=1.3)
#'
#' @export
MAplotW <- function(Mvalue, Avalue=NULL, useComp=1, filtFin=NULL, ProjNa=NULL, FCthrs=NULL, subTxt=NULL,
grayIncrem=TRUE, col=NULL, pch=16, compNa=NULL, batchFig=FALSE, cexMa=1.8, cexLa=1.1, limM=NULL, limA=NULL,
annotColumn=c("SpecType","GeneName","EntryName","Accession","Species","Contam"), annColor=NULL, cexPt=NULL, cexSub=NULL, cexTxLab=0.7,
namesNBest=NULL, NbestCol=1, NaSpecTypeAsContam=TRUE, useMar=c(6.2,4,4,2), returnData=FALSE, callFrom=NULL, silent=FALSE, debug=FALSE) {
## MA plot
## optional arguments for explicit title in batch-mode
fxNa <- wrMisc::.composeCallName(callFrom, newNa="MAplotW")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
opar <- graphics::par(no.readonly=TRUE)
opar2 <- opar[-which(names(opar) %in% c("fig","fin","font","mfcol","mfg","mfrow","oma","omd","omi"))] #
on.exit(graphics::par(opar2)) # progression ok
## during function changes in $mar,$cex.main,$cex.lab,$las
plotByFdr <- TRUE #
namesIn <- c(deparse(substitute(Mvalue)), deparse(substitute(Avalue)), deparse(substitute(filtFin)))
basRGB <- c(0.3,0.3,0.3) # grey
fcRGB <- c(1,0,0) # red for points passing FC filt line
multiComp <- TRUE # initialize
splNa <- annot <- ptType <- colPass <- ptBg <- grpMeans <- pcol <- FDRvalue <- FdrList <- FDRty <- NULL # initialize
if(length(pch) <1) pch <- 16
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(!isTRUE(silent)) silent <- FALSE
if(debug) message("Length Mvalue ",length(Mvalue)," ; length Avalue ",length(Avalue)," ; useComp ",useComp)
if(identical(col,"FDR")) {FDR4color <- TRUE; col <- NULL} else FDR4color <- FALSE
if(length(Mvalue) <1) message("Nothing to do, 'Mvalue' seems to be empty !") else {
## data seem valid to make MAplot
if(length(cexTxLab) <0) cexTxLab <- 0.7
if("MArrayLM" %in% class(Mvalue) || "list" %in% class(Mvalue)) {
## try working based on MArrayLM-object (Mvalue)
if(debug) message("'",namesIn[1],"' is list or MArrayLM-object ")
## initial check of useComp
if(length(useComp) >1) { useComp <- wrMisc::naOmit(useComp)[1]
if(!silent) message(fxNa,"Argument 'useComp' should be integer of length=1; using only 1st entry") }
if(length(useComp) <1) { useComp <- 1
if(!silent) message(fxNa,"Argument 'useComp' invalid, setting to 1") }
## address multiple questions (via useComp): need to check 'useComp', thus need to locate FDRvalues or pValues for group-names ..
pcol <- wrMisc::naOmit(match(c("p.value","pvalue","pval","p"), tolower(names(Mvalue))))
FDRcol <- wrMisc::naOmit(match(c("fdr","bh","lfdr","by","bonferroni"), tolower(names(Mvalue))))
## extract FDR-values (or p-values if no FDR available)
if(length(FDRcol) >0) FDRvalue <- Mvalue[[FDRcol[1]]] else if(length(pcol) >0) FDRvalue <- Mvalue[[pcol[1]]]
if(FDR4color || useComp >1) {
if(debug) message(" FDR4color=",FDR4color," need to extract FDR or p-values")
if(length(dim(FDRvalue)) >0) { # FDRvalues are present as multi-column
if(colnames(FDRvalue)[1]=="(Intercept)" && ncol(FDRvalue) >1) {
## extract 2nd col if result from wrMisc::moderTest2grp()
if(debug) message("Extract 2nd col if result from wrMisc::moderTest2grp()")
pNa <- rownames(FDRvalue)
FDRvalue <- as.numeric(FDRvalue[,2])
names(FDRvalue) <- pNa
multiComp <- FALSE
} else {
## select corresponding of multiple comparisons
if(debug) message("Select corresponding FDR of multiple comparisons")
if(useComp > ncol(FDRvalue)) { useComp <- 1
if(!silent) message(fxNa,"Argument 'useComp' for FDR-Values invalid or too high; reset to 1") }
names(useComp) <- colnames(FDRvalue)[useComp]
pNa <- rownames(FDRvalue)
FDRvalue <- as.numeric(FDRvalue[,useComp])
if(length(pNa) >0) names(FDRvalue) <- pNa }
if(length(FDRcol) <1) { FDRty <- "BH"
FDRvalue <- stats::p.adjust(FDRvalue, method="BH") # transform p.value to BH-FDR
} else FDRty <- names(Mvalue)[FDRcol[1]]
} else {useComp <- 1}
} else { # no need to use useComp
plotByFdr <- FALSE
if(useComp >1) { useComp <- 1
if(!silent) message(fxNa,"Ignoring value of argument 'useComp' since no p-Values or FDR-values found")}
}
## look for M-values (need to create if not available - using useComp checked)
Melem <- wrMisc::naOmit(match(c("mvalues","mvalue","m"), tolower(names(Mvalue)))) # which list-element
## look for group-means & identify column association to current question/pairwise comparison
if("means" %in% names(Mvalue)) {
## identify sample-groups to comparsison(s) - needed lateron
if(debug) message("Identify sample-groups to comparsison(s)")
pairwCol <- wrMisc::sampNoDeMArrayLM(Mvalue, useComp, lstMeans="means", lstP=names(Mvalue)[FDRcol[1]], callFrom=fxNa,silent=silent)
grpMeans <- cbind(mean1=Mvalue$means[,pairwCol[1]], mean2=Mvalue$means[,pairwCol[2]])
## are all group-means needed (for exporting) ??
} else warning("Could not find suitable field '$means' in '",namesIn[1],"'")
if(length(Melem) >0) { ## M-values are available
if(debug) message(" M-values are available")
Mvalue$Mval <- Mvalue[[Melem]]
if(length(dim(Mvalue$Mval)) >0) if(ncol(Mvalue$Mval) >1) {
if(useComp[1] > ncol(Mvalue$Mval)) { if(!silent) message(fxNa," 'useComp' is too high, set to 1"); useComp <- 1 }
Mvalue$Mval <- Mvalue$Mval[,useComp]}
} else { # need to construct M-values based on means
if("means" %in% names(Mvalue)) {
## construct Mvalue based on means (only one/current pairwise comparison needed)
if(debug) message("Construct Mvalue based on means")
Mvalue$Mval <- grpMeans[,2] - grpMeans[,1]
Melem <- which(names(Mvalue)=="Mval") # update
} else stop("Can't construct M-values since suitable field '$means' missing in '",namesIn[1],"' !")
}
## now one can check if 'Avalue' & Mvalue match (only if pValues or FDR values used for coloring)
if(length(Avalue) >0) if(length(Avalue) != length(Mvalue$Mval)) { Avalue <- NULL
if(!silent) message(fxNa,"Invalid entry of 'Avalue' (length=",length(Avalue),"but expecting",length(Mvalue$Mval),")")}
if(length(Avalue) != length(Mvalue$Mval)) Avalue <- Mvalue$Aval <- rowMeans(grpMeans[,1:2], na.rm=TRUE) # define fresh A-values
## recuperate filtering - if present, but only when no custom filtering provided
if(length(filtFin) <1 || identical(filtFin, FALSE)) {
Filcol <- wrMisc::naOmit(match(c("filtfin","filter","filt","finfilt"), tolower(names(Mvalue))))
filtFin <- if(length(Filcol) >0) Mvalue[[Filcol[1]]] else rep(TRUE,length(Avalue))
if(length(dim(filtFin)) >1) filtFin <- filtFin[,useComp]
if(debug) message(" recuperate filtering - if present (length ",length(filtFin),")")
}
## recuperate $annot if present and use for symbol
if("annot" %in% names(Mvalue)) {
useAnnCol <- match(annotColumn, colnames(Mvalue$annot))
if(!is.na(useAnnCol[1])) { # annotation (for multiple groups) exists
ptType <- Mvalue$annot[,useAnnCol[1]] # SpecType
chNA <- is.na(ptType)
## associate NAs from 'SpecType' in ptType with conta ?
if(NaSpecTypeAsContam) {
chConta <- tolower(ptType) %in% c("contaminant","contam","conta","cont")
if(any(chConta)) ptType[which(is.na(ptType))] <- unique(ptType[which(chConta)])[1]}
if(any(is.na(ptType))) ptType[which(chNA)] <- "NA"
if(length(pch) < length(Avalue) && length(unique(wrMisc::naOmit(ptType))) >1) {
if(length(pch) >1 && !silent) message(fxNa," (invalid pch) using default 'pch' oriented by $annot and starting from 15")
pch <- 14 + as.integer(as.factor(ptType))
}
useAnnCol <- wrMisc::naOmit(useAnnCol) }
annot <- Mvalue$annot[,useAnnCol]
if(annotColumn[1] %in% colnames(annot)) annot[,annotColumn[1]] <- ptType # update with NAs trasformed to "NA"
}
if(length(pch)==1) pch <- rep(as.integer(pch), length(Avalue))
if(length(filtFin) <1) filtFin <- rep(TRUE, length(Avalue))
## recuperate M values (& dismiss rest of MArrayLM-object)
Mvalue <- Mvalue$Mval
if(length(dim(Mvalue)) >1) { MNa <- rownames(Mvalue)
Mvalue <- as.numeric(Mvalue)
if(length(MNa) >0) names(Mvalue) <- MNa }
## additional check for length
chpM <- length(Mvalue)==length(Avalue)
if(!chpM && !silent) message(fxNa,"Trouble ahead ? p- and M- values have different length !! (M=",length(Mvalue)," vs A=",length(Avalue),")")
## done with extracting MArrayLM-object
if(!silent) message(fxNa,"Successfully extracted ",length(Mvalue)," Mvalues and ",length(Avalue)," Avalues", if(length(annot) >0) c(" plus annotation"))
} else {
## thus argument 'Mvalue' is not 'MArrayLM'-object
## ... case of explicit Avalue argument
if(length(Avalue) <1) stop("Argument 'Avalue' is required (if 'Mvalue' not 'MArrayLM'-type object) !")
multiComp <- FALSE
if(length(dim(Avalue)) >1) if(ncol(Avalue) >1) {
if(!silent) message(fxNa," Note, ",namesIn[2]," has ",ncol(Avalue)," columns, using last column")
pNa <- rownames(Avalue)
Avalue <- as.numeric(Avalue[,ncol(Avalue)] )
names(Avalue) <- pNa}
}
chNA <- is.na(Avalue)
if(all(chNA)) stop(fxNa,"All A-values are NA, nothing to draw !")
## check for (same) order, adjust Mvalue & Avalue according to names
chNa <- list(MNa=if(length(dim(Mvalue)) >1) rownames(Mvalue) else names(Mvalue),
ANa=if(length(dim(Avalue)) >1) rownames(Avalue) else names(Avalue))
nIni <- c(M=length(Mvalue), A=length(Avalue))
if(length(chNa$MNa) >0 && length(chNa$ANa) >0) { # ie both have names, so one can match names
if(!identical(chNa$MNa,chNa$ANa)) {
matchNa <- wrMisc::naOmit(match(chNa$MNa,chNa$ANa))
if(length(matchNa) <1) stop("Both 'Mvalue' and 'Avalue' have names, but none of them match !!")
Avalue <- Avalue[matchNa]
Mvalue <- wrMisc::naOmit(Mvalue[match(names(Avalue),names(Mvalue))])
} } else {
if(length(Mvalue) != length(Avalue)) stop("A- and M- values have different length, but no names to match !! (M=",length(Mvalue)," vs A=",length(Avalue),")")
}
if(length(grpMeans) <1) grpMeans <- matrix(rep(NA,2*length(Mvalue)), ncol=2, dimnames=list(names(Mvalue),c("mean1","mean2")))
if(length(pch)==1 && length(Mvalue) >1) pch <- rep(pch, length(Mvalue))
if(length(pch) != length(Mvalue) && (length(pch) >1)) { if(!silent) message(fxNa," bizzare entry for 'pch'")
pch <- rep(pch, length(Mvalue))[1:length(Mvalue)]}
## start creating merged data for plot (& export)
merg <- if(length(annot) >0) data.frame(ID=NA, grpMeans, Mvalue=Mvalue, Avalue=Avalue, FDR=if(length(FDRvalue) >0) FDRvalue else rep(NA,length(Mvalue)),
filtFin=if(length(filtFin) >0) filtFin else rep(TRUE,length(Mvalue)), annot, pch=pch, stringsAsFactors=FALSE) else {
data.frame(ID=NA, grpMeans, Mvalue=Mvalue, Avalue=Avalue, FDR=if(length(FDRvalue) >0) FDRvalue else rep(NA,length(Mvalue)), filtFin=if(length(filtFin) >0) filtFin else rep(TRUE,length(Mvalue)), pch=pch, stringsAsFactors=FALSE) }
if(length(names(Mvalue)) >0) merg[,1] <- names(Mvalue) else {if(length(names(Avalue)) >0) merg[,1] <- names(Avalue)}
## replace NA in 'SpecType' by 'NA'
if(annotColumn[1] %in% colnames(merg)) { chNa <- is.na(merg[,annotColumn[1]]) # replace NAs in col "SpecType" by "NA"
if(any(chNa)) merg[which(chNa),annotColumn[1]] <- "NA"
} else { merg <- cbind(merg, rep(1,nrow(merg))) # add colum for 'SpecType'
colnames(merg)[ncol(merg)] <- annotColumn[1] }
## adjust col (color) & pch
if(!any(c(1,length(Mvalue)) %in% length(pch))) {
if(!silent) message(fxNa,"Argument 'pch' should be either length=1 or correspond to length of data, reset to default=16")
pch <- 16 }
if(length(col) >1 && length(col) <length(Mvalue)) {
if(!silent) message(fxNa,"Argument 'col' should be either length=1 or correspond to length of data, reset to default=NULL")
col <- NULL }
## prepare/integrate FILTERING
if(length(filtFin) >0) {
## if filtFin is matrix use each line with min 1 instance of TRUE,
if(length(dim(filtFin)) >1) filtFin <- as.logical(as.matrix(filtFin)[,useComp]) # use rows with >= 1 TRUE
if(length(names(filtFin)) >0) {
matchNa <- wrMisc::naOmit(match(rownames(merg), names(filtFin)))
if(length(matchNa)==nrow(merg)) merg[,"filtFin"] <- filtFin[matchNa]
} else if(length(filtFin)==nrow(merg)) merg[,"filtFin"] <- filtFin # no proof that order of filtFin is correct
} else filtFin <- rep(TRUE, nrow(merg))
if(debug) message(fxNa," ++ DONE extracting columns : ",wrMisc::pasteC(colnames(merg),quo="'"))
## apply filtering
msg <- " data provided in 'Mvalue' and 'Avalue' "
if(!silent && nrow(merg) < round(length(Mvalue)/10)) message(" .. note : less than 10% of",msg," were matched") else {
if(!silent && nrow(merg) < length(Mvalue)/2) message(" .. NOTE : less than 50% of",msg," were matched !!")}
if(debug) message(msg," were matched to ",nrow(merg)," common entries")
## apply filtering (keep all lines where at least one condition passes)
if(length(filtFin) >0 && !identical(filtFin, FALSE)) { # use filtering provided
if(sum(filtFin) >0 && sum(filtFin) < nrow(merg)) {
whFilt <- which(merg$filtFin)
if(length(pch) >1) pch <- pch[whFilt]
if(length(col) >1) col <- col[whFilt]
merg <- merg[whFilt,]
if(!silent) message(fxNa," filtered (based on 'filtFin') from ",length(filtFin)," to ",nrow(merg)," lines")
}
} else filtFin <- rep(TRUE, nrow(merg))
## sort merg, so that legend always gets constructed the same order, ascending ('ascend') or descending ('descend')
## update ..
nIDco <- sum(c("ID","nredID","uniqID") %in% colnames(merg)) # number of heading columns in 'merg'
Mvalue <- as.numeric(if("Mvalue" %in% colnames(merg)) merg[,"Mvalue"] else merg[,nIDco+1])
Avalue <- as.numeric(if("Avalue" %in% colnames(merg)) merg[,"Avalue"] else {
if(length(dim(Mvalue)) >0) merg[,ncol(Mvalue) +nIDco +1] else merg[,nIDco+2]})
if("Lfdr" %in% colnames(merg)) FdrList <- merg[,"Lfdr"] else {
if("lfdr" %in% colnames(merg)) FdrList <- merg[,"lfdr"]}
pch <- merg[,"pch"] # update
ptType <- if(annotColumn[1] %in% colnames(merg)) merg[,annotColumn[1]] else rep(1,nrow(merg)) # update "SpecType"
## prepare for plotting
if(is.null(cexSub)) cexSub <- cexLa +0.05
xLab <- paste("A-value", if(!batchFig) "(average abundance)")
tit1 <- paste(c(if(!batchFig) c(ProjNa, if(!is.null(ProjNa)) ": ","MA-Plot"),
if(!is.null(compNa)) c(compNa[1]," vs ",compNa[2])), collapse=" ") # but what title if batchFig=NULL & compNa=NULL -> only "MA-plot"
if(length(FCthrs) <1) FCthrs <- 1.5
#needed?#if(length(FdrThrs) <1) FdrThrs <- 0.05
## count no of passing
passAll <- passFC <- if(length(FCthrs) ==1 && !any(is.na(FCthrs))) abs(merg[,"Mvalue"]) >= log2(FCthrs) else merg[,"filtFin"] ## convert FCthrs to log2
passAll <- merg[,"filtFin"] & passFC
chNA <- is.na(passAll) # passFdr may contain NAs
if(any(chNA)) passAll[which(chNA)] <- FALSE
if(debug) message(fxNa," ",sum(passFC,na.rm=TRUE)," passing FCthrs ")
## color for points passing filter
if(length(col) >0) if(length(col) != nrow(merg)) { col <- NULL
if(!silent) message(fxNa,"Invalid entry for 'col', should be of length=",nrow(merg),", resetting to default")}
if(length(col) <1) {
alph <- sort(c(0.14, round(0.6/log10(length(Mvalue)),2), 0.8))[2] # alph <- round(12/sqrt(nrow(eBayesLst$pValue)),2)
alph2 <- sort(c(round(7/(5 +sum(passAll)^0.7),2), alph,0.9))[2] # for points passing thresholds
useCol <- if(grayIncrem) grDevices::rgb(0.35,0.35,0.35,alph) else grDevices::rgb(0.7,0.7,0.7) # basic color
useCex <- if(length(cexPt) >0) cexPt else max(round(0.8 + 2/(1 +sum(filtFin, na.rm=TRUE))^0.28,2), 1.1)
chCol <- unique(merg[, annotColumn[1]]) # check how many different colors may be needed
chNaC <- is.na(chCol)
if(any(chNaC)) chCol[which(chNaC)] <- "NA"
if(length(annColor) >0) {colPass <- annColor} else if(length(chCol) >4) {
colPass <- cbind(red=c(141,72,90,171, 220,253,244,255), green=c(129,153,194,221, 216,174,109,0), blue=c(194,203,185,164, 83,97,67,0))
colPass <- grDevices::rgb(red=colPass[,1], green=colPass[,2], blue=colPass[,3], alph2, maxColorValue=255)
if(length(chCol) >8) { colPass <- c(colPass, rep(colPass[8], length(chCol) -8))
if(!silent) message(fxNa," > 8 different groups found, using 8th color after 7th group")}
} else colPass <- grDevices::rgb(c(0.95,0.2,0,0.75), c(0.15,0.2,0.9,0.35), c(0.15,0.95,0,0.8), alph2) # red, blue, green, purple (luminosity adjusted)
useCol <- rep(useCol[1], nrow(merg)) # fuse basic gray to colors for different types
## integrate names of annColor as order of colPass
if(length(names(annColor)) >0) {
uniTy <- unique(merg[which(passAll),annotColumn[1]])
colPass <- colPass[match(names(annColor), uniTy)]
}
## assign color for those passing
if(any(passAll)) { if(FDR4color) {
useCol[which(passAll)] <- .colorByPvalue(merg$FDR[which(passAll)])
} else {
useCol[which(passAll)] <- colPass[ if(length(unique(merg[which(passAll),annotColumn[1]])) >1) wrMisc::levIndex(
merg[which(passAll),annotColumn[1]]) else rep(1,sum(passAll))] } } # assign colors for those passing
} else useCol <- col
## adjust fill color for open symbols
chPch <- pch %in% c(21:25)
if(any(chPch)) { ptBg <- useCol
ptBg[which(chPch)] <- useCol[which(chPch)] # background color for filled symbols
useCol[which(chPch)] <- 1 # contour as black
}
## main graphic
tmp <- try(graphics::par(mar=c(6.5,4,4,2), cex.main=cexMa, las=1), silent=TRUE)
## rather directly plot FDR
tmp <- try(graphics::plot(merg[,"Avalue"], merg[,"Mvalue"], pch=pch, cex=useCex, main=tit1,
ylab="M value (log FC)", col=useCol, xlab=xLab, cex.lab=cexLa, xlim=limM,ylim=limA, pt.bg=ptBg), silent=TRUE)
if(inherits(tmp, "try-error")) warning(fxNa,"UNABLE to produce plot !") else {
sTxt <- if(length(subTxt) ==1) subTxt else { if(multiComp) paste0(if(length(names(useComp)) >0) names(useComp) else paste0("useComp=",useComp),"; ",collapse="")}
sTxt <- paste0(sTxt,"n=",length(Mvalue),
if(!all(is.na(c(FCthrs)))) paste(";",sum(passAll, na.rm=TRUE),"(color) points passing", if(!is.na(FCthrs)) paste0("FCthr=", as.character(signif(FCthrs,3))) ))
graphics::mtext(sTxt, cex=0.75, line=0.2)
if(!all(is.na(FCthrs))) {
if(debug) message(fxNa," n=",length(Mvalue)," FCthrs=",as.character(FCthrs)," filt.ini=", sum(filtFin, na.rm=TRUE)," passAll=",sum(passAll,na.rm=TRUE),
" ; range Mva ",wrMisc::pasteC(signif(range(Mvalue,na.rm=TRUE),3))," ; alph=",alph," useCex=",useCex," alph2=",alph2)
graphics::abline(h=c(-1,1)*(log2(FCthrs) + diff(graphics::par("usr")[1:2])/500), col=grDevices::rgb(0.87,0.72,0.72), lty=2) }
## add names to best points
if(length(namesNBest) >0) {
if(any(sapply( c("passThr","pass","passFC"), identical, namesNBest))) namesNBest <- sum(passAll)
if(!is.integer(namesNBest)) namesNBest <- try(as.integer(namesNBest), silent=TRUE)
if(namesNBest >0 && any(passAll)) {
useLi <- if(any(!passAll)) which(passAll) else 1:nrow(merg)
tmP <- as.numeric(merg[useLi,"Avalue"])
names(tmP) <- rownames(merg)[useLi]
## look for more informative names to display
if(length(annot) >0) {
proNa <- annot[match(names(tmP), rownames(annot)), annotColumn[2]] # normally 'Description'
chNa <- is.na(proNa)
if(!all(chNa)) names(tmP)[which(!chNa)] <- proNa[which(!chNa)]
}
useL2 <- order(tmP, decreasing=TRUE)[1:min(namesNBest,sum(passAll))]
xOffs <- signif(diff(graphics::par("usr")[1:2])/170,3)
yOffs <- signif(diff(graphics::par("usr")[3:4])/90,3)
noNa <- if(is.null(names(tmP[useL2]))) 1:length(tmP) else which(is.na(names(tmP)[useL2]))
if(length(noNa) >0 && all(annotColumn %in% colnames(merg))) names(tmP)[useL2[noNa]] <- merg[useLi[useL2[noNa]], wrMisc::naOmit(match(annotColumn[-1], colnames(merg)))[1]]
if(length(NbestCol) <1) NbestCol <- 1
displTx <- names(tmP[useL2])
chNa <- is.na(displTx)
if(any(chNa)) {displTx[which(chNa)] <- "unknown"; cexTxLab <- c(cexTxLab,cexTxLab*0.7)[1+chNa]} # smaller label for 'unknown'
if(all(chNa)) {if(!silent) message(fxNa," no names for display of best")
} else graphics::text(Avalue[useLi[useL2]] +xOffs, Mvalue[useLi[useL2]] +yOffs, displTx, cex=cexTxLab, col=NbestCol, adj=0) }
}
## legend (if multiple symbols)
pch[which(is.na(pch))] <- -2
ch1 <- unique(pch)
if(length(ch1) >1) {
legInd <- which(!duplicated(merg[which(passAll), annotColumn[1]], fromLast=FALSE))
legPch <- pch[which(passAll)[legInd]]
legCol <- useCol[which(passAll)[legInd]]
legBg <- ptBg[which(passAll)[legInd]]
if(alph2 <1) {legCol <- substr(legCol,1,7); legBg <- substr(legBg,1,7)} # reset to no transparency
legLab <- merg[which(passAll)[legInd], annotColumn[1]]
chNa <- is.na(legLab)
if(any(chNa)) legLab[chNa] <- "NA"
legOr <- if(length(legLab) >1) order(legLab) else 1 # not used so far
legLoc <- checkForLegLoc(merg[which(passAll),c("Avalue","Mvalue")] , sampleGrp=legLab, showLegend=FALSE)
legCex <- stats::median(c(useCex,cexTxLab,1.2), na.rm=TRUE)
graphics::legend(legLoc$loc, legend=legLab, col=if(FDR4color) grDevices::grey(0.5) else legCol, text.col=1, pch=legPch, if(length(ptBg) >0) pt.bg=ptBg, cex=legCex, pt.cex=1.2*legCex, xjust=0.5, yjust=0.5) # as points
} }
tmp <- try(graphics::par(mar=opar$mar, cex.main=opar$cex.main, las=opar$las), silent=TRUE)
## export results
if(returnData) {
merg <- merg[,-1*c(1,ncol(merg))] # remove col 'ID' 'redundant' & 'pch'
annCo <- wrMisc::naOmit(match(annotColumn, colnames(merg)))
if(length(annCo) >0) cbind(merg[,annCo], merg[,-annCo]) else merg }
} }
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/MAplotW.R
|
#' Volcano-Plot (Statistical Test Outcome versus Relative Change)
#'
#' This type of plot is very common in high-throughput biology, see \href{https://en.wikipedia.org/wiki/Volcano_plot_(statistics)}{Volcano-plot}.
#' Basically, this plot allows comparing the outcome of a statistical test to the relative change (ie log fold-change, M-value).
#'
#' In high-throughput biology data are typically already transformed to log2 and thus, the 'M'-values (obtained by subtrating two group means) represent a relative change.
#' Output from statistical testing by \code{\link[wrMisc]{moderTest2grp}} or \code{\link[wrMisc]{moderTestXgrp}} can be directly read to produce Volcano plots for diagnostic reasons.
#' Please note, that plotting a very high number of points (eg >10000) in transparency may take several seconds.
#'
#' @param Mvalue (MArrayLM-object, numeric or matrix) data to plot; M-values are typically calculated as difference of log2-abundance values and 'pValue' the mean of log2-abundance values;
#' M-values and p-values may be given as 2 columsn of a matrix, in this case the argument \code{pValue} should remain NULL.
#' One may also furnish MArrayLM-objects created bpackage wrProteo or limma.
#' @param pValue (numeric, list or data.frame) if \code{NULL} it is assumed that 2nd column of 'Mvalue' contains the p-values to be used
#' @param useComp (integer, length=1) choice of which of multiple comparisons to present in \code{Mvalue} (if generated using \code{moderTestXgrp()})
#' @param filtFin (matrix or logical) The data may get filtered before plotting: If \code{FALSE} no filtering will get applied; if matrix of \code{TRUE}/\code{FALSE} it will be used as optional custom filter, otherwise (if \code{Mvalue} if an \code{MArrayLM}-object eg from limma) a default filtering based on the \code{filtFin} element will be applied
#' @param ProjNa (character) custom title
#' @param FCthrs (numeric) Fold-Change threshold (display as line) give as Fold-change and NOT log2(FC), default at 1.5, set to \code{NA} for omitting
#' @param FdrList (numeric) FDR data or name of list-element
#' @param FdrThrs (numeric) FDR threshold (display as line), default at 0.05, set to \code{NA} for omitting
#' @param FdrType (character) FDR-type to extract if \code{Mvalue} is 'MArrayLM'-object (eg produced by from \code{moderTest2grp} etc);
#' if \code{NULL} it will search for suitable fields/values in this order : 'FDR','BH','lfdr' and 'BY'
#' @param subTxt (character) custom sub-title
#' @param grayIncrem (logical) if \code{TRUE}, display overlay of points (not exceeding thresholds) as increased shades of gray
#' @param col (character) custom color(s) for points of plot (see also \code{\link[graphics]{par}})
#' @param pch (integer) type of symbol(s) to plot (default=16) (see also \code{\link[graphics]{par}})
#' @param compNa (character) names of groups compared
#' @param batchFig (logical) if \code{TRUE} figure title and axes legends will be kept shorter for display on fewer splace
#' @param cexMa (numeric) font-size of title, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param cexLa (numeric) size of axis-labels, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param limM (numeric, length=2) range of axis M-values
#' @param limp (numeric, length=2) range of axis FDR / p-values
#' @param annotColumn (character) column names of annotation to be extracted (only if \code{Mvalue} is \code{MArrayLM}-object containing matrix $annot).
#' The first entry (typically 'SpecType') is used for different symbols in figure, the second (typically 'GeneName') is used as prefered text for annotating the best points (if \code{namesNBest} allows to do so.)
#' @param annColor (character or integer) colors for specific groups of annotation (only if \code{Mvalue} is \code{MArrayLM}-object containing matrix $annot)
#' @param expFCarrow (logical, character or numeric) optional adding arrow for expected fold-change; if \code{TRUE} the expected ratio will be extracted from numeric concentration-indications from sample-names
#' if \code{numeric} an arrow will be drawn (M-value as 1st position, color of 2nd position of vector).
#' @param cexPt (numeric) size of points, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param cexSub (numeric) size of subtitle, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param cexTxLab (numeric) size of text-labels for points, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param namesNBest (integer or character) for display of labels to points in figure: if 'pass','passThr' or 'signif' all points passing thresholds; if numeric (length=1) this number of best points will get labels
#' if the initial object \code{Mvalue} contains a list-element called 'annot' the second of the column specified in argument \code{annotColumn} will be used as text
#' @param NbestCol (character or integer) colors for text-labels of best points, also used for arrow
#' @param sortLeg (character) sorting of 'SpecType' annotation either ascending ('ascend') or descending ('descend'), no sorting if \code{NULL}
#' @param NaSpecTypeAsContam (logical) consider lines/proteins with \code{NA} in Mvalue$annot[,"SpecType"] as contaminants (if a 'SpecType' for contaminants already exits)
#' @param useMar (numeric,length=4) custom margings (see also \code{\link[graphics]{par}})
#' @param returnData (logical) optional returning data.frame with (ID, Mvalue, pValue, FDRvalue, passFilt)
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @param debug (logical) additional messages for debugging
#' @return This function simply plots an MA-plot (to the current graphical device), if \code{returnData=TRUE} an optional data.frame with (ID, Mvalue, pValue, FDRvalue, passFilt) can be returned
#' @seealso (for PCA) \code{\link{plotPCAw}})
#' @examples
#' library(wrMisc)
#' set.seed(2005); mat <- matrix(round(runif(900),2), ncol=9)
#' rownames(mat) <- paste0(rep(letters[1:25], each=4), rep(letters[2:26],4))
#' mat[1:50,4:6] <- mat[1:50,4:6] + rep(c(-1,1)*0.1,25)
#' mat[3:7,4:9] <- mat[3:7,4:9] + 0.7
#' mat[11:15,1:6] <- mat[11:15,1:6] - 0.7
#' ## assume 2 groups with 3 samples each
#' gr3 <- gl(3, 3, labels=c("C","A","B"))
#' tRes2 <- moderTest2grp(mat[,1:6], gl(2,3), addResults = c("FDR","means"))
#' # Note: due to the small number of lines only FDR chosen to calculate
#' VolcanoPlotW(tRes2)
#' ## Add names of points passing custom filters
#' VolcanoPlotW(tRes2, FCth=1.3, FdrThrs=0.2, namesNBest="passThr")
#'
#' ## assume 3 groups with 3 samples each
#' tRes <- moderTestXgrp(mat, gr3, addResults = c("FDR","means"))
#' # Note: due to the small number of lines only FDR chosen to calculate
#' VolcanoPlotW(tRes)
#' VolcanoPlotW(tRes, FCth=1.3, FdrThrs=0.2)
#' VolcanoPlotW(tRes, FCth=1.3, FdrThrs=0.2, useComp=2)
#'
#' @export
VolcanoPlotW <- function(Mvalue, pValue=NULL, useComp=1, filtFin=NULL, ProjNa=NULL, FCthrs=NULL, FdrList=NULL, FdrThrs=NULL, FdrType=NULL,
subTxt=NULL, grayIncrem=TRUE, col=NULL, pch=16, compNa=NULL, batchFig=FALSE, cexMa=1.8, cexLa=1.1, limM=NULL, limp=NULL,
annotColumn=c("SpecType","GeneName","EntryName","Accession","Species","Contam"), annColor=NULL, expFCarrow=FALSE,cexPt=NULL, cexSub=NULL,
cexTxLab=0.7, namesNBest=NULL, NbestCol=1, sortLeg="descend", NaSpecTypeAsContam=TRUE, useMar=c(6.2,4,4,2), returnData=FALSE, callFrom=NULL, silent=FALSE,debug=FALSE) {
## MA plot
## optional arguments for explicit title in batch-mode
fxNa <- wrMisc::.composeCallName(callFrom, newNa="VolcanoPlotW")
opar <- graphics::par(no.readonly=TRUE)
opar2 <- opar[-which(names(opar) %in% c("fig","fin","font","mfcol","mfg","mfrow","oma","omd","omi"))] #
on.exit(graphics::par(opar2)) # progression ok
plotByFdr <- TRUE #
namesIn <- c(deparse(substitute(Mvalue)), deparse(substitute(pValue)), deparse(substitute(filtFin)))
basRGB <- c(0.3,0.3,0.3) # grey
fcRGB <- c(1,0,0) # red for points passing FC filt line
splNa <- annot <- ptType <- colPass <- ptBg <- grpMeans <- pcol <- FDRvalue <- NULL # initialize
multiComp <- TRUE # initialize
if(debug) silent <- FALSE
if(length(Mvalue) <1) message(fxNa,"Nothing to do, 'Mvalue' seems to be empty !") else {
## data seem valid to make MAplot
if(length(cexTxLab) <0) cexTxLab <- 0.7
if(inherits(Mvalue, "MArrayLM")) {
## try working based on MArrayLM-object (Mvalue)
## initial check of useComp
if(length(useComp) >1) { useComp <- wrMisc::naOmit(useComp)[1]
if(!silent) message(fxNa," argument 'useComp' should be integer of length=1; using only 1st entry") }
if(length(useComp) <1) { useComp <- 1
if(!silent) message(fxNa," argument 'useComp' invalid, setting to 1") }
if(debug) {message(fxNa,"VPW2")}
if(length(pValue) <1) {
## no spearate pValues provided : extract from MArrayLM-object (Mvalue)
pcol <- wrMisc::naOmit(match(c("p.value","pvalue","pval","p"), tolower(names(Mvalue))))
if(length(pcol) >0) pValue <- Mvalue[[pcol[1]]] else stop("can't find suitable element for p-Values from MArrayLM-object")
if(length(dim(pValue)) >0) if(colnames(pValue)[1] =="(Intercept)" & ncol(pValue) >1) {
## extract 2nd col if result from wrMisc::moderTest2grp()
pNa <- rownames(pValue)
pValue <- as.numeric(pValue[,2])
names(pValue) <- pNa
multiComp <- FALSE
} else {
## select corresponding of multiple comparisons
if(useComp > ncol(pValue)) { useComp <- 1
if(!silent) message(fxNa,"Argument 'useComp' for pValues invalid or too high; reset to 1") }
names(useComp) <- colnames(pValue)[useComp]
pNa <- rownames(pValue)
pValue <- as.numeric(pValue[,useComp])
if(length(pNa) >0) names(pValue) <- pNa }
} ## .. otherwise spearate pValue was provided
if(debug) {message(fxNa,"VPW3")}
## look for M-values (need to create if not available - using useComp checked when extracting pValue)
Melem <- wrMisc::naOmit(match(c("mvalues","mvalue","m"), tolower(names(Mvalue)))) # which list-element
Fcol <- wrMisc::naOmit(match(if(length(FdrType) <1) c("fdr","bh","lfdr","by","p.value") else tolower(FdrType), tolower(names(Mvalue)))) # needed for matching means to pair-wise names and for extracting FDR values
if(debug) {message(fxNa,"Fcol : ",wrMisc::pasteC(Fcol)," VPW4")}
if(length(Fcol) <1) stop("Can't find elment suitable for statistical values", if(length(FdrType)==1) c(" to '",FdrType,"'")) else Fcol <- Fcol[1]
if(!silent & length(FdrType) <1) message(fxNa,"Using element '",names(Mvalue)[Fcol],"' as FDR-values for plot")
if("lfdr" %in% names(Mvalue)[Fcol]) { # switch from directly plotting FDR-values to uncorrected p-values
plotByFdr <- FALSE }
## look for group-means & identify column association to current question/pairwise comparison
if("means" %in% names(Mvalue)) {
## identify sammple-groups to comparsison(s) - needed lateron
pairwCol <- wrMisc::sampNoDeMArrayLM(Mvalue, useComp, lstMeans="means", lstP=Fcol, callFrom=fxNa, silent=silent)
grpMeans <- cbind(mean1=Mvalue$means[,pairwCol[1]], mean2=Mvalue$means[,pairwCol[2]])
## are all group-means needed (for exporting) ??
} else {grpMeans <- NULL; warning(fxNa,"Could not find suitable field '$means' in '",namesIn[1],"'") }
if(length(Melem) >0) { ## M-values are available
Mvalue$Mval <- Mvalue[[Melem]]
if(length(dim(Mvalue$Mval)) >0) if(ncol(Mvalue$Mval) >1) {
if(useComp[1] > ncol(Mvalue$Mval)) { if(!silent) message(fxNa," 'useComp' is too high, set to 1"); useComp <- 1 }
Mvalue$Mval <- Mvalue$Mval[,useComp]}
} else { # need to construct M-values based on means
if("means" %in% names(Mvalue)) {
## construct Mvalue based on means (only one/current pairwise comparison needed)
Mvalue$Mval <- grpMeans[,2] - grpMeans[,1]
Melem <- which(names(Mvalue) =="Mval") # update
} else stop("Can't construct M-values since suitable field '$means' missing in '",namesIn[1],"' !")
}
if(debug) {message(fxNa,"VPW4b")}
## now one can check if 'pValue' & Mvalue match
chPM <- length(pValue) >0 && length(as.numeric(pValue)) == length(as.numeric(Mvalue[[Melem]]))
if(!chPM) {
if(length(pcol) >0) { # pVal avilable in Mvalue
if(length(as.numeric(Mvalue[[pcol[1]]][,useComp])) ==length(as.numeric(Mvalue[[Melem]]))) { # pVal from Mvalue seems to fit => use
pValue <- as.numeric(Mvalue[[pcol[1]]][,useComp])
} else stop("'pValue' & 'Mvalue' don't match")
} else stop("'pValue' & 'Mvalue' don't match (no field in MArrayLM-object available)")
}
if(debug) {message(fxNa,"Fcol : ",wrMisc::pasteC(Fcol)," VPW5"); VPW5 <- list(FdrList=FdrList,Mvalue=Mvalue,Fcol=Fcol,Melem=Melem,FdrType=FdrType,plotByFdr=plotByFdr,pValue=pValue,useComp=useComp,pairwCol=pairwCol,grpMeans=grpMeans)}
## extract FDR from MArrayLM-object
if(length(FdrList) <1) {
## no explicit pValue, try to extract from MArrayLM-object (Mvalue)
if(length(Fcol) >0) { FDRvalue <- Mvalue[[Fcol[1]]]
## extract 2nd col if result from wrMisc::moderTest2grp()
if(length(dim(FDRvalue)) >0) if(colnames(FDRvalue)[1] =="(Intercept)" && ncol(FDRvalue) >1) {
pNa <- rownames(FDRvalue)
FDRvalue <- as.numeric(FDRvalue[,2])
names(FDRvalue) <- pNa
multiComp <- FALSE } #else FDRvalue <- as.numeric(FDRvalue[,useComp])
} else {
FDRvalue <- stats::p.adjust(pValue)
if(!silent) message(fxNa,"No FDR data found, generating BH-FDR")}
## need to find corresponding of multiple comparisons
if(length(dim(FDRvalue)) >0) {
pNa <- rownames(FDRvalue)
if(ncol(FDRvalue) >1) { if(useComp > ncol(FDRvalue)) { useComp <- 1
if(!silent) message(fxNa," argument 'useComp' for FDRvalues invalid or too high; reset to 1") }
FDRvalue <- as.numeric(FDRvalue[,useComp])
if(length(pNa) >0) names(FDRvalue) <- pNa }}
}
if(debug) {message(fxNa,"VPW6")}
## recuperate filtering - if present, but only when no custom filtering provided
if(length(filtFin) <1 || isFALSE(filtFin)) {
Fcol <- wrMisc::naOmit(match(c("filtfin","filter","filt","finfilt"), tolower(names(Mvalue))))
filtFin <- if(length(Fcol) >0) Mvalue[[Fcol[1]]] else rep(TRUE,length(pValue))
if(length(dim(filtFin)) >1) filtFin <- filtFin[,useComp]
}
## recuperate $annot if present and use for symbol
if("annot" %in% names(Mvalue)) {
useAnnCol <- match(annotColumn, colnames(Mvalue$annot))
if(!is.na(useAnnCol[1])) { # annotation (for multiple groups) exists
ptType <- Mvalue$annot[,useAnnCol[1]] # SpecType
chNA <- is.na(ptType)
## associate NAs from 'SpecType' in ptType with conta ?
if(NaSpecTypeAsContam) {
chConta <- tolower(ptType) %in% c("contaminant","contam","conta","cont")
if(any(chConta)) ptType[which(is.na(ptType))] <- unique(ptType[which(chConta)])[1]}
if(any(is.na(ptType))) ptType[which(chNA)] <- "NA"
if(length(pch) < length(pValue) && length(unique(wrMisc::naOmit(ptType))) >1) {
if(length(pch) >1 && !silent) message(fxNa," (invalid pch) using default 'pch' oriented by $annot and starting from 15")
pch <- 14 + as.integer(as.factor(ptType))
}
useAnnCol <- wrMisc::naOmit(useAnnCol)
annot <- Mvalue$annot[,useAnnCol]
if(annotColumn[1] %in% colnames(annot)) annot[,annotColumn[1]] <- ptType
} }
if(length(pch)==1) pch <- rep(as.integer(pch), length(pValue))
if(debug) {message(fxNa,"VPW7")}
## recuperate M values (& dismiss rest of MArrayLM-object)
Mvalue <- Mvalue$Mval
if(length(dim(Mvalue)) >1) { MNa <- rownames(Mvalue)
Mvalue <- as.numeric(Mvalue)
if(length(MNa) >0) names(Mvalue) <- MNa }
## additional check for length
chpM <- length(Mvalue)==length(pValue)
if(!chpM & !silent) message(fxNa,"Trouble ahead ? p- and M- values have different length !! (M=",length(Mvalue)," vs p=",length(pValue),")")
## done with extracing MArrayLM-object
if(!silent) message(fxNa,"Successfully extracted ",length(Mvalue)," Mvalues and ",length(pValue)," pValues", if(length(annot) >0) c(" plus anotation"))
} else {
## thus argument 'Mvalue' is not 'MArrayLM'-object
## ... case of explicit pValue argument
if(length(pValue) <1) stop("Argument 'pValue' is required (if 'Mvalue' not 'MArrayLM'-type object) !")
if(length(dim(pValue)) >1) if(ncol(pValue) >1) {
if(!silent) message(fxNa," Note, ",namesIn[2]," has ",ncol(pValue)," columns, using last column")
pNa <- rownames(pValue)
pValue <- as.numeric(pValue[,ncol(pValue)] )
names(pValue) <- pNa}
FDRvalue <- if(length(FdrList) <1) NULL else FdrList
}
if(debug) {message(fxNa,"VPW8")}
## need to introduce -log10 to pValue
chNA <- is.na(pValue)
if(all(chNA)) stop(fxNa," All p-values are NA, nothing to draw !")
if(any(pValue <0, na.rm=TRUE)) warning(fxNa,"Some p-values are negative, this should not be ! Maybe log values were given by error ?")
pValue <- -log10(pValue)
## check for (same) order, adjust Mvalue & pValue according to names
chNa <- list(MNa=if(length(dim(Mvalue)) >1) rownames(Mvalue) else names(Mvalue),
pNa=if(length(dim(pValue)) >1) rownames(pValue) else names(pValue))
nIni <- c(M=length(Mvalue),p=length(pValue))
if(length(chNa$MNa) >0 && length(chNa$pNa) >0) { # ie both have names, so one can match names
if(!all(chNa$MNa==chNa$pNa, na.rm=TRUE)) {
matchNa <- wrMisc::naOmit(match(chNa$MNa, chNa$pNa))
if(length(matchNa) <1) stop("Both 'Mvalue' and 'pValue' have names, but none of them match !!")
if(!all(matchNa, 1:length(pValue), na.rm=TRUE)) {
pValue <- pValue[matchNa]
Mvalue <- wrMisc::naOmit(Mvalue[match(names(pValue), names(Mvalue))]) }
}
} else {
if(length(Mvalue) != length(pValue)) stop("p- and M- values have different length, but no names to match !! (M=",length(Mvalue)," vs p=",length(pValue),")")
}
if(length(grpMeans) <1) grpMeans <- matrix(rep(NA,2*length(Mvalue)), ncol=2, dimnames=list(names(Mvalue),c("mean1","mean2")))
if(debug) {message(fxNa,"VPW9"); VPW9 <- list(FdrList=FdrList,Mvalue=Mvalue,FdrType=FdrType,FDRvalue=FDRvalue,plotByFdr=plotByFdr,pValue=pValue,useComp=useComp,pairwCol=pairwCol,grpMeans=grpMeans, filtFin=filtFin,annotColumn=annotColumn,annot=annot, pch=pch,sortLeg=sortLeg,batchFig=batchFig)}
## prepare/integrate FILTERING
if(length(filtFin) >0) {
## if filtFin is matrix use each line with min 1 instance of TRUE,
if(length(dim(filtFin)) >1) filtFin <- as.logical(as.matrix(filtFin)[,useComp]) # use rows with >= 1 TRUE
if(length(names(filtFin)) >0) {
matchNa <- wrMisc::naOmit(match(rownames(pValue), names(filtFin)))
if(length(matchNa)==length(pValue)) filtFin <- as.logical(filtFin[matchNa])
}
} else filtFin <- rep(TRUE, nrow(merg))
## start creating merged data for plot (& export)
merg <- if(length(annot) >0) data.frame(ID=NA, grpMeans, Mvalue=Mvalue, pValue=pValue,
FDR=if(length(FDRvalue) >0) as.numeric(FDRvalue) else rep(NA,length(pValue)),
filtFin=filtFin, annot, pch=pch, stringsAsFactors=FALSE) else {
data.frame(ID=NA, grpMeans, Mvalue=Mvalue, pValue=pValue, FDR=if(length(FDRvalue) >0) as.numeric(FDRvalue) else rep(NA,length(pValue)),
filtFin=filtFin, pch=pch, stringsAsFactors=FALSE) }
if(length(names(Mvalue)) >0) merg[,1] <- names(Mvalue) else {if(length(names(pValue)) >0) merg[,1] <- names(pValue)}
## replace NA in 'SpecType' by 'NA'
if(annotColumn[1] %in% colnames(merg)) { chNa <- is.na(merg[,annotColumn[1]]) # replace NAs in col "SpecType" by "NA"
if(any(chNa)) merg[which(chNa),annotColumn[1]] <- "NA"
} else { merg <- cbind(merg, rep(1,nrow(merg))) # add colum for 'SpecType'
colnames(merg)[ncol(merg)] <- annotColumn[1] }
if(debug) {message(fxNa,"VPW10")}
## adjust col & pch
if(!any(c(1,length(Mvalue)) %in% length(pch))) {
if(!silent) message(fxNa,"argument 'pch' should be either length=1 or correspond to length of data, reset to default=16")
pch <- 16 }
if(length(col) >1 && length(col) <length(Mvalue)) {
if(!silent) message(fxNa,"argument 'col' should be either length=1 or correspond to length of data, reset to default=NULL")
col <- NULL }
if(debug) message(fxNa," ++ DONE extracting columns : ",wrMisc::pasteC(colnames(merg),quo="'"))
## apply filtering
msg <- " data provided in 'Mvalue' and 'pValue' "
if(debug) {message(fxNa,"VPW10")}
if(!silent && nrow(merg) < round(length(Mvalue)/10)) message(fxNa," .. note : less than 10% of",msg," were matched") else {
if(!silent && nrow(merg) < length(Mvalue)/2) message(fxNa," .. NOTE : less than 50% of",msg," were matched !!")}
if(debug) message(fxNa,msg," were matched to ",nrow(merg)," common entries")
## apply filtering (keep all lines where at least one condition passes)
if(length(filtFin) >0 && any(isFALSE(filtFin), na.rm=TRUE)) { # use filtering provided
if(sum(filtFin) >0 && sum(filtFin) < nrow(merg)) {
whFilt <- which(merg$filtFin)
if(length(pch) >1) pch <- pch[whFilt]
if(length(col) >1) col <- col[whFilt]
merg <- merg[whFilt,]
if(!silent) message(fxNa," filtered (based on 'filtFin') from ",length(filtFin)," to ",nrow(merg)," lines")
}
} else filtFin <- rep(TRUE, nrow(merg))
if(debug) {message(fxNa,"VPW11")}
## sort merg, so that legend always gets constructed the same order, ascending ('ascend') or descending ('descend')
sortLeg <- if(identical(sortLeg,"ascend")) FALSE else {if(identical(sortLeg,"descend")) TRUE else NULL}
if(length(sortLeg) ==1 && annotColumn[1] %in% colnames(merg)) merg <- merg[order(merg[,annotColumn[1]], decreasing=sortLeg),]
## update ..
nIDco <- sum(c("ID","nredID","uniqID") %in% colnames(merg)) # number of heading columns in 'merg'
Mvalue <- as.numeric(if("Mvalue" %in% colnames(merg)) merg[,"Mvalue"] else merg[,nIDco+1])
pValue <- as.numeric(if("pValue" %in% colnames(merg)) merg[,"pValue"] else {
if(length(dim(Mvalue)) >0) merg[,ncol(Mvalue) +nIDco +1] else merg[,nIDco+2]})
if("Lfdr" %in% colnames(merg)) FdrList <- merg[,"Lfdr"] else {
if("lfdr" %in% colnames(merg)) FdrList <- merg[,"lfdr"]}
pch <- merg[,"pch"] # update
ptType <- if(annotColumn[1] %in% colnames(merg)) merg[,annotColumn[1]] else rep(1,nrow(merg)) # update "SpecType"
if(debug) {message(fxNa,"VPW12"); VPW12 <- list(merg=merg,Mvalue=Mvalue,filtFin=filtFin)}
## prepare for plotting
if(is.null(cexSub)) cexSub <- cexLa +0.05
xLab <- "M-value (log2 fold-change)"
tit1 <- paste(c(if(!batchFig) c(ProjNa, if(!is.null(ProjNa)) ": ","Volcano-Plot"),
if(!is.null(compNa)) c(compNa[1]," vs ",compNa[2])), collapse=" ") # but what title if batchFig=NULL & compNa=NULL -> only "Volcano-plot"
if(length(FCthrs) <1) FCthrs <- 1.5
if(length(FdrThrs) <1) FdrThrs <- 0.05
if(debug) {message(fxNa,"VPW12b")}
## count no of passing
passFC <- if(length(FCthrs) ==1 && !any(is.na(FCthrs))) abs(merg[,"Mvalue"]) >= log2(FCthrs) else merg[,"filtFin"] ## convert FCthrs to log2
passFdr <- if(length(FdrThrs) ==1 && !any(is.na(FdrThrs)) && "FDR" %in% colnames(merg)) {merg[,"FDR"] <= FdrThrs} else merg[,"filtFin"]
passAll <- merg[,"filtFin"] & passFC & passFdr
if(debug) {message(fxNa,"VPW12c")}
chNA <- is.na(passAll) # passFdr may contain NAs
if(any(chNA)) passAll[which(chNA)] <- FALSE
if(debug) message(fxNa," ",sum(passFC,na.rm=TRUE)," passing FCthrs ; ",sum(passFdr,na.rm=TRUE)," passing FdrThrs ; combined ",sum(passAll,na.rm=TRUE))
if(debug) {message(fxNa,"VPW13")}
## color for points passing filter
if(length(col) >0) if(length(col) != nrow(merg)) { col <- NULL
if(!silent) message(fxNa," invalid entry for 'col', should be of length=",nrow(merg),", resetting to default")}
if(length(col) <1) {
alph <- sort(c(0.14, round(0.6/log10(length(Mvalue)),2), 0.8))[2] # alph <- round(12/sqrt(nrow(eBayesLst$pValue)),2)
alph2 <- sort(c(round(7/(5 +sum(passAll)^0.7),2), alph,0.9))[2] # for points passing thresholds
useCol <- if(grayIncrem) grDevices::rgb(0.35,0.35,0.35,alph) else grDevices::rgb(0.7,0.7,0.7) # basic color
useCex <- if(length(cexPt) >0) cexPt else max(round(0.8 + 2/(1 +sum(filtFin, na.rm=TRUE))^0.28,2), 1.1)
chCol <- unique(merg[, annotColumn[1]]) # check how many different colors may be needed
chNaC <- is.na(chCol)
if(any(chNaC)) chCol[which(chNaC)] <- "NA"
if(length(annColor) >0) {colPass <- annColor} else if(length(chCol) >4) {
colPass <- cbind(red=c(141,72,90,171, 220,253,244,255), green=c(129,153,194,221, 216,174,109,0), blue=c(194,203,185,164, 83,97,67,0))
colPass <- grDevices::rgb(red=colPass[,1], green=colPass[,2], blue=colPass[,3], alph2, maxColorValue=255)
if(length(chCol) >8) { colPass <- c(colPass, rep(colPass[8], length(chCol) -8))
if(!silent) message(fxNa," > 8 different groups found, using 8th color after 7th group")}
} else colPass <- grDevices::rgb(c(0.95,0.2,0,0.75), c(0.15,0.2,0.9,0.35), c(0.15,0.95,0,0.8), alph2) # red, blue, green, purple (luminosity adjusted)
useCol <- rep(useCol[1], nrow(merg)) # fuse basic gray to colors for different types
## integrate names of annColor as order of colPass
if(length(names(annColor)) >0) {
uniTy <- unique(merg[which(passAll), annotColumn[1]])
colPass <- colPass[match(names(annColor), uniTy)]
}
## assign color for those passing
useCol[which(passAll)] <- if(any(passAll, na.rm=TRUE)) colPass[if(length(unique(merg[which(passAll),annotColumn[1]])) >1) wrMisc::levIndex(merg[which(passAll),annotColumn[1]]) else rep(1,sum(passAll))] # assign colors for those passing
} else useCol <- col
## adjust fill color for open symbols
chPch <- pch %in% c(21:25)
if(any(chPch)) { ptBg <- useCol
ptBg[which(chPch)] <- useCol[which(chPch)] # background color for filled symbols
useCol[which(chPch)] <- 1 # contour as black
}
## main graphics
if(length(Mvalue) >0) {
pl1 <- try(graphics::par(mar=if(length(useMar)==4) useMar else c(6.5,4,4,2), cex.main=cexMa, las=1), silent=TRUE)
if(inherits(pl1, "try-error")) {Mvalue <- NULL; message("UNABLE TO SET PLOT MARGINS !! check plotting device ...")}
if(debug) {message(fxNa,"VPW14")} }
if(length(Mvalue) >0) {
## rather directly plot FDR
if(!"FDR" %in% colnames(merg)) plotByFdr <- FALSE
pl1 <- try(graphics::plot(Mvalue, if(plotByFdr) -1*log10(merg[,"FDR"]) else merg[,"pValue"], pch=pch, cex=useCex, main=tit1,
ylab=if(plotByFdr) "- log10 FDR" else "- log10 p-value (uncorrected)", col=useCol, xlab=xLab, cex.lab=cexLa, xlim=limM,ylim=limp, pt.bg=ptBg), silent=TRUE)
if(inherits(pl1, "try-error")) {Mvalue <- NULL; message("UNABLE TO PLOT !! check plotting device ...")} }
if(length(Mvalue) >0) {
sTxt <- if(length(subTxt) ==1) subTxt else { if(multiComp) paste0(if(length(names(useComp)) >0) names(useComp) else c("useComp=",useComp),"; ",collapse="")}
sTxt <- paste0(sTxt,"n=",length(Mvalue),
if(!all(is.na(c(FCthrs,FdrThrs)))) paste(";",sum(passAll, na.rm=TRUE),"(color) points passing",
if(!is.na(FCthrs)) paste0("(FCthr=", as.character(FCthrs),", ") else " (", paste0("FdrThrs=",as.character(FdrThrs),")")))
graphics::mtext(sTxt,cex=0.75,line=0.2)
if(!all(is.na(c(FCthrs,FdrThrs)))) {
if(debug) message(fxNa," n=",length(Mvalue)," FCthrs=",as.character(FCthrs)," filt.ini=", sum(filtFin, na.rm=TRUE),
" passAll=",sum(passAll,na.rm=TRUE)," ; range Mva ",wrMisc::pasteC(signif(range(Mvalue,na.rm=TRUE),3))," ; alph=",alph," useCex=",useCex," alph2=",alph2)
graphics::abline(v=c(-1,1)*(log2(FCthrs) + diff(graphics::par("usr")[1:2])/500), col=grDevices::rgb(0.87,0.72,0.72), lty=2) }
if(debug) {message(fxNa,"VPW15"); VPW15 <- list(merg=merg,Mvalue=Mvalue,filtFin=filtFin,FCthrs=FCthrs,FdrThrs=FdrThrs,passFdr=passFdr,annotColumn=annotColumn,xLab=xLab,tit1=tit1,col=col,useCol=useCol,assAll=passAll,grayIncrem=grayIncrem,cexPt=cexPt,annColor=annColor,plotByFdr=plotByFdr,limM=limM,limp=limp,ptBg=ptBg,cexLa=cexLa)}
if(sum(passFdr, na.rm=TRUE) >0) {
if(plotByFdr) {
graphics::abline(h=-1*log10(max(merg[passAll,"FDR"], na.rm=TRUE)) -diff(graphics::par("usr")[3:4])/400, col=grDevices::rgb(0.87,0.72,0.72), lty=2)
} else {
graphics::mtext("Note, that FDR and p-value may not correlate perfectly, thus points may appear at good p-value but finally don't get retained",line=-1.4,cex=0.7)
pRa <- range(merg[which(passFdr),"pValue"], na.rm=TRUE)
graphics::abline(h=pRa[1] +diff(graphics::par("usr")[3:4])/400, col=grDevices::rgb(0.87,0.72,0.72), lty=2) }}
## add names to best points
if(length(namesNBest) >0) {
if(any(sapply( c("pass","passThr","passFDR","signif"), identical, namesNBest))) namesNBest <- sum(passAll)
if(!is.integer(namesNBest)) namesNBest <- try(as.integer(namesNBest), silent=TRUE)
if(inherits(namesNBest, "try-error")) { namesNBest <- NULL
message(fxNa,"Unable to understand argument 'namesNBest', must be integer or 'pass','passThr','passFDR' or 'signif' (for display of labels to points in figure)") }
}
if(debug) {message(fxNa,"VPW16")}
if(length(namesNBest) >0) {
if(namesNBest >0 && any(passAll)) {
useLi <- if(any(!passAll)) which(passAll) else 1:nrow(merg)
tmP <- as.numeric(merg[useLi,"pValue"])
names(tmP) <- rownames(merg)[useLi]
## look for more informative names to display
if(length(annot) >0) {
proNa <- annot[match(names(tmP), rownames(annot)), annotColumn[2]] # normally 'Description'
chNa <- is.na(proNa)
if(!all(chNa)) names(tmP)[which(!chNa)] <- proNa[which(!chNa)]
}
useL2 <- order(tmP, decreasing=TRUE)[1:min(namesNBest,sum(passAll))]
xOffs <- signif(diff(graphics::par("usr")[1:2])/170,3)
yOffs <- signif(diff(graphics::par("usr")[3:4])/90,3)
noNa <- if(is.null(names(tmP[useL2]))) 1:length(tmP) else which(is.na(names(tmP)[useL2]))
if(length(noNa) >0 && all(annotColumn %in% colnames(merg))) names(tmP)[useL2[noNa]] <- merg[useLi[useL2[noNa]], wrMisc::naOmit(match(annotColumn[-1], colnames(merg)))[1]]
if(length(NbestCol) <1) NbestCol <- 1
if(is.null(names(tmP[useL2]))) {if(!silent) message(fxNa,"No names available for displaying names of best in plot")
} else { displTx <- wrMisc::naOmit(match(annotColumn[2:4], colnames(merg)))
displTx <- if(length(displTx) >0) cbind(merg[useLi[useL2], displTx], rownames(merg)[useLi[useL2]]) else as.matrix(useLi[useL2])
chNa <- rowSums(!is.na(displTx)) >0
if(any(chNa)) displTx[which(chNa),1] <- "unknown"
displTx <- apply(displTx,1, function(x) wrMisc::naOmit(x)[1])
graphics::text(Mvalue[useLi[useL2]] +xOffs, yOffs -1*log10(merg[useLi[useL2], if(plotByFdr) "FDR" else "pValue"]),
names(tmP)[useL2], cex=cexTxLab, col=NbestCol, adj=0) }
}
}
if(debug) {message(fxNa,"VPW17")}
## legend (if multiple symbols)
pch[which(is.na(pch))] <- -2
ch1 <- unique(pch)
if(length(ch1) >1 && sum(passAll) >0) {
legInd <- which(!duplicated(merg[which(passAll), annotColumn[1]], fromLast=FALSE))
if(length(legInd) <1 && !silent) message(fxNa,"Trouble ahead : Can't find non-duplicated ",annotColumn[1]," for ",sum(passAll)," points passing thresholds ! (ie as 'legInd')")
legPch <- pch[which(passAll)[legInd]]
legCol <- useCol[which(passAll)[legInd]]
legBg <- ptBg[which(passAll)[legInd]]
if(alph2 <1) {legCol <- substr(legCol,1,7); legBg <- substr(legBg,1,7)} # reset to no transparency
legLab <- merg[which(passAll)[legInd], annotColumn[1]]
chNa <- is.na(legLab)
if(any(chNa)) legLab[chNa] <- "NA"
legOr <- if(length(legLab) >1) order(legLab) else 1 # not used so far
legLoc <- checkForLegLoc(cbind(Mvalue, pValue), sampleGrp=legLab, showLegend=FALSE)
legCex <- stats::median(c(useCex, cexTxLab, 1.2), na.rm=TRUE)
if(length(legLab) >0) { chLeg <- try(graphics::legend(legLoc$loc, legend=legLab, col=legCol, text.col=1, pch=legPch,
if(length(ptBg) >0) pt.bg=ptBg, cex=legCex, pt.cex=1.2*legCex, xjust=0.5, yjust=0.5), silent=TRUE) # as points
if(inherits(chLeg, "try-error") && !silent) message(fxNa,"Note: Failed to add legend .. ",chLeg) }
} else legCol <- NULL
if(debug) {message(fxNa,"VPW18")}
## arrow for expected ratio
## how to extract in smartest way ??
drawArrow <- if(length(expFCarrow) >0) {isTRUE(as.logical(expFCarrow[1])) || grepl("^[[:digit:]]+$", expFCarrow[1])} else FALSE
if(drawArrow) {
regStr <-"[[:space:]]*[[:alpha:]]+[[:punct:]]*[[:alpha:]]*"
if(isTRUE(expFCarrow)) {
## automatic extraction of FC
if(debug) message(fxNa," .. ",names(useComp)," -> ",paste(unlist(strsplit(names(useComp), "-")), collapse=" "),"\n")
expM <- sub(paste0("^",regStr),"", sub(paste0(regStr,"$"), "", unlist(strsplit(names(useComp), "-")))) # assume '-' separator from pairwise comparison
arrCol <- 1
chN2 <- try(as.numeric(expM), silent=TRUE)
if(inherits(chN2, "try-error")) { drawArrow <- FALSE #expM <- arrCol <- NA
} else {
expM <- log2(chN2[2] / chN2[1]); arrCol <- 1 # transform automatic extracted to ratio # expFCarrow <- c(expM, 1)
}
msg <- "Argument 'expFCarrow' was set to TRUE; "
if(!silent) message(fxNa, msg, if(drawArrow) "Extract concentration values of group-names for calculating ratios" else "Failed automatic extraction of FC-values (possibly no numeric values in setup)")
} else {
expM <- try(as.numeric(expFCarrow[1]), silent=TRUE)
if(inherits(expM, "try-error")) {
if(!silent) message(fxNa,"Argument 'expFCarrow' was given, but no numeric content in 1st place found, can't draw FC-arrow") #understand 1st value of'expFCarrow' (should be numeric-like)
drawArrow <- FALSE
} else arrCol <- if(length(expFCarrow) >1) expFCarrow[2] else 1
}
if(length(expFCarrow) >1) {arrCol <- expFCarrow[2] # 2nd value of expFCarrow for color
} else arrCol <- 1 # autom : use 3rd if possible
}
if(drawArrow) {
if(is.finite(expM)) {
figCo <- graphics::par("usr") # c(x1, x2, y1, y2)
figRa <- diff(range(figCo[1:2]))*0.1
if(expM > figCo[2] +figRa || expM < figCo[1] -figRa) {if(!silent) message(fxNa,"Can't draw arrow, ",round(expM,2)," is too far outside the plotting frame")
expM <- NA }
}
if(is.finite(expM)) {
arr <- c(0.019,0.14) # start- and end-points of arrow (as relative to entire plot)
graphics::arrows(expM, figCo[3] + arr[1]*(figCo[4] -figCo[3]), expM, figCo[3] + arr[2]*(figCo[4] -figCo[3]),
col=arrCol, lwd=1, length=0.1)
graphics::mtext(paste("expect at",signif(expM,3)), at=expM, side=1, adj=0.5, col=arrCol, cex=cexLa*0.7, line=-0.9)
} else { if(!silent) message(fxNa,"Unable to draw arrow for expexted M-value)") }
}
if(debug) {message(fxNa,"VPW19")}
tmp <- try(graphics::par(mar=opar$mar, cex.main=opar$cex.main, las=opar$las), silent=TRUE) # resetto previous
## export data used for plotting
if(returnData) {
merg <- merg[,-1*c(1,ncol(merg))] # remove col 'ID' 'redundant' & 'pch'
annCo <- wrMisc::naOmit(match(annotColumn, colnames(merg)))
if(length(annCo) >0) cbind(merg[,annCo], merg[,-annCo]) else merg }
} }
}
#' Locate sample index from index or name of pair-wise comparisons
#'
#' This function helps locating sample index from index or name of pair-wise comparisons
#'
#' @param MArrayObj (MArray type objct) main input
#' @param useComp (matrix) types of pair-wise comparisons to be performed
#' @param groupSep (character) separator used with pair-wise grouping
#' @param lstMeans (character) type of summarization, default is 'means'
#' @param lstP (character) type of multiple testing correction data to choose from \code{MArrayObj}
#' @param silent (logical) suppress messages
#' @param debug (logical) supplemental messages for debugging
#' @param callFrom (character) allow easier tracking of messages produced
#' @return This function returns a integer vector of indexes
#' @seealso (for PCA) \code{\link{plotPCAw}})
#' @examples
#' aa <- 1:5
#' @export
.sampNoDeMArrayLM <- function(MArrayObj, useComp, groupSep="-", lstMeans="means", lstP="BH", silent=FALSE, debug=FALSE, callFrom=NULL) {
## old version,not used any more
## locate sample index from index or name of pair-wise comparisons in list or MArrayLM-object
fxNa <- wrMisc::.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 !")
if(length(colnames(MArrayObj[[lstP]])) <1) stop(" Problem with 'MArrayObj' (does not contain matrix of p-values)")
## convert/locate names to index
if(is.character(useComp) && length(grep("[[:alpha:]]",useComp)) >0) useComp <- wrMisc::naOmit(match(useComp, MArrayObj[[lstP]] ))
if(length(useComp) <1) stop("Argument 'useComp' is empty or can't locate in comparison-names")
if(length(useComp) >1) { useComp <- useComp[1]; message(fxNa,"Using only 1st instance of argument 'useComp'")}
if(useComp > ncol(MArrayObj[[lstP]])) {useComp <- 1; message(fxNa,"Argument 'useComp' is too high (max ",ncol(MArrayObj[[lstP]]),"), resetting to 1")}
## main
out <- if(ncol(MArrayObj[[lstP]])==2 && colnames(MArrayObj[[lstP]])[1] =="(Intercept)") 1:2 else {
wrMisc::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 }
#' Colors based on p-Values
#'
#' This function helps defining color-gradient based on p-Values.
#' This fuction requires package RColorBrewer being installed
#'
#' @param x (numeric) p-values (main input)
#' @param br (numeric) custom breaks (used with cut)
#' @param col custom colors (must be of length(br) -1)
#' @param asIndex (logical) custom breaks (used with cut)
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @param debug (logical) supplemental messages for debugging
#' @return This function retruns a color-gradient based on p-Values
#' @seealso (for PCA) \code{\link{plotPCAw}})
#' @examples
#' .colorByPvalue((1:10)/10)
#' @export
.colorByPvalue <- function(x, br=NULL, col=NULL, asIndex=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL) {
## this function should ultimately get incormporated to wtMisc::colorAccording2 as option "pValue" or "FDR"
## colors significant (***,**,*) as red-tones, 0.05-0.075 as pale orange, others as blue-tones
## 'br' .. custom breaks (used with cut)
## 'col' .. custom colors (must be of length(br) -1)
## 'asIndex' .. optional returning of index to \code{col} instead of final color designation
fxNa <- ".colorByPvalue"
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(length(br) >0) br <- sort(unique(wrMisc::naOmit(br)))
if(length(col) != length(br) -1 && length(br) >0) { br <- col <- NULL
if(!silent) message(fxNa, "Entries for 'col' and 'br' don't match, ignoring") }
if(length(col) <1) {
hasDep <- requireNamespace("RColorBrewer", quietly=TRUE)
col <- if(hasDep) grDevices::colorRampPalette(RColorBrewer::brewer.pal(n=7, name="RdYlBu"))( 22 )[c(2:4,7,17:20)] else {
grDevices::heat.colors(n=length(unique(x)) +2)
if(!silent) message(fxNa,"Please install first from CRAN the package 'RColorBrewer'")
}
if(length(col) != length(br)) br <- sort(c(1e-20,10^(-3:0), 0.05,0.075,0.2,0.3))
}
out <- if(asIndex) as.numeric(cut(x, br)) else col[as.numeric(cut(x, br))]
if(asIndex) out <- as.numeric(cut(x, br)) else {
out <- col[as.numeric(cut(x, br))]
chNa <- is.na(x)
if(any(chNa)) out[which(chNa)] <- grDevices::grey(0.4) }
out }
#' Transform levels into index
#'
#' This function transforms levels into index. This function has been depreciated, please use wrMisc::levIndex() insted.
#'
#' @param dat (numeric) initial levels (main input)
#' @param asSortedLevNa (logical)
#' @return This function retruns a color-gradient based on p-Values
#' @seealso (for PCA) \code{\link{plotPCAw}})
#' @examples
#' library(wrMisc)
#' @export
.levIndex <- function(dat, asSortedLevNa=FALSE) {
## transform levels into index; should get integrated to wrMisc
## depreciated, please use wrMisc::levIndex() instead
fxNa <- ".levIndex"
.Deprecated("levIndex()", package="wrMisc", msg="The function .levIndex() has been depreciated, please use wrMisc::levIndex() instead")
if(asSortedLevNa) out <- as.integer(as.factor(dat)) else {
out <- dat
levU <- wrMisc::naOmit(unique(out)) # levels in orig order (non-alpahbetical)
for(i in 1:length(levU)) out[which(out==levU[i])] <- i
out <- as.integer(out)}
out }
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/VolcanoPlotW.R
|
#' Add bagplot to existing plot
#'
#' This function adds a bagplot on an existing (scatter-)plot allowing to highlight the central area of the data.
#' Briefly, a bagplot is a bivariate boxplot, see \href{https://en.wikipedia.org/wiki/Bagplot}{Bagplot}, following the basic idea of a boxplot in two dimensions.
#' Of course, multimodal distributions - if not separated first - may likely lead to mis-interpretation, similarly as it is known for interpreting boxplots.
#' If a group of data consists only of 2 data-points, they will be conected using a straight line.
#' It is recommended using transparent colors to highlight the core part of a group (if only 2 points are available, they will be conected using a straight line),
#' in addition, one could use the option to re-plot all (non-outlyer) points (arguments \code{reCol}, \code{rePch} and \code{reCex} must be used).
#'
#' @details
#' The outlyer detection works similar to the one used in \code{boxplot}: The distance of a given point is compared to the median distance of all points to their respective group-center plus
#' the 25 - 75 quantile-distance (of all points) times the multiplicative factor of argument \code{outCoef}.
#'
#' @param x (matrix, list or data.frame) main numeric input of data/points to plot
#' @param lev1 (numeric) min content of data for central area (default 0.5 for 50 percent)
#' @param outCoef (numeric) parameter for defining outliers (equivalent to \code{range} in \code{\link[graphics]{boxplot}})
#' @param bagCol (character or integer) color for filling center part of bagplot (default light transparent grey); Note: It is highly suggested to use transparency, otherwise points underneith will be covered
#' @param bagCont (character) color for inner and outer contours of bagplot
#' @param bagLwd (numeric) line width for outer contour, set to \code{NULL} for not diaplaying outer contour (see also \code{\link[graphics]{par}})
#' @param nCore (integer) decide when center should be determined by median or mean: if number of points reach \code{nCore} the median will be used
#' @param outlCol (character or integer) color for highlighting outlyers (for text and replottig outlyers points), set to \code{NULL} for not highlighting outlyers at all
#' @param outlPch (integer) symbol replotting highlighted outlyers (for text and replottig outlyers points), set to \code{NULL} for not replotting outlyer-points (see also \code{\link[graphics]{par}})
#' @param outlCex (numeric) cex type expansion factor for labels of highlighted outlyers, set to \code{NULL} for not printing (row)names of outlyers (see also \code{\link[graphics]{par}})
#' @param reCol (character or integer) color for replotting (non-outlyer) points, default set to \code{NULL} for not replotting
#' @param rePch (integer) symbol for replotting (non-outlyer) points, default set to \code{NULL} for not re-plotting (see also \code{\link[graphics]{par}})
#' @param reCex (numeric) cex type expansion factor for lfor replotting (non-outlyer) points, default set to \code{NULL} for not replotting
#' @param ctrPch (integer) symbol for showing group center (see also \code{\link[graphics]{par}})
#' @param ctrCex (numeric) cex type expansion factor for size of group center (see also \code{\link[graphics]{par}})
#' @param ctrCol (character or integer) color for group center symbol
#' @param addSubTi (logical) decide if subtitle (stating that potential outlyers were displayed separatetly) should be added in plot
#' @param returnOutL (logical) decide if rownames of (potential) outlyer values should be returned when running the function
#' @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 primarily a plot, optionally it may return of matrix with outlyers (if argument \code{returnOutL=TRUE})
#' @seealso \code{\link{plotPCAw}}, \code{\link[stats]{princomp}}
#' @examples
#' set.seed(2020); dat1 <- matrix(round(rnorm(2000),3),ncol=2); rownames(dat1) <- 1:nrow(dat1)
#' dat1 <- dat1 + 5*matrix(rep(c(0,1,1,0,0,0,1,1),nrow(dat1)/4), byrow=TRUE, ncol=2)
#' col1 <- rgb(red=c(153,90,203,255), green=c(143,195,211,125), blue=c(204,186,78,115),
#' alpha=90, maxColorValue=255)
#' ## suppose we know the repartition into 4 subgroups which we would like to highlight them
#' grp1 <- rep(1:4, nrow(dat1)/4)
#' plot(dat1, col=grey(0.8), xlab="x", ylab="y", las=1, pch=grp1)
#' for(i in 1:4) addBagPlot(dat1[which(grp1==i),], bagCol=col1[i])
#' ## slightly improved
#' library(wrMisc)
#' col2 <- convColorToTransp(col1, 255)
#' plot(dat1, col=grey(0.8), xlab="x", ylab="y", las=1, pch=grp1)
#' for(i in 1:4) addBagPlot(dat1[which(grp1==i),], bagCol=col1[i], outlPch=i,
#' outlCol=col2[i], bagLwd=3)
#' @export
addBagPlot <- function(x, lev1=0.5, outCoef=2, bagCol=NULL, bagCont=bagCol, bagLwd=1.5, nCore=4, outlCol=2, outlPch=NULL, outlCex=0.6, reCol=NULL, rePch=NULL, reCex=NULL,
ctrPch=NULL, ctrCol=NULL, ctrCex=NULL, addSubTi=TRUE, returnOutL=FALSE, silent=TRUE, callFrom=NULL, debug=FALSE) { # colOutL colCont=NULL,colOutlP=2,colOutlT=2,
## 'x' should be matrix or dataframe (use 1st & 2nd column, ie x & y coord for points) to draw simple bag-plot
## 'lev1' gives the min % of points to be included to core (shaded using 'bagCol'), as long as >nCore data-points available
## "outliers" are determined similar to boxplots using the 'outCoef'-parameter and then shown in color 'colOutL' and their names may be exported
## optional: overall contour (wo outliers) if 'colCont' (=color for contour) given, show center (median) if 'ctrPch' given
fxNa <- wrMisc::.composeCallName(callFrom, newNa="addBagPlot")
msg <- " 'x' must be numeric matrix or data.frame (with at least 1 row and 2 columns)"
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(is.null(x) <0) stop(msg)
if(!inherits(x, "matrix")) x <- try(as.matrix(x), silent=TRUE)
if(inherits(x, "try-error")) stop(msg," - could not transform 'x' to matrix")
if(length(dim(x)) >2) {x <- as.matrix(x[,,1])
if(!silent) message(fxNa," 'x' is >2 dimensions, removing last (as x[,,1])")}
if(any(length(dim(x)) !=2, dim(x) < 2:1)) stop("Invalid argument 'x'; must be matrix or data.frame with min 2 lines and 1 column")
chNA <- is.na(x)
if(any(chNA)) {
rmLi <- which(rowSums(chNA) >0)
if(length(rmLi)==nrow(x)) { x <- NULL
if(!silent) message(fxNa,"Data contain too many NAs, no complete lines left")
} else if(!silent) message(fxNa," ",length(rmLi)," lines contain NAs, can't consider/use them as points") }
if(length(bagCol) <1) bagCol <- grDevices::rgb(0.1,0.1,0.1,0.1)
## main
if(length(x) >0) {
if(debug) {message(fxNa,"aBP1") }
if(is.null(rownames(x))) rownames(x) <- 1:nrow(x)
ctr <- if(nrow(x) < nCore) colMeans(x,na.rm=TRUE) else apply(x, 2, stats::median,na.rm=TRUE) # overall center : medain if >5 elements
di <- sqrt((x[,1] -ctr[1])^2 + (x[,2] -ctr[2])^2) # Euclidean distance to center
keepX <- if(nrow(x) > 2) di <= stats::median(di,na.rm=TRUE) + outCoef*diff(stats::quantile(di, c(0.25,0.75), na.rm=TRUE)) else rep(TRUE,nrow(x))
chdNA <- is.na(keepX)
if(any(chdNA)) keepX[which(chdNA)] <- FALSE
if(sum(keepX) <1) { keepX <- rep(TRUE, nrow(x))
if(!silent) message(fxNa,"Problem defining non-outlyer part of data, keep all")}
## define outlyers
outL <- matrix(x[which(!keepX),], ncol=2)
if(nrow(outL) >0) rownames(outL) <- rownames(x)[which(!keepX)]
offS <- if(nrow(x) >1) apply(x, 2, function(z) max(abs(range(z, finite=TRUE)), na.rm=TRUE))/70 else x/70 #
if(!silent) {if(nrow(x) > 2) message(fxNa,"Keep ",sum(keepX)," out of ",nrow(x)," and consider ",
sum(!keepX)," as outliers") else message(fxNa,"Too few data, use all columns")}
if(sum(keepX) < nrow(x)) { x <- x[which(keepX),]
di <- di[which(keepX)] }
if(debug) {message(fxNa,"aBP2") }
## chull around core data
xCore <- x
liBag <- if(length(di) <4) rep(TRUE, length(di)) else di <= stats::quantile(di, lev1, na.rm=TRUE) +min(di,na.rm=TRUE)/100
if(sum(liBag) <4 && length(di) >2) liBag[order(di, decreasing=FALSE)[1:3]] <- TRUE # have at least 3 points for bag
if(sum(liBag) < length(liBag)/2.7) liBag <- di <= stats::quantile(di, lev1, na.rm=TRUE) + mean(di,na.rm=TRUE)/10
if(sum(liBag) >1 && sum(liBag) < nrow(x)) xCore <- x[which(liBag),]
htps <- grDevices::chull(xCore)
if(nrow(x) > 2) {
## shade core ...
graphics::polygon(xCore[c(htps,htps[1]),], col=bagCol, border=bagCont)
## draw outer contour :
htps2 <- grDevices::chull(x)
if(length(bagLwd) >0 && !all(is.na(bagCont))) { y <- x[htps2,]; y <- cbind(y, y[c(2:nrow(y),1),])
graphics::segments(y[,1], y[,2], y[,3], y[,4], col=bagCont, lwd=bagLwd) }
## optional replotting of non-outlyer-points
if(length(reCol) >0 && length(rePch) >0 && length(reCex) >0) graphics::points(x, pch=rePch, col=reCol, cex=reCex)
} else if(nrow(x)==2) graphics::lines(x[,1], x[,2], lwd=5, col=bagCol) # can only connect 2 remaining points by fat line
if(debug) {message(fxNa,"aBP3") }
## show group-center (only if ctrPch defined)
if(is.null(ctrCol)) ctrCol <- bagCol
if(!is.null(ctrPch)) {
if(is.null(ctrCex)) ctrCex <- 1.5
graphics::points(ctr[1], ctr[2], pch=ctrPch, col=ctrCol, cex=ctrCex) }
## highlight outliers
if(length(outlCol) >0 & nrow(outL) >0) {
if(debug) {message(fxNa,"aBP4"); aBP4 <- list(ctr=ctr,x=x,lev1=lev1,outCoef=outCoef,outL=outL,outlPch=outlPch,outlCol=outlCol,addSubTi=addSubTi,outlCex=outlCex,
offS=offS,bagCol=bagCol,bagCont=bagCont,bagLwd=bagLwd,silent=silent,debug=debug ) }
if(length(outlPch) >0) graphics::points(outL, pch=outlPch, col=outlCol)
if(length(addSubTi) <1 || !is.logical(addSubTi)) addSubTi <- FALSE else if(length(addSubTi) >1) addSubTi <- any(as.logical(addSubTi), na.rm=TRUE)
if(addSubTi && length(outlCex) <1) graphics::mtext(paste("names of ",sum(!sapply(outL, is.null),na.rm=TRUE),
" elements looking like potential outlyers were displayed"), cex=0.55, line=-0.8, col=grDevices::grey(0.4))
if(length(outlCex) >0) graphics::text(outL[,1] +offS[1], outL[,2] +offS[2], col=outlCol, adj=0,cex=outlCex, labels=substr(rownames(outL),1,21))
}
}
if(returnOutL) return( if(length(x) >0) {if(is.null(rownames(outL))) which(!keepX) else rownames(outL)} else NULL )
}
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/addBagPlot.R
|
#' Find best place on plot for placing legend
#'
#' This function tries to find the best location for placing a legend of a bivariate plot, ie scatter-plot.
#' All 4 corners of the data to plot are inspected for the least occupation by data plotted while displaying the content of \code{sampleGrp}.
#' Alternatively, by setting the argument \code{showLegend} the user-defined legend will be returned
#'
#' @param matr (matrix, list or data.frame) main data of plot
#' @param sampleGrp (character or factor) with this option the text to be displayed in the legend may be taken into consideration for its length
#' @param showLegend (logical or character) decide if \code{matr} should be checked for best location; if \code{showLegend} contains any of the standard legend-location designations (eg 'topleft') it will be used in the output
#' @param suplSpace (numeric) allows to consider extra room taken in legend by symbol and surrounding space, interpreted as n additional characters
#' @param testCorner (integer) which corners should be considered (1=left-top, 2=right-top, right-bottom, left-bottom)
#' @param silent (logical) suppress messages
#' @param debug (logical) additonal messages for debugging
#' @param callFrom (character) allows easier tracking of messages produced
#' @return list with $showL indicating if legend is desired and $loc for the proposition of the best location, $nConflicts gives the counts of conflicts
#' @seealso \code{\link[graphics]{legend}}
#' @examples
#' dat1 <- matrix(c(1:5,1,1:5,5), ncol=2)
#' grp <- c("abc","efghijk")
#' (legLoc <- checkForLegLoc(dat1, grp))
#' plot(dat1, cex=3)
#' legend(legLoc$loc, legend=grp, text.col=2:3, pch=1, cex=0.8)
#' @export
checkForLegLoc <- function(matr, sampleGrp=NULL, showLegend=TRUE, suplSpace=4, testCorner=1:4, silent=TRUE, debug=FALSE, callFrom=NULL){
## check 'showLegend' if specified location or logical term (if TRUE, then estimate best location using .bestLegendLoc())
## 'matr' .. matrix of data for display, optimal legend location will get determined for these data (if not specifically given)
## 'sampleGrp' .. legend-names to be displayed
## 'testCorner' specifies places(corners) to be tested: c("topleft","topright","bottomright","bottomleft")
## return list with $showL as logical depending if legend should be drawn, and $loc as location
fxNa <- wrMisc::.composeCallName(callFrom,newNa="checkForLegLoc")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
txt <- "'matr' must be matrix or data.frame with at least 1 row and at least 2 columns"
if(length(dim(matr)) <2) stop(txt)
if(any(dim(matr)[1:2] < 1:2)) stop(txt)
.longTxt <- function(x, nLim=8) { # return longest or almost longest of text-entries in 'x': if more than 'nLim' text-entries look for 87%quantile
out <- NULL # initialize
if(any(nchar(x) >0)) {
y <- graphics::strwidth(as.character(x), units="figure")
if(length(x) >nLim) {
out <- x[order(y, decreasing=TRUE)][round(0.13*length(x))]
} else out <- x[which.max(y)] }
out }
displLeg <- list(showL=FALSE, loc=NA)
if(length(showLegend) <1) showLegend <- FALSE
chLeg <- try(is.logical(showLegend), silent=TRUE)
if(inherits(chLeg, "try-error")) { # non-logical entry, check if precise location
chLoc <- showLegend[1] %in% c("topleft","topright", "top","bottomright", "bottomleft",
"bottom", "left","right","center")
if(silent) message(fxNa,"Argument 'showLegend' was called as TRUE but with '",showLegend,"', (",if(chLoc) "valid" else "INVALID"," location)")
displLeg <- list(showL=chLoc, loc=if(chLoc) showLegend[1] else NA, nConflicts=NA)
} else { # is logical
if(chLeg) { # chLeg is TRUE
sampleGrp <- as.character(wrMisc::naOmit(sampleGrp))
txLe <- if(length(sampleGrp) >0) .longTxt(sampleGrp) else "sample"
txLe <- graphics::strwidth(txLe,units="figure") +suplSpace*graphics::strwidth("z", units="figure")
nLi <- if(length(sampleGrp) >0) length(unique(sampleGrp)) else 4 # presume 4 groups (if no names given)
txHi <- (nLi+2.2)*graphics::strheight("1",units="figure") # need to adjust for extra space towards edge/box of legend
locCount <- .bestLegendLoc(matr[,1:2], txtLen=txLe, txtHi=txHi, silent=silent, debug=debug, callFrom=callFrom)
## prefer legend on left, add small penalty to right locations to favour lactions at left side (in case of egality)
if(length(displLeg) >3) locCount[2:3] <- locCount[2:3] +0.1
best <- which.min(locCount[testCorner])
if(length(displLeg) >3) locCount[2:3] <- locCount[2:3] -0.1 # re-correct to real counts
displLeg <- list(showL=TRUE, loc=names(locCount)[best], nConflicts=locCount)
} else displLeg <- list(showL=FALSE, loc=NA, nConflicts=NA)
}
displLeg }
#' Search best corner of plot for placing for legend
#'
#' This function aims to find best corner for plotting a legend.
#'
#' @param dat (matrix, list or data.frame) main data of plot
#' @param txtLen (numeric, length=1) text width from graphics::strwidth()
#' @param txtHi (numeric, length=1) text height from graphics::strheight() (including inter-line)
#' @param txtLen (numeric, length=1)
#' @param displayPlotSearch (logical) decide if lines to mark area where data is searched for legend should be drawn
#' @param silent (logical) suppress messages
#' @param debug (logical) additonal messages for debugging
#' @param callFrom (character) allows easier tracking of messages produced
#' @return numeric vector with counts of umber of points expected to enter legend-location for each corner (ie legend-localization)
#' @seealso \code{\link{checkForLegLoc}}, \code{\link[graphics]{legend}}
#' @examples
#' dat1 <- matrix(c(1:5,1,1:5,5), ncol=2)
#' (legLoc <- .bestLegendLoc(dat1, txtLen=0.4, txtHi=28))
#' @export
.bestLegendLoc <- function(dat, txtLen, txtHi, displayPlotSearch=FALSE, silent=TRUE, debug=FALSE, callFrom=NULL) {
## try to find best corner for legend ; 'dat': matrix or df (use 1st & 2nd column, ie x & y coord for points)
## 'txtLen' .. text width from graphics::strwidth()
## 'txtHi' .. text height from graphics::strheight() (including inter-line)
## 'displayPlotSearch' .. draw lines to mark area where data is searched for legend
fxNa <- wrMisc::.composeCallName(callFrom, newNa=".bestLegendLoc")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(!(is.matrix(dat) || is.data.frame(dat))) stop(" 'dat' must be matrix or data.frame (with at least 2 columns)")
if(ncol(dat) <2) stop("'dat' should have at least 2 columns")
if(!is.numeric(txtHi)) stop("Argument 'txtHi' should be numeric (of length 1) !")
if(length(txtLen) >1 || length(txtHi) >1) {txtLen <- txtLen[1]; txtHi <- txtHi[1]; warning("Truncating 'txtLen' and 'txtHi' to length 1 !")}
if(is.na(txtLen) | is.na(txtHi) | min(c(txtLen,txtHi)) < 0) stop("Arguments 'txtLen' and 'txtHi' should not be NA or negative !")
if(debug) message(fxNa,"bLL1")
raX <- range(dat[,1], na.rm=TRUE)
raY <- range(dat[,2], na.rm=TRUE)
raX <- c(raX, abs(raX[2] -raX[1]))
raY <- c(raY, abs(raY[2] -raY[1]))
ocX <- txtLen/diff(graphics::par("plt")[1:2]) # fraction of text occupied in x
ocY <- txtHi /diff(graphics::par("plt")[3:4]) # fraction of text occupied in y
locCount <- c(
topleft =sum(dat[,1] < raX[1] + ocX*raX[3] & dat[,2] > raY[2] - ocY*raY[3], na.rm=TRUE) ,
topright =sum(dat[,1] > raX[2] - ocX*raX[3] & dat[,2] > raY[2] - ocY*raY[3], na.rm=TRUE) ,
bottomright=sum(dat[,1] > raX[2] - ocX*raX[3] & dat[,2] < raY[1] + ocY*raY[3], na.rm=TRUE) ,
bottomleft =sum(dat[,1] < raX[1] + ocX*raX[3] & dat[,2] < raY[1] + ocY*raY[3], na.rm=TRUE) )
if(debug) message(callFrom," txtLen: ",signif(txtLen,3))
if(isTRUE(displayPlotSearch)) {
graphics::abline(v=c(raX[1] + ocX*raX[3], raX[2] - ocX*raX[3]), lty=2)
graphics::abline(h=c(raY[2] - ocY*raY[3], raY[1] + ocY*raY[3]), lty=2) }
if(debug) message(fxNa," locCount: ", paste(locCount,collapse=" "))
locCount }
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/checkForLegLoc.R
|
#' Convert points of plot to coordinates in pixels
#'
#' This function allows conversion the plotting positions ('x' and 'y' coordinates) of points in a given plot into coordinates in pixels (of the entire plotting region).
#' It was designed to be used as coordinates in an html file for mouse-over interactivity (display of names of points and links).
#' Of course, the size of the plotting region is crucial and may not be changed afterwards (if the plot is not written to file using \code{png} etc).
#' In turn the function \code{\link{mouseOverHtmlFile}} will use the pixel-coordinates, allowing to annotate given points of a plot for mouse-over interactive html.
#'
#' @param x (numeric) initial plotting coordinates on x-axis, names of vector - if available- will be used as IDs
#' @param y (numeric) initial plotting coordinates on y-axis
#' @param useMar (numeric,length=4) margins defined with plot, see also \code{\link[graphics]{par}}
#' @param plotDim (integer, length=2) dimension of the plotting device in pixels, see also \code{\link[graphics]{par}}
#' @param plotRes (integer) resoltion of plotting device, see also \code{\link[graphics]{par}}
#' @param fromTop (logical) toggle if poordinates should start from top
#' @param silent (logical) suppress messages
#' @param debug (logical) additonal messages for debugging
#' @param callFrom (character) allows easier tracking of messages produced
#' @return matrix with x- and y-coordinates in pixels
#' @seealso \code{\link{mouseOverHtmlFile}}
#' @examples
#' df1 <- data.frame(id=letters[1:10], x=1:10, y=rep(5,10),mou=paste("point",letters[1:10]),
#' link=file.path(tempdir(),paste0(LETTERS[1:10],".html")), stringsAsFactors=FALSE)
#' ## Typically one wants to get pixel-coordinates for plots written to file.
#' ## Here we'll use R's tempdir, later you may want to choose other locations
#' pngFile <- file.path(tempdir(),"test01.png")
#' png(pngFile, width=800, height=600, res=72)
#' ## here we'll just plot a set of horiontal points at default parameters ...
#' plot(df1[,2:3], las=1, main="test01")
#' dev.off()
#' ## Note: Special characters should be converted for proper display in html during mouse-over
#' library(wrMisc)
#' df1$mou <- htmlSpecCharConv(df1$mou)
#' ## Let's add the x- and y-coordiates of the points in pixels to the data.frame
#' df1 <- cbind(df1,convertPlotCoordPix(x=df1[,2], y=df1[,3], plotD=c(800,600),plotRes=72))
#' head(df1)
#' ## using mouseOverHtmlFile() one could now make an html document with interactive
#' ## display of names and clockable links to the coordinates we determined here ...
#' @export
convertPlotCoordPix <- function(x, y, useMar=c(6.2,4,4,2), plotDim=c(1400,800), plotRes=100, fromTop=TRUE, callFrom=NULL, silent=FALSE, debug=FALSE){
## convert point-coordinates 'x' and 'y' (of plot) in pixel coordinates (eg for use with mouse-over tip in Html)
## return matrix with 2 columns : pxX & pxY .. coresponding pixel coordinates (with length(x) rows)
## expecting 'useMar' as margins given in par() (as bottom,left,top,right) in inch
## 'plotDim' should be image size for png-device in pixels (width, height), 'plotRes' should be 'plotRes' for png()
## (default) 'fromTop'=TRUE : coordinates will be counted from top border of image
## like png(plotDim[1],plotDim[2,plotRes=plotRes]
fxNa <- wrMisc::.composeCallName(callFrom, newNa="convertPlotCoordPix")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
msg <- "Arguments 'x' & 'y' should be finite numeric and of same length ! "
if(length(x) != length(y) || length(x) <1 || length(y) <1) stop(msg)
isFinit <- cbind(x=is.finite(x), y=is.finite(y))
if(debug) {message(fxNa,"cPCP0")}
if(any(!isFinit)) {
if(all(!isFinit[,1]) || all(!isFinit[,2])) stop(msg)
if(any(!isFinit[,1])) x[which(!isFinit[,1])] <- sum(x[which(isFinit[,1])])/length(isFinit[,1])
if(any(!isFinit[,2])) y[which(!isFinit[,2])] <- sum(y[which(isFinit[,2])])/length(isFinit[,2]) }
msg0 <- "numeric vector of length"
msg <- paste("'plotDim' should be",msg0,"2 (x & y dimension in pixel)")
if(length(plotDim) !=2) stop(msg)
if(debug) {message(fxNa,"cPCP1")}
msg <- paste("'useMar' should be",msg0,"4; 'plotRes'",msg0,"1")
if(length(useMar) !=4 || length(plotRes) !=1) stop(msg)
if(any(!is.finite(useMar), !is.finite(plotRes))) stop(msg)
if(debug) message(fxNa,"cPCP2")
if(is.null(names(x))) {
if(!is.null(names(y))) { names(x) <- names(y) }}
msg2 <- " 'useMar' should be vector of 4 values (as bottom,left,top,right)"
msg3 <- " 'plotDim' should be vector of 2 values (as width & hight of png)"
if(!all(is.finite(useMar)) || length(useMar) !=4) stop(msg2)
if(any(useMar <0)) stop(msg2)
if(!all(is.finite(plotDim)) || length(plotDim) !=2) stop(msg3)
if(any(plotDim <= 0)) stop(msg3)
if(debug) message(fxNa,"cPCP3")
##
if(!silent) message(fxNa,"Supl params : mar=",paste(useMar,collapse=",")," dim=",
plotDim[1],"x",plotDim[2]," res=",plotRes)
out <- .predPointsPix(x, y, dimPng=plotDim, res=plotRes,marg=useMar,fromTop=fromTop)
if(any(!isFinit[,1])) out[which(!isFinit[,1]),1] <- NA
if(any(!isFinit[,2])) out[which(!isFinit[,2]),2] <- NA
out }
#' Estimate size/distance of margin to edge of image (png) in pixels
#'
#' This function allows estimating size/distance of margin to edge of image (png) in pixel and return numeric vector.
#'
#' @param marg (numeric) distance of margin in inch (as given in \code{par(mar=c( ))})
#' @param res (numeric, length=1) resolution of image (png)
#' @param silent (logical) suppress messages
#' @param debug (logical) additonal messages for debugging
#' @param callFrom (character) allows easier tracking of messages produced
#' @return This function returns a numeric vetctor matrix with (estimated) distance to figure margins in pixels
#' @seealso \code{\link{convertPlotCoordPix}}, \code{\link{mouseOverHtmlFile}}
#' @examples
#' .determFigMargPix(c(5,4,4,2),100)
#' @export
.determFigMargPix <- function(marg, res, callFrom=NULL, silent=FALSE, debug=FALSE){
## estimate size/distance of margin to edge of image (png) in pixel (return numeric vector)
## in case of 4 margin values it is assumed that these follow the order as in par() ie c(bottom,left,top,right)
## marg .. distance of margin in inch (as given in par(mar=c()), )
## res .. resolution of image (png)
fxNa <- wrMisc::.composeCallName(callFrom, newNa=".determFigMargPix")
sloC <- -0.3735 +0.2034*res # based on optimization wr12may15
offSC <- -0.2 -4.714e-12*(res^5)
dis <- floor(offSC + sloC*(marg))
dis <- dis - if(length(dis) ==4) c(1,2,1,2) else 1 # additional correction (based on 800x600 at res=100)
dis[dis <0] <- 0
if(length(dis) ==4) names(dis) <- c("bottom","left","top","right")
dis }
#' Predict and return pixel location of points of current plot
#'
#' This function allows predicting the pixel location of points of current plot.
#' Note: may be imprecise in case of x or y with all same values.
#'
#' @param x (numeric) initial coordinates for plot
#' @param y (numeric) initial coordinates for plot
#' @param dimPng (numeric, length=2) width and hight of png
#' @param res (numeric, length=1) resultion of png
#' @param marg (numeric, length=4) margins in inches (as given by \code{par(mar=c(...))})
#' @param fromTop (logical) default counting in html is from top
#' @param scExt (numeric, length=1) extending scale (default at 0.04 ie 4 \%)
#' @param displ (logical) optional plot
#' @param silent (logical) suppress messages
#' @param debug (logical) additonal messages for debugging
#' @param callFrom (character) allows easier tracking of messages produced
#' @return This function returns a numeric matrix with 2 columns 'xPix' and 'yPix' (with length(x) rows); and optionally a plot (if argument \code{displ=TRUE})
#' @seealso \code{\link{convertPlotCoordPix}}, \code{\link{mouseOverHtmlFile}}
#' @examples
#' .predPointsPix(x=c(1,100), y=c(1,100), dimPng=c(700,600), res=200, marg=c(5,4,4,2))
#' @export
.predPointsPix <- function(x, y, dimPng, res, marg, fromTop=TRUE, scExt=0.04, displ=FALSE, callFrom=NULL, silent=FALSE, debug=FALSE){
## predict & return pixel location of points of (default) plot() (which uses 4% extension of scales)
## return 2 col matrix with columns 'xPix' and 'yPix' (with length(x) rows)
## 'x' & 'y' .. initial coordinates for plot (to be made separately)
## 'pngDim' as width & hight of png
## 'res' as resultion of png
## 'marg' as par(mar=c(parMargTop, parMargLe, parMargBot, parMargRi) )
## 'fromTop' ... default counting in html is from top
## 'scExt' .. extending scale at 4%
## note: may be imprecise in case of x or y with all same values
fxNa <- wrMisc::.composeCallName(callFrom, newNa=".predPointsPix")
plPx <- matrix(abs(.determFigMargPix(marg,res)[c(2,4,3,1)] +c(0,-1*dimPng[1],0,-1*dimPng[2])), ncol=2, dimnames=list(c("start","end"),c("x","y")))
if(displ) graphics::plot(x,y,las=1)
plaRa <- abs(c(diff(range(x)), diff(range(y))))
## extRa .. pos in pix of corners (le,ri,bot,top) of plot in plot-coord
extRa <- c(range(x) +plaRa[1]*scExt*c(-1,1), range(y) +plaRa[2]*scExt*c(-1,1)) # value of extended x-scal (new min & max), ext y-scale (new min&max)
if(displ) {graphics::points(extRa[1],extRa[3], pch=3,col=2); graphics::points(extRa[2],extRa[4],pch=3,col=3)} #
if(length(unique(x))==1) extRa[1:2] <- range(pretty(unique(x)*c(0.55,1))) +plaRa[1]*scExt*c(-1,1)
if(length(unique(y))==1) extRa[3:4] <- range(pretty(unique(x)*c(0.55,1))) +plaRa[2]*scExt*c(-1,1)
xIncr <- diff(plPx[,1])/diff(extRa[1:2]) # how many pix per x-unit
yIncr <- diff(plPx[,2])/diff(extRa[3:4]) # how many pix per y-unit
xPix <- plPx[1,1] +(x-extRa[1])*xIncr
yPix <- if(fromTop) plPx[1,2] +diff(plPx[,2])- (y-extRa[3])*yIncr else {
dimPng[2] -plPx[2,2] +(y-extRa[3])*yIncr } # calculate as counted from top or bottom of png-image
round(cbind(xPix,yPix)) }
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/convertPlotCoordPix.R
|
#' Cumulative (or sorted) frequency plot (takes columns of 'dat' as separate series)
#'
#' Display data as sorted or cumulative frequency plot. This type of plot represents an alternative to plotting data as histograms.
#' Histograms are very universal and which are very intuitive. However,fine-tuning the bandwith (ie width of the bars) may be very delicate,
#' fine resultion details may often remain hidden.
#' One of the advanges of directly displaying all data-points is that subtile differences may be revealed easier, compared to calssical histograms.
#' Furthermore, the plot prensented her offeres more options to display multiple series of data simultaneaously.
#' Thus, this type of plot may be useful to compare eg results of data normalization.
#' Of course, with very large data-sets (eg > 3000 values) this gain of 'details' will be less important (compared to histograms) and will penalize speed.
#' In such cases the argument \code{thisResol} will get useful as it allows to reduce the resultion and introduce binning.
#' Alternatively for very large data-sets one may looking into density-plots or vioplots (eg \code{\link{vioplotW}}).
#' The argument \code{CVlimit} allows optionally excluding extreme values.
#' If numeric (& > 2 columns), its value will be used \code{\link[wrMisc]{exclExtrValues}} to identify series with column-median > 'CVlimit'.
#' Of course, exclusion of extreme values should be done with great care, important features of the data may get lost.
#'
#' @param dat (matrix or data.frame) data to plot/inspect
#' @param cumSum (logical) for either plotting cumulates Sums (then \code{thisResol} for number of breaks) or (if \code{=FALSE}) simply sorted values -> max resolution
#' @param exclCol (integer) columlns to exclude
#' @param colNames (character) for alternative column/series names in display, as long as \code{displColNa=TRUE}
#' @param displColNa (logical) display column-names
#' @param tit (character) custom title
#' @param xLim (numeric) custom limit for x-axis (see also \code{\link[graphics]{par}})
#' @param yLim (numeric) custom limit for y-axis (see also \code{\link[graphics]{par}})
#' @param xLab (character) custom x-axis label
#' @param yLab (character) custom y-axis label
#' @param col (integer or character) custom colors
#' @param CVlimit (numeric) for the tag 'outlier column' (uses \code{\link[wrMisc]{exclExtrValues}}) identify & mark column with median row-CV > \code{CVlimit}
#' @param thisResol (integer) resolution \code{res} for binning large data-sets
#' @param supTxtAdj (numeric) parameter \code{adj} for supplemetal text
#' @param supTxtYOffs (numeric) supplemental offset for text on y axis
#' @param useLog (character) default="", otherwise for setting axis in log-scale "x", "y" or "xy"
#' @param silent (logical) suppress messages
#' @param debug (logical) additonal messages for debugging
#' @param callFrom (character) allows easier tracking of messages produced
#' @return This function plots to the current garphical device
#' @seealso \code{\link[graphics]{layout}}, \code{\link[wrMisc]{exclExtrValues}} for decision of potential outliers; \code{\link[graphics]{hist}}, \code{\link{vioplotW}}
#' @examples
#' set.seed(2017); dat0 <- matrix(rnorm(500), ncol=5, dimnames=list(NULL,1:5))
#' cumFrqPlot(dat0, tit="Sorted values")
#' cumFrqPlot(dat0, cumSum=TRUE, tit="Sum of sorted values")
#' @export
cumFrqPlot <- function(dat, cumSum=FALSE, exclCol=NULL, colNames=NULL, displColNa=TRUE, tit=NULL, xLim=NULL, yLim=NULL,
xLab=NULL, yLab=NULL, col=NULL, CVlimit=NULL, thisResol=NULL, supTxtAdj=0, supTxtYOffs=0, useLog="", silent=FALSE, debug=FALSE, callFrom=NULL) {
## cumulative frequency plot (takes columns of 'dat' as separate series)
argNa <- deparse(substitute(dat))
fxNa <- wrMisc::.composeCallName(callFrom, newNa="cumFrqPlot")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(length(dim(dat)) >2) {
if(!silent) message(fxNa," ('dat' has >2 dims) Using ONLY 1st and 2nd dimension of 'dat' for plotting !")
dat <- dat[,,1] }
if(!is.null(colNames)) if(length(colNames) != ncol(as.matrix(dat))) {
warning("Number of items in 'colNames' doesn't match data provided"); colNames <- NULL }
if(length(exclCol) >0) dat <- dat[,-1*exclCol]
if(is.null(colNames)) colNames <- colnames(dat)
dat <- wrMisc::.keepFiniteCol(as.matrix(dat), silent, callFrom=fxNa)
if(!is.matrix(dat) && !is.data.frame(dat)) dat <- as.matrix(as.numeric(dat))
## optional removing of extreme values (outlyers)
if(length(CVlimit) >0 && is.numeric(CVlimit)) {
dat <- apply(dat, 2, wrMisc::exclExtrValues, result="val", CVlim=CVlimit, maxExcl=1, goodValues=FALSE, silent=silent, callFrom=fxNa)
}
if(debug) message(fxNa,"cFP1")
## sort
dat <- apply(dat, 2, sort, decreasing=FALSE,na.last=TRUE) # put NAs to end
repNA <- !is.finite(dat)
nNA <- colSums(repNA)
if(any(nNA ==nrow(dat))) {
if(!silent) message(fxNa,"Problem with columns ",wrMisc::pasteC(colnames(dat)[which(nNA ==nrow(dat))],quote="'")," , removing")
dat <- dat[,which(nNA <nrow(dat))]}
## median for display
datMed <- apply(dat, 2, stats::median,na.rm=TRUE)
## take slices if thisResol
## taking slices before cumSum should go much faster on very big data, but some loss in precision since need to mulitply results for cumSum
if(length(thisResol) >0 && is.numeric(thisResol)) {
if(thisResol[1] > nrow(dat)/1.5) { # can't go better than full resolution ! Or, if < 50% stay full res
if(!silent) message(fxNa,"Reducing resolution to '",thisResol,"' brings not sufficient/major again, remain at full resolution")
thisResol <- NULL }}
if(length(thisResol) >0) if(is.numeric(thisResol)) {
xx <- round(nrow(dat)/thisResol)
xy <- (1:thisResol)*xx
chXY <- xy > nrow(dat)
if(any(chXY)) xy <- xy[which(!chXY)]
dat <- dat[xy,]
if(cumSum) dat <- dat*xx
}
## cumsum (if needed)
if(cumSum) {
dat <- apply(dat,2,cumsum) ## note that NAs
}
##prepare figure
if(length(col) <1) col <- 1:ncol(dat)
if(is.null(xLab)) xLab <- paste("Value of ", if(cumSum) "cumulated" else "sorted"," per column")
if(is.null(yLab)) yLab <- "fraction of data"
if(is.null(xLim)) xLim <- range(dat,na.rm=TRUE,finite=TRUE)
if(is.null(yLim)) yLim <- c(0,1) #c(1,nrow(dat))/nrow(dat)
if(length(xLim) !=2) {if(!is.null(xLim)) warning("Invalid entry for 'xLim', ignoring"); xLim <- NULL }
if(length(yLim) !=2) {if(!is.null(yLim)) warning("Invalid entry for 'yLim', ignoring"); yLim <- NULL }
## plot empty
msg1 <- paste0(fxNa,": Unknow argument content ('",useLog,"') for 'useLog'; resetting to default no log")
if(length(useLog) !=1) { if(!silent) message(msg1); useLog <- ""}
if(!(useLog %in% c("","x","y","xy"))) { warning(msg1); useLog <- ""}
graphics::plot(c(1,nrow(dat)), c(range(dat, na.rm=TRUE)),
xlim=xLim, ylim=yLim, las=1, main=tit, xlab=xLab, ylab=yLab, type="n", log=useLog) # plot empty frame
## add lines and legend-text
for(j in 1:ncol(dat)) {
graphics::lines(dat[,j],(1:nrow(dat))/nrow(dat), col=col[j])
graphics::mtext(paste(" med ",if(displColNa) colNames[j],"=",signif(datMed[j],3)),
line=-2*j/3 +supTxtYOffs, cex=0.7, col=col[j], adj=supTxtAdj)
}
}
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/cumFrqPlot.R
|
#' Add arrow for expected Fold-Change to VolcanoPlot or MA-plot
#'
#' This function allows adding an arrow indicating a fold-change to MA- or Volcano-plots.
#' When comparing mutiple concentratios of standards in benchmark-tests it may be useful to indicate the expected ratio in a pair-wise comparison.
#' In case of main input as list or MArrayLM-object (as generated from limma), the colum-names of multiple pairwise comparisons can be used
#' for extracting a numeric content (supposed as concentrations in sample-names) which will be used to determine the expected ratio used for plotting.
#' Optionally the ratio used for plotting can be returned as numeric value.
#'
#' #' @details The argument \code{addText} also allows specifying a fixed position when using \code{addText=c(loc="bottomleft")}, also bottomright, topleft, topright, toleft and toright may be used.
#' In this case the elemts \code{side} and \code{adjust} will be redefined to accomodate the text in the corner specified.
#'
#' @param FC (numeric, list or MArrayLM-object) main information for drawing arrow : either numeric value for fold-change/log2-ratio of object to search for colnames of statistical testing for extracting numeric part
#' @param useComp (integer) only used in case FC is list or MArrayLM-object an has multiple pairwise-comparisons
#' @param isLin (logical) inidicate if \code{FC} is log2 or not
#' @param asX (logical) indicate if arrow should be on x-axis
#' @param col (integer or character) custom color
#' @param arr (numeric, length=2) start- and end-points of arrow (as relative to entire plot)
#' @param lwd (numeric) line-width of arrow
#' @param addText (logical or named vector) indicate if text explaining arrow should be displayed, use \code{TRUE} for default (on top right of plot),
#' or any combination of 'loc','line','cex','side','adj','col','text' (or 'txt') for customizing specific elements
#' @param returnRatio (logical) return ratio
#' @param silent (logical) suppress messages
#' @param debug (logical) additonal messages for debugging
#' @param callFrom (character) allows easier tracking of messages produced
#' @return This function plots only an arrow onto current plotting device (and some explicative text), if \code{returnRatio=TRUE} also returns numeric value for extracted ratio
#'
#' @seealso \code{\link[wrGraph]{MAplotW}}, \code{\link[wrGraph]{VolcanoPlotW}}
#' @examples
#' plot(rnorm(20,1.5,0.1), 1:20)
#' foldChangeArrow(FC=1.5)
#'
#' @export
foldChangeArrow <- function(FC, useComp=1, isLin=TRUE, asX=TRUE, col=2, arr=c(0.005,0.15), lwd=NULL,
addText=c(line=-0.9,cex=0.7,txt="expected",loc="toright"), returnRatio=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL){
##
fxNa <- wrMisc::.composeCallName(callFrom, newNa="foldChangeArrow")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
figCo <- graphics::par("usr") # c(x1, x2, y1, y2)
if(length(FC) >1 && any(c("MArrayLM","list") %in% class(FC)) ) {
## try working based on MArrayLM-object or list
## look for names of pairwise comparisons to extract numeric parts for calculating expected ratio ...
chNa <- names(FC) %in% c("t","BH","FDR","p.value")
if(any(chNa)) {
if(all(length(useComp)==1, length(dim(FC[[which(chNa)[1]]])) ==2, dim(FC[[which(chNa)[1]]]) > 0:1)) {
colNa <- colnames(FC[[which(chNa)[1]]])
ch2 <- colNa[1]=="(Intercept)" && length(colNa)==2
} else ch2 <- TRUE
if(!ch2) {
regStr <-"[[:space:]]*[[:alpha:]]+[[:punct:]]*[[:alpha:]]*"
colNa <- sub(paste0("^",regStr),"", sub(paste0(regStr,"$"), "", unlist(strsplit(colNa[useComp], "-"))) )
chN2 <- try(as.numeric(colNa), silent=TRUE)
if(inherits(chN2, "try-error") && length(colNa)==2) {
FC <- chN2[2] / chN2[1]
} else ch2 <- TRUE
## note: wrMisc::numPairDeColNames() sorts numeric values, can't use here
chN2 <- all(length(colNa)==2, nchar(sub("[[:digit:]]*\\.?[[:digit:]]*","",colNa)) <1) # contains only usable digits
isLin <- FALSE # assume log2 when from testing result
} else ch2 <- TRUE
} else ch2 <- TRUE
if(ch2) FC <- NULL
}
FC <- try(as.numeric(FC), silent=TRUE)
if(!"try-error" %in% class(FC)) {
if(!isLin) FC <- log2(FC)
## extract/check graphical parameters
if(any(identical(addText, TRUE), c("line","cex","side","adj","col","text","txt","loc") %in% names(addText))) {
## bottomleft, bottomright, topleft, topright, toleft and toright
mLi <- if("line" %in% names(addText)) try(as.numeric(addText["line"][1]), silent=TRUE) else -0.9
mCex <- if("cex" %in% names(addText)) try(as.numeric(addText["cex"][1]), silent=TRUE) else 0.7
mSide <- if("side" %in% names(addText)) try(as.integer(addText["side"][1]), silent=TRUE) else 1
mAdj <- if("adj" %in% names(addText)) try(as.integer(addText["adj"][1]), silent=TRUE) else 1
mCol <- if("col" %in% names(addText)) addText["col"][1] else col
mTxt <- if("text" %in% names(addText)) addText["text"][1] else {if("txt" %in% names(addText)) addText["txt"][1] else "arrow: expected="}
if("loc" %in% names(addText)) {
mTxt <- paste(mTxt, signif(if(isLin) 2^FC else FC,3))
## check for left/right/center
chRi <- grep("right$", as.character(addText["loc"]))
chLe <- grep("left$", as.character(addText["loc"]))
chCe <- grep("center$", as.character(addText["loc"]))
if(length(chLe) >0) { mAdj <- 0; mTxt <- paste0(" ",mTxt) # this is left.xxx
if(arr[1] < 0.15 && FC < figCo[1] +diff(figCo[1:2])/3) arr[1] <- 0.015 # raise min starting hight to avoid crossing text
} else { if(length(chRi) >0) {mAdj <- 1; mTxt <- paste0(mTxt," ") # this is right.xxx
if(arr[1] < 0.15 && FC > figCo[2] -diff(figCo[1:2])/3) arr[1] <- 0.015 # raise min starting hight to avoid crossing text
} else {
if(length(chCe) >0) mAdj <- 0.5; if(arr[1] < 0.15) arr[1] <- 0.015 }}
## check for top/bottom
chTop <- grep("^top", as.character(addText["loc"]))
chBot <- grep("^bottom", as.character(addText["loc"]))
if(length(chTop) >0) mSide <- 3 else if(length(chBot) >0) mSide <- 1
chTo <- c(grep("tori", as.character(addText["loc"])), grep("tole", as.character(addText["loc"])))
if(length(chTo) >0) graphics::mtext(mTxt, at=FC, side=mSide, adj=0, col=mCol, cex=mCex, line=mLi) else {
graphics::mtext(mTxt, side=mSide, adj=mAdj, col=mCol, cex=mCex, line=mLi)
} }
}
chArr <- (arr[2] -arr[1]) > 0.05
if(!chArr) arr[2] <- arr[1] +0.04
## draw arrow
if(asX) graphics::arrows(FC, figCo[3] + arr[1]*(figCo[4] -figCo[3]), FC, figCo[3] + arr[2]*(figCo[4] -figCo[3]),
col=col, lwd=lwd, length=0.1) else { graphics::arrows(figCo[3] + arr[1]*(figCo[4] -figCo[3]), FC,
figCo[3] + arr[2]*(figCo[4] -figCo[3]), FC, col=col, lwd=lwd, length=0.1) }
if(returnRatio) return(FC)
} else if(!silent) message("Unable to extract usable values for drawing arrow")
}
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/foldChangeArrow.R
|
#' Histogram (version by WR)
#'
#' This function proposes a few special tweaks to the general \code{\link[graphics]{hist}} function :
#' In a number of settings data are treated and plotted as log-data. This function allows feeding directly log2-data and displaying the x-axis
#' (re-translated) in linear scale (see argument \code{isLog}).
#' The default settings allow making (very) small histograms ('low resolution'), which may be used as a rough overview of bandwidth and distribution of values in \code{dat}.
#' Similar to \code{\link[graphics]{hist}}, by changing the parameters \code{nBars} and/or \code{breaks} very 'high resolution' histograms can be produced.
#' By default it displays n per set of data (on the top of the figure).
#' Note that the argument for (costom) title \code{main} is now called \code{tit}.
#'
#' @param dat (matrix, list or data.frame) data to plot
#' @param fileName (character) name of file for saving graphics
#' @param output (character, length=1) options for output on 'screen' or saving image in various formats (set to 'jpg','png' or 'tif')
#' @param nBars (integer) number of bars in histogram (default for 'low resolution' plot to give rough overview)
#' @param breaks (integer) for (partial) compatibility with hist() : use only for number of breaks (or 'FD'), gets priority over 'nBars'
#' @param tit (character) custom title
#' @param subTi (character) may be \code{FALSE} for NOT displaying, or any text, otherwise range
#' @param xLab (character) custom x-axes label
#' @param yLab (character) custom y-axes label
#' @param las (integer) optional fixed text orientation of x-axis numbers : use 1 for horizontal and 2 for perpendicular, see also \code{\link[graphics]{par}}
#' @param xcex (numeric) cex-type expansion factor for x-axis numbers, see also \code{\link[graphics]{par}}
#' @param imgxSize (integer) width of image when saving to file, see also \code{\link[graphics]{par}}
#' @param useCol (character or integer) custom colors, see also \code{\link[graphics]{par}}
#' @param useBord (character) custom histogram elements border color, see also \code{\link[graphics]{par}}
#' @param isLog (logical) for lin scale signal intensity values where repesentation needs log, assume log2 if \code{TRUE}
#' @param cexSubTi (numerical) subtitle size (expansion factor cex), see also \code{\link[graphics]{par}}
#' @param cropHist (logical) -not implemented yet- designed for cutting off bars with very low ('insignificant') values
#' @param parDefault (logical) to automatic adjusting par(marg=,cex.axis=0.8), see also \code{\link[graphics]{par}}
#' @param silent (logical) suppress messages
#' @param debug (logical) additonal messages for debugging
#' @param callFrom (character) allow easier tracking of messages produced
#' @return This function produces a histogram type graphic (to the ccurrent graphical device)
#' @seealso \code{\link[graphics]{hist}}
#' @examples
#' set.seed(2016); dat1 <- round(c(rnorm(200,6,0.5),rlnorm(300,2,0.5),rnorm(100,17)),2)
#' dat1 <- dat1[which(dat1 <50 & dat1 > 0.2)]
#' histW(dat1, br="FD", isLog=FALSE)
#' histW(log2(dat1), br="FD", isLog=TRUE)
#'
#' ## quick overview of distributions
#' layout(partitionPlot(4))
#' for(i in 1:4) histW(iris[,i], isLog=FALSE, tit=colnames(iris)[i])
#' @export
histW <- function(dat, fileName="histW", output="screen", nBars=8, breaks=NULL, tit=NULL, subTi=NULL,xLab=NULL,yLab=NULL,las=NULL,xcex=0.7,
imgxSize=900, useCol=NULL, useBord=NULL, isLog=TRUE, cexSubTi=NULL, cropHist=TRUE, parDefault=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL) {
## make (small) histogram, eg as overview of bandwidth of values in 'dat'
## 'isLog' .. for lin scale SI values where repesentation needs log
## 'breaks' .. for (partial) compatibility with hist() : use only for number of breaks (or 'FD'), gets priority over 'nBars'
## 'output' .. options for saving image in various formats (set to 'jpg','png',...)
## 'subTi' .. may be FALSE for NOT displaying, or any text, otherwise range
## png & co : image height chosen automatically based on number of cols/bars (lower with many bars)
## 'cropHist' ..[not implemented yet] designed for cutting off bars with very low ('insignificant') values
## 'parDefault' .. to automatic adjusting par(marg=,cex.axis=0.8)
argN <- deparse(substitute(dat))
fxNa <- wrMisc::.composeCallName(callFrom, newNa="histW")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
opar <- graphics::par(no.readonly=TRUE)
opar2 <- opar[-which(names(opar) %in% c("fig","fin","font","mfcol","mfg","mfrow","oma","omd","omi"))] #
on.exit(graphics::par(opar2)) # progression ok
maxNoXLabels <- NA # max number of border-values to display
msg1 <- " NOT sufficent rights to write : "
if(length(output) <1) output <- "screen" else if(length(output) >1) output <- output[1]
if(any(output %in% c("png","tiff","tif","jpg","jpeg"))) if(file.access(fileName, mode=0) ==0) {
if(file.access(fileName, mode=2) <0) stop("File exists ",msg1,fileName) }
if(length(dat) <1) stop( " 'dat must be vector of numeric values")
if(is.null(tit)) tit <- paste("Signal Histogram of",argN)
if(is.null(xLab)) xLab <- ""
if(is.null(yLab)) yLab <- paste("Frequency")
if(is.null(useCol)) useCol <- grDevices::grey(0.8)
if(is.null(useBord)) useBord <- grDevices::grey(0.7)
if(length(maxNoXLabels) !=1) maxNoXLabels <- NA
if(length(breaks)==1) nBars <- breaks
hist.ini <- graphics::hist(dat, plot=FALSE, breaks=nBars)
if(is.character(nBars)) nBars <- length(hist.ini$breaks)
if(sum(hist.ini$density, na.rm=TRUE) <1) hist.ini$density <- hist.ini$density/sum(hist.ini$density, na.rm=TRUE)
relCo <- rbind(rel=hist.ini$density, interv=1:length(hist.ini$counts))
inte <- hist.ini$density
maxCla <- which(inte==max(inte))
if(length(inte < nBars) && (sum(inte[maxCla:min(length(inte),maxCla+1)]) > 0.8*sum(inte) |
sum(inte[maxCla:max(1,maxCla-1)]) > 0.8*sum(inte))) {
if(!silent) message(fxNa,"Too much information in 2 neighbour classes (out of ",length(inte),"), trying to increasing number of classes")
hist.ini <- graphics::hist(dat, plot=FALSE, breaks=nBars +1)
relCo <- rbind(rel=hist.ini$density, interv=1:length(hist.ini$counts)) }
mainHist <- hist.ini
if(cropHist) {
## crop borders to avoid showing very low bars not yet finished/implemented
mainHist <- mainHist }
imgSize <- round(c(imgxSize, imgxSize*(sort(c(0.8, 1.1 + log10(length(mainHist$breaks))/3,1.4))[2]))) ## improve ?
pl2fi <- FALSE # info if plot to file
tmp <- NULL
if(output == "png") {tmp <- try(grDevices::png(file=fileName, width=imgSize[1], height=imgSize[2],res=140), silent=TRUE); pl2fi <- TRUE}
if(output %in% c("jpg","jpeg")) {tmp <- try(grDevices::jpeg(file=fileName, width=imgSize[1], height=imgSize[2],res=140), silent=TRUE); pl2fi <- TRUE}
if(output %in% c("tif","tiff")) {tmp <- try(grDevices::tiff(file=fileName, width=imgSize[1], height=imgSize[2],res=140), silent=TRUE); pl2fi <- TRUE}
## create plot
if(inherits(tmp, "try-error")) {
warning(fxNa,"Cannot create file '",output,"' (or other selected format) !")
} else {
nBars <- length(mainHist$breaks)
## try to adopt number of x-axis labels displayed to space available
ch1 <- if(pl2fi) imgSize[1]/150 else graphics::par("pin")[1] # bring px-size & screen-width to similar measure ..
nCharLab <- min(max(nchar(c(utils::head(mainHist$breaks), utils::tail(mainHist$breaks)))),5) # max no of character used in legend (but no more than 5)
## how many axis labels can one reasonably display ?
if(debug) message("Initial ch1 ",signif(ch1,3)," nCharLab ",nCharLab," nBars ",nBars)
ch1 <- max(2+ ch1 *5 / (1 +nCharLab*xcex), 3)
if(length(maxNoXLabels)==1 && is.finite(maxNoXLabels)) if(nBars >maxNoXLabels) ch1 <- max(nBars %/% maxNoXLabels, ch1)
ch2 <- round(nBars/ch1)
ch1 <- round(ch1)
if(debug) message("Final ch1 ",signif(ch1,3)," nBars ",nBars," ch2 ",ch2)
showBorder <- if(nBars >3 && nBars >ch1) ch2*(1:(nBars/ch2)) else 1:nBars
## define las # x-axis numbers text orientation
txtLas <- if(length(las) !=1) 1 + (nCharLab >4) else las
if(parDefault) graphics::par(mar=c(0.8 +txtLas, 5, 2.6, 0.8), cex.axis=xcex) # mar(bot,le,top,ri)
cexSubTi <- if(!is.numeric(cexSubTi) || length(cexSubTi) !=1) graphics::par("font.sub")*0.7
txt2 <- c("Initial values range from "," to ")
graphics::plot(mainHist, xlab=xLab, ylab=yLab, col=useCol, border=useBord, main=tit, xaxt="n", las=1)
graphics::segments(hist.ini$breaks[showBorder], 0, hist.ini$breaks[showBorder], -1*signif(max(hist.ini$counts,na.rm=TRUE)/110,3) ) # x-axis ticks
## look for alternatve of making plot, rather as contour-lines for overlay ?
if(isLog) {
tx <- signif(c(2^min(dat), 2^hist.ini$breaks[-1*c(1,length(hist.ini$breaks))], 2^max(dat)),2)[showBorder]
if(length(tx) > length(unique(tx))) tx <- signif(c(2^min(dat), 2^hist.ini$breaks[-1*c(1,length(hist.ini$breaks))], 2^max(dat)),3)[showBorder]
graphics::mtext(tx, at=hist.ini$breaks[showBorder], col=1, side=1, li=-0.2, cex=0.75, xlab=xLab, las=txtLas)
txt2 <- paste(txt2[1], signif(2^min(dat,na.rm=TRUE),4), txt2[2], signif(2^max(dat,na.rm=TRUE),5)) # 'initial values range form ..to..'
} else {
tx <- signif(hist.ini$breaks[-1*length(hist.ini$breaks)],2)[showBorder]
if(length(tx) > length(unique(tx))) tx <- signif(c(min(dat), hist.ini$breaks[-1*c(1,length(hist.ini$breaks))], max(dat)),3)[showBorder]
graphics::mtext(tx, at=hist.ini$breaks[showBorder], col=1, side=1, li=-0.2, cex=0.75, xlab=xLab, las=1)
txt2 <- paste(txt2[1], signif(min(dat,na.rm=TRUE),4), txt2[2], signif(max(dat,na.rm=TRUE),5)) }
if(!identical(subTi,FALSE)) graphics::mtext(if(is.null(subTi)) txt2 else subTi,li=-0.4, cex=cexSubTi)
}
if(output %in% c("png","tif","tiff","jpg","jpeg")) grDevices::dev.off()
tmp <- try(graphics::par(mar=opar$mar, cex.main=opar$font.sub), silent=TRUE)
}
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/histW.R
|
#' Display numeric content of matrix as image
#'
#' To get a quick overview of the spatial distribution of smaller data-sets it may be useful to display numeric values as colored boxes.
#' Such an output may also be referred to as heatmap (note that the term 'heatmap' is frequently associated with graphical display of hierarchcal clustering results).
#' The function \code{\link[graphics]{image}} provides the basic support to do so (ie heatmap without rearranging rows and columns by clustering).
#' To do this more conveniently, the function \code{imageW} offers additional options for displaying row- and column-names or displaying NA-values as custom-color.
#'
#' @details
#' This function allows two modes of operation : 1) plotting using standard R -graphics or 2) using the framework of grid- and lattice-graphics (since version 1.2.6).
#' The latter version allows integrating a legend for the color-scale and adding grid-lines, rotation of axis-labels or removing tick-marks.
#' Please note that sometimes the center-color segment may not end up directly with the center-color, in this case you may adjust using the argument \code{centColShift=-1}
#'
#' @param data (matrix or data.frame) main input
#' @param latticeVersion (logical) use lattice for plotting (this will include a color-legend)
#' @param transp (logical) decide if data should get transposed (if \code{TRUE} the data will be displayed exacetly same order as when printing the values as table);
#' set to \code{FALSE} to get behaviour prior to version 1.3.0.
#' @param col (character or integer) colors; in lattice version 2 or 3 color-names to define central- and end-points of gradient (starting with color for lowest values, optional central color and color for highest values), default is 60 shades 'RdYlBu' RColorBrewer, if 'heat.colors' use heat.colors in min 15 shades
#' @param NAcol (character or integer) custom color for NA-values, default is light grey
#' @param rowNa (character) optional custom rownames
#' @param colNa (character) optional custom colnames
#' @param tit (character) custom figure title
#' @param xLab (character) optional custom text for x-axis 'values'
#' @param yLab (character) optional custom text for y-axis 'values'
#' @param las (numeric) style of axis labels (see also \code{\link[graphics]{par}}); in case of \code{latticeVersion=TRUE} this argument will override default \code{rotXlab=0} and/or \code{rotYlab=0}
#' @param nColor (integer, only used in lattice version) number of color-blocks in color gradient (made based on central- and end-points from \code{col}
#' @param balanceCol (logical, only used in lattice version) if \code{TRUE} the color-radient aims to color the value closest to 0 with the center color (from \code{col} (default gray)
#' @param gridCol (character, only used in lattice version) define color of grid
#' @param gridLty (integer, only used in lattice version) define line-type of grid (see also lty \code{\link[graphics]{par}})
#' @param centColShift (integer, only used in lattice version) shift central (default grey) color element for negative scale up or down (ie increase or reduce number of color-blocks for negatve values),
#' used for correcting automatic scaling rounding issues to ensure the central elements captures 0
#' @param cexDispl (numeric, length=1, only used in lattice version) define cex size for displaying (rounded) values in plot, set to \code{NULL} for omitting
#' @param panel.background.col (character, only used in lattice version)
#' @param supLat (list, only used in lattice version) additional arguments/parameters passed to \code{levelplot}
#' @param rotXlab (numeric, 0 - 360, lattice version only) control rotation of x-axis labels
#' @param rotYlab (numeric, 0 - 360, lattice version only) control rotation of y-axis labels
#' @param cexXlab (numeric) cex-like expansion factor for x-axis labels (see also \code{\link[graphics]{par}})
#' @param cexAxs (numeric) cex-like expansion factor for x- and y-axis text/labels (see also \code{\link[graphics]{par}})
#' @param cexYlab (numeric) cex-like expansion factor for y-axis labels (see also \code{\link[graphics]{par}})
#' @param Xtck (numeric or logical) expansion factor for length of tick-marks on x-axis (default=0 for no tick-marks)
#' @param Ytck (numeric or logical) expansion factor for length of tick-marks on y-axis
#' @param cexTit (numeric) cex-like expansion factor for title (see also \code{\link[graphics]{par}})
#' @param silent (logical) suppress messages
#' @param debug (logical) additional messages for debugging
#' @param callFrom (character) allow easier tracking of messages produced
#'
#' @seealso \code{\link[graphics]{image}}, for the lattice version \code{\link[lattice]{levelplot}}, heatmaps including hierarchical clustering \code{\link[stats]{heatmap}} or \code{heatmap.2} from package \href{https://CRAN.R-project.org/package=gplots}{gplots}
#' @return This function plots in image (to the current graphical device) as \code{image} does
#' @examples
#' imageW(as.matrix(iris[1:40,1:4]), transp=FALSE, tit="Iris (head)")
#' imageW(as.matrix(iris[1:20,1:4]), latticeVersion=TRUE, col=c("blue","red"),
#' rotXlab=45, yLab="Observation no", tit="Iris (head)")
#' @export
imageW <- function(data, latticeVersion=FALSE, transp=TRUE, NAcol="grey95", tit=NULL, rowNa=NULL, colNa=NULL, xLab=NULL, yLab=NULL, las=2,
col=NULL, nColor=9, balanceCol=TRUE, gridCol="grey75", gridLty=1, centColShift=0, cexDispl=NULL, panel.background.col="white", supLat=list(),
rotXlab=0, rotYlab=0, cexXlab=0.7, cexAxs=NULL, cexYlab=0.9, Xtck=0, Ytck=0, cexTit=1.6, silent=FALSE, debug=FALSE, callFrom=NULL) {
## improved version if image() or levelplot()
fxNa <- wrMisc::.composeCallName(callFrom, newNa="imageW")
argNa <- deparse(substitute(data))
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(!isTRUE(silent)) silent <- FALSE
doPlot <- if(length(data) >0) is.numeric(data) else FALSE
transp <- !isFALSE(transp)
if(length(dim(data)) <2) data <- try(matrix(as.numeric(data), ncol=1, dimnames=list(names(data), NULL)), silent=TRUE)
if(inherits(data, "try-error")) doPlot <- FALSE else {
if(is.data.frame(data) && doPlot) {doPlot <- is.numeric(as.matrix(data)); data <- as.matrix(data)}}
if(debug) {message(fxNa," xiW0 debug: ",debug)}
if(doPlot) {
## checks & adjust
if(length(xLab) >1 && !all(is.na(xLab))) {
if(transp) {
if(length(xLab) ==ncol(data) && length(colNa) <1 ) { colNa <- xLab; xLab <- NA
if(!silent) message(fxNa,"(72) It seems you meant 'colNa' when using argument 'xLab' (interpreting as such) ...")
} else { if(length(xLab) >1) if(!silent) message(fxNa,"Invalid entry for 'xLab'"); xLab <- NA }
} else {
if(length(xLab) ==nrow(data) && length(rowNa) <1 ) { rowNa <- xLab; xLab <- NA
if(!silent) message(fxNa,"(76) It seems you meant 'rowNa' when using argument 'xLab' (interpreting as such) ...")
} else { if(length(xLab) >1) if(!silent) message(fxNa,"Invalid entry for 'xLab'"); xLab <- NA }
}
} else { if(length(xLab) >1) if(!silent) message(fxNa,"Invalid entry for 'xLab'"); xLab <- NA }
if(length(yLab) >1 && !all(is.na(yLab))) {
if(transp) {
if(length(yLab) ==nrow(data) && length(rowNa) <1 ) { rowNa <- yLab; yLab <- NA
if(!silent) message(fxNa,"(84) It seems you meant 'rowNa' when using argument 'yLab' (interpreting as such) ...")
} else { if(length(yLab) >1) if(!silent) message(fxNa,"Invalid entry for 'yLab'"); yLab <- NA }
} else {
if(length(yLab) ==ncol(data) && length(colNa) <1 ) { colNa <- yLab; yLab <- NA
if(!silent) message(fxNa,"(88) It seems you meant 'colNa' when using argument 'yLab' (interpreting as such) ...")
} else { if(length(yLab) >1) if(!silent) message(fxNa,"Invalid entry for 'xLab'"); yLab <- NA}
}
} else { if(length(yLab) >1) if(!silent) message(fxNa,"Invalid entry for 'xLab'"); yLab <- NA}
if(length(rowNa) <nrow(data)) rowNa <- rownames(data)
if(length(rowNa) <1) rowNa <- if(length(nrow(data)) >1) 1:nrow(data) else ""
if(length(colNa) < ncol(data)) colNa <- colnames(data)
if(length(colNa) <1) colNa <- if(length(ncol(data)) >1) 1:ncol(data) else ""
if(debug) {message(fxNa," xiW1"); xiW1 <- list(data=data,xLab=xLab,yLab=yLab,transp=transp, tit=tit,rowNa=rowNa,colNa=colNa)}
if(latticeVersion) {
## reformat input
if(!transp) data <- t(data) # was initially written for transp=T, re-transform if not chosen
if(length(rotXlab)==0 && any(las %in% c(2,3))) rotXlab <- 0
if(length(rotYlab)==0 && any(las %in% c(0,3))) rotYlab <- 0
ma2 <- expand.grid(1:ncol(data), 1:nrow(data))
ma2 <- cbind(ma2, as.numeric(t(data[nrow(data):1,])))
colnames(ma2) <- c("x","y","z")
if(any(is.na(xLab))) xLab <- NULL
if(any(is.na(yLab))) yLab <- NULL
## colors
if(length(col) <2) col <- c("blue","grey80","red")
nCol2 <- try(round(nColor[1]), silent=TRUE)
msg <- "Note: Argument 'nColor' should contain integer at least as high as numbers of colors defined to pass through; resetting to default=9"
if(inherits(nCol2, "try-error")) { message(fxNa,msg); nCol2 <- 9 }
if(nCol2 < length(col)) { message(fxNa,msg); nCol2 <- 9 }
miMa <- range(data, na.rm=TRUE)
width <- (miMa[2] - miMa[1])/ nCol2
bre <- miMa[1] + (0:nCol2) *width # breaks
clo0 <- which.min(abs(as.numeric(data))) # (first) value closest to 0, try to include in grey segm
clo0br <- min(which(bre >= as.numeric(data)[clo0])) #+ (-1:0) # upper break/bound for center color (close/including 0)
if(clo0br >1 && clo0br < length(bre) -1 && length(col) >2) { # some values in lower & upper gradient
maxLe <- max(clo0br -1, length(bre) -clo0br) -as.integer(balanceCol)
negCol <- try(grDevices::colorRampPalette(col[1:2])(if(balanceCol) maxLe else length(clo0br -1)), silent=TRUE)
if(inherits(negCol, "try-error")) { negCol <- NULL
if(!silent) message(fxNa,"Invalid color-gradient for neg values")
}
negCol <- negCol[-length(negCol)] # max neg-col -> grey (wo defined grey); remove 'grey' from last position
posCol <- try((grDevices::colorRampPalette(col[2:3])(if(balanceCol) maxLe else length(length(bre) -1 -clo0br))), silent=TRUE) # (grey -> max pos-col)
if(inherits(posCol, "try-error")) {
if(!silent) warning(fxNa,"Invalid color-gradient for pos values")
}
if(debug) message(fxNa, "/1 clo0br ",clo0br," max nCol ",nCol2," le negCol ",length(negCol)," le posCol ",length(posCol))
if(balanceCol) {
centColShift <- if(length(centColShift) <1 || !is.numeric(centColShift)) 0 else as.integer(centColShift)
.keepLastN <- function(x,lastN) x[(length(x) -lastN +1):length(x)]
if(length(negCol) != clo0br -2 +centColShift) {
if(debug) message(fxNa,"Correct negCol (prev=",length(negCol),") centColShift=",centColShift," to : ",clo0br -2 +centColShift)
if(length(negCol) > clo0br -2 +centColShift) negCol <- .keepLastN(negCol, clo0br -2 +centColShift)
if(length(negCol) < clo0br -2 +centColShift) {negCol <- grDevices::colorRampPalette(col[1:2])(clo0br -1 +centColShift)
negCol <- negCol[-length(negCol)] }
}
if(length(posCol) != length(bre) -length(negCol) -1) {
if(debug) message(fxNa,"Corr posCol (prev ",length(posCol),") to ",maxLe + centColShift," to ",length(bre) -length(negCol) -1)
if(length(posCol) > length(bre) -length(negCol) -1) posCol <- posCol[1:(length(bre) -clo0br)]
if(length(posCol) < length(bre) -length(negCol) -1) {
posCol <- grDevices::colorRampPalette(col[2:3])(length(bre) -length(negCol) -1) }
}
}
cols <- c(negCol, posCol)
if(debug) message(fxNa, "/2 clo0br ",clo0br," max nCol ",nCol2," le cols ",length(cols)," le negCol ",length(negCol)," le posCol ",length(posCol))
} else { # plain color gradient
cols <- if(length(col)==2) grDevices::colorRampPalette(col[1:2])(length(bre) -1) else {
c(grDevices::colorRampPalette(col[1:2])(floor(length(bre)/2)), (grDevices::colorRampPalette(col[2:3])(length(bre) -floor(length(bre)/2)))[-1])
}
}
##
myPanel <- function(...) {
grid::grid.rect(gp=grid::gpar(col=NA, fill=NAcol)) # fill NA
lattice::panel.levelplot(...)
argXYZ <- list(...)
if(length(cexDispl)==1 && is.numeric(cexDispl)) lattice::panel.text(argXYZ$x, argXYZ$y, signif(argXYZ$z,2), cex=cexDispl) # add rounded numeric value
if(any(is.na(gridCol))) gridCol <- NULL
chGri <- (1:6) %in% gridLty
if(length(gridCol) >0 && any(chGri)) { # add grid-lines
lattice::panel.abline(h=0.5 +1:(nrow(data) -1), col=gridCol, lty=gridLty) # vertical
lattice::panel.abline(v=0.5 +1:(ncol(data) -1), col=gridCol, lty=gridLty) } # hor
}
## lattice levelplot
if(doPlot) lattice::levelplot(z ~ x *y, data = ma2, aspect=nrow(data)/ncol(data), col.regions=cols,
region = TRUE, cuts =length(cols) -1, xlab = yLab, ylab = xLab, main = tit,
scales=list(relation="free", x=list(at=1:ncol(data), labels=if(transp) colNa else rowNa, cex=cexXlab, rot=rotXlab, tck=as.numeric(Xtck)),
y=list(at=nrow(data):1, labels=if(transp) rowNa else colNa, cex=cexYlab, rot=rotYlab, tck=as.numeric(Ytck))), # axis labels
par.settings=list(axis.line=list(col='black')),
panel=myPanel
)
} else {
## (until v1.2.5) standard graphics version (ie non-lattice)
if(debug) message(fxNa," (175) xLab=",xLab," yLab=",yLab)
if(transp) data <- t(data)
if(ncol(data) >1) data <- data[,ncol(data):1] # reverse for intuitive display left -> right
if(identical(col,"heat.colors") || identical(col,"heatColors")) col <- rev(grDevices::heat.colors(sort(c(15, prod(dim(data)) +2))[2] ))
chRCo <- requireNamespace("RColorBrewer", quietly=TRUE)
msgRCo <- c(fxNa,"Package 'RColorBrewer' not installed",", ignore argument 'col'")
if(identical(col,"YlOrRd")) {if(chRCo) col <- RColorBrewer::brewer.pal(9,"YlOrRd") else { col <- NULL; if(!silent) message(msgRCo) }}
if(identical(col,"RdYlGn")) {if(chRCo) col <- RColorBrewer::brewer.pal(11,"RdYlGn") else { col <- NULL; if(!silent) message(msgRCo) }}
if(identical(col,"Spectral")) {if(chRCo) col <- RColorBrewer::brewer.pal(11,"Spectral") else { col <- NULL; if(!silent) message(msgRCo) }}
if(identical(col,"RdBu")) {if(chRCo) col <- RColorBrewer::brewer.pal(11,"RdBu") else { col <- NULL; if(!silent) message(msgRCo) }}
if(length(col) <1) { if(!chRCo) message(msgRCo[1:2],"Using rainbow colors instead of 'RdYlBu'")
col <- if(chRCo) grDevices::colorRampPalette(rev(RColorBrewer::brewer.pal(n=7, name="RdYlBu")))(60) else grDevices::rainbow(60)}
chNa <- is.na(data)
if(any(chNa) && length(NAcol) >0) { if(!is.matrix(data)) data <- as.matrix(data)
mi <- min(data, na.rm=TRUE)
## mark NAs
if(any(chNa)) data[which(chNa)] <- min(data, na.rm=TRUE) -diff(range(data, na.rm=TRUE))*1.1/(length(col))
col <- c(NAcol,col) }
## main plot
yAt <- (0:(length(rowNa)-1))/(length(rowNa)-1)
if(debug) {message(fxNa," xiW2"); xiW2 <- list(data=data, xLab=xLab,yLab=yLab,transp=transp,tit=tit,rowNa=rowNa,colNa=colNa,yAt=yAt)}
if(doPlot) {
if(debug) message(fxNa," (197) xLab=",xLab," yLab=",yLab)
graphics::image(data, col=col, xaxt="n", yaxt="n", main=tit, cex.main=cexTit, xlab=if(transp) yLab else xLab, ylab=if(transp) xLab else yLab)
graphics::mtext(at=(0:(length(colNa)-1))/(length(colNa)-1), colNa, side=if(transp) 1 else 2, line=0.3, las=las, cex=cexYlab) # 'colNames'
graphics::mtext(at=if(transp) rev(yAt) else yAt, rowNa, side=if(transp) 2 else 1, line=0.3, las=las, cex=cexXlab) # 'rowNames'
graphics::box(col=grDevices::grey(0.8)) }}
} else if(!silent) message(fxNa,"Argument 'data' invalid, please furnish matrix or data.frame with min 2 lines & min 1 col")
}
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/imageW.R
|
#' Add histogram to existing plot
#'
#' Add histogram at pleace of legend using colors from 'colorRamp'.
#'
#' @param x (numeric) main input/component of plot
#' @param colRamp (character or integer) set of colors, default is rainbow-like
#' @param location (character) for location of histogram inside existing plot (may be 'br','bl','tl','tr','bottomright', 'bottomleft','topleft','topright')
#' @param legTit (character, length=1) optional title for histogram-insert
#' @param cex (numeric) expansion factor (see also \code{\link[graphics]{par}})
#' @param srt (numeric) angle for histogram text labels (90 will give vertical label) (see also \code{\link[graphics]{par}})
#' @param offS (\code{NULL} or numeric, length=5) fine-tuning of where histogram-insert will be placed and how elements therein are ditributed
#' (default c(xOff=0.2,yOff=0.25,leftOffS=0.05, upperBarEnd=1.05,txtOff=0.02),
#' 1st and 2nd determine proportio of insert relative to entire plotting region, 3rd defines space left on bottom for text,
#' 4th if bars hit ceiling of insert or proportion to leave, 5th for shifting text towards top when turned other than 90 degrees )
#' @param border (logical) decide of draw gray rectangle or not around legend
#' @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 produces a histogram on the current plottig device
#' @examples
#' dat <- rnorm(90); plot(dat)
#' legendHist(dat, col=1:5)
#' @export
legendHist <- function(x, colRamp=NULL, location="bottomright", legTit=NULL, cex=0.7, srt=67, offS=NULL, border=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL){
## add histogram instead of legend using colors from 'colorRamp', so far as bottomright
fxNa <- wrMisc::.composeCallName(callFrom, newNa="legendHist")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(length(x) <0 && !silent) message("'x' seems to be empty, nothing to do")
if(length(x) >0) {
if(is.null(colRamp)) {
colRamp <- cbind(red=c(141,72,90,171, 220,253,244,255), green=c(129,153,194,221, 216,174,109,0), blue=c(194,203,185,164, 83,97,67,0)) # rainbow-like gradient
colRamp <- grDevices::rgb(red=colRamp[,1], green=colRamp[,2], blue=colRamp[,3], maxColorValue=255)}
cutInt <- wrMisc::cutToNgrp(x, colRamp, NAuse=FALSE)
tmp <- graphics::par("usr")
.sw <- function(location, x, offSet) { # function for setting corner-coordinates according of 'x'
## uses only 1st & 2nd val of offSet
if(length(location) !=1) location <- "bottomright"
location <- tolower(as.character(location))
if(any(c("bottomri","botri","bori","br") %in% location)) location <- "bottomright"
if(any(c("bottomle","botle","bole","bl") %in% location)) location <- "bottomleft"
if(any(c("topri","tori","tr") %in% location)) location <- "topright"
if(any(c("toptle","tole","tl") %in% location)) location <- "topleft"
## make int %value of offSet absolute :
offSet[1:2] <- offSet[1:2]*c(x[2] -x[1], x[4] -x[3])
switch(location,
bottomright= c(xMin=x[2] -offSet[1], x[2:3], yMax=x[3] +offSet[2]),
bottomleft= c(xMin=x[1], xMax=x[1] +offSet[1], x[3], yMax=x[3] +offSet[2]),
topleft= c(xMin=x[1], xMax=x[1] +offSet[1], x[4] -offSet[2], yMax=x[4]),
topright= c(xMin=x[2] -offSet[1], x[2], x[4] -offSet[2], yMax=x[4]))}
if(length(offS) <5) offS <- c(xOff=0.2, yOff=0.25, leftOffS=0.05, upperBarEnd=if(length(legTit) >0) 1.15 else 1.05, txtOff=0.02) # %of x-range, % of y-range
legCor <- .sw(location, tmp, offS)
legCor <- c(legCor, legCor[3] +offS[2]*(legCor[4] -legCor[3])) # add 5th component: bottom y axis start for Hist (shifted by offS[2] %
legWi <- abs(c(legCor[2] -legCor[1], legCor[4] -legCor[3])) # width of insert on x and y
br <- seq(legCor[1] +legWi[2]*offS[3], legCor[2] -legWi[2]*0, length.out=length(colRamp)+1) # define breaks on x-axis, uses offS[3], so far nn offset to right
chBr <- br > legCor[2]
if(any(chBr)) br[length(br)] <- legCor[2]
mids <- br[2] -br[1] # $breaks on x
mids <- br[-length(br)] +mids/2 # midPoints on x
tb <- table(cutInt$grouped) #
tb <- legCor[5]+ (legCor[4] -legCor[5])*tb/(max(tb,na.rm=TRUE)*offS[4]) # upper end of bars & factor offS[4] typically 1.05
if(border) graphics::rect(legCor[1], legCor[3], legCor[2], legCor[4], col=grDevices::rgb(1,1,1,0.5), border=grDevices::grey(0.7)) # broder of 'legend'
srtCo <- c((90 -srt)*(br[2] -br[1])/90, (legCor[4] -legCor[3])*offS[5] ) # supl offset for text-labels, uses factor offS[5]
for(j in 1:length(colRamp)) {
graphics::text(mids -srtCo[1], rep(srtCo[2] +legCor[3], length(mids)), paste(">",signif(cutInt$legTxt[,1],3)), adj=0, srt=srt, cex=cex)
graphics::rect(br[j], legCor[5], br[j+1], tb[j], col=colRamp[j], border=border) # main histogram
if(length(legTit) >0) graphics::text(mean(legCor[1:2]), max(tb,na.rm=TRUE) +(legCor[2]-legCor[1])*0.025, legTit[1], cex=cex) # histogram-insert title
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/legendHist.R
|
#' Create mouse-over interactive html-pages (with links)
#'
#' @description
#' This function allows generating html pages with interactive mouse-over to display information for the points of the plot and www-links when clicking based on embedded png file.
#' Basically, an html page will be generated which contains a call to display to an image file specified in \code{pngFileNa} and in the body below pixel-coordinated will be
#' given for disply of information at mouse-over and embedded links.
#'
#' @details
#' Basically theer are two options for defining the path to the image embedded :
#' 1) Absolute path : I turn you can moove the html to different locations, as long as it still can see the png-file the image can be displayed. However, this may
#' not be any more the case when the html file is sent to another person. If the png-file is accessible as url, it should be easily visible.
#' 2) Relative path : The simplest case would be to give only the file-name with no path at all, thus the png-file is supposed to be in the same directory as the html-file.
#' This option is very 'transportable'.
#' Basically the same applies to the clickable links which may be provided. In high-throughput biology one typically points here to data-bases accessible
#' over the internet where urls to specific pages. With UniProt such links can easily be constructed when using protein identifiers as rownames.
#'
#' @param myCoor (matrix or data.frame) with initial x&y coordinates of points for plot; with IDs (1st column !!) & coordinates (2nd & 3rd col), data for mouse-over & link (4th & 5th);
#' NOTE : if 'colNa' NOT given, colnames of 'myCoor' will be inspected & filtered (columns of non-conform names may get lost) !!!
#' Associated with (already existing) figure file 'pngFileNa' and make html page where points may be indicated by mouse-over
#' @param pngFileNa (character, length=1) filename for complementary png figure (must already exist)
#' @param HtmFileNa (character, length=1) filename for html file produced
#' @param mouseOverTxt (character, length=1) text for interactive mouse-over in html, if \code{NULL}, will use col specified by 1st 'colNa' or (if NULL) rownames of 'myCoor'
#' @param displSi (integer, length=2) size of image ('pngFileNa') at display in html (width,height), see also \code{\link[graphics]{par}}
#' @param colNa (character) if not \code{NULL} min length of 3 to custom specify the column-names to be used : 1st for mouse-over and 2nd+3rd for coordinates associated (and optional 4th for links)
#' @param tit (character) title to be displayed on top of figure
#' @param myHtmTit (character) title of Html page; 'htmlExt' .. checking and correcting filename-extension (only main Html page)
#' @param myComment (character) modify comment embedded in html-document
#' @param textAtStart (character) text in html before figure
#' @param textAtEnd (character) text in html after figure
#' @param pxDiam (integer, length=1) diameter for mouse-over tip to appear (single val or vector), simpler version/solution than with 'Tooltip' package
#' @param addLinks (character) for clickable links, either 1) vector of links or 2) single character-chain to be used for pasting to rownames (eg https://www.uniprot.org/uniprot/)
#' or 3) \code{TRUE} to check presence of 4th name specified in 'colNa' to be useed as columname from 'myCoor' dominates over eventual presence of 4th name in 'colNa'
#' @param linkExt (character) if specified : links will get specified ending, define as \code{NULL} or "" for taking 'addLinks' asIs
#' @param htmlExt (character, length=1) extension used when making html files
#' @param callFrom (character) allow easier tracking of messages produced
#' @param silent (logical) suppress messages
#' @param debug (logical) additional messages for debugging
#' @return plot
#' @seealso \code{\link{convertPlotCoordPix}}; use \code{\link[wrMisc]{htmlSpecCharConv}} to convert special characters for proper html display
#' @examples
#' ## Note, this example writes files to R's tempdir,
#' ## Otherwise, if you simply work in the current directory without spcifying paths you'll
#' ## get an html with relatove paths, which simply needs the png file in the same path
#' df1 <- data.frame(id=letters[1:10], x=1:10, y=rep(5,10), mou=paste("point",letters[1:10]),
#' link=file.path(tempdir(),paste0(LETTERS[1:10],".html")), stringsAsFactors=FALSE)
#' ## here we'll use R's tempdir, later you may want to choose other locations
#' pngFile <- file.path(tempdir(),"test01.png")
#' png(pngFile,width=800, height=600,res=72)
#' ## here we'll just plot a set of horiontal points ...
#' plot(df1[,2:3],las=1,main="test01")
#' dev.off()
#' ## Note : Special characters should be converted for display in html pages during mouse-over
#' library(wrMisc)
#' df1$mou <- htmlSpecCharConv(df1$mou)
#' ## Let's add the x- and y-coordiates of the points in pixels to the data.frame
#' df1 <- cbind(df1,convertPlotCoordPix(x=df1[,2],y=df1[,3],plotD=c(800,600),plotRes=72))
#' head(df1)
#' ## Now make the html-page allowing to display mouse-over to the png made before
#' htmFile <- file.path(tempdir(),"test01.html")
#' mouseOverHtmlFile(df1,pngFile,HtmFileNa=htmFile,pxDiam=15,
#' textAtStart="Points in the figure are interactive to mouse-over ...",
#' textAtEnd="and/or may contain links")
#' ## We still need to make some toy links
#' for(i in 1:nrow(df1)) cat(paste0("point no ",i," : ",df1[i,1]," x=",df1[i,2]," y=",
#' df1[i,3]), file=df1$link[i])
#' ## Now we are ready to open the html file using any browser
#' \dontrun{
#' browseURL(htmFile)
#' }
#' @export
mouseOverHtmlFile <- function(myCoor, pngFileNa, HtmFileNa=NULL, mouseOverTxt=NULL, displSi=c(800,600),
colNa=NULL, tit="", myHtmTit="", myComment=NULL, textAtStart=NULL, textAtEnd=NULL, pxDiam=5,
addLinks=NULL, linkExt=NULL, htmlExt="htm", callFrom=NULL, silent=FALSE, debug=FALSE){
## make html file/output where (www-)links & supplemental information is accessible at mouse-over on image/plot (eg IDs/names in plot)
## assume, that initial png is already made and coordinates are already converted to pixel level of png-image
## 'displSi' size of image ('pngFileNa') at display in html (width,height)
## 'addLinks' for clickable links, either 1) vector of links or 2) single char-chain to be used for pasting to rownames (eg https://www.uniprot.org/uniprot/)
## or 3) TRUE to check presence of 4th name specified in 'colNa' to be useed as columname from 'myCoor'
## dominates over eventual presence of 4th name in 'colNa'
myCoorTy <- NULL
fxNa <- wrMisc::.composeCallName(callFrom, newNa="mouseOverHtmlFile")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(length(dim(myCoor)) !=2) stop(" Expecting matrix or data.frame")
if(nrow(myCoor) <1) stop(" 'myCoor' seems to be empty !")
if(!is.data.frame(myCoor)) myCoor <- as.data.frame(myCoor, stringsAsFactors=FALSE)
if(is.null(myComment)) myComment <- c(" Produced by R using createHtmlWithPointsIdentif()", " from package WRmisc, ",Sys.Date())
.corPath <- function(x,asHtml=TRUE) {
## correct mixed slash and backslash in file path
if(length(grep("ming.32",R.Version()$platform)) >0) {
x <- gsub("\\\\", "/", x) # (for some editors) "
if(asHtml && length(grep("[[:upper:]]:", substr(x,1,2))) >0) {
x <- paste0("file:///",x) }
} else if(asHtml & length(grep("^/",x)) >0) x <- paste0("file:///",x)
x }
## check colNa
colN2 <- rep(NA,5)
names(colN2) <- c("ID","x","y","mouseOver","link")
potIDname <- wrMisc::.plusLowerCaps(c("ID","Id","Ident","Identifier","UniqID","uniqID","UniqueID"))
potXname <- wrMisc::.plusLowerCaps(c("xPix","xPred","coorX","htmlX","xCoor","dataX","X"))
potYname <- wrMisc::.plusLowerCaps(c("yPix","yPred","coorY","htmlY","yCoor","dataY","Y"))
potMouseOvname <- wrMisc::.plusLowerCaps(c("mouseOver","mouseInfo","Mouse","Mou","Hint","Name","fullName","FullName","Combined","CustName","custName","Info"))
potLinkname <- wrMisc::.plusLowerCaps(c("LINK","Link","Li","Http","WWW","AddLink","addLink"))
## determine column names to be extracted
if(length(colNa) ==2) colN2[2:3] <- colNa else if(length(colNa) >2) colN2[1:length(colNa)] <- colNa
if(length(colNa) <1) {
if(ncol(myCoor)==2) colN2[2:3] <- colnames(myCoor) else {
remColNa <- colnames(myCoor)
if(any(potIDname %in% remColNa)) {aa <- .serachColName(remColNa,potIDname,plusLowerCaps=FALSE,returnList=TRUE)
remColNa <- aa$remainNa; colN2[1] <- aa$foundNa}
if(any(potXname %in% remColNa)) {aa <- .serachColName(remColNa,potXname,plusLowerCaps=FALSE,returnList=TRUE)
remColNa <- aa$remainNa; colN2[2] <- aa$foundNa}
if(any(potYname %in% remColNa)) {aa <- .serachColName(remColNa,potYname,plusLowerCaps=FALSE,returnList=TRUE)
remColNa <- aa$remainNa; colN2[3] <- aa$foundNa}
if(any(potMouseOvname %in% remColNa)) {aa <- .serachColName(remColNa,potMouseOvname,plusLowerCaps=FALSE,returnList=TRUE)
remColNa <- aa$remainNa; colN2[4] <- aa$foundNa}
if(any(potLinkname %in% remColNa)) {aa <- .serachColName(remColNa,potLinkname,plusLowerCaps=FALSE,returnList=TRUE)
remColNa <- aa$remainNa; colN2[5] <- aa$foundNa}}}
## select data to be used
myCoor <- data.frame(myCoor[,colN2[which(!is.na(colN2))]], stringsAsFactors=FALSE) # set proper order of cols
if(is.na(colN2[1])) {
myCoor$ID <- if(is.null(rownames(myCoor))) 1:nrow(myCoor) else rownames(myCoor)
colN2[1] <- "ID"
if(!silent) message(fxNa,"Using column '",colnames(myCoor[colN2[1]]),"' for mouse-over")
}
if(!isFALSE(mouseOverTxt)) if(is.null(mouseOverTxt)) {
if(is.na(colN2[4])) {
myCoor$mouseOver <- myCoor[,colN2[1]] # nothing specified, use names as default
if(!silent) message(fxNa,"Using column '",colnames(myCoor[colN2[1]]),"' for mouse-over")
colN2[4] <- "mouseOver" }
} else { if(length(mouseOverTxt) ==nrow(myCoor) && length(unique(mouseOverTxt)) > 1) {
myCoor$mouseOver <- mouseOverTxt } else {
if(!silent) message(fxNa,"Ignoring invalid entry for 'mouseOverTxt' (expecting length ",nrow(myCoor)," but found ",length(mouseOverTxt),")")
myCoor$mouseOver <- myCoor[,"ID"]
} }
##
if(isTRUE(addLinks)) { # colNa has priority over IDs
myCoor$link <- myCoor[,if(is.na(colN2[5])) colN2[1] else colN2[5]]
colN2[5] <- "addLinks" } else {
if(length(addLinks) >0) {if(length(addLinks) ==nrow(myCoor) && length(unique(addLinks)) > 1 && max(nchar(addLinks),na.rm=TRUE) >0) {
myCoor$link <- addLinks
colN2[5] <- "addLinks" } else {
if(!silent) message(fxNa,"Invalid entry for 'addLinks' (expecting length ",nrow(myCoor)," but found ",length(addLinks),")")}}} # no default
## check extensions of specified links (ie myCoor$link) : if 'linkExt' specified (& longer than 0 char) add to this ending if not present
if(length(linkExt) >0) if(nchar(linkExt) >0) {
chExt <- grep(paste0(linkExt,"$"), myCoor$link)
if(length(chExt) < nrow(myCoor) && length(chExt) >0) myCoor$link[chExt] <- paste0(myCoor$link[chExt],linkExt)
}
## prepare for making html file
if(!file.exists(pngFileNa)) stop("Cannot find file which should be used for embedding image into html !")
msg <- " 'displSi' : Expecting numeric vector of lengt 2 (for display size in px in html) !"
if(!is.numeric(displSi) || length(displSi) <2) stop(msg)
if(length(HtmFileNa) !=1) HtmFileNa <- pngFileNa
baseFiNa <- sub(".PNG$","",sub(".png$","",sub(".htm$","",sub(".html$","",HtmFileNa))))
if(nchar(HtmFileNa)== nchar(baseFiNa)) {
htmlExt <- if(length(htmlExt) <0) "" else htmlExt[1] # allow file wo extesion if empty argument 'htmlExt'
if(!silent) message(fxNa,"Setting file-name + extension to : ",baseFiNa,".",htmlExt)
} else {
htmlExt <- substr(HtmFileNa, unlist(regexec("\\.htm",HtmFileNa)), nchar(HtmFileNa))}
HtmFileNa <- wrMisc::.checkFileNameExtensions(baseFiNa, htmlExt) # check file extensions for HtmFileNa & pngFileNa
.convTxtToHtmPar <- function(txt) { # convert character vector to paragraphs <p>My paragraph.</p>
txt <- as.character(txt)
nLi <- length(txt)
apply(matrix(c(rep("<p>",nLi), txt,rep("</p>",nLi)), nrow=nLi), 1, paste, collapse="") }
## main, ie html creation
htmVec <- c('<!DOCTYPE html>', '<html lang="en">', '<head>', '<meta charset="utf-8">')
htmTit <- paste(c('<title>',myHtmTit,'</title>'),collapse="")
htmVec <- c(htmVec, htmTit,"</head>","<body>")
htmCom <- paste(c("<!-- ",myComment,"-->"),collapse="")
htmGraTit <- if(is.null(tit)) NULL else paste(c("<h2>",tit,"</h2>"),collapse="") # graphic title
htmVec <- c(htmVec,htmCom,htmGraTit)
if(!is.null(textAtStart)) htmVec <- c(htmVec, .convTxtToHtmPar(textAtStart))
htmImg <- paste(c('<img src="',.corPath(pngFileNa),'" alt="wrGraph_imageForMouseOver" usemap="#colormap" style="width:',
displSi[1],'px;height:',displSi[2],'px">'),collapse="")
htmVec <- c(htmVec,htmImg,'<map name="colormap">')
ar1 <- '<area title="'
ar3 <- 'shape="circle" coords="'
ar5 <- ' alt="'
ar7 <- '"'
htmCor <- data.frame(ar1, na1=myCoor[,colN2[4]],'" ', ar3,corX=myCoor[,colN2[2]],
',', corY=myCoor[,colN2[3]], ',', diam=pxDiam, naZ='"',stringsAsFactors=FALSE)
if(!is.na(colN2[5])) htmCor <- data.frame(htmCor[,-1*ncol(htmCor)], na2='" href="', na3=.corPath(myCoor$link),'"',stringsAsFactors=FALSE)
htmCor <- cbind(htmCor, last=" >")
htmCor <- as.character(apply(htmCor, 1, paste, collapse=""))
htmVec <- c(htmVec, htmCor, "</map>")
if(!is.null(textAtEnd)) htmVec <- c(htmVec, .convTxtToHtmPar(textAtEnd))
htmVec <- c(htmVec,"</body>","</html>")
if(is.null(HtmFileNa)) HtmFileNa <- paste0(sub(".png$","",pngFileNa),".html")
if(file.exists(HtmFileNa) && !silent) message(fxNa," BEWARE, file '",HtmFileNa,"' will be overwritten !")
tryWrite <- try(cat(paste(htmVec, collpse="\n"), file=HtmFileNa))
if(inherits(tryWrite, "try-error")) warning(fxNa," PROBLEM : couldn't write Html file '",
HtmFileNa,"' ! (file open ? check path,rights etc)")
}
#' Search Column Name
#'
#' This function provides help when seraching column names
#'
#' @param x (matrix or data.frame) main input
#' @param searchColNa (character)
#' @param plusLowerCaps (logical) add lower caps to search
#' @param returnList (logical)
#' @param callFrom (character) allow easier tracking of messages produced
#' @param silent (logical) suppress messages
#' @param debug (logical) additional messages for debugging
#' @return integer vector with index of colnames found or list with $foundNa and $remainNa
#' @seealso \code{\link{convertPlotCoordPix}}; use \code{\link[wrMisc]{htmlSpecCharConv}} to convert special characters for proper html display
#' @examples
#' mat1 <- matrix(1:6, ncol=3, dimnames=list(NULL, LETTERS[1:3]))
#' .serachColName(mat1, c("C","F","A"))
#' @export
.serachColName <- function(x, searchColNa, plusLowerCaps=TRUE, returnList=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL) {
## 'x' character vector of column-names to inspect, or matrix/data.frame where colnames will be extracted/inspected
## 'searchColNa' (character)
fxNa <- wrMisc::.composeCallName(callFrom, newNa=".serachColName")
x <- if(length(dim(x)) >1) colnames(x) else as.character(x)
if(length(x) <1) return(NULL) else {
errMsg <- "Argument 'searchColNa' is emty or all NA !"
if(length(searchColNa) <1) stop(errMsg)
chNa <- is.na(searchColNa)
if(any(chNa)) {if(all(chNa)) stop(errMsg) else searchColNa <- searchColNa[which(!chNa)]}
if(plusLowerCaps) searchColNa <- wrMisc::.plusLowerCaps(searchColNa)
out <- wrMisc::naOmit(match(searchColNa, x))
if(length(out) <1) stop("None of the terms found")
if(returnList) list(foundNa=x[out[1]], remainNa=x[-out]) else out[1] }}
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/mouseOverHtmlFile.R
|
#' Make matrix for layout to partition plotting area
#'
#' This function proposes a matrix for use with \code{\link[graphics]{layout}} to arrange given number of plots to be placed on a page/plotting area.
#' In certain instances the proposed layout may accomodate slightly more plots, eg \code{nFig=5} can not be arranged in 2 or 3 columns without an empty last spot.
#' Portrait (vertival) or lanscape (horizontal) layout proportions can be chosen. The user can also impose a given number of columns.
#'
#' @param nFig (integer) number of figures to be arrages on single plotting surface (ie window or plotting device)
#' @param returnMatr (logical) will return matrix ready for use by \code{\link[graphics]{layout}}; returns vector with nRow and nCol if \code{=FALSE}
#' @param horiz (logical) will priviledge horizontal layout if \code{TRUE}
#' @param figNcol (integer) optional number of columns
#' @param byrow (logical) toggle if output is in order of rows or columns (equivament to \code{\link[base]{matrix}}
#' @param silent (logical) suppress messages
#' @param debug (logical) additonal messages for debugging
#' @param callFrom (character) allows easier tracking of messages produced
#' @return matrix for use with \code{layout} or (if \code{returnMatr=FALSE} numeric vector with number of segements in x- an y-axis)
#' @seealso \code{\link[graphics]{layout}}
#' @examples
#' partitionPlot(5); partitionPlot(14,horiz=TRUE)
#' @export
partitionPlot <- function(nFig, returnMatr=TRUE, horiz=TRUE, figNcol=NULL, byrow=TRUE, silent=TRUE, debug=FALSE, callFrom=NULL) {
## function to create layout-matrix for multiple separate plots
## to do : test more non-square layouts for (near-)perfect fit to 'nFig'
fxNa <- wrMisc::.composeCallName(callFrom, newNa="partitionPlot")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(is.null(figNcol)) figNcol <- ceiling(sqrt(nFig))
figNrow <- ceiling(nFig/figNcol)
figDim <- c(ceiling(nFig/figNcol), figNcol)
if(figDim[2] < figDim[1] && horiz || figDim[2] > figDim[1] && !horiz) figDim <- figDim[2:1]
out <- if(returnMatr) matrix(1:(figDim[2]*figDim[1]), ncol=figDim[2], byrow=byrow) else figDim
if(debug) message(fxNa,"Figure as ",wrMisc::pasteC(if(returnMatr) dim(out) else figDim))
out }
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/partitionPlot.R
|
#' Separate and plot data by 2 groups
#'
#' Plot series of data as membership of 2 different grouping vectors (eg by grp=patient and grp2=age-group).
#'
#' @param dat (numeric) main data (may contain \code{NA})
#' @param grp (character or factor) grouping of columns of 'dat', eg replicate association
#' @param grp2 (character or factor) aadditional/secondary grouping of columns of 'dat'
#' @param col (character or integer) use custom colors, see also \code{\link[graphics]{par}}
#' @param pch (integer) symbol to mark group-center (see also \code{\link[graphics]{par}})
#' @param tit (character) custom title
#' @param cex (numeric) expansion factor for text (see also \code{\link[graphics]{par}})
#' @param lwd (integer) line-width (see also \code{\link[graphics]{par}})
#' @param lty (integer) line-type (see also \code{\link[graphics]{par}})
#' @param yLab (character) custom y-axis label
#' @param cexLab (numeric) expansion factor for labels: 1st value for main groups (\code{grp}, eg genotypes), 2nd for detailed text (\code{grp2}, eg animal IDs) (see also \code{\link[graphics]{par}})
#' @param sepLines (logical) optional drawing of horizontal lines aiming to separate groups (in analogy to support vectors)
#' @param silent (logical) suppress messages
#' @param debug (logical) additional messages for debugging
#' @param callFrom (character) allow easier tracking of messages produced
#' @return list with \code{$annot}, \code{$abund} for initial/raw abundance values and \code{$quant} with final normalized quantitations, or returns data.frame with annot and quant if \code{separateAnnot=FALSE}
#' @seealso \code{\link[utils]{read.table}}, \code{\link[wrMisc]{normalizeThis}})
#' @examples
#' set.seed(2020); rand1 <- round(runif(12),2) +rep(1:3,each=4)
#' plotBy2Groups(rand1, gl(2,6,labels=LETTERS[5:6]), gl(4,3,labels=letters[1:4]))
#'
#' @export
plotBy2Groups <- function(dat, grp, grp2=NULL, col=NULL, pch=NULL, tit=NULL, cex=2, lwd=0.5, lty=2, yLab=NULL, cexLab=NULL, sepLines=FALSE,silent=FALSE,debug=FALSE, callFrom=NULL) {
## plot indiv values as membership of 2 grouping vectors (eg by grp=patient and grp2=age-group)
fxNa <- wrMisc::.composeCallName(callFrom,newNa="plotBy2Groups")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
opar <- graphics::par(no.readonly=TRUE) # so far no commads used modifying parameters
namesXYZ <- c(deparse(substitute(dat)), deparse(substitute(grp)), deparse(substitute(grp2)))
## check for undefined elments
if(length(grp2) <1) grp2 <- grp
dat0 <- dat <- as.numeric(dat)
chNaGrp <- is.na(grp) | is.na(grp2)
if(any(chNaGrp)) { if(all(chNaGrp)) stop(" No individual defined by both groups")
if(!silent) message(fxNa,"Remove ",sum(chNaGrp)," due to NAs in (one of the) groups")
dat <- dat[which(!chNaGrp)]
dat0 <- dat0[which(!chNaGrp)]
grp <- grp[which(!chNaGrp)]
grp2 <- grp2[which(!chNaGrp)]
}
## add'l step to check if grp2 is in correct order ... ?
zz <- as.numeric(as.factor(grp))
chBr <- sum(zz[-1] - zz[-length(zz)] !=0) >= length(unique(zz))
if(chBr) { # update order of grp
chOrd1 <- order(grp)
grp <- grp[chOrd1]
grp2 <- grp2[chOrd1]
dat <- dat[chOrd1]
dat0 <- dat0[chOrd1]
}
if(length(grp2) < length(dat0)) stop(" 'grp2' not matching 'dat'")
## work with grp2 (eg group of patients)
nGrp2 <- table(grp2)[rank(unique(grp2))]
grp2ctr <- cumsum(nGrp2) -sapply(nGrp2, function(x) mean(0:(x-1), na.rm=TRUE))
grp2b <- rep(1:length(unique(grp2)), nGrp2) # same regrouping but starts at 1 and increases by 1
## organize dat by grp2
dat <- by(as.numeric(dat), grp2b, as.numeric) # ranking remaines
names(dat) <- names(nGrp2)
## work with grp (eg group 'age-class', already organized by grp2)
grp3 <- tapply(grp2, grp, function(x) unique(x))
grp3 <- grp3[match(unique(grp), names(grp3))]
nGrp3 <- sapply(grp3, length)
grp3ctr <- cumsum(nGrp3) -sapply(nGrp3, function(x) mean(0:(x-1), na.rm=TRUE))
## prepare for plot
if(is.null(col)) col <- as.numeric(as.factor(grp))
if(is.null(pch)) pch <- as.numeric(as.factor(grp))
if(length(cexLab) <2) cexLab <- c(0.9,0.7)
if(is.null(tit)) tit <- paste(namesXYZ[1]," organized by ",if(sum(nchar(namesXYZ[2:3])) > 19) "two factors" else paste(namesXYZ[2],"and",namesXYZ[3]))
graphics::plot(grp2b, unlist(dat), col=col, pch=pch,main=tit,cex=2,las=1,xaxt='n',xlab="",ylab=yLab)
graphics::mtext(at=unique(grp2b), names(grp2ctr),cex=0.7,side=1,col=col[grp2ctr]) # animal no
graphics::mtext(at=grp3ctr, names(grp3ctr), cex=0.9,side=1,line=1.5,col=unique(col)) # genotype
## separation lines
if(sepLines) {
datG <- by(dat0, grp, as.numeric)
datG <- datG[match(unique(grp), names(datG))]
datGr <- sapply(datG, range, na.rm=TRUE)
ra0 <- datGr[,-1] - datGr[2:1, -ncol(datGr)]
if(length(dim(ra0)) <2) ra0 <- as.matrix(ra0)
ch <- if(length(dim(ra0)) >1) abs(ra0[1,]) < abs(ra0[2,]) else abs(ra0[1]) < abs(ra0[2])
sepLi <- apply(cbind(1:(ncol(datGr)-1), 1 +ch),1,function(x) datGr[x[2], x[1]] + ra0[3-x[2], x[1]]/2)
graphics::abline(h=sepLi, col=unique(col)[1:length(sepLi)], lty=lty, lwd=lwd)
}
}
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/plotBy2Groups.R
|
#' Plot linear regression and confidence interval of regression
#'
#' This function provides help to display a series of bivariate points given in 'dat' (multiple data formats possible), to model a linear regression and plot the results.
#' Furthermore, a confidence interval to the regression may be added to the plot, regression parameters get be displayed.
#'
#' @param dat (numeric, data.frame or list) main data to plot/inspect. If numeric 'dat' will be used as dependent variable (y-data)
#' together with numeric 'indepVarLst' (independent variable); if list, then list-elments \code{indepVarLst} and \code{dependVar} will be used; if matrix, the the 1st and 2nd colum will be used
#' @param indepVarLst (character) if 'dat' is list, this designes the list element with the explanatory or independent variable (ie the variable used for explaining, typically x-data)
#' @param dependVar (character) if 'dat' is list, this designes the list element with dependent variable (ie the variable to be explained, typically y-data) to test
#' @param cusTxt (character) optional custom text to display in subtitle (instead of p-value to H0: slope.regression=0)
#' @param regrLty (integer) line type for regression
#' @param regrLwd (integer) line width for regression
#' @param regrCol (integer) color of regression-line
#' @param confInt (numeric, between 0 and 1) the probabiity alpha for the regression interval, if \code{NULL} no confidence intervall will be plotted/calculated
#' @param confCol (character) (background) color for confidence-interval
#' @param xLab (character) optional custom x-label
#' @param yLab (character) optional custom y-label
#' @param xLim (numeric) custom limit for x-axis (see also \code{\link[graphics]{par}})
#' @param yLim (numeric) custom limit for y-axis (see also \code{\link[graphics]{par}})
#' @param tit (character) optional title
#' @param nSignif (integer) number of significant digits for regression parameters in subtitle of plot
#' @param col (integer or character) custom color for points (choose \code{NULL} for not plotting the actual data)
#' @param pch (integer or character) type of symbol for points (see also \code{\link[graphics]{par}})
#' @param silent (logical) suppress messages
#' @param debug (logical) additional messages for debugging
#' @param callFrom (character) allow easier tracking of messages produced
#' @return This functions simply plots (to the current graphical devce); an invisible list containing $data, $linRegr, $confInterval (if calculated) may be returned, too
#' @seealso \code{\link[wrMisc]{exclExtrValues}} for decision of potential outliers; \code{\link[graphics]{hist}}, \code{\link{vioplotW}}
#' @examples
#' set.seed(2020); dat1 <- rep(1:6,each=2) +runif(12,0,1)
#' plotLinReg(dat1, gl(6,2))
#' ## extract elements out of list :
#' li2 <- list(aa=gl(5,2), bb=dat1[1:10])
#' plotLinReg(li2, indepVarLst="aa", dependVar="bb")
#' @export
plotLinReg <- function(dat, indepVarLst=NULL, dependVar=NULL, cusTxt=NULL, regrLty=1, regrLwd=1, regrCol=1, confInt=0.95,
confCol=NULL, xLab=NULL, yLab=NULL, xLim=NULL, yLim=NULL, tit=NULL, nSignif=3, col=1, pch=1, silent=FALSE, debug=FALSE, callFrom=NULL) {
## plot linear regression for single gene/protein based on list containing data & annotation for multiple proteins/genes/elements
##
argNa <- c(deparse(substitute(dat)), deparse(substitute(indepVarLst)), deparse(substitute(dependVar)))
fxNa <- wrMisc::.composeCallName(callFrom, newNa="plotLinReg")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
opar <- graphics::par(no.readonly=TRUE)
asNumDf <- function(x, colNa=c("x","y")) {
## check matrix or data.frame with 2 columns if numeric, try to convert to data.frame of 2 numeric
if(!is.data.frame(x)) x <- as.data.frame(x[,1:2], stringsAsFactors=FALSE)
if(length(colNa) !=2) stop("Argument 'colNa' must be of length=2")
chNum <- c(is.numeric(x[,1]), is.numeric(x[,2])) # check for factors
if(any(!chNum)) for(i in which(!chNum)) {
num <- try(wrMisc::convToNum(x[,i], spaceRemove=TRUE, remove=NULL, silent=silent, callFrom=fxNa), silent=TRUE)
if("character" %in% class(num)) {
num <- as.numeric(as.character(as.factor(x[,i])))
warning("Trouble converting column no ",i," to numeric (",wrMisc::pasteC(utils::head(x[,i])),", interpreted as ",wrMisc::pasteC(utils::head(num)),")") }
x[,i] <- num }
colnames(x) <- colNa
x }
extrFromList <- function(x, yy, zz, colNa=c("x","y")) {
## look for list-elements names 'yy' & 'zz', use their content ('yy' as 'x' and 'zz' as 'y')
if(all(is.integer(c(yy[1],zz[1])))) {
if(any(c(yy[1],zz[1]) <1) || length(x) < max(c(yy[1],zz[1]))) stop(" index values for list-elements of 'x' out of range")
} else {
## thus yy& zz are considered/tested as names of x
msg <- "both arguments 'yy' and 'zz' must correspond to list-elements of 'x'"
if(length(yy) <1) stop(msg)
if(length(zz) <1) { # if 'zz' NULL, try to extract 1st & 2nd col of x$yy
isBad <- TRUE
if(length(dim(x[[yy]])) >1) if(ncol(x[[yy]]) >1) { isBad <- FALSE
x <- as.data.frame(x[[yy]][,1:2], stringsAsFactors=FALSE) }
if(isBad) stop(msg)
} else {
chNa1 <- c(yy[1], zz[1]) %in% names(x)
if(!all(chNa1)) stop("Cannot find ",wrMisc::pasteC(c(yy[1],zz[1])[which(!chNa1)], quoteC="'")," in list 'x'")
x <- data.frame(x[[yy]], x[[zz]], stringsAsFactors=FALSE)}
}
colnames(x) <- colNa
x }
extrFromMatr <- function(x, yy, zz, name1=c("y","ordinate","dat","measure","pred","depend"), name2=c("x","abscissa","grp","grp2","dat2","obs","indep"),
colNa=c("x","y"), silent=silent, fxNa=fxNa) {
## extract column specified in 'zz' or look among names in 'name1'
## if no name found for 'yy' just avoid using using the column found for 'zz'
chColNa1 <- wrMisc::extrColsDeX(x, extrCol=list(if(is.null(zz)) name1 else zz), doExtractCols=FALSE, callFrom=fxNa,silent=silent)
chColNa2 <- wrMisc::extrColsDeX(x, extrCol=list(if(is.null(yy)) name2 else yy), doExtractCols=FALSE, callFrom=fxNa,silent=silent)
if(!all(chColNa1,chColNa2)) stop("Cannot find column-names to use from 'x'")
x <- data.frame(x[,if(length(chColNa2) >0) chColNa2[1] else { if(chColNa1[1]==2) 1 else chColNa1[1]+1}], x[,chColNa1[2]],stringsAsFactors=FALSE)
colnames(x) <- colNa
x }
##
msg <- df0<- NULL # initialize
## check main input : see if matrix providing x & y
if(length(dat) <1) {
msg <- c(" incomplete data, nothing to do")
} else {
if(!is.list(dat) && length(dat) >2 && length(indepVarLst) >2 && length(dim(dat)) <1 && length(dim(indepVarLst)) <1) {
## simplest case: both x & y as separate numeric vector (of same length)
if(length(dat) !=length(indepVarLst)) stop("Length of 'dat' and 'indepVarLst' don't match !")
df0 <- data.frame(x=indepVarLst, y=dat, stringsAsFactors=FALSE)
argNa[4:5] <- argNa[2:1]
} else {
## if S3 (from limma) or (other) list, need to locate-list-elements
if(is.list(dat)) {
df0 <- extrFromList(dat, indepVarLst, dependVar)
argNa[4:5] <- argNa[2:3]
} else {
## dat is not a list, assume dat is matrix
if(length(dim(dat)) >1) { if(ncol(dat) >1) {
df0 <- extrFromMatr(dat, indepVarLst, dependVar, silent,fxNa)
} else {
## dat is neiter a matrix, try extracting 1st col of indepVarLst
df0 <- data.frame(x=if(length(dim(indepVarLst)) >1) indepVarLst[,1] else indepVarLst, y=dat, stringsAsFactors=FALSE) }
argNa[4:5] <- argNa[2:3]
} else msg <- "unknown format of 'dat'" }}}
## check if plot can be produced
if(length(msg) >0 || length(df0) <1) message(fxNa,"Can't plot",msg) else {
## make linear model
df0 <- asNumDf(df0)
lm0 <- stats::lm(y ~ x, data=df0)
if(length(lm0$coefficients) >2) message(fxNa,"Bizzare : The regression model was expected as 2 coefficients, but has ",
length(lm0$coefficients)," coefficients ",wrMisc::pasteC(names(lm0$coefficients),quoteC="'"))
## start plotting
argNa[4:5] <- gsub("\"","",argNa[4:5]) # remove protected 'double' quotes
if(is.null(xLab)) xLab <- if(argNa[4]=="NULL") "x" else argNa[4] # explanatory variable
if(is.null(yLab)) yLab <- if(argNa[5]=="NULL" | argNa[5]==xLab) "y" else argNa[5]
tmp <- try(graphics::plot(y ~ x, data=df0, las=1, xlab=xLab, ylab=yLab, pch=pch,col=col, main=tit), silent=TRUE)
if(inherits(tmp, "try-error")) warning(fxNa," Plot cannot be produced") else {
graphics::abline(lm0, lty=regrLty, lwd=regrLwd, col=regrCol)
suplTx <- paste(c("; ",if(length(cusTxt) <1) paste("p.slope =",signif(stats::coef(summary(lm0))[2,"Pr(>|t|)"],2)) else cusTxt), collapse=" ")
graphics::mtext(paste("regression (rounded): y =",signif(stats::coef(lm0)[2],nSignif)," x +",signif(stats::coef(lm0)[1],nSignif),suplTx,
", r2=",signif(stats::cor(df0$y,df0$x)^2,nSignif)),cex=0.75,line=0.15)
if(length(confInt) >0) { ra <- c(range(df0$x,na.rm=TRUE), abs(mean(df0$x,na.rm=TRUE)))
newx <- seq(ra[1]-0.05*ra[3],ra[2]+0.05*ra[3],length.out=200)
if(length(confCol) <1) confCol <- grDevices::rgb(0.3,0.3,0.3,0.07) # (background) color for confidence-interval
confInterval <- stats::predict(lm0, newdata=data.frame(x=newx), interval="confidence", level=confInt) # can do single conf interv at a time ..
graphics::polygon(cbind(x=c(newx,rev(newx)),y=c(confInterval[,"lwr"],confInterval[length(newx):1,"upr"])),col=confCol,border=NA)
graphics::points(y ~ x, df0, col=col)
graphics::mtext(paste(" confidence interval at ",100*confInt,"% shown"), line=-1.05,cex=0.65,adj=0,col=wrMisc::convColorToTransp(confCol,alph=240)) } }
}
invisible(list(data=df0,linRegr=lm0,if(length(confInt) >0) confInterval=confInterval)) }
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/plotLinReg.R
|
#' PCA plot with bag-plot to highlight groups
#'
#' @description
#' This function allows to plot \href{https://en.wikipedia.org/wiki/Principal_component_analysis}{principal components analysis (PCA)},
#' with options to show center and potential outliers for each of the groups (columns of data).
#' The main points of this implementation consist in offering bagplots to highlight groups of columns/samples and support to (object-oriented)
#' output from \href{https://bioconductor.org/packages/release/bioc/html/limma.html}{limma} and \href{https://CRAN.R-project.org/package=wrProteo}{wrProteo}.
#'
#' @details
#' One motivation for this implementation of plotting PCA was to provide a convenient way for doing so with of MArrayLM-objects or lists
#' as created by \href{https://bioconductor.org/packages/release/bioc/html/limma.html}{limma} and \href{https://CRAN.R-project.org/package=wrProteo}{wrProteo}.
#'
#' Another motivation for this implementation come from integrating the idea of bag-plots to better visualize different groups of points
#' (if they can be organized so beforehand as distinct groups) :
#' The main body of data is shown as 'bag-plots' (a bivariate boxplot, see \href{https://en.wikipedia.org/wiki/Bagplot}{Bagplot})
#' with different transparent colors to highlight the core part of different groups (if they contain more than 2 values per group).
#' Furthermore, group centers are shown as average or median (see 'nGrpForMedian') with stars & index-number (if <25 groups).
#'
#' Layout is automatically set to 2 or 4 subplots (if plotting more than 2 principal components makes sense).
#'
#' Note : This function uses \code{\link[stats]{prcomp}} for calculating Eigenvectors and principal components, with default \code{center=TRUE} and \code{scale.=FALSE} (different to \code{princomp()}. which standardizes by default).
#' This way the user has to option to intervene on arguments \code{center} and \code{scale.}. However, this should be done with care.
#'
#' Note: \code{NA}-values cannot (by definition) be processed by (any) PCA - all lines with any non-finite values/content (eg \code{NA}) will be omitted !
#'
#' Note : Package RColorBrewer may be used if available.
#'
#' For more options with PCA (and related methods) you may also see also the package \href{https://CRAN.R-project.org/package=FactoMineR}{FactoMineR}
#' which provides a very wide spectrum of possibiities, in particular for combined numeric and categorical data.
#'
#' @param dat (matrix, data.frame, MArrayLM-object or list) data to plot. Note: \code{NA}-values cannot be processed - all lines with non-finite data (eg \code{NA}) will be omitted !
#' In case of MArrayLM-object or list \code{dat} must conatain list-element named 'datImp','dat' or 'data'.
#' @param sampleGrp (character or factor) should be factor describing groups of replicates, NAs are not supported
#' @param tit (character) custom title
#' @param useSymb (integer) symbols to use (see also \code{\link[graphics]{par}})
#' @param center (logical or numeric) decide if variables should be shifted to be zero centered, argument passed to \code{\link[stats]{prcomp}}
#' @param scale. (logical or numeric) decide if scaling to obtain unit variance, argument passed to \code{\link[stats]{prcomp}}
#' Alternatively, a vector of length equal the number of columns of x can be supplied. The value is passed to scale.
#' @param colBase (character or integer) use custom colors
#' @param useSymb2 (integer) symbol to mark group-center (no mark of group-center if default NULL) (equivalent to \code{pch}, see also \code{\link[graphics]{par}})
#' @param cexTxt (integer) expansion factor for text (see also \code{\link[graphics]{par}})
#' @param cexSub (integer) expansion factor for subtitle line text (see also \code{\link[graphics]{par}})
#' @param displBagPl (logical) if \code{TRUE}, show bagPlot (group-center) if >3 points per group otherwise the average-confidence-interval
#' @param outCoef (numeric) parameter for defining outliers, see \code{\link{addBagPlot}} (equivalent to \code{range} in \code{\link[graphics]{boxplot}})
#' @param getOutL (logical) return outlyer samples/values
#' @param showLegend (logical or character) toggle to display legend, if character it designes the location within the plot to display the legend ('bottomleft','topright', etc..)
#' @param nGrpForMedian (integer) decide if group center should be displayed via its average or median value: If group has less than 'nGrpForMedian' values, the average will be used, otherwise the median; if \code{NULL} no group centers will be displayed
#' @param pointLabelPar (character) define formatting for optional labels next to points in main figure (ie PC1 vs PC2); may be \code{TRUE} or list containing elments 'textLabel', 'textCol', 'textCex',
#' 'textOffSet', 'textAdj' for fine-tuning
#' @param rowTyName (character) for subtitle : specify nature of rows (genes, proteins, probesets,...)
#' @param rotatePC (integer) optional rotation (by -1) for fig&ure of the principal components specified by index
#' @param suplFig (logical) to include plots vs 3rd principal component (PC) and Screeplot
#' @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 make a plot and may retiurn an optional matrix of outlyer-data (depending on argument \code{getOutL})
#' @seealso \code{\link[stats]{prcomp}} (used here for the PCA underneith) , \code{\link[stats]{princomp}}, see the package \href{https://CRAN.R-project.org/package=FactoMineR}{FactoMineR} for multiple plotting options or ways of combining categorical and numeric data
#' @examples
#' set.seed(2019); dat1 <- matrix(round(c(rnorm(1000), runif(1000,-0.9,0.9)),2),
#' ncol=20, byrow=TRUE) + matrix(rep(rep(1:5,6:2), each=100), ncol=20)
#' biplot(prcomp(dat1)) # traditional plot
#' (grp = factor(rep(LETTERS[5:1],6:2)))
#' plotPCAw(dat1, grp)
#' @export
plotPCAw <- function(dat, sampleGrp, tit=NULL, useSymb=c(21:25,9:12,3:4), center=TRUE, scale.=TRUE, colBase=NULL, useSymb2=NULL,
cexTxt=1, cexSub=0.6, displBagPl=TRUE, outCoef=2, getOutL=FALSE, showLegend=TRUE, nGrpForMedian=6, pointLabelPar=NULL, rowTyName="genes",
rotatePC=NULL, suplFig=TRUE, callFrom=NULL, silent=FALSE, debug=FALSE) {
## note : so far not well adopted for plotting all points in transparent grey with same symb for interactive mouse-over
fxNa <- wrMisc::.composeCallName(callFrom, newNa="plotPCAw")
msg <- " 'dat' must be matrix, data.frame (with at least 1 line and 2 columns) or list/MArrayLM-object (with element 'datImp','dat' or 'data' as matrix or data.frame)"
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if("MArrayLM" %in% class(dat) || is.list(dat)) { chDat <- c("datImp","dat","data","quant","datRaw") %in% names(dat)
chGr <- c("groups","grp","sampleGroups") %in% names(dat)
if(any(chGr, na.rm=TRUE) && length(sampleGrp) <1) {
chGrpNa <- c("groups","grp","sampleGroups")
sampleGrp <- dat[[which(names(dat) %in% chGrpNa)[1]]]
} else if("sampleSetup" %in% names(dat)) if(any(chGrpNa %in% names(dat$sampleSetup), na.rm=TRUE)) {
sampleGrp <- dat$sampleSetup[[ which(chGrpNa %in% names(dat$sampleSetup))[1]]] }
if(any(chDat, na.rm=TRUE)) dat <- dat[[which(names(dat) %in% c("datImp","dat","data","datRaw"))[1]]] else stop(msg) }
if(any(length(dim(dat)) !=2, dim(dat) < 1:2, na.rm=TRUE)) stop(msg)
if(length(sampleGrp) <1 || sum(is.na(sampleGrp))==length(sampleGrp)) stop("Argument 'sampleGrp' seems to be empty (or all NA)")
if(length(sampleGrp) != ncol(dat)) stop(fxNa,"Length of argument 'sampleGrp' must match number of columns of 'dat'")
if(!is.factor(sampleGrp)) sampleGrp <- as.factor(sampleGrp)
if(!isFALSE(center)) center <- TRUE
if(!isFALSE(scale.)) scale. <- TRUE
if(!isFALSE(suplFig)) suplFig <- TRUE
nGrpLim <- 25 # decide/limit if group-centers are shown as stars
## reduce to columns defined by 'sampleGrp' (groups declared as NA will be removed) and to columns with finite data
if(length(dat) >0) {
dat <- dat[,!is.na(sampleGrp)]
chFin <- is.finite(dat)
chCol <- colSums(chFin) <2
if(sum(chCol) >0) {
dimIni <- dim(dat)
if(!silent) message(fxNa,"Removing ",sum(chCol)," (out of ",ncol(dat),") columns with less than 2 finite values")
dat <- dat[,which(!chCol)]
chFin <- chFin[,which(!chCol)]
if(ncol(dat) <2) stop("After removing bad (non-finite) columns less than 2 columns remain !")
sampleGrp <- sampleGrp[which(!chCol)]
if(length(useSymb) == dimIni[2]) useSymb <- useSymb[which(!chCol)] }
opar <- graphics::par(no.readonly=TRUE)
if(suplFig && ncol(dat) > 3) on.exit(opar) else {
opar2 <- opar[which(names(opar) %in% c("mar","mfrow"))]
on.exit(opar2)
}
if(debug) {message(fxNa,"plotPCAw_1") }
## remove rows with NAs
chRow <- rowSums(!chFin) # check for lines with non-finite values (avoid error during svd/pca ..)
if(any(chRow >0, na.rm=TRUE)) if(sum(chRow >0) ==nrow(dat)) stop("All lines have some non-finite values !?!") else {
if(!silent) message(fxNa,"Eliminating ",sum(chRow >0)," (out of ",nrow(dat),") lines with non-finite values")
dat <- dat[which(chRow <1),] }
## remove 0 variance rows
isZeroVar <- function(x) length(unique(wrMisc::naOmit(x)))==1
ch1 <- apply(dat, 1, isZeroVar)
if(any(ch1, na.rm=TRUE)) {
if(!silent) message(fxNa,"Eliminating ",sum(ch1)," (out of ",nrow(dat),") lines with 0 variance values (ie all values identical)")
dat <- dat[which(ch1),] }
averNa3 <- wrMisc::naOmit(sampleGrp)
if(suplFig && ncol(dat) > 3) graphics::layout(matrix(c(1,1:3,4,4),3,2,byrow=TRUE), heights=c(10,5,4))
if(!identical(ncol(dat),length(wrMisc::naOmit(sampleGrp))) && !silent) warning("'plotPCA': number of columns and number of (QC-filtered) arrays in 'AverNa2' don't match !")
nGrp <- length(levels(sampleGrp))
if(!is.null(colBase)) if(length(colBase) != nGrp) {
if(!silent) message(fxNa,"Ignore invalid 'colBase', expecting length ",nGrp)
colBase <- NULL }
chPa <- requireNamespace("RColorBrewer", quietly=TRUE)
if(!silent && !chPa) message(fxNa,"Please install package 'RColorBrewer' for improved color-gradients")
if(is.null(colBase)) colBase <- if(nGrp <10 && chPa) { RColorBrewer::brewer.pal(max(3,nGrp),"Set1")[1:nGrp]
} else {
grDevices::rainbow(1.5 +nGrp*1.08)[1:(nGrp+1)][-ceiling(length(levels(sampleGrp))/2)]}
useCol <- colBase[order(as.numeric(unique(averNa3)))]
chGr <- duplicated(sampleGrp)
if(!any(chGr, na.rm=TRUE)) { displBagPl <- FALSE; if(debug) message(fxNa,"All samples belong to different groups, can't plot bagplots ...")}
if(!identical(unique(table(averNa3)), as.integer(1))) useCol <- useCol[as.numeric(wrMisc::naOmit(sampleGrp))]
if(debug) {message(fxNa,"plotPCAw_3") }
}
## MAIN
if(length(dat >0)) { pca <- try(stats::prcomp(t(dat), center=center, scale.=scale.), silent=TRUE)
if(inherits(pca, "try-error")) {dat <- NULL; pca <- NULL}}
if(length(dat) >0) {
percVar <- 100*round(pca$sdev^2/sum(pca$sdev^2),3)
pca.grpMed <- pca.grpAv <- matrix(nrow=nGrp, ncol=min(4,ncol(pca$x)))
tabAverNa3 <- table(averNa3)
if(length(nGrpForMedian) >0) { for(i in 1:min(4,ncol(pca$x))) {
pca.grpMed[,i] <- unlist(tapply(pca$x[,i], averNa3, stats::median, na.rm=TRUE))
pca.grpAv[,i] <- unlist(tapply(pca$x[,i], averNa3, mean, na.rm=TRUE)) }
rownames(pca.grpMed) <- rownames(pca.grpAv) <- unique(averNa3)
pca.grpMed[names(tabAverNa3)[which(tabAverNa3 <nGrpForMedian)],] <- pca.grpAv[names(tabAverNa3)[which(tabAverNa3 < nGrpForMedian)],]}
if(debug) {message(fxNa,"plotPCAw_4 .. displLeg: ",displLeg);
plotPCAw_4 <- list(dat=dat,sampleGrp=sampleGrp,averNa3=averNa3,pca=pca,pca.grpMed=pca.grpMed,center=center,scale.=scale.,tit=tit,cexTxt=cexTxt,useSymb=useSymb ) }
useCex <- round( (1/nGrp +0.65)*cexTxt, 2)
useSymb.ori <- rep(useSymb, 1 +length(levels(sampleGrp)) %/% length(useSymb)) [1:length(levels(sampleGrp))] #
useSymb <- (useSymb.ori[order(unique(as.numeric(averNa3)))] )[as.numeric(wrMisc::naOmit(sampleGrp))]
useTxtCol <- 1
figNumOffs <- function(pca, cols=c(1,2), fact=100) signif(c(abs(diff(range(pca$x[,cols[1]])))/fact, abs(diff(range(pca$x[,cols[2]])))/fact), digits=3)
outL <- list()
length(outL) <- length(unique(averNa3)); names(outL) <- unique(averNa3)
lab123 <- paste0("PC",1:3," (",percVar[1:3],"%)")
useTit <- if(is.null(tit)) "Principal Components of Samples" else tit
if(suplFig) useTit <- paste(useTit, if(nchar(useTit) < 35) ": 1st and 2nd Component" else ", PC1 & PC2")
## optional rotate axis
if(length(rotatePC) >0 && is.numeric(rotatePC)) {
chRo <- rotatePC >0 && rotatePC <= ncol(dat)
if(any(!rotatePC, na.rm=TRUE)) rotatePC <- rotatePC[which(rotatePC)]
if(length(rotatePC) >0) pca$x[,rotatePC] <- -1*pca$x[,rotatePC] }
if(debug) {message(fxNa,"plotPCAw_5 .. lab123: ",wrMisc::pasteC(lab123)); plotPCAw_5 <- list(dat=dat,sampleGrp=sampleGrp,averNa3=averNa3,pca=pca,useTit=useTit,cexTxt=cexTxt,showLegend=showLegend ) }
## start plot
ch1 <- try(graphics::plot(pca$x[,c(1,2)], main=useTit, cex.axis=0.7*cexTxt, cex.lab=cexTxt*0.75, cex.main=if(ncol(dat) > 3) 1.4 else 0.85, xlab=lab123[1], ylab=lab123[2], las=1, type="n")) # empty plot
if(inherits(ch1, "try-error")) {dat <- NULL; message(fxNa,"UNABLE TO DRAW PLOT !! check current plotting device...")} }
if(length(dat) >0) {
## check for legend-location (if legend should be drawn)
if(is.character(showLegend) && length(showLegend)==1) {
chL <- showLegend %in% c("bottomleft","bottomright","topright","topleft")
if(!chL) showLegend <- TRUE
}
displLeg <- if(is.logical(showLegend)) {if(showLegend) checkForLegLoc(matr=pca$x, sampleGrp=sampleGrp, showLegend=showLegend, suplSpace=5.5, silent=silent,callFrom=callFrom) else list(FALSE)
} else { if(is.character(showLegend)) list(TRUE, showLegend) else list(FALSE)}
if(debug) {message(fxNa,"plotPCAw_5b .. displLeg: ",displLeg); plotPCAw_5 <- list(dat=dat,sampleGrp=sampleGrp,averNa3=averNa3,pca=pca,useTit=useTit,cexTxt=cexTxt,lab123=lab123,displLeg=displLeg ) }
if(displLeg[[1]] && showLegend) graphics::legend(displLeg[[2]], pch=useSymb.ori, col=colBase,
paste(1:length(levels(sampleGrp)),"..",substr(unique(averNa3),1,25)), text.col=colBase,
cex=cexTxt*max(0.4, round(0.75 -((length(unique(sampleGrp)) %/% 5)/31),3)), xjust=0.5, yjust=0.5)
graphics::points(pca$x[,c(1,2)], pch=useSymb,col=useCol,cex=0.8)
if(debug) { message(fxNa,"plotPCAw_6 .. displLeg: ",unlist(displLeg[1:2])) }
## prepare for labels on points
if(length(pointLabelPar) >0) {
chLe <- sapply(pointLabelPar, length) %in% c(1,ncol(dat))
if(any(!chLe, na.rm=TRUE) && !silent) message(fxNa,"Some elements of argument 'pointLabelPar' may have odd lengths, they might be discarded")
if(identical(pointLabelPar,TRUE)) .addTextToPoints(x=pca$x, cex=0.6*cexTxt, adj="auto") else {
if(length(pointLabelPar) >0) .addTextToPoints(x=pca$x, paramLst=pointLabelPar, cex=0.6*cexTxt, adj="auto") }}
if(debug) {message(fxNa,"plotPCAw_7 .. displBagPl=",displBagPl); plotPCAw_7 <- list(dat=dat,sampleGrp=sampleGrp,pca=pca,useTit=useTit,cexTxt=cexTxt,lab123=lab123,showLegend=showLegend,displLeg=displLeg,
nGrp=nGrp,averNa3=averNa3,pointLabelPar=pointLabelPar,colBase=colBase,
outCoef=outCoef,useSymb2=useSymb2,nGrpForMedian=nGrpForMedian,nGrpLim=nGrpLim,displBagPl=displBagPl,pca.grpMed=pca.grpMed,figNumOffs=figNumOffs, callFrom=callFrom,fxNa=fxNa, silent=silent, debug=debug)}
## prepare for bagplot
for(i in 1:length(levels(sampleGrp))) {
useCol2 <- grDevices::rgb(t(grDevices::col2rgb(colBase[order(as.numeric(unique(averNa3)))][i])/256),
alpha=if(max(table(sampleGrp)) > 2) signif(0.04 +0.25/nGrp, digits=3) else 0.1)
dispOut <- length(unlist(pointLabelPar)) <1
outli <- if(displBagPl) addBagPlot(pca$x[which(as.numeric(wrMisc::naOmit(sampleGrp)) %in% i), 1:2], bagCol=useCol2, outCoef=outCoef,
ctrPch=useSymb2, returnOutL=TRUE, outlCol=useCol2, addSubTi=length(pointLabelPar >0) , callFrom=fxNa, silent=silent, debug=debug) else NULL
if(length(outli) >0) outL[[i]] <- outli }
if(debug) {message(fxNa,"plotPCAw_7.",i," .. displBagPl=",displBagPl) }
if(length(nGrpForMedian) >0 && length(levels(sampleGrp)) < nGrpLim & !is.null(useSymb2)) { # display of group-center (number & )
cexCtr <- if(cexTxt <=1) useCex +0.2 else useCex
if(!displBagPl && any(duplicated(sampleGrp), na.rm=TRUE)) { # add group-centers for those where multiple replicates/points were drawn (if not drawn by addBagPot)
## which points have replicates ? set point not needed to draw as pch as NA
pch1 <- useSymb; col1 <- useCol # indiv points
if(!all(duplicated(sampleGrp))) pch1 <- rep(NA,length(pch1))
if(any(duplicated(sampleGrp), na.rm=TRUE)) pch1[ which(!duplicated(sampleGrp, fromLast=TRUE) & !duplicated(sampleGrp, fromLast=FALSE)) ] <- NA
graphics::points(pca.grpMed[,c(1,2)], col=useCol, pch=pch1, cex=1.7) # draw group-means as same color, but bigger symbol
}
graphics::text(pca.grpMed[,c(1,2)] + 1.1*figNumOffs(pca, cols=c(1,2)), # group-center names
as.character(1:nGrp)[order(as.numeric(unique(averNa3)))], cex=cexCtr, font=2,col=1) }
if(debug) {message(fxNa,"plotPCAw_8") }
## subtitle
graphics::mtext(paste0("n=",nrow(dat)," ",rowTyName, " ; Samples shown as open symbols",
if(isTRUE(pointLabelPar)) ", color stars and black numbers for group-centers",
if(displBagPl) ", groups highlighted as bagplot"), cex=cexSub, line=0.25)
## add more plots to include 3rd PC
if(suplFig && ncol(dat) > 3) {
graphics::plot(pca$x[,c(2,3)], pch=useSymb, main="PCA : 2nd and 3rd Component", col=useCol, cex=0.6, cex.axis=0.6*cexTxt, cex.lab=cexTxt*0.7, xlab=lab123[2], ylab=lab123[3], las=1 )
for(i in 1:length(unique(sampleGrp))) {
useCol2 <- grDevices::rgb(t(grDevices::col2rgb(colBase[order(as.numeric(unique(averNa3)))][i])/256), alpha=if(max(table(sampleGrp)) > 2) signif(0.04 +0.25/nGrp,digits=3) else 0.1)
if(displBagPl) addBagPlot(pca$x[as.numeric(averNa3) %in% i,c(2,3)], outCoef=outCoef, bagCol=useCol2, ctrPch=useSymb2, returnOutL=FALSE, silent=silent, debug=debug) }
if(length(nGrpForMedian) >0 && length(levels(sampleGrp)) < nGrpLim & !is.null(useSymb2)) {
graphics::points(pca.grpMed[,c(2,3)], col=colBase[order(as.numeric(unique(averNa3)))], pch=useSymb2, cex=1.1)
cexCtr2 <- if(cexTxt <=1) useCex -0.1 else useCex
graphics::text(pca.grpMed[,c(2,3)]+ 1.7*figNumOffs(pca, cols=c(2,3)), as.character(1:nGrp)[order(as.numeric(unique(averNa3)))], cex=cexCtr2, col=1) }
graphics::plot(pca$x[,c(1,3)], pch=useSymb, main="PCA : 1st and 3rd Component", col=useCol, cex=0.6, cex.axis=0.6*cexTxt, cex.lab=cexTxt*0.7, xlab=lab123[1], ylab=lab123[3],las=1 )
for(i in 1:length(unique(sampleGrp))) {
useCol2 <- grDevices::rgb(t(grDevices::col2rgb(colBase[order(as.numeric(unique(averNa3)))][i])/256), alpha=if(max(table(sampleGrp)) > 2) signif(0.04+0.25/nGrp,digits=3) else 0.1)
if(displBagPl) addBagPlot(pca$x[as.numeric(averNa3) %in% i,c(1,3)], outCoef=outCoef, bagCol=useCol2,ctrPch=useSymb2,returnOutL=FALSE,silent=TRUE) }
if(length(nGrpForMedian) >0 && length(levels(sampleGrp)) < nGrpLim & !is.null(useSymb2)) {
graphics::points(pca.grpMed[,c(1,3)],col=colBase[order(as.numeric(unique(averNa3)))], pch=useSymb2, cex=1.1)
graphics::text(pca.grpMed[,c(1,3)] +1.7*figNumOffs(pca, cols=c(1,3)), as.character(1:nGrp)[order(as.numeric(unique(averNa3)))], cex=useCex-0.1, col=1) }
}
if(suplFig) { graphics::plot(pca, main="Screeplot on Variance Captured by the Principal Components", cex.main=if(ncol(dat) > 3) 1.3 else 0.8, cex.axis=0.6*cexTxt )
graphics::mtext(at=(1.2*(1:length(pca$sdev)) -0.5)[1:min(10,ncol(dat))], as.character(1:length(pca$sdev))[1:min(10,ncol(dat))], cex=0.7, side=1) }
if(getOutL && !is.null(rownames(pca$x))) return(outL)
} else warning(fxNa,"OMIT plot ! Unable to calculate principal components !")
}
#' Add text to points on plot
#'
#' @description
#' This function allows to add custom text as lables to points on standard xy-plot.
#'
#' @param x (matrix, data.frame) coordinated of ponts on plot
#' @param paramLst (list) additional parameters for plotting (priority over separate cex or col), otherwise names displayed will be taken from 'labels' or rownames of coordinates 'x'
#' @param labels (character) the text to be displayed (has not priority over 'paramLst'), if nothing valid found numbers will be displayed
#' @param cex (character) (numeric) size of text, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param col (character or integer) use custom colors
#' @param adj (character) values other than 0,0.5 or 1 will lead to 'auto' where text is displayed only to left of sufficient space available
#' @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 make a plot and may retiurn an optional matrix of outlyer-data (depending on argument \code{getOutL})
#' @seealso \code{\link[stats]{prcomp}} (used here for the PCA underneith) , \code{\link[stats]{princomp}}, see the package \href{https://CRAN.R-project.org/package=FactoMineR}{FactoMineR} for multiple plotting options or ways of combining categorical and numeric data
#' @examples
#' set.seed(2019); dat1 <- matrix(round(runif(30),2), ncol=2)
#' plot(dat1) # traditional plot
#' .addTextToPoints(dat1, labels=letters[1:nrow(dat1)])
#' @export
.addTextToPoints <- function(x, paramLst=NULL, labels=NULL, cex=NULL, col=NULL, adj="auto", callFrom=NULL, silent=FALSE, debug=FALSE){
## add text at given position(s) to (scatter) plot (left top display), eg names describing points
## 'x' should be matrix or data.frame with numeric coordinates for plotting labels,
## paramLst may be list with additional parameters (priority over separate cex or col), otherwise names displayed will be taken from 'labels' or rownames of coordinates 'x'
## 'labels' .. for text to be displayed (has not priority over 'paramLst'), if nothing valid found numbers will be displayed
## 'adj' .. values other than 0,0.5 or 1 will lead to 'auto' where text is displayed only to left of sufficient space available
fxNa <- wrMisc::.composeCallName(callFrom, newNa=".addTextToPoints")
textCex <- textLabel <- textAdj <- textCol <- textOffSet <- NULL
if(length(dim(x)) !=2) message(fxNa," Trouble ahead, 'x' shound be matrix or data.frame of min 2 columns")
if(length(adj) >0) textAdj <- paramLst$textAdj <- adj
if(length(cex) >0) textCex <- cex
if(length(col) ==nrow(x) || length(col)==1) textCol <- col
textLabel <- if(length(labels) != length(x) ) names(x) else labels
if(debug) message(fxNa,"aTTP1")
if(is.list(paramLst) && length(paramLst) >0) {
textLabel <- if("labels" %in% names(paramLst)) paramLst$labels else {if(is.null(rownames(x))) 1:nrow(x) else rownames(x)}
if("textLabel" %in% names(paramLst)) textLabel <- paramLst$textLabel
if("col" %in% names(paramLst)) textCol <- paramLst$col
if("textCol" %in% names(paramLst)) textCol <- paramLst$textCol
if("cex" %in% names(paramLst)) textCex <- paramLst$cex
if("textCex" %in% names(paramLst)) textCex <- paramLst$textCex
if("offSet" %in% names(paramLst)) textOffSet <- paramLst$offSet
if("textOffSet" %in% names(paramLst)) textOffSet <- paramLst$textOffSet
if("adj" %in% names(paramLst)) textAdj <- paramLst$adj
if(is.null(names(paramLst)) & is.character(paramLst[[1]])) textLabel <- paramLst[[1]]
if("textAdj" %in% names(paramLst)) {
if(!any(c(0,0.5,1) %in% paramLst$textAdj, na.rm=TRUE)) {
strW <- graphics::strwidth(textLabel, cex=if("cex" %in% names(paramLst)) paramLst$cex else 1) + 0.2
chLe <- graphics::par("usr")[1] < x[,1] -strW
paramLst$textAdj <- 0 + chLe }
textAdj <- paramLst$textAdj }
} else {if(is.character(paramLst) && length(paramLst)==nrow(x)) textLabel <- paramLst}
if(length(textLabel) != nrow(x)) textLabel <- rownames(x)
if(is.null(textLabel)) textLabel <- 1:nrow(x)
if(length(textCol) <1) textCol <- rep(grDevices::grey(0.8), nrow(x)) else if(length(textCol) ==1) textCol <- rep(textCol, nrow(x))
if(length(textAdj) <1) textAdj <- 1:nrow(x)
if(length(textOffSet) <1) {ra <- graphics::par("usr"); textOffSet <- c(2,-4)*signif((ra[c(2,4)] - ra[c(1,3)])/300,3) }
textOffSet <- matrix(rep(textOffSet, each=nrow(x)), ncol=2)
if(0 %in% textAdj) textOffSet[,1] <- textOffSet[,1]*(2*textAdj -1)
if(length(unique(textAdj)) >1) { for(i in unique(textAdj)) { j <- which(textAdj==i)
graphics::text(x[j,c(1,2)] -textOffSet[j,], labels=textLabel[j], col=textCol[j], cex=textCex, adj=i)}
} else graphics::text(x[,c(1,2)] -textOffSet, labels=textLabel, col=textCol, cex=textCex, adj=textAdj) }
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/plotPCAw.R
|
#' x-y plot with 2 legends
#'
#' This is a modified version of \code{plot} for 2-dimensional data,
#' allowing to choose symbols and colors of points according to two additional columns of \code{dat}.
#'
#'
#'
#' @param dat (matrix or data.frame) main input
#' @param useCol (character or integer) columns form \code{dat}: The 1st and 2nd column are used as x- and y-axis
#' @param tit (character) optional custom title
#' @param subTi (character) optional custom subtitle
#' @param subCex (numeric) cex-like expansion factor for subtitle (see also \code{\link[graphics]{par}})
#' @param pch (integer) symbols to use for plotting (see also \code{\link[graphics]{par}}), will be associated to 4th column of \code{useCol}
#' @param xlim (numeric, length=2) x- axis limits (see also \code{\link[graphics]{par}})
#' @param ylim (numeric, length=2) y- axis limits (see also \code{\link[graphics]{par}})
#' @param xlab (character) custom x-axis label
#' @param ylab (character) custom x-axis label
#' @param ablines (list) optional horzontal and/or vertical gray dashed guide-lines
#' @param legendloc (character) location of legend (of symbols)
#' @param txtLegend (character) optional label for legend (of symbols)
#' @param histLoc (character) location of histomgram-legend (of 3rd column of \code{useCol})
#' @param legHiTi (character) optional title for histomgram-legend
#' @param silent (logical) suppress messages
#' @param debug (logical) additonal messages for debugging
#' @param callFrom (character) allows easier tracking of messages produced
#' @seealso (standard plots) \code{plot} from the package \code{base}
#' @return graphical output only
#' @examples
#' x1 <- cbind(x=c(2,1:7), y=8:1 +runif(8), grade=rep(1:4,2))
#' plotW2Leg(x1,useCol=c("x","y","y","grade"))
#' @export
plotW2Leg <- function(dat,useCol=c("logp","slope","medAbund","startFr"), tit=NULL, subTi=NULL, subCex=0.9, pch=21:25, xlim=NULL, ylim=NULL,
xlab=NULL, ylab=NULL, ablines=NULL, legendloc="topright", txtLegend=NULL, histLoc="bottomleft", legHiTi=NULL, silent=TRUE, debug=FALSE, callFrom=NULL) {
## plot with 2 extra legends
fxNa <- wrMisc::.composeCallName(callFrom, newNa="plotW2Leg")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(is.null(tit)) tit <- "log p-value vs slope"
msg <- "Invalid entries for 'useCol' (should be column-names or integer as index)"
if(length(useCol) <4) useCol <- c(useCol, rep(NA, 4 -length(useCol)))
if(!is.integer(useCol)) {chCol <- match(useCol, colnames(dat))
if(all(is.na(chCol))) stop(msg)
if(any(is.na(chCol)) && !silent) message(fxNa,"Trouble ahead ! Can't find columns ",wrMisc::pasteC(useCol[is.na(chCol)],quoteC="'"))
useCol <- chCol
} else if(any(useCol <1 | useCol >ncol(dat))) stop(msg)
if(debug) message(fxNa,"pW2L1")
useColor <- if(!is.na(useCol[3])) wrMisc::colorAccording2(dat[,useCol[3]], gradTy="rainbow", revCol=TRUE, nEndOmit=14) else grDevices::gray(0.6)
stRa <- if(!is.na(useCol[4])) range(dat[,useCol[4]], na.rm=TRUE) else NA
graphics::plot(dat[,useCol[1:2]], type="n", main=tit, xlab=xlab, ylab=ylab, xlim=xlim, ylim=ylim, las=1)
if(length(subTi) >0) graphics::mtext(subTi, cex=subCex)
## guide-lines
if(length(ablines) >0) {
if("v" %in% names(ablines)) graphics::abline(v=ablines$v, lty=2, col="grey")
if("v" %in% names(ablines)) graphics::abline(h=ablines$v, lty=2, col="grey") }
## legend for symbols
if(!is.na(useCol[4]) && length(legendloc)==1) graphics::legend(legendloc, paste(
if(length(txtLegend) <1) paste(colnames(dat)[useCol[4]],"=") else txtLegend,
stRa[1]:stRa[2]), text.col=1, pch=21:25, col=1, pt.bg="white", cex=0.9, xjust=0.5, yjust=0.5)
if(length(subTi) >0) graphics::mtext(subTi,cex=0.9)
## histigram legend
if(!is.na(useCol[3]) && length(histLoc)==1) {
if(length(legHiTi) <1) legHiTi <- colnames(dat)[useCol[3]]
hi1 <- graphics::hist(dat[,useCol[3]], plot=FALSE)
legendHist(sort(dat[,useCol[3]]), colRamp=useColor[order(dat[,useCol[3]])][cumsum(hi1$counts)], location=histLoc, legTit=legHiTi) }
## the main points (on top)
pch1 <- if(!is.na(useCol[4])) pch[dat[,useCol[4]]] else {if(length(pch)==nrow(dat)) pch else rep(pch[1], nrow(dat))}
ptCol <- useColor
if(any(pch1 %in% 21:25)) ptCol[which(pch1 %in% 21:25)] <- 1
graphics::points(dat[,useCol[1:2]], col=ptCol, bg=useColor, pch=pch1)
}
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/plotW2Leg.R
|
#' Plot profiles according to CLustering
#'
#' This function was made for visualuzing the result of clustering of a numeric vector or clustering along multiple columns of a matrix.
#' The data will be plotted like a reglar scatter-plot, but some extra space is added to separate clusters and dashed lines highlight cluster-borders.
#' If no mean/representative value is spacified, a geometric mean will be calculated along all columns of \code{dat}.
#' In case \code{dat} has multiple columns, a legend and a representative (default geometric mean) dashed grey line will be displayed.
#'
#' @param dat (matrix or data.frame) main input with data to plot as points
#' @param clu (numeric or character) clustering results; if length=1 and character this term will be understood as colum-name with cluster-numbers from \code{dat}
#' @param meanD (numeric) mean/representative of multiple series for display as lines; if length=1 and character this term will be understood as columname with cluster-numbers from \code{dat}
#' @param tit (character) optional custom title
#' @param col (character) custom colors
#' @param pch (integer) custom plotting symbols (see also \code{\link[graphics]{par}})
#' @param xlab (character) custom x-axis label
#' @param ylab (character) custom y-axis label
#' @param cex (numeric) cex-like expansion factor (see also \code{\link[graphics]{par}})
#' @param cexTit (numeric) cex-like expansion factor for title (see also \code{\link[graphics]{par}})
#' @param meCol (character) color for (dashed) line of mean/representative values
#' @param meLty (integer) line-type line of mean/representative values (see also \code{lty} in \code{\link[graphics]{par}})
#' @param meLwd (numeric) line-width line of mean/representative values (see also \code{lwd} in \code{\link[graphics]{par}})
#' @param legLoc (character) legend location
#' @param silent (logical) suppress messages
#' @param debug (logical) additonal messages for debugging
#' @param callFrom (character) allows easier tracking of messages produced
#' @return This functin returns a plot only
#' @examples
#' set.seed(2020); dat1 <- runif(12)/2 + rep(6:8, each=4)
#' dat1Cl <- stats::kmeans(dat1, 3)$cluster
#' dat1Cl <- 5- dat1Cl # bring cluster-numbers in ascending form
#' dat1Cl[which(dat1Cl >3)] <- 1 # bring cluster-numbers in ascending form
#' profileAsClu(dat1, clu=dat1Cl)
#' @export
profileAsClu <- function(dat, clu, meanD=NULL, tit=NULL, col=NULL, pch=NULL, xlab=NULL, ylab=NULL, meCol="grey", meLty=1, meLwd=1, cex=NULL, cexTit=NULL, legLoc="bottomleft", silent=TRUE, debug=FALSE, callFrom=NULL) {
##
fxNa <- wrMisc::.composeCallName(callFrom, newNa="profileAsClu")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
argNames <- c(deparse(substitute(dat)), deparse(substitute(clu)), deparse(substitute(z)))
msg <- "Invalid argument 'dat'; must be matrix or data.frame with min 2 lines"
if(length(dat) <1) stop(msg)
if(length(dim(dat)) <2) dat <- as.matrix(dat)
if(any(length(dim(dat)) !=2, dim(dat) <1)) stop(msg)
if(length(clu)==1) { if(is.character(clu)) cluC <- which(colnames(dat)==clu)
clu <- dat[,cluC]; dat <- dat[,-cluC] }
if(length(clu) != nrow(dat)) stop("Length of 'clu' does not match number of lines from 'dat')")
chClu <- clu[-1] - clu[-length(clu)]
if(any(any(chClu <0) && any(chClu >0), any(chClu < -1), any(chClu >1))) stop("Invalid 'clu'; cluster numbers must be sorted")
if(debug) message(fxNa,"pAC1")
## main
nClu <- length(unique(clu))
## geometrix mean
if(length(meanD)==1) { if(is.character(meanD)) meanC <- which(colnames(dat)==meanD)
if(length(meanC)==1) {meanD <- dat[,meanC]; dat <- dat[,-meanC]} else {
message(fxNa,"Can't find column '",meanD,"'")
meanD <- NULL} }
if(length(dim(dat)) <2) dat <- as.matrix(dat)
if(is.null(meanD) && ncol(dat) >1) meanD <- apply(dat, 1, prod)^(1/ncol(dat))
cluLoc <- table(clu)[rank(unique(clu))]
cluBord <- cumsum(cluLoc[-nClu]) +0.5
cluLoc <- cumsum(cluLoc) - cluLoc/2 +0.5
meanLi <- matrix(NA, nrow=nrow(dat) +nClu, ncol=2)
inc <- 0
if(debug) message(fxNa,"pAC2")
for(i in unique(clu)) { li <- which(clu==i); meanLi[inc+li,] <- cbind(li, meanD[li]); inc <- inc +1}
meanLi[which(is.na(meanLi[,1])),1] <- c(cluBord,NA)
if(is.null(col)) col <- 1:ncol(dat)
if(is.null(pch)) pch <- unique(clu)
if(is.null(ylab)) ylab <- argNames[1]
ch1 <- try(graphics::plot(c(range(dat,na.rm=TRUE), rep(NA,nrow(dat)-2)), type="n", las=1, ylab=ylab, main=tit, cex=cex, cex.main=cexTit, xlab=xlab), silent=TRUE)
if(inherits(ch1, "try-error")) warning(fxNa,"UNABLE TO PRODUCE PLOT ! \n initial message : ",ch1) else {
graphics::mtext(paste("clu", unique(clu)), side=3, at=cluLoc) # cluster names
if(ncol(dat) >1) graphics::lines(meanLi, col=meCol, lty=meLty, lwd=meLwd) # geom mean line
graphics::abline(v=cluBord, lty=4, col=grDevices::grey(0.8)) # clu borders
for(i in 1:ncol(dat)) graphics::points(1:nrow(dat), dat[,i], pch=pch[clu], col=col[i])
if(ncol(dat) >1) ch1 <- try(graphics::legend(legLoc,c(colnames(dat),"geomMean"), text.col=c(col,1), pch=c(rep(1,ncol(dat)), NA),
lty=c(rep(NA,ncol(dat)),meLty), lwd=c(rep(NA,ncol(dat)),meLwd), col=c(col[1:ncol(dat)], meCol), cex=0.85, xjust=0.5, yjust=0.5), silent=TRUE)
if(inherits(ch1, "try-error")) message(fxNa,"Unable to plot legend") }
}
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/profileAsClu.R
|
#' Staggered Chart for Ploting Counts to Multiple Leveles of the Threshold used
#'
#' The basic idea of this plot is to show how counts data change while shifting a threshold-criterium.
#' At each given threshold the counts are plotted like a staggered bar-chart (or staggered histogram) but without vertical lines to illustrated the almost continuous change
#' from preceedig or following threshold-value.
#' Initially this plot was designed for showing the absolute count-data used when constructing roc-curves (eg using
#' the function \code{summarizeForROC} of package \href{https://CRAN.R-project.org/package=wrProteo}{wrProteo} ).
#' The main input should furnish the panel of threshold as one column and the coresponding counts data as min 2 columns.
#' The threshold coumns gets specified using the argument \code{threColumn}, the counts-data may either be specified using argument \code{countsCol}
#' or be searched using \code{\link[base]{grep}} using column-names containing the text given in argument \code{varCountNa} with may be combined with
#' a fixed preceeding part given as argument \code{fixedCountPat}.
#'
#' Investigate count data prepared for plotting ROC curves : cumulative counts plot by species (along different statistical test thresholds).
#' Note : Package \href{https://CRAN.R-project.org/package=wrProteo}{wrProteo} may be used to prepare input (matrix of ROC data).
#'
#' @param roc (numeric matrix or data.frame) main input: one column with thresholds and multiple columns of assoicated count data
#' @param threColumn (integer or character) to specify the column with threshold-data, in typica proteomics benchmark studies this would be 'alph' (for the statistical test threshold)
#' @param countsCol (character of integer, min length=2) choice of column(s) with count-data in 'roc' to be used for display, if not \code{NULL} will override alternative search of columns using 'varCountNa' and 'fixedCountPat'
#' @param varCountNa (character) alternative way to select the columns from 'roc': searched using \code{\link[base]{grep}} using column-names containing the text given in argument \code{varCountNa} with may be combined with a fixed preceeding part given as argument \code{fixedCountPat}
#' In proteomics benchmark studies this would typically be the species-abbreciations (eg 'H','S','E')
#' @param fixedCountPat (character) optional pattern to help identifying counts-data: if not \code{NULL} it will be used as fixed part in column names to get pasted to \code{varCountNa}.
#' In proteomics benchmark studies this would typically be 'n.pos.'
#' @param sortAscending (logical) decide if data should be sorted ascending or descending
#' @param vertLine (numeric) for optional vertical line, typically used to highlight alpha 0.05
#' @param col (character) custom colors, see also \code{\link[graphics]{par}}
#' @param tit (character) cutom title
#' @param logScale (logical) display threshld values (x-axis) on log-scale
#' @param las.alph (numeric) orientation of label of alpha-cutoff, see also \code{\link[graphics]{par}}
#' @param displMaxSpec (logical) display on right side of figure max count value of contributing group species
#' @param silent (logical) suppress messages
#' @param debug (logical) additonal messages for debugging
#' @param callFrom (character) allows easier tracking of messages produced
#' @return plot only
#' @seealso \code{\link[stats]{ecdf}}, for preparing input to ROC: function \code{summarizeForROC} in package \href{https://CRAN.R-project.org/package=wrProteo}{wrProteo}
#' @examples
#' set.seed(2019); test1 <- cbind(a=sample.int(n=7,size=50,repl=TRUE),
#' b=sample.int(n=11,size=50,repl=TRUE),c=sample.int(n=18,size=50,repl=TRUE))
#' test1 <- cbind(alph=seq(0,1,length.out=50),a=cumsum(test1[,1]),b=cumsum(test1[,2]),
#' c=cumsum(test1[,3]))
#' staggerdCountsPlot(test1,countsCol=c("a","b","c"))
#' ## example below requires the package wrProteo
#' @export
staggerdCountsPlot <- function(roc, threColumn=1, countsCol=NULL, fixedCountPat="n.pos.", varCountNa=NULL, sortAscending=TRUE, vertLine=NULL,
col=NULL, tit=NULL, logScale=FALSE, las.alph=2, displMaxSpec=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL) {
## was previously cumulCountPlot
##
argN <- deparse(substitute(roc))
fxNa <- wrMisc::.composeCallName(callFrom,newNa="staggerdCountsPlot")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
msg <- "Argument 'roc' should be matrix (or data.frame) with threshold- and count data (min 2 columns and 2 rows) !"
if(length(dim(roc)) !=2) stop(msg) else if(any(dim(roc) <2)) stop(msg)
## look for counting data
if(length(countsCol) >0) {
countsCol <- wrMisc::extrColsDeX(roc, extrCol=countsCol, doExtractCols=FALSE, callFrom=fxNa,silent=silent)
} else {
chColCo <- grep(paste("^",fixedCountPat,sep=""),colnames(roc))
countsCol <- grep(if(length(stats::na.omit(chColCo)) >0) paste("^",fixedCountPat,varCountNa,sep="") else varCountNa, colnames(roc)) }
## look for column with thresholds threColumn
if(length(threColumn) <1) stop("Argument 'threColumn' seems to be empty")
if(length(threColumn) >1) threColumn <- threColumn[1]
threColumn <- wrMisc::extrColsDeX(roc, extrCol=threColumn, doExtractCols=FALSE, callFrom=fxNa,silent=silent)
if(length(varCountNa) <1) varCountNa <- colnames(roc)[countsCol]
if(debug) message(fxNa,"sCP1")
## sort
newOrd <- order(roc[,threColumn], decreasing=!sortAscending)
if(!identical(1:nrow(roc), newOrd)) roc <- roc[newOrd,]
## eliminiate all 0 count line
chAll0 <- rowSums(roc[,countsCol]) <= 0
if(any(chAll0)) { if(!silent && sum(!chAll0) < nrow(roc)/3) message(fxNa,"Reducing from ",nrow(roc)," -> ",sum(!chAll0)," rows")
roc <- roc[which(!chAll0),] }
maxCoA <- max(rowSums(roc[,countsCol],na.rm=TRUE))
alph <- roc[,threColumn]
if(is.null(col)) col <- if(length(varCountNa)==3) {grDevices::rgb(red=c(243,165,240),green=c(184,154,240),blue=c(107,198,150),maxColorValue=255) # pale orange (Ec), purple (Sc), yellow (Hs)
} else 1+(1:length(countsCol))
maxCo1 <- max(roc[,countsCol[1]], na.rm=TRUE)
revInd <- c(1:nrow(roc), nrow(roc):1)
al2 <- roc[revInd,threColumn]
if(is.null(tit)) tit <- paste("Species counts ",wrMisc::pasteC(varCountNa,quoteC="'")," of ",argN)
## help for log-scale
tmp <- max(0.0003, min(roc[,threColumn]))
graphics::plot(range(alph), c(0,maxCoA),type="n", xlab=paste("cutoff ",names(threColumn)), ylab="count", main=tit,
xaxs="i", yaxs="i", if(logScale) xlim=c(tmp,max(alph,na.rm=TRUE)), log= if(logScale) "x" else "",las=1)
graphics::polygon( c(alph,range(alph)[c(2,2,1)]), c(roc[,countsCol[1]],maxCo1,0,0), col=col[1], border=grDevices::grey(0.6)) # OK
if(length(countsCol) >1) for(i in 2:length(countsCol)) graphics::polygon( al2, c(if(i >2) rowSums(roc[,countsCol[(i-1):1]]) else roc[,countsCol[1]],
rowSums(roc[nrow(roc):1, countsCol[i:1]])), col=col[i])
if(length(vertLine) >0) {graphics::abline(v=0.05,lty=2,col=grDevices::grey(0.4)) # display alpha
graphics::mtext(paste(names(threColumn),"=",vertLine),at=vertLine,side=3,line=if(logScale) -1 else 0.1, cex=0.7, las=las.alph)}
if(displMaxSpec) { z <- roc[nrow(roc),countsCol]
z <- rbind(z,cumsum(z))
graphics::mtext(paste("max",varCountNa), side=4, at=z[2,]-z[1,]/2, cex=0.6, las=3, line=0.1)
graphics::mtext(roc[nrow(roc),countsCol], side=4, at=z[2,]-z[1,]/2, cex=0.7, las=3, line=-1)}
graphics::legend("topleft", if(length(varCountNa)==length(countsCol)) varCountNa else colnames(roc)[countsCol], text.col=1, pch=22, col=1, pt.bg=col, cex=0.9,pt.cex=1.6,xjust=0.5,yjust=0.5)
}
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/staggerdCountsPlot.R
|
#' Violin-plots version W
#'
#' This function allows generating \href{https://en.wikipedia.org/wiki/Violin_plot}{Violin plots}) using a variety of input formats and offers additional options for colors.
#' Main input may be multiple vectors, a matrix or list of multiple data-elements (entries may be of variable length),
#' individual colors for different sets of data or color-gradients can be specified, and the display of n per set of data was integtated
#' (based on an inspiration from the discussion 'Removing-NAs-from-dataframe-for-use-in-Vioplot' on the forum Nabble).
#' It is also possible to plot pairwise half-violins for easier pairwise-comparisons (using \code{halfViolin="pairwise"}).
#' Many arguments are kept similar to \href{https://CRAN.R-project.org/package=vioplot}{vioplot} (here, the package \code{vioplot} is not required/used).
#'
#' @details The (relative) width of the density-profiles ('Violins') may be manually adjusted using the parameter \code{wex} which applieds to all profiles drawn.
#' Please note that different n (eg for different columns) will not be shown, so far.
#'
#' Note : Arguments have to be given with full names, lazy evaluation of arguments will not work properly with this function (since '...' is used to capture additional data-sets).
#' Note : \href{https://CRAN.R-project.org/package=vioplot}{vioplot} offers better options for plotting formulas
#'
#' @param x (matrix, list or data.frame) data to plot, or first series of data
#' @param ... (numeric) additional sets of data to plot
#' @param finiteOnly (logical) eliminate non-finite elements to avoid potential errors (eg when encountering \code{NA})
#' @param removeEmpty (logical) omit empty series (or less than 4 finite numeric entries) of data from plot
#' @param halfViolin (logical or character) decide with \code{TRUE} or \code{FALSE} if full or only half of violins should be plotted, if "pairwise" always 2 data-sets will be plotted back-to-back
#' @param boxCol (character) decide if boxplot should be adde inside the violin, use "def" for default transparent grey
#' @param hh (numeric, length <4) smoothing parameter (standard deviation to kernel function, if omited anormal optimal smoothing parameter is used); equivalent to argument \code{h} in package \href{https://CRAN.R-project.org/package=vioplot}{vioplot} ; see also \code{\link[sm]{sm.density}}
#' @param xlim (\code{NULL} or numeric, length=2) custom limit on x-axis, see also \code{\link[graphics]{par}}
#' @param ylim (\code{NULL} or numeric, length=2) custom limit on y-axis, see also \code{\link[graphics]{par}}
#' @param nameSer (character) custom label for data-sets or columns (length must match number of data-sets)
#' @param cexNameSer (numeric) size of individual data-series labels as cex-expansion factor (see also \code{\link[graphics]{par}})
#' @param horizontal (logical) orientation of plot
#' @param col (character or integer) custom colors or gradients like 'rainbow', 'grayscale', 'heat.colors', 'topo.colors', 'Spectral' or 'Paired', or you may use colors made by the package \href{https://CRAN.R-project.org/package=colorRamps}{colorRamps}
#' @param border (character) custom color for figure border
#' @param xlab (character) custom x-axis label
#' @param ylab (character) custom y-axis label
#' @param cexLab (numeric) size of axis labels as cex-expansion factor (see also \code{\link[graphics]{par}})
#' @param cexAxis (numeric) size of numeric y-axis labels as cex-expansion factor (see also \code{\link[graphics]{par}})
#' @param lty (integer) line-type for linear regression line (see also \code{\link[graphics]{par}})
#' @param pointCol (character or numeric) display of median: color (defauly white)
#' @param cexPt (numeric) display of median : size of point as cex-expansion factor (see also \code{\link[graphics]{par}})
#' @param tit (character) custom title to figure
#' @param las (integer) orientation of axis labels (see also \code{\link[graphics]{par}})
#' @param lwd (integer) width of line(s) (see also \code{\link[graphics]{par}})
#' @param rectCol (character) color of rectangle
#' @param at (numeric) custom locoation of data-series names, ie the points at which tick-marks are to be drawn, will be passed to \code{\link[graphics]{axis}}, it's length ust match the number of data-sets
#' @param add (logical) add to existing plot if \code{TRUE}
#' @param wex (integer) relative expansion factor of the violin
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @param debug (logical) additional messages for debugging
#' @return This function plots a figure (to the current graphical device)
#' @seealso the package \href{https://CRAN.R-project.org/package=vioplot}{vioplot}, \code{\link[sm]{sm}} is used for the density estimation
#' @examples
#' set.seed(2013)
#' dat6 <- matrix(round(rnorm(300) +3, 1), ncol=6,
#' dimnames=list(paste0("li",1:50), letters[19:24]))
#' vioplotW(dat6)
#' ## variable number of elements (each n is displayed)
#' dat6b <- apply(dat6, 2, function(x) x[which(x < 5)])
#' dat6b[[4]] <- dat6b[[4]][dat6b[[4]] < 4]
#' vioplotW(dat6b, col="Spectral")
#' vioplotW(dat6b, col="Spectral" ,halfViolin="pairwise", horizontal=TRUE)
#' vioplotW(dat6b, col="Spectral", halfViolin="pairwise", horizontal=FALSE)
#' @export
vioplotW <- function(x, ..., finiteOnly=TRUE, removeEmpty=FALSE, halfViolin=FALSE, boxCol="def", hh=NULL, xlim=NULL, ylim=NULL, nameSer=NULL, cexNameSer=NULL, horizontal=FALSE,
col="rainbow", border="black", xlab=NULL, ylab=NULL, cexLab=NULL, cexAxis=NULL, lty=1, pointCol=NULL, cexPt=NULL,
tit=NULL, las=1, lwd=1, rectCol="black", at=0, add=FALSE, wex=NULL, silent=FALSE, debug=FALSE, callFrom=NULL) {
## wr variant for violin-plots, inspired&extended based on https://r.789695.n4.nabble.com/Removing-NAs-from-dataframe-for-use-in-Vioplot-td4720274.html
## 'col'.. individual fill-colors, may specify gradients (default 'rainbow','grayscale','Spectral','Paired')
## default display (short)column names and n
fxNa <- wrMisc::.composeCallName(callFrom, newNa="vioplotW")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
fixArg <- c("x","finiteOnly","halfViolin","boxCol","hh","xlim","ylim","nameSer","horizontal","col","border","las", # fixed argument names to check (and adjust)
"lty","tit","lwd","rectCol","at","add","wex","drawRect", "colMed","pchMed","silent","debug","callFrom")
datas <- list(...)
out <- useColNo <- NULL
argN <- c(x=deparse(substitute(x)), sup=deparse(substitute(...)))
argL <- match.call(expand.dots = FALSE)$... # extr arg names, based on https://stackoverflow.com/questions/55019441/deparse-substitute-with-three-dots-arguments
if(debug) {message(callFrom," -> vioplotW vv0"); vv0 <- list(datas=datas,x=x,argN=argN,finiteOnly=finiteOnly,halfViolin=halfViolin,boxCol=boxCol,hh=hh,xlim=xlim,ylim=ylim,nameSer=nameSer,tit=tit,argL=argL,fixArg=fixArg)}
## separate specific arguments from all-input (lazy fitting) & clean datas
if(length(datas) >0) {
pMa <- pmatch(names(argL), fixArg) # will only find if unique (partial) match
if(length(argL) >0 && length(pMa) >0) { pMa[which(nchar(names(argL)) <3)] <- NA # limit to min 3 chars length for lazy matching
if(any(!is.na(pMa))) for(i in which(!is.na(pMa))) {assign(fixArg[pMa[i]], datas[[i]]); names(datas)[i] <- "replaceReplace"}}
chRepl <- names(datas) %in% "replaceReplace"
if(any(chRepl)) {datas <- datas[-which(chRepl)]; argL <- argL[-which(chRepl)]}
}
## combine datas and x & set x to beginning , convert matrices to list of vectors
if(length(x) >0) {
## check x
x <- try(wrMisc::asSepList(x, asNumeric=TRUE, silent=silent, debug=debug, callFrom=fxNa), silent=TRUE)
if(inherits(x, "try-error")) {datas <- NULL; if(!silent) message(fxNa,"Problem with separating data from main entry '",argN[1],"'")}}
if(length(datas) >0) {
datas <- try(wrMisc::asSepList(datas, asNumeric=TRUE, silent=silent, debug=debug, callFrom=fxNa), silent=TRUE)
if(inherits(datas, "try-error")) {datas <- NULL; if(!silent) message(fxNa,"Problem with separating data from supplemental data")}}
if(length(datas) >0) {
## now add x
if(length(x) >0) {
datas[[length(datas) +(1:length(x))]] <- x
newNa <- if(length(argN[1]) >0) argN[1] else "x"
names(datas)[1 +length(datas) -(length(x):1)] <- if(length(x)==1) newNa else { paste0(newNa,"_",1:length(x))}
if(length(datas) >1) datas <- datas[c(1 +length(datas) -length(x):1, 2:(length(datas) -length(x)))] } # reset order
} else { datas <- x
if(debug) {message(fxNa,"vv1b")} }
if(debug) {message(fxNa,"vv1c"); vv1c <- list(datas=datas,x=x,argN=argN,finiteOnly=finiteOnly,halfViolin=halfViolin,boxCol=boxCol,hh=hh,removeEmpty=removeEmpty,xlim=xlim,ylim=ylim,nameSer=nameSer,tit=tit,argL=argL,fixArg=fixArg)}
.filtX <- function(x, nMin=4, nullRet=NULL) {x <- wrMisc::naOmit(x); if(length(x) >= nMin) {chN <- is.finite(x); if(sum(chN) >= nMin) x[which(chN)] else nullRet } else nullRet}
doPlot <- length(x) >0 && length(datas) >0
if(doPlot) { ## add'l filter
## filter for min length=4
iniLe <- length(datas)
datas <- lapply(datas, .filtX, nMin=4, nullRet=NULL)
datas <- lapply(datas, function(x) {x <- wrMisc::naOmit(x); if(length(x) >3) x})
if(isTRUE(removeEmpty)) {
chL <- sapply(datas, length) <1
if(any(chL)) { if(all(chL)) { warning(fxNa,"INSUFFICIENT data, can't plot"); doPlot <- FALSE
} else {datas <- datas[which(!chL)]; if(!silent) message(fxNa,"REMOVING ",sum(!chL)," out of ",iniLe, " entries since too short for plotting !")}}
}
}
##
msg <- NULL
rangeVa <- 1.5 # how much to extent fitted distribution beyond real min/max (for ra2)
if(is.null(pointCol)) pointCol <- grDevices::rgb(1,1,1,0.9) # color of (white) point to mark median
if(is.null(cexPt)) cexPt <- 1.7
pwBoC <- boxCoor <- NULL
chPa <- requireNamespace("sm", quietly=TRUE)
if(!chPa) { doPlot <- FALSE
message(fxNa,"Cannot find package 'sm' which is needed for function, please install first from CRAN !")}
if(isTRUE(halfViolin)) halfViolin <- FALSE
if(!isTRUE(horizontal)) horizontal <- FALSE
if(debug) {message(fxNa,"Starting to prepare data, vv2"); vv2 <- list(datas=datas,x=x,argN=argN,finiteOnly=finiteOnly,halfViolin=halfViolin,boxCol=boxCol,hh=hh,xlim=xlim,ylim=ylim,nameSer=nameSer,tit=tit,argN=argN,argL=argL,halfViolin=halfViolin,horizontal=horizontal)}
n <- length(datas)
if(doPlot && n >0) {
if("rainbow" %in% col) col <- grDevices::rainbow(round(n*1.08))[1:n]
if("grayscale" %in% col) col <- grDevices::gray.colors(n)
if("heat.colors" %in% col) col <- grDevices::heat.colors(n)
if("topo.colors" %in% col) col <- grDevices::topo.colors(n)
chPa <- requireNamespace("RColorBrewer", quietly=TRUE)
if(!chPa && any(c("Spectral","Paired") %in% col)) { col <- "rainbow"
warning("Cannot find package 'RColorBrewer' (install first from CRAN) which is needed for your choice of argument 'col' ! (ignoring") }
if("Spectral" %in% col && chPa) col <- RColorBrewer::brewer.pal(min(n,11), "Spectral")
if("Paired" %in% col && chPa) col <- RColorBrewer::brewer.pal(12,"Paired")[c(5:6,1:4,7:12)][1:min(n,12)]
## need to re-write ??
if(length(n) ==1 && n==1) datas[[1]] <- as.matrix(datas[[1]])
if(isTRUE(finiteOnly)) datas <- lapply(datas, function(x) {chFini <- is.finite(x); if(any(!chFini)) x <- x[which(chFini)]; x})
if(debug) {message(fxNa, "Starting to prepare data, vv3")}
if(identical(boxCol,"def")) boxCol <- grDevices::rgb(0,0,0,0.4)
## prepare input data
if(length(col) <n) col <- rep(col,n)[1:n]
if(isTRUE(horizontal) && n >1) {
datas <- datas[n:1] # return order that plot will read top -> bottom
col <- col[length(col):1] }
if(length(at) != n) at <- 1:n
if(length(datas)==1) at <- 1
if(debug) {message(fxNa,"vv5, prepare 'at' ",wrMisc::pasteC(utils::head(at))); vv5 <- list(datas=datas,x=x,argN=argN,rangeVa=rangeVa,finiteOnly=finiteOnly,halfViolin=halfViolin,boxCol=boxCol,hh=hh,col=col,at=at,xlim=xlim,ylim=ylim,nameSer=nameSer,tit=tit,argN=argN,argL=argL,halfViolin=halfViolin,horizontal=horizontal,n=n)}
sumry <- function(x) { # take summary and then points for boxplot lwr,firQ,med,thiQ,upr
outNA <- c(lwr=NA,firQ=NA,med=NA,thiQ=NA,upr=NA)
if(length(x) >0) { if(is.numeric(x)) {y <- summary(as.numeric(x)); c(lwr=min(y[1], y[2] -(y[5] -y[2])*rangeVa, na.rm=TRUE),
firQ=as.numeric(y[2]), med=as.numeric(y[3]), thiQ=as.numeric(y[5]), upr=max(y[6], y[5] +(y[5] -y[2])*rangeVa, na.rm=TRUE))} else outNA} else outNA
}
ra2 <- as.matrix(sapply(datas, sumry))
colnames(ra2) <- names(datas)
if(debug) {message(fxNa,"vv5b, prepare 'at' ",wrMisc::pasteC(utils::head(at))); vv5b <- list()}
smDensity <- sm::sm.density
smArgs <- list(display="none")
if(!(is.null(hh))) {smArgs[1 +(1:length(hh))] <- hh; names(smArgs)[length(smArgs) +1 -(length(hh):1)]
if(debug) message(fxNa, "New arguments added to smArgs :",unlist(hh)) }
raYGlob <- c(min=min(ra2[1,], na.rm=TRUE), max=max(ra2[5,], na.rm=TRUE)) # used ?
if(debug) {message(fxNa,"vv6, raYGlob ",wrMisc::pasteC(signif(raYGlob,4)))
vv6 <- list(datas=datas,x=x,argN=argN,finiteOnly=finiteOnly,halfViolin=halfViolin,boxCol=boxCol,hh=hh,smDensity=smDensity,smArgs=smArgs,raYGlob=raYGlob,xlim=xlim,ylim=ylim,nameSer=nameSer,tit=tit,argN=argN,argL=argL,halfViolin=halfViolin,horizontal=horizontal)}
smFx <- function(yy, halfViolin, debug=FALSE) {
if(length(dim(yy)) <2) yy <- as.matrix(yy)
suY <- if(ncol(yy)==1) summary(as.numeric(yy)) else summary(yy)
raY <- c(lwr=min(suY[1], na.rm=TRUE), upr=max(suY[6], na.rm=TRUE) ) # no extension for estimation range
smRes <- do.call("smDensity", c(list(yy, xlim=raY), smArgs))
if(debug) {message("smFx : sm1"); sm1 <- list(yy=yy,halfViolin=halfViolin,suY=suY,raY=raY,smRes=smRes)}
## do we care about the upper and lower ends of a variability band, or standard error estimate (which may not always get produced) ?
## truncate to range of real values
chRa <- smRes$eval.points >= min(suY[1], na.rm=TRUE) & smRes$eval.points <= max(suY[6], na.rm=TRUE)
if(!all(chRa)) {
smRes$eval.points <- smRes$eval.points[which(chRa)]
smRes$estimate <- smRes$estimate[which(chRa)] }
if(debug) {message("smFx :sm2"); sm2 <- list(yy=yy,halfViolin=halfViolin,suY=suY,raY=raY,smRes=smRes)}
## now add points to start & end from baseline=0
chBa <- any(smRes$estimate[c(1,length(smRes$estimate))] != 0)
if(chBa) { nPo <- length(smRes$estimate)
smRes$estimate <- c(0, smRes$estimate,0)
smRes$eval.points <- smRes$eval.points[c(1,1:nPo,nPo)] }
if(debug) {message("smFx : sm3"); sm3 <- list(yy=yy,halfViolin=halfViolin,suY=suY,raY=raY,smRes=smRes)}
if(!any(sapply(list("yes","pairwise",TRUE), identical, halfViolin ))) {
## need to 'double' data for symmetric violin
nPo <- length(smRes$estimate) # otherwise left/upper half
smRes$estimate <- c(smRes$estimate, -1*smRes$estimate[nPo:1] )
smRes$eval.points <- smRes$eval.points[c(1:nPo, nPo:1)] }
list(evalPo=smRes$eval.points, estimate=smRes$estimate, se=smRes$se, summary=suY) }
smFx2 <- function(yy, halfViolin, debug=FALSE, callFrom=NULL) {
out <- try(smFx(yy, halfViolin, debug=FALSE), silent=TRUE)
#chEr <- sapply(out, inherits, "try-error")
#if(any(chEr)) { warning(callFrom,"Problem with calculating density ! Need to omit this series")
# out <- out[which(!chEr)] }
out }
vioDat <- lapply(datas, smFx2, halfViolin, debug=debug, callFrom=fxNa)
## correct for empty series
chNull <- colSums(is.na(ra2)) ==5
if(any(chNull)) for(i in which(chNull)) vioDat[[i]] <- list(estimate=NULL)
xLim <- if(length(xlim) ==2) xlim else { #
c(1 -max(0.2, vioDat[[1]]$estimate, na.rm=TRUE), n +max(0.2, vioDat[[n]]$estimate, na.rm=TRUE))} # supposed vertical display, note final xLim is changed by wex
yLim <- if(length(ylim) ==2) ylim else range(ra2[c(1,5),], na.rm=TRUE)
if(debug) {message(fxNa,"vv7, Init xlim=",wrMisc::pasteC(signif(xLim),4)," ylim=",wrMisc::pasteC(signif(yLim,4)) )
vv7 <- list(datas=datas,x=x,vioDat=vioDat,xLim=xLim,yLim=yLim,argN=argN,finiteOnly=finiteOnly,halfViolin=halfViolin,boxCol=boxCol,hh=hh,smDensity=smDensity,smArgs=smArgs,raYGlob=raYGlob,xlim=xlim,ylim=ylim,nameSer=nameSer,tit=tit,argN=argN,argL=argL,halfViolin=halfViolin,horizontal=horizontal)}
## configure data/sample-names
label <- if(is.null(nameSer)) names(datas) else nameSer
if(is.null(label) || all(is.na(label))) label <- 1:n
if(identical(halfViolin,"pairwise")) {
xLim <- xLim -c(0, ceiling(n/2))
labA <- label[2*(1:(ceiling(n/2))) -1]
labB <- c(label[2*(1:(floor(n/2)))], if(n %%2 >0) " ")
## check if half-series names just differ by extension
if(FALSE) {
labelH <- "(half-series names differing just by extension) - not yet implemented"
} else {
## (if not differing just by extension) concatenate half-series names and decide if text should contain carriage return
nBL <- nBR <- nBl <- nchar(labA) - nchar(labB)
chLe <- nBL < 0
if(any(!chLe)) {nBL[which(!chLe)] <- 0 # left text is wider, no need to add add'l blanks)
nBR[which(!chLe)] <- abs(nBR) }
if(any(chLe)) {nBL[which(chLe)] <- abs(nBl) # left text is smaller, need to add extra blanks
if(any(chLe)) nBR[which(chLe)] <- 0 }
conMultFx <- function(y) sapply(y, function(x) paste(rep(" ",x),collapse=""))
label <- if(isTRUE(horizontal)) paste(labB,labA,sep="\n\n") else paste0(conMultFx(nBL),labA, paste0(rep(" ",c(2))), conMultFx(nBR),labB)} # try to make symmetrix by adding blanks
at <- at[1:ceiling(n/2)] }
## configure n per samples
nDisp <- sapply(datas, function(x) sum(!is.na(x)))
nDisp <- if(length(unique(nDisp)) >1) paste0(rep(c("n=",""), if(n >6) c(1,n-1) else c(n,0)),nDisp) else paste(if(n >1) " each","n=",nDisp[1])
if(!isTRUE(add)) graphics::plot.new()
## for boxplot like insert
boxFa <- 0.06 # box half-width
boxCoor <- cbind(xL=(1:n) -boxFa, yB=ra2[2,], xR=(1:n) +boxFa, yT=ra2[4,]) # basic representation
## prepare half-violins
if(identical(halfViolin,"pairwise")) {
boxFa <- boxFa +identical(halfViolin,"pairwise")/50 # adjust box width
pwBoC <- matrix(NA, nrow=5, ncol=n, dimnames=list(c("xLe","yBo","xRi","yTo","xPo"),NULL)) # coords for box
impa <- which(1:n %% 2 >0)
pair <- 2* which(impa +1 <= n)
pwBoC[,impa] <- rbind(1:length(impa) -boxFa, ra2[2,impa], 1:length(impa), ra2[4,impa], 1:length(impa) -boxFa/2)
pwBoC[,pair] <- rbind(1:length(pair), ra2[2,pair], 1:length(pair) +boxFa, ra2[4,pair], 1:length(impa) +boxFa/2)
}
if(debug) {message(fxNa,"vv7c"); vv7c <- list( )}
## automatic adjustement of wex
## make automatic size of wex : smaller if many violins ...
if(length(wex) !=1) wex <- NULL else if(!is.finite(wex)) wex <- NULL
if(length(wex) <1) {
we1 <- sapply(vioDat, function(y) if(length(y$estimate) >0) stats::quantile(y$estimate, c(0.75,1), na.rm=TRUE) else rep(NA,2))
wex <- if(length(dim(we1)) >1) signif(0.5/max(apply(we1, 1, max, na.rm=TRUE) *c(0.99), na.rm=TRUE), 4) else signif(0.5/max(we1, na.rm=TRUE))
if(debug) {message(fxNa,"vv7d use wex=",signif(wex,4))}
}
for(i in 1:length(vioDat)) vioDat[[i]]$estimate <- vioDat[[i]]$estimate *wex # change proportionally with of violins
if(debug) {message(fxNa,"vv8"); vv8 <- list(datas=datas, vioDat=vioDat,ra2=ra2,pwBoC=pwBoC,boxCoor=boxCoor,xLim=xLim,ylim=yLim,at=at,wex=wex,halfViolin=halfViolin,cexPt=cexPt,boxCol=boxCol )}
## main plotting
if(!isTRUE(horizontal)) { # plot vertical
xLim <- c(1- max(vioDat[[1]]$estimate)*1.1, n/(1 +identical(halfViolin,"pairwise")) + max(vioDat[[n]]$estimate)*1.1) # readjust xLim to final wex
if(!isTRUE(add)) {
graphics::plot.window(xlim=xLim, ylim=yLim)
graphics::axis(2, las=las, cex.axis=cexAxis)
graphics::axis(1, at=at, label=label, las=las, cex.axis=cexNameSer, adj=0.5) # name/labels for indiv series of data
if(length(xlab) >0) graphics::mtext(xlab, cex=cexLab, side=1, line=2.5)
if(length(ylab) >0) graphics::mtext(ylab, cex=cexLab, side=2, line=2.5)
if(!is.null(tit)) graphics::title(main=tit)
}
graphics::box()
if(identical(halfViolin,"pairwise")) {
for(i in 1:n) graphics::polygon(ceiling(i/2) +vioDat[[i]]$estimate*(1 -2*(i %% 2)), vioDat[[i]]$evalPo, col=col[i], border=border)
graphics::rect(pwBoC[1,], pwBoC[2,], pwBoC[3,], pwBoC[4,], col=boxCol, border=NA)
graphics::points(pwBoC[5,],ra2[3,], pch=16, cex=cexPt, col=pointCol)
graphics::segments(pair/2, ra2[2,impa], pair/2, ra2[4,impa], col="grey", lty=2) # grey line to separate adjacent boxes
} else {for(i in 1:n) graphics::polygon(i +vioDat[[i]]$estimate, vioDat[[i]]$evalPo, col=col[i], border=border)
graphics::rect(boxCoor[,1], boxCoor[,2], boxCoor[,3], boxCoor[,4], col=boxCol, border=NA)
graphics::points(1:n, ra2[3,], pch=16, cex=cexPt, col=pointCol)
}
if(length(boxCol >0)) { ## add boxplot-like
}
} else {
## this is a horizontal plot ..
yLim <- c(1- max(vioDat[[1]]$estimate)*1.1, n/(1 +identical(halfViolin,"pairwise")) + max(vioDat[[n]]$estimate)*1.1) # readjust yLim to final wex
if(!isTRUE(add)) {
graphics::plot.window(xlim=yLim, ylim=xLim)
graphics::axis(1, cex.axis=cexNameSer)
graphics::axis(2, cex.axis=cexAxis, at=at, label=label, cex=cexNameSer, las=las)
if(length(xlab) >0) graphics::mtext(xlab, cex=cexLab, side=1, line=2.5)
if(length(ylab) >0) graphics::mtext(ylab, cex=cexLab, side=2, line=2.5)
if(!is.null(tit)) graphics::title(main=tit)
}
graphics::box()
if(identical(halfViolin,"pairwise")) {
for(i in 1:n) graphics::polygon(vioDat[[i]]$evalPo, ceiling(i/2) +vioDat[[i]]$estimate*(1 -2*(i %% 2)), col=col[i], border=border)
graphics::rect(pwBoC[2,], pwBoC[1,], pwBoC[4,], pwBoC[3,], col=boxCol, border=NULL)
graphics::points(ra2[3,], pwBoC[5,], pch=16, cex=cexPt, col=pointCol)
graphics::segments(ra2[2,impa], pair/2, ra2[4,impa], pair/2, col="grey",lty=2) # grey line to separate adjacent boxes
} else {for(i in 1:n) graphics::polygon(vioDat[[i]]$evalPo,i +vioDat[[i]]$estimate, col=col[i], border=border)
graphics::rect(boxCoor[,2], boxCoor[,1], boxCoor[,4], boxCoor[,3], col=boxCol, border=NA)
graphics::points( ra2[3,], 1:n, pch=16, cex=cexPt, col=pointCol)
}
}
## display n by series (only if variable along data-set)
if(length(nDisp) <2) graphics::mtext(nDisp, adj=0, side=3, cex=0.7, line=-1, las=1) else {
if(identical(halfViolin,"pairwise")) {
nDisp <- cbind(nDisp[2*(1:(ceiling(n/2))) -1], c(nDisp[2*(1:(floor(n/2)))], if(n %%2 >0) " "))
if(horizontal) graphics::mtext(paste(nDisp[,2],nDisp[,1],sep="\n\n"), at=(1:nrow(nDisp))+0.01, side=3-horizontal, cex=0.7, line=-1.5, las=1) else {
graphics::mtext(paste(nDisp[,1],nDisp[,2],sep=" , "), at=1:nrow(nDisp), side=3, cex=0.7, line=-0.8)}
} else graphics::mtext(nDisp, at=(1:n) +horizontal/9, side=3-horizontal, las=1, cex=0.7, line=-0.8-horizontal)
}
if(length(msg) >0) graphics::mtext(msg, side=1, cex=0.7, las=1) # add note about groups/columns of data not plotted
}
}
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/R/vioplotW.R
|
## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse=TRUE, comment = "#>")
## ----setup, echo=FALSE, messages=FALSE, warnings=FALSE------------------------
suppressPackageStartupMessages({
library(wrMisc)
library(wrGraph)
library(FactoMineR)
library(factoextra)
})
## ----setup2, echo=TRUE, eval=FALSE--------------------------------------------
# install.packages("wrGraph")
## ----setup3, echo=TRUE, eval=FALSE--------------------------------------------
# if(!requireNamespace("FactoMineR", quietly=TRUE)) install.packages("FactoMineR")
# if(!requireNamespace("factoextra", quietly=TRUE)) install.packages("factoextra")
## ----vignBrowse, echo=TRUE, eval=FALSE----------------------------------------
# # access vignette :
# browseVignettes("wrGraph") # ... and the select the html output
## ----setup4, echo=TRUE--------------------------------------------------------
library("wrMisc")
library("wrGraph")
# This is version no:
packageVersion("wrGraph")
## ----partitionPlot1, out.width="110%", out.heigth="110%", echo=TRUE-----------
## as the last column of the Iris-data is not numeric we choose -1
(part <- partitionPlot(ncol(iris)-1))
layout(part)
for(i in colnames(iris)[-5]) hist(iris[,i], main=i)
## ----LegLoc1, echo=TRUE-------------------------------------------------------
dat1 <- matrix(c(1:5,1,1:5,5), ncol=2)
grp <- c("abc","efghijk")
(legLoc <- checkForLegLoc(dat1, grp))
# now with more graphical parameters (using just the best location information)
plot(dat1, cex=2.5, col=rep(2:3,3),pch=rep(2:3,3))
legLoc <- checkForLegLoc(dat1, grp, showLegend=FALSE)
legend(legLoc$loc, legend=grp, text.col=2:3, pch=rep(2:3), cex=0.8)
## ----Hist1, out.width="110%", out.heigth="110%", echo=TRUE--------------------
set.seed(2016); dat1 <- round(c(rnorm(200,6,0.5), rlnorm(300,2,0.5), rnorm(100,17)),2)
dat1 <- dat1[which(dat1 <50 & dat1 > 0.2)]
histW(dat1, br="FD", isLog=FALSE)
## ----Hist2, out.width="110%", out.heigth="110%", echo=TRUE--------------------
## view as log, but x-scale in linear
histW(log2(dat1), br="FD", isLog=TRUE, silent=TRUE)
## ----Hist4, out.width="110%", out.heigth="150%", echo=TRUE--------------------
## quick overview of distributions
layout(partitionPlot(4))
for(i in 1:4) histW(iris[,i], isLog=FALSE, tit=colnames(iris)[i])
## ----Hist5, out.width="110%", out.heigth="150%", echo=TRUE--------------------
layout(1)
plot(iris[,1:2], col=rgb(0.4,0.4,0.4,0.3), pch=16, main="Iris Data")
legendHist(iris[,1], loc="br", legTit=colnames(iris)[1], cex=0.5)
legendHist(iris[,2], loc="tl", legTit=colnames(iris)[2], cex=0.5)
## ----vioplot1, fig.height=6, fig.width=8, echo=TRUE---------------------------
vioplotW(iris[,-5], tit="Iris-Data Violin Plot")
## ----vioplot2, fig.height=6, fig.width=8, echo=TRUE---------------------------
## less smoothing
vioplotW(iris[,-5], tit="Iris-Data Violin Plot ('nervous')", hh=0.15)
## ----cumFrqPlot1, echo=TRUE---------------------------------------------------
cumFrqPlot(iris[,1:4])
## ----imageW, echo=TRUE--------------------------------------------------------
par(mar=c(4, 5.5, 4, 1))
imageW(as.matrix(iris[1:40,1:4]), transp=FALSE, tit="Iris-Data (head)")
## ----imageW2, fig.height=2.5, fig.width=9, fig.align="center", echo=TRUE------
imageW(as.matrix(iris[1:20,1:4]), latticeVersion=TRUE, transp=FALSE, col=c("blue","red"),
rotXlab=45, yLab="Observation no", tit="Iris-Data (head)")
## ----imageW3, fig.height=6, fig.width=5, echo=TRUE----------------------------
ma1 <- matrix(-7:16,nc=4,dimnames=list(letters[1:6],LETTERS[1:4]))
ma1[1,2:3] <- 0
ma1[3,3] <- ma1[3:4,4] <- NA
imageW(ma1, latticeVersion=TRUE, col=c("blue","grey","red"), NAcol="grey92",
rotXlab=0, cexDispl=0.8, tit="Balanced color gradient")
## ----imageW4, fig.height=6, fig.width=5, echo=TRUE----------------------------
imageW(ma1, latticeVersion=TRUE, col=c("blue","grey","red"), NAcol="grey92",
rotXlab=0, nColor=8, cexDispl=0.8, tit="Balanced color gradient")
## ----cumulCountPlot1, echo=TRUE-----------------------------------------------
thr <- seq(min(iris[,1:4]), max(iris[,1:4])+0.1,length.out=100)
irisC <- sapply(thr,function(x) colSums(iris[,1:4] < x))
irisC <- cbind(thr,t(irisC))
head(irisC)
staggerdCountsPlot(irisC[,], countsCol=colnames(iris)[1:4], tit="Iris-Data")
staggerdCountsPlot(irisC[,], varCountNa="Sepal", tit="Iris-Data")
staggerdCountsPlot(irisC[,], varCountNa="Sepal", tit="Iris-Data (log-scale)", logScale=TRUE)
## ----plotBy2Groups1, echo=TRUE------------------------------------------------
dat <- iris[which(iris$Species %in% c("setosa","versicolor")),]
plotBy2Groups(dat$Sepal.Length, gl(2,50,labels=c("setosa","versicolor")),
gl(20,5), yLab="Sepal.Length")
## ----plotLinReg1, echo=TRUE---------------------------------------------------
plotLinReg(iris$Sepal.Length, iris$Petal.Width, tit="Iris-Data")
## ----PCA1, fig.height=7, fig.width=7, echo=TRUE-------------------------------
## the basic way
iris.prc <- prcomp(iris[,1:4], scale.=TRUE)
biplot(iris.prc) # traditional plot
## ----PCA3, echo=TRUE----------------------------------------------------------
## via FactoMineR
chPa <- c(requireNamespace("FactoMineR", quietly=TRUE), requireNamespace("dplyr", quietly=TRUE),
requireNamespace("factoextra", quietly=TRUE))
if(all(chPa)) {
library(FactoMineR); library(dplyr); library(factoextra)
iris.Fac <- PCA(iris[,1:4],scale.unit=TRUE, graph=FALSE)
fviz_pca_ind(iris.Fac, geom.ind="point", col.ind=iris$Species, palette=c(2,4,3),
addEllipses=TRUE, legend.title="Groups" )
} else message("You need to install packages 'dplyr', 'FactoMineR' and 'factoextra' for this figure")
## ----PCA4, echo=TRUE----------------------------------------------------------
## via wrGraph, similar to FactoMineR but with bagplots
plotPCAw(t(as.matrix(iris[,-5])), gl(3,50,labels=c("setosa","versicolor","virginica")),
tit="Iris Data", rowTyName="types of leaves", suplFig=FALSE, cexTxt=1.3, rotatePC=2)
## ----PCA5, fig.height=12, fig.width=9, fig.align="center", echo=TRUE----------
## including 3rd component and Screeplot
plotPCAw(t(as.matrix(iris[,-5])), gl(3,50,labels=c("setosa","versicolor","virginica")),
tit="Iris Data PCA", rowTyName="types of leaves", cexTxt=2)
## ----PCA6, fig.height=7, fig.width=9, fig.align="center", echo=TRUE-----------
## creat copy of data and add rownames
irisD <- as.matrix(iris[,-5])
rownames(irisD) <- paste(iris$Species, rep(1:50,3), sep="_")
plotPCAw(t(irisD), gl(3,50,labels=c("setosa","versicolor","virginica")), tit="Iris Data PCA",
rowTyName="types of leaves", suplFig=FALSE, cexTxt=1.6, rotatePC=2, pointLabelPar=list(textCex=0.45))
## ----MA0, fig.height=6, fig.width=8, fig.align="center", echo=TRUE------------
## toy data
set.seed(2005); mat <- matrix(round(runif(2400),3), ncol=6)
mat[11:90,4:6] <- mat[11:90,4:6] +round(abs(rnorm(80)),3)
mat[11:90,] <- mat[11:90,] +0.3
dimnames(mat) <- list(paste("li",1:nrow(mat),sep="_"),paste(rep(letters[1:2],each=3),1:6,sep=""))
## assume 2 groups with 3 samples each
matMeans <- round(cbind(A=rowMeans(mat[,1:3]), B=rowMeans(mat[,4:6])),4)
## ----MA1, fig.height=6, fig.width=8, fig.align="center", echo=TRUE------------
## now we are ready to plot, M-values can be obtained by subtracting thr group-means
MAplotW(M=matMeans[,2] -matMeans[,1], A=rowMeans(mat))
## ----MA4, echo=TRUE-----------------------------------------------------------
## assume 2 groups with 3 samples each and run moderated t-test (from package 'limma')
tRes <- wrMisc::moderTest2grp(mat, gl(2,3), addResults=c("FDR","Mval","means"))
## ----MA5,fig.height=6, fig.width=8, fig.align="center", echo=TRUE------------
## convenient way, change fold-change threshold to 2x and mark who is beyond :
MAplotW(tRes, FCth=2, namesNBest="passFC")
## ----Volc1, fig.height=6, fig.width=8, fig.align="center", echo=TRUE----------
## let's generate some toy data
set.seed(2005); mat <- matrix(round(runif(900),2), ncol=9)
rownames(mat) <- paste0(rep(letters[1:25],each=4), rep(letters[2:26],4))
mat[1:50,4:6] <- mat[1:50,4:6] + rep(c(-1,1)*0.1,25)
mat[3:7,4:9] <- mat[3:7,4:9] + 0.7
mat[11:15,1:6] <- mat[11:15,1:6] - 0.7
## assume 2 groups with 3 samples each
gr3 <- gl(3,3,labels=c("C","A","B"))
tRes2 <- moderTest2grp(mat[,1:6], gl(2,3))
VolcanoPlotW(tRes2)
# now with thresholds, labels and arrow for expected ratio
VolcanoPlotW(tRes2, FCth=1.3, FdrThrs=0.2, namesNBest="pass", expFCarrow=c(0.75,2))
## ----Volc2, fig.height=6, fig.width=9.5, fig.align="center", echo=TRUE-------
## assume 3 groups with 3 samples each
tRes <- moderTestXgrp(mat, gr3)
layout(matrix(1:2, nrow=1))
VolcanoPlotW(tRes, FCth=1.3, FdrThrs=0.2, useComp=2)
VolcanoPlotW(tRes, FCth=1.3, FdrThrs=0.2, useComp=3)
## ----createHtmlWithPointsIdentif1, echo=TRUE----------------------------------
## Let's make some toy data
df1 <- data.frame(id=letters[1:10], x=1:10, y=rep(5,10) ,mou=paste("point",letters[1:10]),
link=file.path(tempdir(),paste(LETTERS[1:10],".html",sep="")),stringsAsFactors=FALSE)
## here we'll use R's tempdir, later you may want to choose other locations
pngFile <- file.path(tempdir(),"test01.png")
png(pngFile, width=800, height=600, res=72)
## here we'll just plot a set of horiontal points ...
plot(df1[,2:3], las=1, main="test01")
dev.off()
## Note : Special characters should be converted for proper display in html during mouse-over
df1$mou <- htmlSpecCharConv(df1$mou)
## Let's add the x- and y-coordiates of the points in pixels to the data.frame
df1 <- cbind(df1, convertPlotCoordPix(x=df1[,2], y=df1[,3], plotD=c(800,600), plotRes=72))
head(df1)
## Now make the html-page allowing to display mouse-over to the png made before
htmFile <- file.path(tempdir(),"test01.html")
mouseOverHtmlFile(df1, pngFile, HtmFileNa=htmFile, pxDiam=15,
textAtStart="Points in the figure are interactive to mouse-over ...",
textAtEnd="and/or may contain links")
## We still need to make some toy links
for(i in 1:nrow(df1)) cat(paste("point no ",i," : ",df1[i,1]," x=",df1[i,2]," y=",
df1[i,3],sep=""), file=df1$link[i])
## Now we are ready to open the html file using any browser ..
#from within R# browseURL(htmFile)
## ----sessionInfo, echo=FALSE--------------------------------------------------
sessionInfo()
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/inst/doc/wrGraphVignette1.R
|
---
title: "Getting started with wrGraph"
author: Wolfgang Raffelsberger
date: '`r Sys.Date()`'
output:
knitr:::html_vignette:
toc: true
fig_caption: yes
pdf_document:
highlight: null
number_sections: no
vignette: >
%\VignetteIndexEntry{wrGraphVignette1}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
## Introduction
This package contains a collection of various plotting functions, mostly as an extension of packages
[wrMisc](https://CRAN.R-project.org/package=wrMisc) and [wrProteo](https://CRAN.R-project.org/package=wrProteo).
```{r, include = FALSE}
knitr::opts_chunk$set(collapse=TRUE, comment = "#>")
```
```{r setup, echo=FALSE, messages=FALSE, warnings=FALSE}
suppressPackageStartupMessages({
library(wrMisc)
library(wrGraph)
library(FactoMineR)
library(factoextra)
})
```
This package is available from [CRAN](https://cran.r-project.org/), you might also have to install [wrMisc](https://CRAN.R-project.org/package=wrMisc), too.
If not yet installed, the lastest versions of this package can be installed like this :
```{r setup2, echo=TRUE, eval=FALSE}
install.packages("wrGraph")
```
During this vignette we'll also use the packages [FactoMineR](https://CRAN.R-project.org/package=FactoMineR) and [factoextra](https://CRAN.R-project.org/package=factoextra), let's test if they are installed and install if not yet present.
```{r setup3, echo=TRUE, eval=FALSE}
if(!requireNamespace("FactoMineR", quietly=TRUE)) install.packages("FactoMineR")
if(!requireNamespace("factoextra", quietly=TRUE)) install.packages("factoextra")
```
You cat start the vignette for this package by typing :
```{r vignBrowse, echo=TRUE, eval=FALSE}
# access vignette :
browseVignettes("wrGraph") # ... and the select the html output
```
To get started, we need to load the packages [wrMisc](https://CRAN.R-project.org/package=wrMisc) and [wrGraph (this package)](https://CRAN.R-project.org/package=wrGraph).
```{r setup4, echo=TRUE}
library("wrMisc")
library("wrGraph")
# This is version no:
packageVersion("wrGraph")
```
## Prepare Layout For Accomodating Multiple Smaller Plots
The function *partitionPlot()* prepares a matrix to serve as grid for segmenting the current device
(ie the available plotting region). It aims to optimize the layout based on a given number of plots to accommodate.
The user may choose if the layout should rather be adopted to landscape (default) or portrait geometry.
This might be useful in particular when during an analysis-pipeline it's not known/clear in advance how many plots might be needed in a single figure space.
```{r partitionPlot1, out.width="110%", out.heigth="110%", echo=TRUE}
## as the last column of the Iris-data is not numeric we choose -1
(part <- partitionPlot(ncol(iris)-1))
layout(part)
for(i in colnames(iris)[-5]) hist(iris[,i], main=i)
```
## Optimal Legend Location
The function *checkForLegLoc()* allows to check which corner of a given graph is less crowded for placing a legend there.
Basic legends can be added directly, or one can simply recuperate the location information.
```{r LegLoc1, echo=TRUE}
dat1 <- matrix(c(1:5,1,1:5,5), ncol=2)
grp <- c("abc","efghijk")
(legLoc <- checkForLegLoc(dat1, grp))
# now with more graphical parameters (using just the best location information)
plot(dat1, cex=2.5, col=rep(2:3,3),pch=rep(2:3,3))
legLoc <- checkForLegLoc(dat1, grp, showLegend=FALSE)
legend(legLoc$loc, legend=grp, text.col=2:3, pch=rep(2:3), cex=0.8)
```
## One More Histogram Function ...
Histograms are a very versatile tool for rapidly gaining insights in the distribution of data.
This package presents a histogram function allowing to conveniently **work with log2-data** and (if desired)
display numbers calculated back to linear values on the x-axis.
Default settings aim to give rather a quick overview, for "high resolution" representations one could set a high number of breaks or one might also consider other/alternative graphical representations. Some of the alternatives are shown later in this vignette.
```{r Hist1, out.width="110%", out.heigth="110%", echo=TRUE}
set.seed(2016); dat1 <- round(c(rnorm(200,6,0.5), rlnorm(300,2,0.5), rnorm(100,17)),2)
dat1 <- dat1[which(dat1 <50 & dat1 > 0.2)]
histW(dat1, br="FD", isLog=FALSE)
```
One interesting feature is the fact that this fucntions can handle log-data (and display x-axis classes as linear) :
```{r Hist2, out.width="110%", out.heigth="110%", echo=TRUE}
## view as log, but x-scale in linear
histW(log2(dat1), br="FD", isLog=TRUE, silent=TRUE)
```
Now we can combine this with the previous segmentation to accomodate 4 histograms :
```{r Hist4, out.width="110%", out.heigth="150%", echo=TRUE}
## quick overview of distributions
layout(partitionPlot(4))
for(i in 1:4) histW(iris[,i], isLog=FALSE, tit=colnames(iris)[i])
```
### Small Histogram(s) as Legend
With some plots it may be useful to add small histograms for the x- and/or y-data.
```{r Hist5, out.width="110%", out.heigth="150%", echo=TRUE}
layout(1)
plot(iris[,1:2], col=rgb(0.4,0.4,0.4,0.3), pch=16, main="Iris Data")
legendHist(iris[,1], loc="br", legTit=colnames(iris)[1], cex=0.5)
legendHist(iris[,2], loc="tl", legTit=colnames(iris)[2], cex=0.5)
```
## Violin Plots
[Violin plots](https://en.wikipedia.org/wiki/Violin_plot) or vioplots are basically an adaptation of plotting the
[Kernel density estimation](https://en.wikipedia.org/wiki/Kernel_density_estimation) allowing to compare multiple data-sets.
Please note, that although smoothed distributions please the human eye, some data-sets do not have such a continuous character.
Compared to the 'original' vioplots in R from package [vioplot](https://CRAN.R-project.org/package=vioplot),
the function provided here offers more flexibility for data-formats accepted (including data.frames and lists), coloring and display of n.
All NA-values are ignored and n is adkusted accordingly.
In the case of the Iris-data, there are no NAs and thus n is constant, in consequence the number of values (n) is displayed only once.
However, frequently the number of values per data-set/violin n may vary (presence of NAs of list with vectors of different sizes).
```{r vioplot1, fig.height=6, fig.width=8, echo=TRUE}
vioplotW(iris[,-5], tit="Iris-Data Violin Plot")
```
The smoothing of the curves uses default parameters from the function _sm.density_ from the package [sm](https://CRAN.R-project.org/package=sm).
In some cases the Kernel smoothing may appear to strong, this behaviour can be modified using the argument _hh_ (which is passed on as argument _h_ to the function _sm.density_).
```{r vioplot2, fig.height=6, fig.width=8, echo=TRUE}
## less smoothing
vioplotW(iris[,-5], tit="Iris-Data Violin Plot ('nervous')", hh=0.15)
```
## Plotting Sorted Values ('Summed Frequency')
This plot offers an alternative to histograms and density-plots.
While histograms and density-plots are very intuitive, their interpretation may pose some difficulties due to the smoothing effect
of Kernel-functions or the non-trivial choice of optimal width of bars (histogram) may influence interpretation.
As alternative, a plot is presented which basically reads like a summed frequency plot and has the main advantage, that all points of data
may be easily displayed.
Thus the resultant plot does not suffer from deformation due to binning or smoothing and offers maximal 'resolution'.
```{r cumFrqPlot1, echo=TRUE}
cumFrqPlot(iris[,1:4])
```
For example, the Iris-data are rounded. As a result in the plot above the line is not progressing smooth but with more marked character of steps of stairs.
To get the same conclusion one would need to increase the number of bars in a histogram very much which would makes it in our experience more difficult to evaluate the same time the global distribution character.
At this plot you may note that the curves patal.width and petal.length look differently.
On the previous vioplots you may have noticed the bimodal character of the values, again this plot may be helpful to identify distributions which are very difficult to see well using boxplots.
## Color-Code Numeric Content Of Matrix (Heatmap)
To get a quick overview of the distribution of data and, in particular, of local phenomena it is useful to express numeric values as colored boxes. The function _image()_ from the graphic-package provides basic help.
Generally this type of display is called _heatmap_, however, most functions in R combine this directly with organizing by hierarchical clustering (_heatmap()_ (package stats) or _heatmap.2()_ from package [gplots](https://CRAN.R-project.org/package=wrMisc)).
Simple plotting without reorganizing rows and columns can be done using the function _imageW()_ from this package, offering convenient options for displaying row- and column-names.
Using the argument _transp_ you can decide if the data should be shown _as is_ or rotated by 90 degrees (as in example below).
Furthermore, the output can be produced using stadard graphics or using the trellis/lattice framework. The latter includes also an automatic legend for the color-codes.
Below, the first 40 lines of the Iris-dataset are used :
```{r imageW, echo=TRUE}
par(mar=c(4, 5.5, 4, 1))
imageW(as.matrix(iris[1:40,1:4]), transp=FALSE, tit="Iris-Data (head)")
```
Here again the Iris-data plotted using the lattice/trellis framework :
```{r imageW2, fig.height=2.5, fig.width=9, fig.align="center", echo=TRUE}
imageW(as.matrix(iris[1:20,1:4]), latticeVersion=TRUE, transp=FALSE, col=c("blue","red"),
rotXlab=45, yLab="Observation no", tit="Iris-Data (head)")
```
Note, by default this version forces the _aspect_ argument of _levelplot()_ to square shapes.
In some cases it may be desirable to pass the color-gradient through the value of 0 at a predefined color (use the center element of tha argument _col_).
One can also display the (rounded) values and choose a custom color for NA-values.
```{r imageW3, fig.height=6, fig.width=5, echo=TRUE}
ma1 <- matrix(-7:16,nc=4,dimnames=list(letters[1:6],LETTERS[1:4]))
ma1[1,2:3] <- 0
ma1[3,3] <- ma1[3:4,4] <- NA
imageW(ma1, latticeVersion=TRUE, col=c("blue","grey","red"), NAcol="grey92",
rotXlab=0, cexDispl=0.8, tit="Balanced color gradient")
```
By changing the number of desired color-steps we can get the value of 0 better centered to grey color.
Below, the value of +1 is shown in grey as -1 in contrast to the example above.
```{r imageW4, fig.height=6, fig.width=5, echo=TRUE}
imageW(ma1, latticeVersion=TRUE, col=c("blue","grey","red"), NAcol="grey92",
rotXlab=0, nColor=8, cexDispl=0.8, tit="Balanced color gradient")
```
## Examine Counts Based On Variable Threshold Levels (for ROC curves)
The next plot is dedicated to visualize counting results with moving thresholds.
While a given threshold criteria moves up or down the resulting number of values passing may not necessarily follow in a linear way.
This function lets you follow multiple types of samples (eg type of leave in the Iris-data) in a single plot.
In particular when constructing [ROC curves](https://en.wikipedia.org/wiki/Receiver_operating_characteristic) it may also be helpful to visualize the (absolute) counting data used underneath before determining TP and FP ratios.
Typically used in context of benchmark-tests in proteomics.
```{r cumulCountPlot1, echo=TRUE}
thr <- seq(min(iris[,1:4]), max(iris[,1:4])+0.1,length.out=100)
irisC <- sapply(thr,function(x) colSums(iris[,1:4] < x))
irisC <- cbind(thr,t(irisC))
head(irisC)
staggerdCountsPlot(irisC[,], countsCol=colnames(iris)[1:4], tit="Iris-Data")
staggerdCountsPlot(irisC[,], varCountNa="Sepal", tit="Iris-Data")
staggerdCountsPlot(irisC[,], varCountNa="Sepal", tit="Iris-Data (log-scale)", logScale=TRUE)
```
## Compare Two Groups With Sub-Organisation Each
In real-world testing data have often some nested structure.
For example repeated measures from a set of patients which can be organized as diseased and non-diseased.
This plot allows to plot all values obtained from the each patient together, then organized by disease-groups.
For this example suppose the Iris-data were organized as 10 sets of 5 measures each (of course, in this case it is a pure hypothesis).
Then, we can plot while highlighting the two factors (ie species and set of measurement).
Basically we need to furnish with the main data two additional factors for the groupings.
Note, that the 1st factor should contain the smaller sub-groups to visually inspect if there are any batch effects.
This plot is not well adopted to big data (it will get too crowded).
```{r plotBy2Groups1, echo=TRUE}
dat <- iris[which(iris$Species %in% c("setosa","versicolor")),]
plotBy2Groups(dat$Sepal.Length, gl(2,50,labels=c("setosa","versicolor")),
gl(20,5), yLab="Sepal.Length")
```
## Plotting Linear Regression And Confidence Intervals
The function _plotLinReg()_ provides help to display a series of bivariate points given in 'dat' (multiple data formats possible), to model a [linear regression](https://en.wikipedia.org/wiki/Linear_regression) and plot the results.
```{r plotLinReg1, echo=TRUE}
plotLinReg(iris$Sepal.Length, iris$Petal.Width, tit="Iris-Data")
```
## Principal Components Analysis (PCA)
Principal components analysis, [PCA](https://en.wikipedia.org/wiki/Principal_component_analysis), is a very powerful method
to investigate similarity and correlation in larger sets of data.
Please note that several implementations exist in R (eg *prcomp()* in the base package stats or the package
[FactoMineR](https://CRAN.R-project.org/package=FactoMineR)).
We'll start by looking at the plot produced with the basic function and FactoMineR, too.
Let's look at the similarity of the 3 Iris-species from the Iris data-set.
```{r PCA1, fig.height=7, fig.width=7, echo=TRUE}
## the basic way
iris.prc <- prcomp(iris[,1:4], scale.=TRUE)
biplot(iris.prc) # traditional plot
```
```{r PCA3, echo=TRUE}
## via FactoMineR
chPa <- c(requireNamespace("FactoMineR", quietly=TRUE), requireNamespace("dplyr", quietly=TRUE),
requireNamespace("factoextra", quietly=TRUE))
if(all(chPa)) {
library(FactoMineR); library(dplyr); library(factoextra)
iris.Fac <- PCA(iris[,1:4],scale.unit=TRUE, graph=FALSE)
fviz_pca_ind(iris.Fac, geom.ind="point", col.ind=iris$Species, palette=c(2,4,3),
addEllipses=TRUE, legend.title="Groups" )
} else message("You need to install packages 'dplyr', 'FactoMineR' and 'factoextra' for this figure")
```
However, some sets of points do not always follow elliptic shapes.
Note, that FactoMineR represented the 2nd principal component upside-down compared to the very first PCA figure.
To facilitate comparisons, the function *plotPCAw* has an argument allowing to rotate/flip any principal component axis.
With more crowded data-sets it may be useful to rather highlight the more dense regions.
For this reason this package proposes to use [bagplots](https://en.wikipedia.org/wiki/Bagplot)
to highlight the region with 50% of data-points (in analogy to boxplots),
a simple line draws the contour of the most distant points.
```{r PCA4, echo=TRUE}
## via wrGraph, similar to FactoMineR but with bagplots
plotPCAw(t(as.matrix(iris[,-5])), gl(3,50,labels=c("setosa","versicolor","virginica")),
tit="Iris Data", rowTyName="types of leaves", suplFig=FALSE, cexTxt=1.3, rotatePC=2)
```
Thus, you can see in this case, there is some intersection between *versicolor* and *virginica* species,
but the center regions stay apart. Of course, similar to boxplots, this representation is nor adopted/recommended
for multi-modal distributions within one group of points.
One might get some indications about this by starting the data-analysis by inspecting histograms or vioplots for each set/column of data.
You can also add the 3rd principal component and the Scree-plot :
```{r PCA5, fig.height=12, fig.width=9, fig.align="center", echo=TRUE}
## including 3rd component and Screeplot
plotPCAw(t(as.matrix(iris[,-5])), gl(3,50,labels=c("setosa","versicolor","virginica")),
tit="Iris Data PCA", rowTyName="types of leaves", cexTxt=2)
```
### Label all points in PCA
In some cases it may be useful to identify all individual points on a plot.
```{r PCA6, fig.height=7, fig.width=9, fig.align="center", echo=TRUE}
## creat copy of data and add rownames
irisD <- as.matrix(iris[,-5])
rownames(irisD) <- paste(iris$Species, rep(1:50,3), sep="_")
plotPCAw(t(irisD), gl(3,50,labels=c("setosa","versicolor","virginica")), tit="Iris Data PCA",
rowTyName="types of leaves", suplFig=FALSE, cexTxt=1.6, rotatePC=2, pointLabelPar=list(textCex=0.45))
```
## MA-Plot
The aim of [MA-plots](https://en.wikipedia.org/wiki/MA_plot) consists in displaying a relative change on one axis (ordinate) while
showing the absolute (mean) value on the x-axis (abscissa).
This plot is very useful when inspecting larger data-sets for random or systematic effects,
numerous implementations for specific applications exist (eg *plotMA* in [DEseq2](https://bioconductor.org/packages/release/bioc/html/DESeq2.html)).
The version presented here is rather generic and uses transparent points to avoid getting plots too crowded.
First, let's generate some toy data:
```{r MA0, fig.height=6, fig.width=8, fig.align="center", echo=TRUE}
## toy data
set.seed(2005); mat <- matrix(round(runif(2400),3), ncol=6)
mat[11:90,4:6] <- mat[11:90,4:6] +round(abs(rnorm(80)),3)
mat[11:90,] <- mat[11:90,] +0.3
dimnames(mat) <- list(paste("li",1:nrow(mat),sep="_"),paste(rep(letters[1:2],each=3),1:6,sep=""))
## assume 2 groups with 3 samples each
matMeans <- round(cbind(A=rowMeans(mat[,1:3]), B=rowMeans(mat[,4:6])),4)
```
One way of using the function _MAplotW()_ is by providing (explicitely) the M- and A-values.
By default a threshold-line is drawn for a fold-change of 1.5x (which on log2 scale apprears at +/- 0.58).
```{r MA1, fig.height=6, fig.width=8, fig.align="center", echo=TRUE}
## now we are ready to plot, M-values can be obtained by subtracting thr group-means
MAplotW(M=matMeans[,2] -matMeans[,1], A=rowMeans(mat))
```
The function _MAplotW_ may also be used to conveniently inspect results from t-tests performed with the package [wrMisc](https://CRAN.R-project.org/package=wrMisc)
or from the very popular package [limma](https://www.bioconductor.org/packages/release/bioc/html/limma.html).
```{r MA4, echo=TRUE}
## assume 2 groups with 3 samples each and run moderated t-test (from package 'limma')
tRes <- wrMisc::moderTest2grp(mat, gl(2,3), addResults=c("FDR","Mval","means"))
```
This object conatains data for different types of plots (MA-plot, Volcano-Plot, etc ..), let's also mark the names of those passing the fold-change threshold.
```{r MA5,fig.height=6, fig.width=8, fig.align="center", echo=TRUE}
## convenient way, change fold-change threshold to 2x and mark who is beyond :
MAplotW(tRes, FCth=2, namesNBest="passFC")
```
In the plot above one can see easily most of the points from the second group which have been increased in lines 11 to 90,
many of them exceed a (based on linear data) fold-change of 2 (which on log2 scale appears at 1.0).
## Volcano-Plot
The aim of [Volcano-plots](https://en.wikipedia.org/wiki/Volcano_plot_(statistics)) is to display a log-ratios on the x-axis (ordinate) and outcome of statistical test on the other axis (abscissa). Typically the statistical values are represented as negative log10.
This plot is very useful when inspecting larger data-sets for random or systematic effects.
Points with high log-ratios (ie high fold-change) may not always have enthusiastic p-values, too.
Many times such divergences may point to high intra-group variability.
Numerous implementations for specific applications exist (eg the package [EnhancedVolcano](https://bioconductor.org/packages/release/bioc/html/EnhancedVolcano.html)).
The version presented here is rather generic and uses transparent points to avoid getting plots too crowded.
Furthermore, this version has the advantage to take all information needed directly in MArrayLM-objects, like the output of moderTest2grp() or moderTestXgrp().
```{r Volc1, fig.height=6, fig.width=8, fig.align="center", echo=TRUE}
## let's generate some toy data
set.seed(2005); mat <- matrix(round(runif(900),2), ncol=9)
rownames(mat) <- paste0(rep(letters[1:25],each=4), rep(letters[2:26],4))
mat[1:50,4:6] <- mat[1:50,4:6] + rep(c(-1,1)*0.1,25)
mat[3:7,4:9] <- mat[3:7,4:9] + 0.7
mat[11:15,1:6] <- mat[11:15,1:6] - 0.7
## assume 2 groups with 3 samples each
gr3 <- gl(3,3,labels=c("C","A","B"))
tRes2 <- moderTest2grp(mat[,1:6], gl(2,3))
VolcanoPlotW(tRes2)
# now with thresholds, labels and arrow for expected ratio
VolcanoPlotW(tRes2, FCth=1.3, FdrThrs=0.2, namesNBest="pass", expFCarrow=c(0.75,2))
```
Note, that this exampe is very small and for this reason the function _fdrtool()_ used internally issues some warnings since the estimation of lfdr is not optimal.
```{r Volc2, fig.height=6, fig.width=9.5, fig.align="center", echo=TRUE}
## assume 3 groups with 3 samples each
tRes <- moderTestXgrp(mat, gr3)
layout(matrix(1:2, nrow=1))
VolcanoPlotW(tRes, FCth=1.3, FdrThrs=0.2, useComp=2)
VolcanoPlotW(tRes, FCth=1.3, FdrThrs=0.2, useComp=3)
```
## Standalone html Page With Plot And Mouse-Over Interactive Features
The idea of this function dates before somehow similar applications were made possible using [Shiny](https://shiny.posit.co/).
In this case the original idea was simply to provide help to identify points in a plot and display via mouse-over labels to display and by providing clickable links.
To do so, very simple html documents are created which display a separately saved image and have a section indicating at which location of the figure which information should be displayed as mouse-over and providing the clickable links.
In high-throughput biology many times researchers want quickly know which protein or gene a given point in a graphic corresponds and being able to get further information on this protein or gene via links to [UniProt](https://www.uniprot.org) or [GenBank](https://www.ncbi.nlm.nih.gov/genbank).
As this functionality was made for separate html documents it's output cannot be easily integrated into a vignette like this one.
To generate such a simple mouse-over interactive html document, the user is invited to run the code
of this vignette. At the last step you could ask R to open the interactive html page in the default browser.
Concerning the path provided in the argument *pngFileNa* of the function *mouseOverHtmlFile*:
In a real world case, you might want to choose other
locations to save files rather than R-temp which will be deleted when closing your instance of R.
It is also possible to work with relative paths (eg by giving the png-filename without path).
Then the resultant html will simply require the png-file to be in the same directory as the html itself, and similarly for the clickable links.
This results in files that are very easy to distribute to other people, in particular if the clickable links are pointing to the internet,
however, the pnh-file always needs to be in the same directory as the html ...
If you have the possibility to make the png-file accessible through a url, you could also provide this url.
The example below shows usage when specifying absolute paths.
Please note that the resulting html will not display the image if your browser cannot access the image any more.
```{r createHtmlWithPointsIdentif1, echo=TRUE}
## Let's make some toy data
df1 <- data.frame(id=letters[1:10], x=1:10, y=rep(5,10) ,mou=paste("point",letters[1:10]),
link=file.path(tempdir(),paste(LETTERS[1:10],".html",sep="")),stringsAsFactors=FALSE)
## here we'll use R's tempdir, later you may want to choose other locations
pngFile <- file.path(tempdir(),"test01.png")
png(pngFile, width=800, height=600, res=72)
## here we'll just plot a set of horiontal points ...
plot(df1[,2:3], las=1, main="test01")
dev.off()
## Note : Special characters should be converted for proper display in html during mouse-over
df1$mou <- htmlSpecCharConv(df1$mou)
## Let's add the x- and y-coordiates of the points in pixels to the data.frame
df1 <- cbind(df1, convertPlotCoordPix(x=df1[,2], y=df1[,3], plotD=c(800,600), plotRes=72))
head(df1)
## Now make the html-page allowing to display mouse-over to the png made before
htmFile <- file.path(tempdir(),"test01.html")
mouseOverHtmlFile(df1, pngFile, HtmFileNa=htmFile, pxDiam=15,
textAtStart="Points in the figure are interactive to mouse-over ...",
textAtEnd="and/or may contain links")
## We still need to make some toy links
for(i in 1:nrow(df1)) cat(paste("point no ",i," : ",df1[i,1]," x=",df1[i,2]," y=",
df1[i,3],sep=""), file=df1$link[i])
## Now we are ready to open the html file using any browser ..
#from within R# browseURL(htmFile)
```
## Acknowledgements
The author wants to acknowledge the support by the [IGBMC](https://www.igbmc.fr) (CNRS UMR 7104, Inserm U 1258, UdS), [CNRS](https://www.cnrs.fr/en), [Université de Strasbourg](https://www.unistra.fr) and [Inserm](https://www.inserm.fr) and of course all collegues from the [IGBMC proteomics platform](https://proteomics.igbmc.fr).
The author wishes to thank the [CRAN-staff](https://CRAN.R-project.org) for all their efforts in maintaining this repository of R-packages.
Thank you for you interest in this package.
This package is constantly evolving, new functions may get added to the next version.
## Appendix: Session-Info
For completeness, here detailed documentation of versions used to produce this document.
\small
```{r sessionInfo, echo=FALSE}
sessionInfo()
```
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/inst/doc/wrGraphVignette1.Rmd
|
---
title: "Getting started with wrGraph"
author: Wolfgang Raffelsberger
date: '`r Sys.Date()`'
output:
knitr:::html_vignette:
toc: true
fig_caption: yes
pdf_document:
highlight: null
number_sections: no
vignette: >
%\VignetteIndexEntry{wrGraphVignette1}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
## Introduction
This package contains a collection of various plotting functions, mostly as an extension of packages
[wrMisc](https://CRAN.R-project.org/package=wrMisc) and [wrProteo](https://CRAN.R-project.org/package=wrProteo).
```{r, include = FALSE}
knitr::opts_chunk$set(collapse=TRUE, comment = "#>")
```
```{r setup, echo=FALSE, messages=FALSE, warnings=FALSE}
suppressPackageStartupMessages({
library(wrMisc)
library(wrGraph)
library(FactoMineR)
library(factoextra)
})
```
This package is available from [CRAN](https://cran.r-project.org/), you might also have to install [wrMisc](https://CRAN.R-project.org/package=wrMisc), too.
If not yet installed, the lastest versions of this package can be installed like this :
```{r setup2, echo=TRUE, eval=FALSE}
install.packages("wrGraph")
```
During this vignette we'll also use the packages [FactoMineR](https://CRAN.R-project.org/package=FactoMineR) and [factoextra](https://CRAN.R-project.org/package=factoextra), let's test if they are installed and install if not yet present.
```{r setup3, echo=TRUE, eval=FALSE}
if(!requireNamespace("FactoMineR", quietly=TRUE)) install.packages("FactoMineR")
if(!requireNamespace("factoextra", quietly=TRUE)) install.packages("factoextra")
```
You cat start the vignette for this package by typing :
```{r vignBrowse, echo=TRUE, eval=FALSE}
# access vignette :
browseVignettes("wrGraph") # ... and the select the html output
```
To get started, we need to load the packages [wrMisc](https://CRAN.R-project.org/package=wrMisc) and [wrGraph (this package)](https://CRAN.R-project.org/package=wrGraph).
```{r setup4, echo=TRUE}
library("wrMisc")
library("wrGraph")
# This is version no:
packageVersion("wrGraph")
```
## Prepare Layout For Accomodating Multiple Smaller Plots
The function *partitionPlot()* prepares a matrix to serve as grid for segmenting the current device
(ie the available plotting region). It aims to optimize the layout based on a given number of plots to accommodate.
The user may choose if the layout should rather be adopted to landscape (default) or portrait geometry.
This might be useful in particular when during an analysis-pipeline it's not known/clear in advance how many plots might be needed in a single figure space.
```{r partitionPlot1, out.width="110%", out.heigth="110%", echo=TRUE}
## as the last column of the Iris-data is not numeric we choose -1
(part <- partitionPlot(ncol(iris)-1))
layout(part)
for(i in colnames(iris)[-5]) hist(iris[,i], main=i)
```
## Optimal Legend Location
The function *checkForLegLoc()* allows to check which corner of a given graph is less crowded for placing a legend there.
Basic legends can be added directly, or one can simply recuperate the location information.
```{r LegLoc1, echo=TRUE}
dat1 <- matrix(c(1:5,1,1:5,5), ncol=2)
grp <- c("abc","efghijk")
(legLoc <- checkForLegLoc(dat1, grp))
# now with more graphical parameters (using just the best location information)
plot(dat1, cex=2.5, col=rep(2:3,3),pch=rep(2:3,3))
legLoc <- checkForLegLoc(dat1, grp, showLegend=FALSE)
legend(legLoc$loc, legend=grp, text.col=2:3, pch=rep(2:3), cex=0.8)
```
## One More Histogram Function ...
Histograms are a very versatile tool for rapidly gaining insights in the distribution of data.
This package presents a histogram function allowing to conveniently **work with log2-data** and (if desired)
display numbers calculated back to linear values on the x-axis.
Default settings aim to give rather a quick overview, for "high resolution" representations one could set a high number of breaks or one might also consider other/alternative graphical representations. Some of the alternatives are shown later in this vignette.
```{r Hist1, out.width="110%", out.heigth="110%", echo=TRUE}
set.seed(2016); dat1 <- round(c(rnorm(200,6,0.5), rlnorm(300,2,0.5), rnorm(100,17)),2)
dat1 <- dat1[which(dat1 <50 & dat1 > 0.2)]
histW(dat1, br="FD", isLog=FALSE)
```
One interesting feature is the fact that this fucntions can handle log-data (and display x-axis classes as linear) :
```{r Hist2, out.width="110%", out.heigth="110%", echo=TRUE}
## view as log, but x-scale in linear
histW(log2(dat1), br="FD", isLog=TRUE, silent=TRUE)
```
Now we can combine this with the previous segmentation to accomodate 4 histograms :
```{r Hist4, out.width="110%", out.heigth="150%", echo=TRUE}
## quick overview of distributions
layout(partitionPlot(4))
for(i in 1:4) histW(iris[,i], isLog=FALSE, tit=colnames(iris)[i])
```
### Small Histogram(s) as Legend
With some plots it may be useful to add small histograms for the x- and/or y-data.
```{r Hist5, out.width="110%", out.heigth="150%", echo=TRUE}
layout(1)
plot(iris[,1:2], col=rgb(0.4,0.4,0.4,0.3), pch=16, main="Iris Data")
legendHist(iris[,1], loc="br", legTit=colnames(iris)[1], cex=0.5)
legendHist(iris[,2], loc="tl", legTit=colnames(iris)[2], cex=0.5)
```
## Violin Plots
[Violin plots](https://en.wikipedia.org/wiki/Violin_plot) or vioplots are basically an adaptation of plotting the
[Kernel density estimation](https://en.wikipedia.org/wiki/Kernel_density_estimation) allowing to compare multiple data-sets.
Please note, that although smoothed distributions please the human eye, some data-sets do not have such a continuous character.
Compared to the 'original' vioplots in R from package [vioplot](https://CRAN.R-project.org/package=vioplot),
the function provided here offers more flexibility for data-formats accepted (including data.frames and lists), coloring and display of n.
All NA-values are ignored and n is adkusted accordingly.
In the case of the Iris-data, there are no NAs and thus n is constant, in consequence the number of values (n) is displayed only once.
However, frequently the number of values per data-set/violin n may vary (presence of NAs of list with vectors of different sizes).
```{r vioplot1, fig.height=6, fig.width=8, echo=TRUE}
vioplotW(iris[,-5], tit="Iris-Data Violin Plot")
```
The smoothing of the curves uses default parameters from the function _sm.density_ from the package [sm](https://CRAN.R-project.org/package=sm).
In some cases the Kernel smoothing may appear to strong, this behaviour can be modified using the argument _hh_ (which is passed on as argument _h_ to the function _sm.density_).
```{r vioplot2, fig.height=6, fig.width=8, echo=TRUE}
## less smoothing
vioplotW(iris[,-5], tit="Iris-Data Violin Plot ('nervous')", hh=0.15)
```
## Plotting Sorted Values ('Summed Frequency')
This plot offers an alternative to histograms and density-plots.
While histograms and density-plots are very intuitive, their interpretation may pose some difficulties due to the smoothing effect
of Kernel-functions or the non-trivial choice of optimal width of bars (histogram) may influence interpretation.
As alternative, a plot is presented which basically reads like a summed frequency plot and has the main advantage, that all points of data
may be easily displayed.
Thus the resultant plot does not suffer from deformation due to binning or smoothing and offers maximal 'resolution'.
```{r cumFrqPlot1, echo=TRUE}
cumFrqPlot(iris[,1:4])
```
For example, the Iris-data are rounded. As a result in the plot above the line is not progressing smooth but with more marked character of steps of stairs.
To get the same conclusion one would need to increase the number of bars in a histogram very much which would makes it in our experience more difficult to evaluate the same time the global distribution character.
At this plot you may note that the curves patal.width and petal.length look differently.
On the previous vioplots you may have noticed the bimodal character of the values, again this plot may be helpful to identify distributions which are very difficult to see well using boxplots.
## Color-Code Numeric Content Of Matrix (Heatmap)
To get a quick overview of the distribution of data and, in particular, of local phenomena it is useful to express numeric values as colored boxes. The function _image()_ from the graphic-package provides basic help.
Generally this type of display is called _heatmap_, however, most functions in R combine this directly with organizing by hierarchical clustering (_heatmap()_ (package stats) or _heatmap.2()_ from package [gplots](https://CRAN.R-project.org/package=wrMisc)).
Simple plotting without reorganizing rows and columns can be done using the function _imageW()_ from this package, offering convenient options for displaying row- and column-names.
Using the argument _transp_ you can decide if the data should be shown _as is_ or rotated by 90 degrees (as in example below).
Furthermore, the output can be produced using stadard graphics or using the trellis/lattice framework. The latter includes also an automatic legend for the color-codes.
Below, the first 40 lines of the Iris-dataset are used :
```{r imageW, echo=TRUE}
par(mar=c(4, 5.5, 4, 1))
imageW(as.matrix(iris[1:40,1:4]), transp=FALSE, tit="Iris-Data (head)")
```
Here again the Iris-data plotted using the lattice/trellis framework :
```{r imageW2, fig.height=2.5, fig.width=9, fig.align="center", echo=TRUE}
imageW(as.matrix(iris[1:20,1:4]), latticeVersion=TRUE, transp=FALSE, col=c("blue","red"),
rotXlab=45, yLab="Observation no", tit="Iris-Data (head)")
```
Note, by default this version forces the _aspect_ argument of _levelplot()_ to square shapes.
In some cases it may be desirable to pass the color-gradient through the value of 0 at a predefined color (use the center element of tha argument _col_).
One can also display the (rounded) values and choose a custom color for NA-values.
```{r imageW3, fig.height=6, fig.width=5, echo=TRUE}
ma1 <- matrix(-7:16,nc=4,dimnames=list(letters[1:6],LETTERS[1:4]))
ma1[1,2:3] <- 0
ma1[3,3] <- ma1[3:4,4] <- NA
imageW(ma1, latticeVersion=TRUE, col=c("blue","grey","red"), NAcol="grey92",
rotXlab=0, cexDispl=0.8, tit="Balanced color gradient")
```
By changing the number of desired color-steps we can get the value of 0 better centered to grey color.
Below, the value of +1 is shown in grey as -1 in contrast to the example above.
```{r imageW4, fig.height=6, fig.width=5, echo=TRUE}
imageW(ma1, latticeVersion=TRUE, col=c("blue","grey","red"), NAcol="grey92",
rotXlab=0, nColor=8, cexDispl=0.8, tit="Balanced color gradient")
```
## Examine Counts Based On Variable Threshold Levels (for ROC curves)
The next plot is dedicated to visualize counting results with moving thresholds.
While a given threshold criteria moves up or down the resulting number of values passing may not necessarily follow in a linear way.
This function lets you follow multiple types of samples (eg type of leave in the Iris-data) in a single plot.
In particular when constructing [ROC curves](https://en.wikipedia.org/wiki/Receiver_operating_characteristic) it may also be helpful to visualize the (absolute) counting data used underneath before determining TP and FP ratios.
Typically used in context of benchmark-tests in proteomics.
```{r cumulCountPlot1, echo=TRUE}
thr <- seq(min(iris[,1:4]), max(iris[,1:4])+0.1,length.out=100)
irisC <- sapply(thr,function(x) colSums(iris[,1:4] < x))
irisC <- cbind(thr,t(irisC))
head(irisC)
staggerdCountsPlot(irisC[,], countsCol=colnames(iris)[1:4], tit="Iris-Data")
staggerdCountsPlot(irisC[,], varCountNa="Sepal", tit="Iris-Data")
staggerdCountsPlot(irisC[,], varCountNa="Sepal", tit="Iris-Data (log-scale)", logScale=TRUE)
```
## Compare Two Groups With Sub-Organisation Each
In real-world testing data have often some nested structure.
For example repeated measures from a set of patients which can be organized as diseased and non-diseased.
This plot allows to plot all values obtained from the each patient together, then organized by disease-groups.
For this example suppose the Iris-data were organized as 10 sets of 5 measures each (of course, in this case it is a pure hypothesis).
Then, we can plot while highlighting the two factors (ie species and set of measurement).
Basically we need to furnish with the main data two additional factors for the groupings.
Note, that the 1st factor should contain the smaller sub-groups to visually inspect if there are any batch effects.
This plot is not well adopted to big data (it will get too crowded).
```{r plotBy2Groups1, echo=TRUE}
dat <- iris[which(iris$Species %in% c("setosa","versicolor")),]
plotBy2Groups(dat$Sepal.Length, gl(2,50,labels=c("setosa","versicolor")),
gl(20,5), yLab="Sepal.Length")
```
## Plotting Linear Regression And Confidence Intervals
The function _plotLinReg()_ provides help to display a series of bivariate points given in 'dat' (multiple data formats possible), to model a [linear regression](https://en.wikipedia.org/wiki/Linear_regression) and plot the results.
```{r plotLinReg1, echo=TRUE}
plotLinReg(iris$Sepal.Length, iris$Petal.Width, tit="Iris-Data")
```
## Principal Components Analysis (PCA)
Principal components analysis, [PCA](https://en.wikipedia.org/wiki/Principal_component_analysis), is a very powerful method
to investigate similarity and correlation in larger sets of data.
Please note that several implementations exist in R (eg *prcomp()* in the base package stats or the package
[FactoMineR](https://CRAN.R-project.org/package=FactoMineR)).
We'll start by looking at the plot produced with the basic function and FactoMineR, too.
Let's look at the similarity of the 3 Iris-species from the Iris data-set.
```{r PCA1, fig.height=7, fig.width=7, echo=TRUE}
## the basic way
iris.prc <- prcomp(iris[,1:4], scale.=TRUE)
biplot(iris.prc) # traditional plot
```
```{r PCA3, echo=TRUE}
## via FactoMineR
chPa <- c(requireNamespace("FactoMineR", quietly=TRUE), requireNamespace("dplyr", quietly=TRUE),
requireNamespace("factoextra", quietly=TRUE))
if(all(chPa)) {
library(FactoMineR); library(dplyr); library(factoextra)
iris.Fac <- PCA(iris[,1:4],scale.unit=TRUE, graph=FALSE)
fviz_pca_ind(iris.Fac, geom.ind="point", col.ind=iris$Species, palette=c(2,4,3),
addEllipses=TRUE, legend.title="Groups" )
} else message("You need to install packages 'dplyr', 'FactoMineR' and 'factoextra' for this figure")
```
However, some sets of points do not always follow elliptic shapes.
Note, that FactoMineR represented the 2nd principal component upside-down compared to the very first PCA figure.
To facilitate comparisons, the function *plotPCAw* has an argument allowing to rotate/flip any principal component axis.
With more crowded data-sets it may be useful to rather highlight the more dense regions.
For this reason this package proposes to use [bagplots](https://en.wikipedia.org/wiki/Bagplot)
to highlight the region with 50% of data-points (in analogy to boxplots),
a simple line draws the contour of the most distant points.
```{r PCA4, echo=TRUE}
## via wrGraph, similar to FactoMineR but with bagplots
plotPCAw(t(as.matrix(iris[,-5])), gl(3,50,labels=c("setosa","versicolor","virginica")),
tit="Iris Data", rowTyName="types of leaves", suplFig=FALSE, cexTxt=1.3, rotatePC=2)
```
Thus, you can see in this case, there is some intersection between *versicolor* and *virginica* species,
but the center regions stay apart. Of course, similar to boxplots, this representation is nor adopted/recommended
for multi-modal distributions within one group of points.
One might get some indications about this by starting the data-analysis by inspecting histograms or vioplots for each set/column of data.
You can also add the 3rd principal component and the Scree-plot :
```{r PCA5, fig.height=12, fig.width=9, fig.align="center", echo=TRUE}
## including 3rd component and Screeplot
plotPCAw(t(as.matrix(iris[,-5])), gl(3,50,labels=c("setosa","versicolor","virginica")),
tit="Iris Data PCA", rowTyName="types of leaves", cexTxt=2)
```
### Label all points in PCA
In some cases it may be useful to identify all individual points on a plot.
```{r PCA6, fig.height=7, fig.width=9, fig.align="center", echo=TRUE}
## creat copy of data and add rownames
irisD <- as.matrix(iris[,-5])
rownames(irisD) <- paste(iris$Species, rep(1:50,3), sep="_")
plotPCAw(t(irisD), gl(3,50,labels=c("setosa","versicolor","virginica")), tit="Iris Data PCA",
rowTyName="types of leaves", suplFig=FALSE, cexTxt=1.6, rotatePC=2, pointLabelPar=list(textCex=0.45))
```
## MA-Plot
The aim of [MA-plots](https://en.wikipedia.org/wiki/MA_plot) consists in displaying a relative change on one axis (ordinate) while
showing the absolute (mean) value on the x-axis (abscissa).
This plot is very useful when inspecting larger data-sets for random or systematic effects,
numerous implementations for specific applications exist (eg *plotMA* in [DEseq2](https://bioconductor.org/packages/release/bioc/html/DESeq2.html)).
The version presented here is rather generic and uses transparent points to avoid getting plots too crowded.
First, let's generate some toy data:
```{r MA0, fig.height=6, fig.width=8, fig.align="center", echo=TRUE}
## toy data
set.seed(2005); mat <- matrix(round(runif(2400),3), ncol=6)
mat[11:90,4:6] <- mat[11:90,4:6] +round(abs(rnorm(80)),3)
mat[11:90,] <- mat[11:90,] +0.3
dimnames(mat) <- list(paste("li",1:nrow(mat),sep="_"),paste(rep(letters[1:2],each=3),1:6,sep=""))
## assume 2 groups with 3 samples each
matMeans <- round(cbind(A=rowMeans(mat[,1:3]), B=rowMeans(mat[,4:6])),4)
```
One way of using the function _MAplotW()_ is by providing (explicitely) the M- and A-values.
By default a threshold-line is drawn for a fold-change of 1.5x (which on log2 scale apprears at +/- 0.58).
```{r MA1, fig.height=6, fig.width=8, fig.align="center", echo=TRUE}
## now we are ready to plot, M-values can be obtained by subtracting thr group-means
MAplotW(M=matMeans[,2] -matMeans[,1], A=rowMeans(mat))
```
The function _MAplotW_ may also be used to conveniently inspect results from t-tests performed with the package [wrMisc](https://CRAN.R-project.org/package=wrMisc)
or from the very popular package [limma](https://www.bioconductor.org/packages/release/bioc/html/limma.html).
```{r MA4, echo=TRUE}
## assume 2 groups with 3 samples each and run moderated t-test (from package 'limma')
tRes <- wrMisc::moderTest2grp(mat, gl(2,3), addResults=c("FDR","Mval","means"))
```
This object conatains data for different types of plots (MA-plot, Volcano-Plot, etc ..), let's also mark the names of those passing the fold-change threshold.
```{r MA5,fig.height=6, fig.width=8, fig.align="center", echo=TRUE}
## convenient way, change fold-change threshold to 2x and mark who is beyond :
MAplotW(tRes, FCth=2, namesNBest="passFC")
```
In the plot above one can see easily most of the points from the second group which have been increased in lines 11 to 90,
many of them exceed a (based on linear data) fold-change of 2 (which on log2 scale appears at 1.0).
## Volcano-Plot
The aim of [Volcano-plots](https://en.wikipedia.org/wiki/Volcano_plot_(statistics)) is to display a log-ratios on the x-axis (ordinate) and outcome of statistical test on the other axis (abscissa). Typically the statistical values are represented as negative log10.
This plot is very useful when inspecting larger data-sets for random or systematic effects.
Points with high log-ratios (ie high fold-change) may not always have enthusiastic p-values, too.
Many times such divergences may point to high intra-group variability.
Numerous implementations for specific applications exist (eg the package [EnhancedVolcano](https://bioconductor.org/packages/release/bioc/html/EnhancedVolcano.html)).
The version presented here is rather generic and uses transparent points to avoid getting plots too crowded.
Furthermore, this version has the advantage to take all information needed directly in MArrayLM-objects, like the output of moderTest2grp() or moderTestXgrp().
```{r Volc1, fig.height=6, fig.width=8, fig.align="center", echo=TRUE}
## let's generate some toy data
set.seed(2005); mat <- matrix(round(runif(900),2), ncol=9)
rownames(mat) <- paste0(rep(letters[1:25],each=4), rep(letters[2:26],4))
mat[1:50,4:6] <- mat[1:50,4:6] + rep(c(-1,1)*0.1,25)
mat[3:7,4:9] <- mat[3:7,4:9] + 0.7
mat[11:15,1:6] <- mat[11:15,1:6] - 0.7
## assume 2 groups with 3 samples each
gr3 <- gl(3,3,labels=c("C","A","B"))
tRes2 <- moderTest2grp(mat[,1:6], gl(2,3))
VolcanoPlotW(tRes2)
# now with thresholds, labels and arrow for expected ratio
VolcanoPlotW(tRes2, FCth=1.3, FdrThrs=0.2, namesNBest="pass", expFCarrow=c(0.75,2))
```
Note, that this exampe is very small and for this reason the function _fdrtool()_ used internally issues some warnings since the estimation of lfdr is not optimal.
```{r Volc2, fig.height=6, fig.width=9.5, fig.align="center", echo=TRUE}
## assume 3 groups with 3 samples each
tRes <- moderTestXgrp(mat, gr3)
layout(matrix(1:2, nrow=1))
VolcanoPlotW(tRes, FCth=1.3, FdrThrs=0.2, useComp=2)
VolcanoPlotW(tRes, FCth=1.3, FdrThrs=0.2, useComp=3)
```
## Standalone html Page With Plot And Mouse-Over Interactive Features
The idea of this function dates before somehow similar applications were made possible using [Shiny](https://shiny.posit.co/).
In this case the original idea was simply to provide help to identify points in a plot and display via mouse-over labels to display and by providing clickable links.
To do so, very simple html documents are created which display a separately saved image and have a section indicating at which location of the figure which information should be displayed as mouse-over and providing the clickable links.
In high-throughput biology many times researchers want quickly know which protein or gene a given point in a graphic corresponds and being able to get further information on this protein or gene via links to [UniProt](https://www.uniprot.org) or [GenBank](https://www.ncbi.nlm.nih.gov/genbank).
As this functionality was made for separate html documents it's output cannot be easily integrated into a vignette like this one.
To generate such a simple mouse-over interactive html document, the user is invited to run the code
of this vignette. At the last step you could ask R to open the interactive html page in the default browser.
Concerning the path provided in the argument *pngFileNa* of the function *mouseOverHtmlFile*:
In a real world case, you might want to choose other
locations to save files rather than R-temp which will be deleted when closing your instance of R.
It is also possible to work with relative paths (eg by giving the png-filename without path).
Then the resultant html will simply require the png-file to be in the same directory as the html itself, and similarly for the clickable links.
This results in files that are very easy to distribute to other people, in particular if the clickable links are pointing to the internet,
however, the pnh-file always needs to be in the same directory as the html ...
If you have the possibility to make the png-file accessible through a url, you could also provide this url.
The example below shows usage when specifying absolute paths.
Please note that the resulting html will not display the image if your browser cannot access the image any more.
```{r createHtmlWithPointsIdentif1, echo=TRUE}
## Let's make some toy data
df1 <- data.frame(id=letters[1:10], x=1:10, y=rep(5,10) ,mou=paste("point",letters[1:10]),
link=file.path(tempdir(),paste(LETTERS[1:10],".html",sep="")),stringsAsFactors=FALSE)
## here we'll use R's tempdir, later you may want to choose other locations
pngFile <- file.path(tempdir(),"test01.png")
png(pngFile, width=800, height=600, res=72)
## here we'll just plot a set of horiontal points ...
plot(df1[,2:3], las=1, main="test01")
dev.off()
## Note : Special characters should be converted for proper display in html during mouse-over
df1$mou <- htmlSpecCharConv(df1$mou)
## Let's add the x- and y-coordiates of the points in pixels to the data.frame
df1 <- cbind(df1, convertPlotCoordPix(x=df1[,2], y=df1[,3], plotD=c(800,600), plotRes=72))
head(df1)
## Now make the html-page allowing to display mouse-over to the png made before
htmFile <- file.path(tempdir(),"test01.html")
mouseOverHtmlFile(df1, pngFile, HtmFileNa=htmFile, pxDiam=15,
textAtStart="Points in the figure are interactive to mouse-over ...",
textAtEnd="and/or may contain links")
## We still need to make some toy links
for(i in 1:nrow(df1)) cat(paste("point no ",i," : ",df1[i,1]," x=",df1[i,2]," y=",
df1[i,3],sep=""), file=df1$link[i])
## Now we are ready to open the html file using any browser ..
#from within R# browseURL(htmFile)
```
## Acknowledgements
The author wants to acknowledge the support by the [IGBMC](https://www.igbmc.fr) (CNRS UMR 7104, Inserm U 1258, UdS), [CNRS](https://www.cnrs.fr/en), [Université de Strasbourg](https://www.unistra.fr) and [Inserm](https://www.inserm.fr) and of course all collegues from the [IGBMC proteomics platform](https://proteomics.igbmc.fr).
The author wishes to thank the [CRAN-staff](https://CRAN.R-project.org) for all their efforts in maintaining this repository of R-packages.
Thank you for you interest in this package.
This package is constantly evolving, new functions may get added to the next version.
## Appendix: Session-Info
For completeness, here detailed documentation of versions used to produce this document.
\small
```{r sessionInfo, echo=FALSE}
sessionInfo()
```
|
/scratch/gouwar.j/cran-all/cranData/wrGraph/vignettes/wrGraphVignette1.Rmd
|
#' Express difference as ppm
#'
#' This function transforms offset (pariwise-difference) between 'x' & 'y' to ppm (as normalized difference ppm, parts per million, ie (x-y)/y ).
#' This type of expressiong differences is used eg in mass-spectrometry.
#' @param x (numeric) typically for measured variable
#' @param y (numeric) typically for theoretical/expected value (vector must be of same length as 'x')
#' @param nSign (integer) number of significant digits in 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 numeric vector of (ratio-) ppm values
#' @seealso \code{\link{ratioToPpm}} for classical ppm
#' @examples
#' set.seed(2017); aa <- runif(10,50,900)
#' cbind(x=aa,y=aa+1e-3,ppm=XYToDiffPpm(aa,aa+1e-3,nSign=4))
#' @export
XYToDiffPpm <- function(x, y, nSign=NULL, silent=FALSE, debug=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom,newNa="XYToDiffPpm")
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(any(length(x) <1, length(y) <1, length(x)!= length(y))) stop("Length of 'y' (",length(y),") not corresponding to 'x' (",length(x),")")
x <- 1e6*(x-y)/y
if(length(nSign)>0) signif(x,as.numeric(nSign)) else x }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/XYToDiffPpm.R
|
#' Add text before file-extension
#'
#' This function helps changing charater srings like file-names and allows adding the character vector 'add'
#' (length 1) before the extension (defined by last '.') of the input string 'x'.
#' Used for easily creating variants/additional filenames but keeping current extension.
#' @param x main character vector
#' @param add character vector to be added
#' @param sep (character) separator between 'x' & 'add' (character, length 1)
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @param debug (logical) additional messages for debugging
#' @return modified character vector
#' @examples
#' addBeforFileExtension(c("abd.txt","ghg.ijij.txt","kjh"),"new")
#' @export
addBeforFileExtension <- function(x, add, sep="_", silent=FALSE, callFrom=NULL, debug=FALSE) {
fxNa <- .composeCallName(callFrom, newNa="addBeforFileExtension")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(length(add) >1) add <- add[1]
if(length(grep("\\.",x)) >0) {
extLoc <- sapply(gregexpr("\\.",x),function(y) y[length(y)])
if(any(extLoc <0)) extLoc[extLoc <0] <- nchar(x[extLoc <0])+1
paste0(substr(x,1,extLoc-1),sep,add,substr(x,extLoc,nchar(x)))
} else paste(x,add,sep=sep) }
#' checkFileNameExtensions
#' Function for checking file-names.
#' @param fileNa (character) file name to be checked
#' @param ext (character) file extension
#' @return modified character vector
#' @examples
#' .checkFileNameExtensions("testFile.txt","txt")
#' @export
.checkFileNameExtensions <- function(fileNa, ext){
msg <- " need at least 1 character-string as 'fileNa' and as 'ext'"
if(any(length(fileNa) <1,length(ext) <1)) stop(msg)
ext <- sub("^\\.","",ext) # remove starting point-separator
ext <- unique(paste(".",ext,sep=""))
che <- nchar(fileNa) > nchar(sub(paste(ext[1],"$",sep=""),"",fileNa))
if(length(ext) >1) for(i in 2:length(ext)) {
che <- che || nchar(fileNa) > nchar(sub(paste(ext[i],"$",sep=""),"",fileNa))}
if(sum(!che) >0)fileNa[!che] <- paste(fileNa[!che],ext[1],sep="")
fileNa }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/addBeforFileExtension.R
|
#' Linear rescaling of numeric vertor or matrix
#'
#' \code{adjBy2ptReg} takes data within window defined by 'lims' and determines linear transformation so that these points get the regression characteristics 'regrTo',
#' all other points (ie beyond the limits) will follow the same transformation.
#' In other words, this function performs 'linear rescaling', by adjusting (normalizing) the vector 'dat' by linear regression so that points falling in 'lims'
#' (list with upper & lower boundaries) will end up as 'regrTo'.
#'
#' @param dat numeric vector, matrix or data.frame
#' @param lims (list, length=2) should be list giving limits (list(lo=c(min,max),hi=c(min,max)) in data allowing identifying which points will be used for determining slope & offset
#' @param regrTo (numeric, length=2) to which characteristics data should be regressed
#' @param refLines (NULL or integer) optional subselection of lines of dat (will be used internal as refDat)
#' @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 matrix (of same dimensions as inlut matrix) with normalized values
#' @seealso \code{\link{normalizeThis}}
#' @examples
#' set.seed(2016); dat1 <- round(runif(50,0,100),1)
#' ## extreme values will be further away :
#' adjBy2ptReg(dat1,lims=list(c(5,9), c(60,90)))
#' plot(dat1, adjBy2ptReg(dat1, lims=list(c(5,9),c(60,90))))
#' @export
adjBy2ptReg <- function(dat, lims, regrTo=c(0.1,0.9), refLines=NULL, silent=FALSE, debug=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="adjBy2ptReg")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(length(refLines) >0) {
if(is.character(refLines) && !is.null(rownames(dat))) refLines <- match(refLines, names(dat)) else {
refLines <- as.integer(refLines)
refLines <- refLines[which(refLines >0 & refLines < length(dat))]}}
dat1 <- if(length(refLines) >0) dat[refLines] else dat
if(is.null(names(dat1))) names(dat1) <- 1:length(dat1)
msg <- "'lims' should be list giving limits (list(lo=c(min,max), hi=c(min,max))"
if(!is.list(lims)) lims <- as.list(lims)
if(length(lims) != 2) stop(msg)
lim2 <- if(all(sapply(lims, length) ==1)) {
list(lo=which(dat1 == lims[[1]]), hi=which(dat1 == lims[[1]]))
} else {
if(all(sapply(lims, length) ==2)) { list(
lo=which(dat1 >= min(lims[[1]],na.rm=TRUE) & dat1 <= max(lims[[1]],na.rm=TRUE)),
hi=which(dat1 >= min(lims[[2]],na.rm=TRUE) & dat1 <= max(lims[[2]],na.rm=TRUE)))
} else stop(" cannot figure out 'lims' !\n ",msg)}
chLe <- sapply(lim2, length)
if(any(chLe <1)) message(fxNa,"Limits seem too tight : lo ",chLe[1]," & hi ",chLe[2]," entries found !")
lim3 <- sapply(lim2, function(x) sum(dat1[x], na.rm=TRUE)/length(x)) # mean value at lo & hi indexing
normFact <- if(length(lims) ==1) (regrTo[1]/lim3[1]) else (regrTo[2] -regrTo[1])/ (lim3[2] -lim3[1]) # slope
normFact <- c(k=normFact, d= if(length(lims) ==1) 0 else regrTo[1] -normFact*lim3[1])
norD <- dat1*normFact[1] + normFact[2]
dat[which(is.finite(dat))] <- as.numeric(norD)
dat }
#' Model linear regression and optional plot
#'
#' This function allows to model a linear regression and optionally to plot the results
#'
#' @param dat (vector or matrix) main input
#' @param typeOfPlot (character)
#' @param toNinX (logical)
#' @param plotData (logical)
#' @param silent (logical) suppress messages
#' @param debug (logical) display additional messages for debugging
#' @param callFrom (character) allow easier tracking of messages produced
#' @return numeric vector with intercept and slope, optional plot
#' @seealso \code{\link[base]{append}}; \code{\link{lrbind}}
#' @examples
#' .datSlope(c(3:6))
#' @export
.datSlope <- function(dat, typeOfPlot="sort", toNinX=FALSE, plotData=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa=".datSlope")
if(length(typeOfPlot) >1) {
if(!silent) message(fxNa,"Invalid entry for typeOfPlot ",paste(typeOfPlot, collapse=", ")," (use 1st)")
typeOfPlot <- typeOfPlot[1] }
dat <- as.numeric(naOmit(sort(dat)))
y <- if(tolower(typeOfPlot) %in% "cumsum") cumsum(sort(dat)) else sort(dat)
y <- data.frame(out=y, n=1:length(dat))
out <- if(toNinX) stats::lm(n ~ out, data=y)$coefficients else stats::lm(out ~ n, data=y)$coefficients
if(plotData) { if(toNinX) {
chF <- try(graphics::plot(y, type="s", ylab=if("cumsum" %in% tolower(typeOfPlot)) "cumsum" else "sorted"), silent=TRUE)
if(!inherits(chF, "try-error")) { for(i in 2:ncol(out)) graphics::points(y); graphics::abline(out, lty=2, col=2)
} else {
if(!silent) message(fxNa,"UNABLE to plot data !")}
} else {
chF <- try(graphics::plot(1:nrow(y), y[,1], type="s", ylab=if("cumsum" %in% tolower(typeOfPlot)) "cumsum" else "sorted"), silent=TRUE)
if(!inherits(chF, "try-error")) {graphics::points(1:nrow(y), y[,1]); graphics::abline(out, lty=2, col=2)} else {
if(!silent) message(fxNa,"UNABLE to plot data !")}
}
}
names(out) <- c("intercept","slope")
out }
#' Check regression arguments
#'
#' This function allows to check arguments for linear regression. Used as argument checking for \code{regrBy1or2point} and \code{regrMultBy1or2point}
#'
#' @param inData (numeric vector) main input
#' @param refList (list)
#' @param regreTo (numeric vector)
#' @param callFrom (character) allow easier tracking of messages produced
#' @return list
#' @seealso \code{\link[base]{append}}; \code{\link{lrbind}}
#' @examples
#' .datSlope(c(3:6))
#' @export
.checkRegrArguments <- function(inData, refList, regreTo, callFrom=NULL){
## argument checking for regrBy1or2point() & regrMultBy1or2point()
## 'inData' should be
## returns corrected/adjusted 'refList' and 'regreTo' (as list)
fxNa <- .composeCallName(callFrom, newNa=".checkRegrArguments")
if(!is.list(refList)) refList <- list(refList)
if(is.list(inData) && !is.data.frame(inData)) message(fxNa,"Potential problem : not expecting list (length=",length(inData),") at place of 'inDat' !!")
if(min(sapply(refList, length)) <2) {
warning(fxNa,sum(sapply(refList, length) <2)," entries of 'refLst' contain less than 2 array-positions (well-names)")
refList <- refList[which(sapply(refList, length) >1)] }
datIsMa <- !is.null(dim(inData))
checkRefFields <- unlist(refList) %in% (if(datIsMa) rownames(inData) else names(inData))
if(sum(checkRefFields) <1) {
message(fxNa," 'refList' ",paste(unlist(refList),collapse=" "))
message("Head(names(inDat) ",paste(if(datIsMa) utils::head(rownames(inData)) else utils::head(names(inData)),collapse=" ")," ...")
stop(" none of the fields given in 'refList' appear in names of 'inDat' !") }
if(sum(checkRefFields) < sum(sapply(refList, length))) message(fxNa,"Some of the fields given in 'refLst' do not appear in names of 'inDat' !")
if(length(refList) > length(regreTo)) message(fxNa,"Need as many values 'regrTo' as types (of samples) given in 'refLst' !")
list(refLst=refList, regrTo=regreTo) }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/adjBy2ptReg.R
|
#' Adjust Value With Different Decimal Prefixes To Single Prefix Plus Unit
#'
#' This function provides help converting values with with different unit-prefixes to a single prefix-unit type.
#' This can be used to convert a vector of mixed prefixes like 'p' and 'n'.
#' Any text to the right of the unit will be ignored.
#'
#' @details
#' Please note that the current version recognizes and converts only interger values, decimals or scientific writing won't work.
#' The resultant numeric vector expresses all values as lowest prefix unit level.
#' In case of invalid entries \code{NA}s will be returned.
#'
#' Please note the 'u' is used for 'micro'.
#'
#' @param x (character) vector containing digit uunit-prefix and unit terms
#' @param pref (character) multiplicative unit-prefixes, assumes as increasing factors of 1000
#' @param unit (character) unit name, the numeric part may be sepatated by one space-character
#' @param sep (character) separator characters that may appear between integer numeric value and unit description
#' @param headingTxt (character) additional text preceeding the numeric part of 'x' to be ingnored/removed
#' @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 with quantities extracted and adjusted to a single type of unit (without the unit description)
#' @seealso \code{\link{convToNum}}
#' @examples
#' adjustUnitPrefix(c("10.psec abc","2 fsec etc"), unit="sec")
#' @export
adjustUnitPrefix <- function(x, pref=c("z","a","f","p","n","u","m"), unit="sec", sep=c("."," ",""), headingTxt="", silent=FALSE, debug=FALSE, callFrom=NULL) {
## fix amol/fmol
## 'x' (char) name including units (to be mined)
## conVal' (numeric) custom provided numeric value, if NULL all digit content at beginning (following after 'headingTxt') will be extracted (note, this won't extract digits after comma or scientific notation)
## 'pref' (char) must be incrementing by factor 1000
## 'headingTxt' (char) constant part of text before numeric part of concentration indications
fxNa <- .composeCallName(callFrom, newNa="adjustUnitPrefix")
if(isTRUE(debug)) silent <- FALSE
if(!isTRUE(silent)) silent <- FALSE
if(length(unit) >1) { if(!silent) message(fxNa,"Argument 'unit' must be of length=1, truncating...")
unit <- unit[1]}
pref2 <- paste0(pref, collapse="|")
sep2 <- if("" %in% sep) sep[-which(sep %in% "")] else sep
sep3 <- if(length(sep2) <1) protectSpecChar(sep) else paste0(protectSpecChar(sep2),"{0,1}")
if(length(sep3) >1) sep3 <- paste0("(",paste0(sep3, collapse="|"),")")
if(length(headingTxt) ==1) { if(is.na(headingTxt)) headingTxt <- ""
if(nchar(headingTxt) >0) x <- sub(paste0("^",headingTxt,sep3), "", x)} # remove headingTxt (+sep)
if(debug) {message(fxNa,"aCP1")}
conVal <- sub(paste0("^","[[:digit:]]+",sep3), "", x)
conVal <- try(as.numeric(substr(x, 1, nchar(x) - nchar(conVal))), silent=TRUE)
if(debug) {message(fxNa,"aCP2"); aCP2 <- list(x=x,pref=pref,unit=unit,headingTxt=headingTxt,sep=sep,sep2=sep2,sep3=sep3,conVal=conVal)}
if(inherits(conVal, "try-error") || length(x) <1) { if(!silent) message(fxNa,"Invalid entry for x, returning NA")
rep(NA, length(x))
} else {
xUnit <- sub(paste0("^[[:digit:]]+",sep3), "", x) # unit + ev other
xExt <- nchar(sub(paste0("^.+",unit),"", xUnit)) # number of char after unit
if(any(xExt >0)) xUnit[which(xExt >0)] <- substr(xUnit[which(xExt >0)], 1, (nchar(xUnit)- xExt)[which(xExt >0)]) # remove extension
if(sum(duplicated(xUnit)) >0) {
molCh <- sapply(pref, function(x) nchar(xUnit) > nchar(sub(paste0("^",x),"", xUnit)))
molCh <- molCh[,min(which(colSums(molCh) >0)):max(which(colSums(molCh) >0))] # reduce to actual range of prefixes found
minPref <- colnames(molCh)[1]
conVal <- conVal*1000^(0:(ncol(molCh) -1))[apply(molCh,1, which)]
names(conVal) <- paste0(conVal, minPref, unit)
} else names(conVal) <- paste0(conVal,xUnit)
conVal }
}
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/adjustUnitPrefix.R
|
#' Append vectors or lists, without duplcating common elements
#'
#' This function allows combining two vectors or lists without duplicating common content (definded by name of list-elements).
#'
#' @details When setting the argument \code{rmDuplicate=FALSE} the function will behave like \code{append}.
#'
#' @param x (vector or list) must have names to allow checking for duplicate names in y
#' @param y (vector or list) must have names to allow checking for duplicate names in x
#' @param rmDuplicate (logical) avoid duplicating liste-elements present in both x and y (based on names of list-elements)
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of message(s) produced
#' @return If both \code{x} and \code{y} are vectors, the output will be a vector, otherwise it will be a list
#' @seealso \code{\link[base]{append}}; \code{\link{lrbind}}
#' @examples
#' li1 <- list(a=1, b=2, c=3)
#' li2 <- list(A=11, B=12, c=3)
#' appendNR(li1, li2)
#' append(li1, li2)
#' @export
appendNR <- function(x, y, rmDuplicate=TRUE, silent=FALSE, callFrom=NULL) {
fxNa <- .composeCallName(callFrom, newNa="appendNR")
if(!rmDuplicate | length(x) <1 | length(y) <1) { x <- append(x, y)
} else {
chY <- !names(y) %in% names(x) # names of y not in x (ie new)
if(any(chY)) {
xLe <- length(x)
x <- append(x, y[which(chY)])
if(!silent) message(fxNa," adding ",sum(chY)," new names/elements (",sum(!chY)," already present)")
names(x)[xLe + seq(sum(chY))] <- names(y[which(chY)]) } }
x }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/appendNR.R
|
#' CV of array
#'
#' \code{arrayCV} gets CVs for replicates in 2 or 3 dim array and returns CVs as matrix.
#' This function may be used to calculate CVs from replicate microtiter plates (eg 8x12) where replicates are typically done as multiple plates,
#' ie initial matrixes that are the organized into arrays.
#' @param arr (3-dim) array of numeric data like where replicates are along one dimesion of the array
#' @param byDim (integer) over which dimension repliates are found
#' @param silent (logical) suppres messages
#' @param callFrom (character) allow easier tracking of message produced
#' @return matrix of CV values
#' @seealso \code{\link{rowCVs}}, \code{\link{rowGrpCV}}, \code{\link{replPlateCV}}
#' @examples
#' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)),ncol=10)
#' head(arrayCV(dat1,byDim=2))
#' @export
arrayCV <- function(arr, byDim=3, silent=TRUE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="arrayCV")
curDiNa <- dimnames(arr)
if(byDim > length(dim(arr))) { byDim <- length(dim(arr))
message(fxNa," dimension number for argument 'byDim' too high, adjusting to ",byDim) }
basDim <- if(byDim != 1) 1 else 2
arrCV <- matrix(nrow=dim(arr)[basDim], ncol=dim(arr)[byDim], dimnames=curDiNa[c(basDim,byDim)] ) # (1:3)[!(1:3 %in% c(basDim,byDim))]
if(!silent) message(fxNa," CV output in matrix/array of ",nrow(arrCV)," x ",ncol(arrCV)," ")
if(length(dim(arr)) ==3) {
for(i in 1:dim(arr)[byDim]) {arrCV[,i] <- if(byDim==3) rowCVs(arr[,,i]) else {
if(byDim ==2) rowCVs(arr[,i,]) else rowCVs(arr[i,,]) }}
} else arrCV <- matrix(rowCVs(arr), dimnames=list(rownames(arr),NULL))
arrCV }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/arrayCV.R
|
#' Organize Data as Separate List-Entries
#'
#' \code{asSepList} allows reorganizing most types of input into a list with separate numeric vectors. For example, matrixes or data.frames will be split into separate columns
#' (differnt to \code{\link[wrMisc]{partUnlist}} which maintains the original structure). This function also works with lists of lists.
#' This function may be helpful for reorganizing data for plots.
#'
#' @param y list to be separated/split in vectors
#' @param minLen (integer) min length (or number of rows), as add'l element to eliminate arguments given without names when asSepList is called in vioplot2
#' @param asNumeric (logical) to transform all list-elements in simple numeric vectors (won't work if some entries are character)
#' @param exclElem (character) optinal names to exclude if any (lazy matching) matches (to exclude other arguments be misinterpreted as data)
#' @param sep (character) separator when combining name of list-element to colames
#' @param fillNames (logical) add names for list-elements/ series when not given
#' @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, partially unlisted to vectors
#' @seealso \code{\link[wrMisc]{partUnlist}}, \code{\link[base]{unlist}}
#' @examples
#' bb <- list(fa=gl(2,2), c=31:33, L2=matrix(21:28,nc=2),
#' li=list(li1=11:14, li2=data.frame(41:44)))
#' asSepList(bb)
#' ## multi data-frame examples
#' ca <- data.frame(a=11:15, b=21:25, c=31:35)
#' cb <- data.frame(a=51:53, b=61:63)
#' cc <- list(gl(3,2), ca, cb, 91:94, short=81:82, letters[1:5])
#' asSepList(cc)
#' cd <- list(e1=gl(3,2), e2=ca, e3=cb, e4=91:94, short=81:82, e6=letters[1:5])
#' asSepList(cd)
#' @export
asSepList <- function(y, minLen=4, asNumeric=TRUE, exclElem=NULL, sep="_", fillNames=TRUE, silent=FALSE, callFrom=NULL, debug=FALSE) {
## convert all data-series of list (ie all list elements or columns) in separate list-elements (OK with list of lists) eg for plots
## 'asNumeric'.. to transform all list-elements in simple numeric vectors (won't work if some entries are character)
## 'minLen' .. min length (or number of rows), as add'l element to eliminate arguments given wo names when asSepList is called in vioplot2
## 'fxArg' .. optinal, names to exclude if any (lazy matching) matches (to exclude other arguments be mis-interpreted as data, used in vioplot2)
fxNa <- .composeCallName(callFrom, newNa="asSepList")
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(!isTRUE(silent)) silent <- FALSE
namesY <- sub("[[:punct:]].*|[[:space:]].*|","",deparse(substitute(y))) # reduce to alphanum content
if(length(y) >0) {
if(!inherits(y,"list")) {
y <- .asDF2(y)
chNam <- if(length(colnames(y)) <1) rep(TRUE, ncol(y)) else colnames(y) %in% ""
if(any(chNam)) colnames(y)[which(chNam)] <- paste0(namesY,sep,which(chNam))
y <- as.list(y)
if(debug) {message(fxNa,"aSL1 non-list concert to list of length ",length(y)); aSL1 <- list(y=y,asNumeric=asNumeric,minLen=minLen) }
} else {
.matr2List <- function(z) as.list(as.data.frame(z))
chSubLi <- sapply(y, is.list) & !sapply(y, is.data.frame)
if(debug) {message(fxNa,"aSL1 list-entry; ini length of 'y' ",length(y)); aSL1 <- list(y=y,asNumeric=asNumeric,chSubLi=chSubLi) }
w <- NULL
## try to separate sub-lists
if(length(y) >0 & any(chSubLi)) { # run partUnlist() on all sub-lists
if(length(y)==1) { y <- .asDF2(y[[1]])
if(debug) {message(fxNa,"aSL1b")}
chNam <- if(length(colnames(y)) <1) rep(TRUE, ncol(y)) else colnames(y) %in% ""
if(any(chNam)) colnames(y)[which(chNam)] <- paste0(namesY,sep,which(chNam))
y <- as.list(y)
} else {
isLi <- sapply(y, inherits, "list")
chNam <- if(length(names(y)) >0) names(y) =="" else rep(FALSE, length(y))
if(any(chNam) & isTRUE(fillNames)) {newNa <- paste(namesY,which(chNam),sep=sep)
if(any(newNa %in% names(y))) newNa <- paste0(namesY,sep,"_",which(chNam))
names(y)[which(chNam)] <- newNa }
if(debug) {message(fxNa,"aSL2 ")}
if(any(isLi)) y <- partUnlist(y, silent=silent, debug=debug,callFrom=fxNa) #[which(chSubLi)])
## now need to separate matrix-columns (& check names)
iniDim <- lapply(y, ncol)
ch2d <- sapply(iniDim, function(x) length(x)==1)
if(any(ch2d)) { ## contains matrix or data.frame, need to separate cols
w <- lapply(y[which(ch2d)], .matr2List)
w <- partUnlist(w, silent=silent,debug=debug,callFrom=fxNa)
names(w) <- paste0(rep(names(y)[which(ch2d)],unlist(iniDim[which(ch2d)])),sep, unlist(lapply(unlist(iniDim[which(ch2d)]), function(x) if(x >1) 1:x else ""))) }
y <- y[-which(ch2d)] # remove matrix parts
y[length(y) +(1:length(w))] <- w # attach separated columns
names(y)[1 +length(y) -(length(w):1)] <- names(w)
if(debug) {message(fxNa,"aSL3 length of basic part ",length(y)," length of matrix-part ",length(w))}
## adjust order
newOr <- as.list(match(names(iniDim), names(y)))
chNa <- is.na(match(names(iniDim), names(y)))
if(any(chNa, na.rm=TRUE)) newOr[which(chNa)] <- lapply(paste0("^",names(iniDim)[which(is.na(match(names(iniDim), names(y))))],sep), grep, names(y))
y <- y[unlist(newOr)]
names(y) <- sub(paste0(sep,"$"),"", names(y)) # remove tailing sep from single-column matrices
}
}
}
if(debug) {message(fxNa,"aSL4 length of list output (befor minLen-filter) ",length(y))}
## check length
chLe <- sapply(y, length) < minLen
if(any(chLe, na.rm=TRUE)) { y <- y[which(!chLe)]
if(all(chLe, na.rm=TRUE) & !silent) message(fxNa,"All elements of ',namesY,' below length-limit (",minLen,") - nothing remains") }
## convert to numeric
if(isTRUE(asNumeric)) { chMode <- sapply(y, function(x) "numeric" %in% mode(x))
if(any(!chMode)) y[which(!chMode)] <- lapply(y, convToNum, callFrom=fxNa,silent=silent) }
if(debug) {message(fxNa,"aSL5 length of list output (after minLen-filter) ",length(y))}
} else if(debug(fxNa,"Empty input, nothing to do"))
if(debug) message(fxNa,"returning list of length ",length(y))
y }
#' Convert anything to data.frame
#'
#' This function allows converting anything to data.frame
#'
#' @param z (numeric vector, factor, matrix or list) main input
#' @return data.frame
#' @seealso \code{\link[base]{as.data.frame}}
#' @examples
#' .asDF2(c(3:6))
#' @export
.asDF2 <- function(z) if(is.factor(z)) as.data.frame(as.character(z)) else as.data.frame(z) # convert anything to data.frame-like
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/asSepList.R
|
#' Connect edges to from tree and extract all possible branches
#'
#' It is assumed that multiple fragments from a common ancestor bay be charcterized by the their start- and end-sites by integer values.
#' For example, If 'abcdefg' is the ancestor, the fragments 'bcd' (from position 2 to 4) to and 'efg' may then be assembled.
#' To do so, all fragments must be presented as matix specifying all start- and end-sites (and fragment-names).
#' \code{buildTree} searchs contiguous fragments from columns 'posCo' (start/end) from 'disDat' to build tree & extract path information starting with line 'startFr'.
#' Made for telling if dissociated fragments contribute to long assemblies.
#' This function uses various functions of package \href{https://CRAN.R-project.org/package=data.tree}{data.tree} which must be installed, too.
#'
#' @param disDat (matrix or data.frame) integer values with 1st column, ie start site of fragment, 2nd column as end of fragments, rownames as unique IDs (node-names)
#' @param startFr (integer) index for 1st node (typically =1 if 'disDat' sorted by "beg"), should point to a terminal node for consective growing of branches
#' @param posCo (character) colnames specifying the begin & start sites in 'disDat', if NULL 1st & 2nd col will be used
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of message(s) produced
#' @return This function returns a list with $paths (branches as matrix with columns 'sumLen' & 'n'), $usedNodes (character vector of all names used to build tree) and $tree (object from data.tree)
#' @seealso package \href{https://CRAN.R-project.org/package=data.tree}{data.tree} original function used \code{\link[data.tree]{Node}}; in this package : for exploiting edge/tree related issues \code{\link{simpleFragFig}}, \code{\link{countSameStartEnd}} and \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")
#' buildTree(frag2)
#' countSameStartEnd(frag2)
#' @export
buildTree <- function(disDat, startFr=NULL, posCo=c("beg","end"), silent=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="buildTree")
if(!isTRUE(silent)) silent <- FALSE
datOK <- TRUE
if(length(disDat) <1) datOK <- FALSE
if(length(dim(disDat)) <2) disDat <- matrix(disDat, nrow=1, dimnames=list("1",names(disDat))) # assume as single entry
rowNa <- rownames(disDat)
if(is.null(rowNa)) rowNa <- 1:nrow(disDat)
chCol <- match(colnames(disDat), posCo)
disDat <- if(sum(is.na(chCol[1:2])) <1) {
cbind(beg=as.integer(disDat[,chCol[1]]), end=as.numeric(disDat[,chCol[2]]))
} else disDat <- as.matrix(disDat[,1:2])
rownames(disDat) <- rowNa
chSlash <- grep("/", rownames(disDat))
if(length(chSlash) >0) message(fxNa,"TROUBLE ahead, names of nodes should NOT contain '/' !!")
disDat <- cbind(disDat[,1:2], le=disDat[,2] -disDat[,1] +1) # add col for length # if(ncol(disDat)==2)
if(!requireNamespace("data.tree", quietly=TRUE)) {
warning(fxNa,"Package 'data.tree' missing ! Please install from CRAN first .. returning NULL)")
datOK <- FALSE
} else {
## check if package is functioning
setX <- try(data.tree::Node$new("_Root_")) # virtual node as generic root, need to avoid reserved names (see NODE_RESERVED_NAMES_CONST)
if(inherits(setX, "try-error")) { datOK <- FALSE
warning(fxNa,"Problem running package data-tree : Can't even create a new generic node")}
}
if(datOK) {
## main
## check for dupl
chDup <- duplicated(paste(disDat[,1],disDat[,2],sep="_"), fromLast=FALSE)
names(chDup) <- rownames(disDat)
if(any(chDup)) {
chDu2 <- duplicated(paste(disDat[,1],disDat[,2],sep="_"), fromLast=TRUE)
hasDu <- chDu2 & !chDup # the originals (of dupl) to keep
names(hasDu) <- rownames(disDat)
## remove duplicated/redundant
dupDat <- lapply(which(hasDu), function(x) {z <- paste(disDat[,2],disDat[,1],sep="_"); which(z %in% z[x])}) # index of replicated elements (line-no)
if(!silent) message(fxNa,": ", sapply(dupDat, function(x) {y <- names(chDup)[x]; paste(" ",y[1]," duplicated by ",paste(y[-1],collapse=" "),"\n ")}))
disDat <- disDat[which(!chDup),] # cleaned main data
} else dupDat <- NULL
## check possible start sites
nodeWPrev <- sort(unique(names(which(rep(disDat[,1], nrow(disDat)) == rep(disDat[,2] +1, each=nrow(disDat))))))
rootBaseNa <- if(length(nodeWPrev) >0) rownames(disDat)[which(!rownames(disDat) %in% nodeWPrev)] else rownames(disDat)
rootBase <- which(rownames(disDat) %in% rootBaseNa)
names(rootBase) <- rootBaseNa
## check startFr
startFr <- if(is.null(startFr)) rootBase[1] else try(as.integer(startFr))
if(inherits(startFr, "try-error")) stop(fxNa,": 'startFr' should be NULL or integer (of length 1) !")
if(!startFr %in% rootBase) { if(!silent) message(fxNa,": choice of 'startFr' is not close to root, resetting to ",rootBase[1]," ('",names(rootBase)[1],"')")
startFr <- rootBase[1] }
names(startFr) <- rownames(disDat)[startFr]
tm1 <- disDat[,1] == disDat[startFr,2] +1 # startFr has following
tm1 <- list(lo=tm1, it=0 +tm1, preN=rep(NA,nrow(disDat)), disDat=disDat, iter=1, start=startFr)
## grow 1st branch
if(any(tm1$lo)) tm1 <- .growTree(tm1,setX) else {
x1 <- setX$AddChild(names(startFr), len=disDat[startFr,3])
tm1$it[startFr] <- 1
}
## look for other starting points (ie nodes not yet used)
chSup <- rownames(disDat) %in% rootBaseNa[-which(rootBaseNa == names(startFr))]
names(chSup) <- rownames(disDat)
if(any(chSup)) {
while(any(chSup)) {
j <- which(chSup)[1]
tm3 <- disDat[,1]== disDat[j,2] +1
tm3 <- list(lo=tm3, it=0 +tm3, preN=rep(NA,nrow(disDat)), disDat=disDat, iter=1, start=j)
tm3 <- .growTree(tm3,setX)
chSup[j] <- FALSE }
} else tm3 <- NULL
## now extract n and cumulated length fo fragments
setX$sumLen <- setX$len # initialize variable for summed length
traversal <- data.tree::Traverse(setX, filterFun=data.tree::isNotRoot)
data.tree::Do(traversal, function(node) node$sumLen <- node$parent$sumLen + node$len)
setX$n <- 1 # initialize variable for path length
data.tree::Do(traversal, function(node) node$n <- node$parent$n + 1)
out <- data.tree::ToDataFrameTable(setX, "pathString","sumLen","n")
rownames(out) <- sub("^_Root_\\/","",out[,1])
out$n <- out$n-1
out <- as.matrix(out[,-1])
if(length(dupDat) >0) {
## need list indicating which node(s) is/are duplicate of which node : dupDat
replOut <- function(x,chDup,out) { # fetch original of eliminated duplicated elements, reconstruct output with adjusted rownames
se <- function(v) paste0("/",v,"/")
y <- grep(se(names(chDup)[x[1]]), se(rownames(out)))
z <- se(rownames(out)[y])
w <- sub("^/","",sub("/$","",sapply(names(chDup)[x[-1]], function(w) sub(se(names(chDup)[x[1]]), se(w),z))))
matrix(rep(t(out[y,]), length(x)-1), ncol=ncol(out), dimnames=list(w,colnames(out)), byrow=TRUE) }
replOut(dupDat[[1]], chDup, out)
supMat <- lapply(dupDat, replOut, chDup, out)
out2 <- matrix(unlist(sapply(supMat, as.integer)), ncol=ncol(out), byrow=FALSE)
dimnames(out2) <- list(unlist(sapply(supMat, rownames)), colnames(out))
out <- rbind(out, out2)
}
list(paths=out, usedNodes=sort(names(chSup)[which(!chSup)]), tree=setX )
} }
#' Grow tree
#'
#' This function allows growing tree-like structures (data.tree objects)
#'
#' @param tm (list) main input, $disDat .. matrix with integer start & end sites for fragments; $lo (logical) which fragments may be grown; $start (integer) index for which line of $disDat to start; $it numeric version of $lo; $preN for previous tree objects towards root; $iter for iterator (starting at 1))
#' @param setX .. data.tree object (main obj from root)
#' @param addToObj .. data.tree object (branch on which to add new branches/nodes)
#' @return list
#' @seealso \code{\link{buildTree}}
#' @examples
#' .datSlope(c(3:6))
#' @export
.growTree <- function(tm, setX, addToObj=NULL) {
## grow tree 'setX' based on 'tm'
## 'tm' .. list ($disDat .. matrix with integer start & end sites for fragments; $lo (logical) which fragments may be grown; $start (integer) index for which line of $disDat to start; $it numeric version of $lo; $preN for previous tree objects towards root; $iter for iterator (starting at 1))
## 'setX' .. data.tree object (main obj from root)
## 'addToObj' .. data.tree object (branch on which to add new branches/nodes)
newNodeNa <- paste0("b",0,"_",tm$disDat[tm$start,1])
namesX <- deparse(substitute(setX)) # name of tree-object (typically 'setX' )
assign(newNodeNa, get(namesX)$AddChild(rownames(tm$disDat)[tm$start], len=tm$disDat[tm$start,3])) # add new 1st level branch to '_Root_'
if(any(tm$lo)) tm$preN[which(tm$lo)] <- newNodeNa
while(any(tm$lo)) { # need to grow further ..
tm$iter <- tm$iter +1
j <- which(tm$lo)[1]
addToObj <- if(tm$iter==2) newNodeNa else tm$preN[j]
assign(paste0("b",tm$it[j],"_",j), get(addToObj)$AddChild(rownames(tm$disDat)[j],len=tm$disDat[j,3]))
tm$lo[j] <- FALSE # this one is done ...
tm0 <- tm$disDat[,1]== tm$disDat[j,2] +1 # test for potential children
if(any(tm0)) {z <- which(tm0);
tm$lo[z] <- TRUE # set to-do status for children
tm$it[z] <- tm$it[j]+1 # tree-level
tm$preN[z] <- paste0("b",tm$it[j],"_",j) # report (prev)name of node
reOrd <- c(z,which(!tm0)) # need to change order to treat children next (for treatig correctly branched trees)
tm$lo <- tm$lo[reOrd]
tm$it <- tm$it[reOrd]
tm$preN <- tm$preN[reOrd]
tm$disDat <- tm$disDat[reOrd,] }
}
tm }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/buildTree.R
|
#' cbind to non-redundant
#'
#' \code{cbindNR} combines all matrixes given as arguments to non-redundant column names (by ADDING the number of 'duplicated' columns !).
#' Thus, this function works similar to \code{cbind}, but allows combining multiple matrix-objects containing redundant column-names.
#' Of course, all input-matrixes must have the same number of rows !
#' By default, the output gets sorted by column-names.
#' Note, due to the use of '...' arguments must be given by their full argument-names, lazy evaluation might not recognize properly argument names.
#'
#' @param ... all matrixes to get combined in cbind way
#' @param convertDFtoMatr (logical) decide if output should be converted to matrix
#' @param sortOutput (logical) optional sorting by column-names
#' @param summarizeAs (character) decide of combined values should get summed (default, 'sum') or averaged ('mean')
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @return This function returns a matrix or data.frame (as cbind would return)
#' @seealso \code{\link[base]{cbind}}, \code{\link{nonAmbiguousNum}}, \code{\link{firstOfRepLines}}
#' @examples
#' ma1 <- matrix(1:6, ncol=3, dimnames=list(1:2,LETTERS[3:1]))
#' ma2 <- matrix(11:16, ncol=3, dimnames=list(1:2,LETTERS[3:5]))
#' cbindNR(ma1, ma2)
#' cbindNR(ma1, ma2, summarizeAs="mean")
#' @export
cbindNR <- function(..., convertDFtoMatr=TRUE, sortOutput=TRUE, summarizeAs="sum", silent=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="cbindNR")
inpL <- list(...)
isDatafr <- sapply(inpL, is.data.frame)
if(convertDFtoMatr & any(isDatafr) >0) {
inpL[isDatafr] <- lapply(inpL[isDatafr], as.matrix)
}
isMatr <- sapply(inpL,is.matrix)
if(any(!isMatr) & !silent) {
message(fxNa," removing ",sum(!isMatr, na.rm=TRUE)," entries from input which are apparently not matrixes")
inpL <- inpL[which(isMatr)]}
if(length(inpL) <1) stop(" It seems the input doesn't contain any (valid) matrixes")
matrDim <- sapply(inpL,dim)
if(length(unique(matrDim[1,])) >1) stop(" Some matrixes don't have the same number of rows (found ",paste(matrDim[1,],collapse=" "),")")
nrColNa <- unique(unlist(lapply(inpL,colnames)))
if(!silent) message(fxNa," treating ",length(nrColNa)," different (types of) columns : ",paste(utils::head(nrColNa),collapse=" "))
out <- matrix(0,nrow=nrow(inpL[[1]]), ncol=length(nrColNa), dimnames=list(rownames(inpL[[1]]),nrColNa))
startCol <- 1
nByCol <- rep(0,length(nrColNa))
names(nByCol) <- nrColNa
for(i in 1:length(inpL)) { useCol <- match(colnames(inpL[[i]]), colnames(out))
out[,useCol] <- out[,useCol] + inpL[[i]]
nByCol[useCol] <- nByCol[useCol] +1
startCol <- startCol + ncol(inpL[[i]])}
if(identical(summarizeAs,"mean") & any(nByCol >1)) { useCol <- which(nByCol >1)
out[,useCol] <- out[,useCol] / matrix(rep(nByCol[useCol], each=nrow(out)), nrow=nrow(out))
}
if(sortOutput) { out <- out[,order(colnames(out))]
if(!silent) message(fxNa," sorting columns of output") }
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/cbindNR.R
|
#' Check how multiple groups of data separate or overlap based on mean +/- sd
#'
#' \code{checkAvSd} compares if/how neighbour groups separate/overlap via the 'engineering approach' (+/- 2 standard-deviations is similar to a=0.05 \code{t.test}).
#' This approach may be used as less elegant alternative to (multi-group) logistic regression.
#' The function uses 'daAv' as matrix of means (rows are tested for up/down character/progression) which get compared with boundaries taken from daSd (for Sd values of each mean in 'daAv').
#' @param daAv matrix or data.frame
#' @param daSd matrix or data.frame
#' @param nByGr optinal specifying number of Elements per group, allows rather using SEM (adopt to variable n of different groups)
#' @param multSd (numeric) the factor specifyin how many sd values should be used as margin
#' @param codeConst (character) which term/word to use when specifying 'constant'
#' @param extSearch (logical) if TRUE, extend search to one group further (will call result 'nearUp' or 'nearDw')
#' @param outAsLogical to switch between 2col-output (separate col for 'up' and 'down') or simple categorical vector ('const','okDw','okUp')
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of message(s) produced
#' @return vector describing character as 'const' or 'okUp','okDw' (or if extSearch=TRUE 'nearUp','nearDw')
#' @seealso \code{\link[wrMisc]{rowGrpMeans}}
#' @examples
#' mat1 <- matrix(rep(11:24,3)[1:40],byrow=TRUE,ncol=8)
#' checkGrpOrderSEM(mat1,grp=gl(3,3)[-1])
#' checkAvSd(rowGrpMeans(mat1,gl(3,3)[-1]),rowGrpSds(mat1,gl(3,3)[-1]) )
#' # consider variable n :
#' checkAvSd(rowGrpMeans(mat1,gl(3,3)[-1]),rowGrpSds(mat1,gl(3,3)[-1]),nByGr=c(2,3,3))
#' @export
checkAvSd <- function(daAv,daSd,nByGr=NULL,multSd=2,codeConst="const",extSearch=FALSE,outAsLogical=TRUE,silent=FALSE,callFrom=NULL){
fxNa <- .composeCallName(callFrom,newNa="checkAvSd")
if(!identical(dim(daAv),dim(daSd))) stop(fxNa," dimensions of 'daAv' and 'daSd' not same !!")
if(is.null(nByGr)) nByGr <- rep(1,ncol(daAv))
nGr <- ncol(daAv)
if(length(nByGr) != nGr & !silent) {
message(fxNa," 'nByGr' doesn't match number of columns in 'daAv' !!") }
incr <- daAv[,-nGr]+ multSd*daSd[,-nGr]/sqrt(nByGr[-nGr]) < daAv[,-1]- multSd*daSd[,-1]/sqrt(nByGr[-1])
decr <- daAv[,-nGr]- multSd*daSd[,-nGr]/sqrt(nByGr[-nGr]) > daAv[,-1]+ multSd*daSd[,-1]/sqrt(nByGr[-1])
if(outAsLogical) {
out <- cbind(up=rowSums(incr,na.rm=TRUE) >= ncol(incr), down=rowSums(decr,na.rm=TRUE) >= ncol(decr))
} else {
outInc <- rowSums(incr,na.rm=TRUE)
outDec <- rowSums(decr,na.rm=TRUE)
out <- rep(codeConst,nrow(daAv))
out[which(outInc == nGr-1)] <- "okUp"
out[which(outDec == nGr-1)] <- "okDw"
if(extSearch & nGr >3){
out[which(outInc == nGr-2)] <- "nearUp"
out[which(outDec == nGr-2)] <- "nearDw" }
}
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/checkAvSd.R
|
#' Check If File Is Available For Reading
#'
#' This function allows tesing if a given file-name corresponds to an existing file (eg for reading lateron).
#' Indications to the path and file-extensions may be given separately. If no files do match .gz compressed versions may be searced, too.
#'
#' @details
#'
#' When the filename given by the user exists but it's file-extension is not matching \code{expectExt}
#' the argument \code{strictExtension} allows to decide if the filename will still be returned or not.
#'
#' When \code{expectExt} is given, initial search will look for perfect matches.
#' However, if nothing is found and \code{strictExtension=FALSE}, a more relaxed and non-case-sensitive search will be performed.
#'
#' @param fileName (character) name of file to be tested; may also include an absolute or relative path
#' @param path (character, length=1) optional separate entry for path of \code{fileName}
#' @param expectExt (character) file extension (will not be considerd if \code{""})
#' @param compressedOption (logical) also look for .gz compressed files
#' @param strictExtension (logical) decide if extesion (\code{expectExt}) - if given - should be considered obligatory
#' @param stopIfNothing (logical) decide if function should give error or warning if no files found
#' @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 with verified path and file-name(s), returns \code{NULL} if nothing
#' @seealso \code{\link[base]{file.exists}}
#' @examples
#' (RhomeFi <- list.files(R.home()))
#' file.exists(file.path(R.home(), "bin"))
#' checkFilePath(c("xxx","unins000"), R.home(), expectExt="dat")
#' @export
checkFilePath <- function(fileName, path, expectExt="", compressedOption=TRUE, strictExtension=FALSE, stopIfNothing=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL) {
## check file-input if available to read
fxNa <- .composeCallName(callFrom, newNa="checkFilePath")
if(isTRUE(debug)) silent <- FALSE
if(!isTRUE(silent)) silent <- FALSE
msg <- "Invalid entry for 'path' "
## check path
if(length(path) >0) { path <- path[1]
if(is.na(path)) path <- NULL else {
if(!dir.exists(path)) { path <- "."
if(!silent) message(fxNa, msg, path[1],"' (not existing), ignoring...")}
} }
if(length(expectExt) <1) expectExt <- "" else if(any(is.na(expectExt))) expectExt <- ""
#if(isTRUE(compressedOption)) compressedOption <-
## check for 'fileName'
msg <- "Invalid entry for 'fileName'"
if(length(fileName) <1) stop(msg) else if(any(is.na(fileName)) || any(nchar(fileName) <1)) stop(msg)
if(nchar(expectExt) >0) if(grepl("^\\.",expectExt)) expectExt <- sub("^\\.", "", expectExt) # remove heading '.' if accidently given
## init check for presence of 'fileName'
paFi <- if(length(path) >0) file.path(path, fileName) else fileName
chFi <- file.exists(paFi)
if(nchar(expectExt) >0 && isTRUE(strictExtension)) chFi <- chFi & grepl(paste0("\\.",expectExt,"$|\\.",expectExt,"\\.gz$"), paFi) # correct for imposed file-extension
if(debug) {message(fxNa,"cFP1 "); cFP1 <- list(fileName=fileName,path=path,paFi=paFi,chFi=chFi,expectExt=expectExt,compressedOption=compressedOption )}
if(any(chFi)) {
paFi <- paFi[which(chFi)]
chFi <- chFi[which(chFi)]
}
if(!any(chFi)) {
## check extension
if(nchar(expectExt) >0) {
##if(!grepl("^\\.",expectExt)) expectExt <- paste0("\\.", expectExt) # add heading '.' if not yet given
paFi <- paste0(sub(paste0("\\.",expectExt,"$"),"", paFi),".",expectExt) # avoid doubling extension
chFi <- file.exists(paFi)
if(any(chFi)) { if(debug) message(fxNa,"When including file-extension found file(s) ",pasteC(paste0(fileName,".",expectExt))[which(chFi)])
paFi <- paFi[which(chFi)]
chFi <- chFi[which(chFi)]
} else {
if(isFALSE(strictExtension)) { # check for upper/lower case of extension
fiLi <- list.files(path=if(length(path) ==1) path else ".", pattern=paste0(sub("\\.[[:alpha:]]+$","", fileName),"\\.",expectExt,"$"), full.names=TRUE, ignore.case=TRUE)
if(length(fiLi) >0) {
paFi <- fiLi
chFi <- rep(TRUE, length(fiLi))
if(debug) message(fxNa,"Found file(s) with different lower/upper case spelling of extension: ",pasteC(basename(paFi), quoteC="'"))
}
}
}
}
if(debug) {message(fxNa,"cFP3 "); cFP3 <<- list(fileName=fileName,path=path,paFi=paFi,chFi=chFi,expectExt=expectExt,compressedOption=compressedOption )}
## now check for compressed (wo or with extension)
if(compressedOption && !any(chFi)) {
msg <- " not found, BUT a .gz compressed version exists, using compressed file(s).."
paFi0 <- paFi
paFi <- paste0(paFi,".gz")
chFi <- file.exists(paFi)
if(any(chFi)) {
if(!silent) message(fxNa,"Note : File(s) ",pasteC(fileName[which(chFi)], quoteC="'"), msg)
paFi <- paFi[which(chFi)]
chFi <- chFi[which(chFi)]
}
if(!any(chFi) && nchar(expectExt) >0 && isFALSE(strictExtension)) {
fiLi <- list.files(path=if(length(path) ==1) path else ".", pattern=paste0(sub("\\.[[:alpha:]]+\\.gz$","", fileName),"\\.",expectExt,"\\.gz$"), full.names=TRUE, ignore.case=TRUE)
if(length(fiLi) >0) {
paFi <- fiLi
chFi <- rep(TRUE, length(fiLi))
if(!silent) message(fxNa,"Note : Found compressed version of file(s) ",pasteC(basename(paFi), quoteC="'"))
}
}
}
if(!silent && length(paFi) < length(fileName)) message(fxNa,"Note ",length(fileName) - length(paFi)," files were NOT found !")
}
if(!any(chFi)) {
msg <- c(" File(s) ",pasteC(fileName,quoteC="'")," NOT found ",if(length(path) >0) paste0(" in path '",path,"'")," !")
if(isTRUE(stopIfNothing)) stop(msg) else warning(msg, " (returning NULL)")
if(nchar(expectExt) >0 && !silent) {
chOth <- grepl(fileName, paFi)
if(any(chOth)) message(fxNa,"Note : The file-extension might not be correct, found other file(s) with different extension(s)")
}
paFi <- NULL
}
if(debug) {message(fxNa,"cFP3 "); cFP3 <- list(fileName=fileName,path=path)}
paFi }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/checkFilePath.R
|
#' checkGrpOrder
#'
#' \code{checkGrpOrder} tests each line of 'x' if expected order appears.
#' Used for comparing groups of measures with expected profile (simply by mataching expected order)
#' @param x matrix or data.frame
#' @param rankExp (numeric) expected order for values in columns, default 'rankExp' =1:ncol(x)
#' @param revRank (logical) if 'revRank'=TRUE, the initial ranks & reversed ranks will be tested
#' @param silent (logical) suppress messages
#' @param debug (logical) display additional messages for debugging
#' @param callFrom (character) allow easier tracking of messages produced
#' @return vector of logical values
#' @seealso \code{\link[wrMisc]{checkGrpOrderSEM}}
#' @examples
#' set.seed(2005); mat1 <- rbind(matrix(round(runif(40),1),nc=4), rep(1,4))
#' checkGrpOrder(mat1)
#' checkGrpOrder(mat1,c(1,4,3,2))
#' @export
checkGrpOrder <- function(x, rankExp=NULL, revRank=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="checkGrpOrder")
if(length(x) <1 | length(dim(x)) !=2) stop(" 'x' should be data.frame or matrix of 2 dimensions")
if(is.null(rankExp)) rankExp <- 1:ncol(x)
if(length(rankExp) != ncol(x)) stop("Number of elements in 'rankExp' doesn't match number of columns in 'x'")
## main
rankExp <- as.numeric(rankExp)
out <- if(revRank) {
apply(x, 1, function(x) {y <- as.numeric(order(x)); identical(rankExp,y) | identical(rev(rankExp),y)})
} else {
apply(x, 1, function(x) identical(rankExp, as.numeric(order(x))) )}
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/checkGroupOrder.R
|
#' Check order of multiple groups including non-overlapping SEM-margins
#'
#' \code{checkGrpOrderSEM} tests each line of 'x' if expected order of (replicate-) groups (defined in 'grp') appears intact,
#' while inluding SEM of groups (replicates) via a proportional weight 'sdFact' as (avGr1-gr1SEM) < (avGr1+gr1SEM) < (avGr2-gr2SEM) < (avGr2+gr2SEM).
#' Used for comparing groups of measures with expected profile (by matching expected order)
#' to check if data in 'x' represting groups ('grp') as lines follow.
#' Groups of size=1: The sd (and SEM) can't be estimated directly without any replicates, however, an estimate can be given by shrinking if 'shrink1sampSd'=TRUE
#' under the hypothesis that the overall mechanisms determining the variances is constant across all samples.
#' @param x matrix or data.frame
#' @param grp (factor) to organize replicate columns of (x)
#' @param sdFact (numeric) is proportional factor how many units of SEM will be used for defining lower & upper bounds of each group
#' @param revRank (logical) optionally revert ranks
#' @param shrink1sampSd (logical)
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of message(s) produced
#' @return logical vector if order correct (as expected based on ranks)
#' @seealso takes only 10% more time than \code{\link[wrMisc]{checkGrpOrder}} wo considering intra-group sd
#' @examples
#' mat1 <- matrix(rep(11:24,3)[1:40],byrow=TRUE,ncol=8)
#' checkGrpOrderSEM(mat1,grp=gl(3,3)[-1])
#' @export
checkGrpOrderSEM <- function(x,grp,sdFact=1,revRank=TRUE,shrink1sampSd=TRUE,silent=FALSE,callFrom=NULL){
fxNa <- .composeCallName(callFrom,newNa="checkGrpOrderSEM")
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)
## main
avs <- .rowGrpMeans(x,grp)
sds <- .rowGrpSds(x,grp)
sdsNaCol <- colSums(is.na(sds)) ==nrow(x)
if(shrink1sampSd & sum(sdsNaCol) >0) {
if(!silent) message(fxNa,sum(sdsNaCol)," single-column groups : estimating possible sd based on other samples/groups")
sds[,which(sdsNaCol)] <- stats::median(naOmit(as.numeric(sds)),na.rm=TRUE) }
nMa <- matrix(rep(naOmit(as.numeric(table(grp))[order(unique(grp))]),each=nrow(x)),nrow=nrow(x))
lims <- list(low=avs - sdFact*sds, hi=avs + sdFact*sds)
out <- matrix(nrow=nrow(x),ncol=2*ncol(avs))
for(i in 1:ncol(avs)) out[,(2*i-1):(2*i)] <- cbind(lims[[1]][,i],lims[[2]][,i])
checkGrpOrder(out,rankExp=1:ncol(out),revRank=revRank) }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/checkGroupOrderSEM.R
|
#' Check for similar values in series
#'
#' This function checks all values of 'x' for similar neighbour values within (relative) range of 'ppm' (ie parts per milion as measure of distance).
#' By default values will be sorted internally, so if a given value of \code{x} has anywhere in \code{x} another value close enough, this will be detected.
#' However, if \code{sortX=FALSE} only the values next to left and right will be considered.
#' Return logical vector : FALSE for each entry of 'x' if value inside of ppm range to neighbour (of sorted values)
#' @param x numeric vector
#' @param ppm (numeric, length=1) ppm-range for considering as similar
#' @param sortX (logical) allows speeding up function when set to FALSE, for large data that are already sorted
#' @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 logical vector : \code{TRUE} for each entry of \code{x} where at least one neighbour is inside of ppm distance/range
#' @seealso similar with more options \code{\link{withinRefRange}}
#' @examples
#' va1 <- c(4:7,7,7,7,7,8:10)+(1:11)/28600; checkSimValueInSer(va1)
#' data.frame(va=sort(va1),simil=checkSimValueInSer(va1))
#' @export
checkSimValueInSer <- function(x, ppm=5, sortX=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL) {
fxNa <- .composeCallName(callFrom, newNa="checkSimValueInSer")
if(isTRUE(debug)) silent <- FALSE
if(!isTRUE(silent)) silent <- FALSE
nNA <- sum(is.na(x))
if(nNA >0 && !silent) message(fxNa,"Found ",nNA," NA values")
so <- if(!isFALSE(sortX)) sort(x) else x
di <- diff(so)
diLim <- so *ppm *1e-6
out <- rep(FALSE, length(x))
names(out) <- names(so)
out[-length(x)] <- abs(di) < abs(diLim[-length(x)]) # close to right neighbour
out[-1] <- out[-1] | abs(di) < abs(diLim[-1]) # close to left neighbour
if(sortX) out[rank(x, ties.method="first")] else out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/checkSimValueInSer.R
|
#' Check for strict (ascencing or descending) order
#'
#' \code{checkStrictOrder} tests lines of 'dat' (matrix of data.frame) for strict order (ascending, descending or constant),
#' each col of data is tested relative to the col on its left.
#' @param dat matrix or data.frame
#' @param invertCount (logical) inverse counting (ie return 0 for all elememts in order)
#' @param silent (logical) suppress messages
#' @param debug (logical) display additional messages for debugging
#' @param callFrom (character) allow easier tracking of messages produced
#' @return matrix with counts of up pairs, down pairs, equal-pairs, if 'invertCount'=TRUE all non-events are counted, ie a resulting 0 means that all columns are following the described characteristics (with variabale col-numbers easier to count)
#' @seealso \code{\link[base]{order}}, \code{\link{checkGrpOrder}}
#' @examples
#' set.seed(2005); mat1 <- rbind(matrix(round(runif(40),1),nc=4), rep(1,4))
#' checkStrictOrder(mat1); mat1[which(checkStrictOrder(mat1)[,2]==0),]
#' @export
checkStrictOrder <- function(dat, invertCount=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="checkStrictOrder")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
testO <- array(NA, dim=c(nrow(dat), ncol(dat) -1, 2))
testId <- matrix(NA, nrow=nrow(dat), ncol=ncol(dat) -1)
for(i in 1:(ncol(dat)-1)) {
testO[,i,1] <- dat[,i] > dat[,i+1]
testO[,i,2] <- dat[,i] < dat[,i+1]
testId[,i] <- dat[,i] == dat[,i+1]
}
if(isTRUE(invertCount)) {testO <- !testO; testId <- !testId}
out <- cbind(up=rowSums(testO[,,2], na.rm=TRUE), down=rowSums(testO[,,1], na.rm=TRUE), eq=rowSums(testId, na.rm=TRUE))
rownames(out) <- rownames(dat)
out }
#' Get first minimum
#'
#' This function allows to find the first minimum of a numeric vector
#'
#' @param x (numeric vector) main input
#' @param positionOnly (logical)
#' @return numeric vector
#' @seealso \code{\link[base]{which.min}}
#' @examples
#' .firstMin(c(4,3:6))
#' @export
.firstMin <- function(x, positionOnly=FALSE) {
## get (first) min of series
## for longer series of data rather use getMedOf1stValley()
minPos <- which.min(x) # no problem with NA
if(positionOnly) minPos else x[minPos] }
#' Rescale respective to specific group
#'
#' This function allows to rescale data 'x' so that specific group 'grpNum' gets normalized to predefined value 'grpVal'.
#' In normal case x will be multiplied by 'grpVal' and devided by value obtained from 'grpNum'.
#' If summary of 'grpNum-positions' or 'grpVal' is 0, then grpVal will be attained by subtraction of summary & adding grpVal
#'
#' @param x (numeric vector) main input
#' @param grpNum (numeric)
#' @param grpVal (numeric)
#' @param sumMeth (character) method for summarizing
#' @param callFrom (character) allow easier tracking of messages produced
#' @return numeric vector
#' @seealso \code{\link[base]{which.min}}
#' @examples
#' .firstMin(c(4,3:6))
#' @export
.medianSpecGrp <- function(x, grpNum, grpVal, sumMeth="median", callFrom=NULL){
## rescale data 'x' so that specific group 'grpNum' gets normalized to predefined value 'grpVal'
## in normal case x will be multiplied by 'grpVal' and devided by value obtained from 'grpNum'
## if summary of 'grpNum-positions' or 'grpVal' is 0, then grpVal will be attained by subtration of summary & adding grpVal
fxNa <- .composeCallName(callFrom,newNa=".medianSpecGrp")
msg1 <- c("argument ","'grpVal' should be numeric; ",
"'grpNum' should be of length 1 and may be numeric or names of 'x'")
if(sum(is.na(x))==length(x)) {
message(fxNa,"argument 'x' seems all empty or NA, nothing to do")
} else {
if(length(grpVal) != 1) stop(fxNa,msg1[c(1:2)])
if(any(sum(is.na(x)) ==length(x), sum(is.na(grpNum)) >0, is.na(grpVal))) stop(msg1[c(1:2,1,3)])
if(length(grep("^[[:digit:]]+$",grpNum)) <1) grpNum <- match(grpNum,names(x))
grpNum <- convToNum(grpNum, remove=NULL)
grpNum <- grpNum[grpNum <= length(x)]
msg2 <- "'grpNum' should be either numeric for positions in 'x' or character for names of 'x'"
if(length(grpNum) <1) stop(fxNa,msg1[1],msg2)
grp1ini <- if(length(grpNum) >1) {
if(identical(sumMeth,"median")) stats::median(x[grpNum],na.rm=TRUE) else mean(x[grpNum],na.rm=TRUE)
} else x[grpNum]
x <- if(all(c(grpVal,grp1ini) !=0)) grpVal*x/grp1ini else x + grpVal - grp1ini # set values
}
x }
#' Rescale respective to specific group
#'
#' This function allows to rescale data 'x' so that 2 specific groups get normalized to predefined values (and all other values follow proportionally)
#' 'grp1Num' and 'grp2Num' should be either numeric for positions in 'x' or character for names of 'x';
#' if 'grp1Num' and/or 'grp2Num' design mulitple locations: perform median or mean summarization, according to 'sumMeth'
#'
#' @param x (numeric vector) main input
#' @param grp1Num (numeric)
#' @param grp1Val (numeric)
#' @param grp2Num (numeric)
#' @param grp2Val (numeric)
#' @param sumMeth (character) method for summarizing
#' @param callFrom (character) allow easier tracking of messages produced
#' @return numeric vector
#' @seealso \code{\link[base]{which.min}}
#' @examples
#' .firstMin(c(4,3:6))
#' @export
.scaleSpecGrp <- function(x, grp1Num, grp1Val, grp2Num=NULL, grp2Val=NULL, sumMeth="mean",callFrom=NULL){
## rescale data 'x' so that 2 specific groups get normalized to predefined values (and all other values follow proportionally)
## 'grp1Num' and 'grp2Num' should be either numeric for positions in 'x' or character for names of 'x'
## if 'grp1Num' and/or 'grp2Num' design mulitple locations: perform median or mean summarization, according to 'sumMeth'
## return object of same dim as 'x'
fxNa <- .composeCallName(callFrom, newNa=".scaleSpecGrp")
msg1 <- c("argument ","'grp1Val'"," and ","'grp2Val'"," should be numeric of length 1; ",
"'grp1Num'","'grp2Num'"," may be numeric or names of 'x'"," .. ignoring")
if(sum(is.na(x)) ==length(x)) {
message(fxNa,"Argument 'x' seems all empty or NA, nothing to do")
} else {
if(sum(is.na(x))==length(x) || sum(is.na(grp1Num)) >0 || is.na(grp1Val)) stop(msg1[c(1:2,5,6,8)])
if(length(grp1Val) !=1) stop(msg1[c(1:2,5)])
if(length(grep("^[[:digit:]]+$", grp1Num)) <1) grp1Num <- match(grp1Num, names(x))
grp1Num <- convToNum(grp1Num, remove=NULL)
grp1Num <- grp1Num[grp1Num <= length(x)]
if(length(grp1Num) <1) stop(fxNa,"Can't find positions/matches for 'grp1Num' in 'x' !")
grp1ini <- if(length(grp1Num) >1) {
if(identical(sumMeth,"median")) stats::median(x[grp1Num],na.rm=TRUE) else mean(x[grp1Num],na.rm=TRUE)
} else x[grp1Num]
if(identical(grp1Val, grp2Val)) {grp2Num <- NULL; message(fxNa," grp1Val and grp2Val should be different ! ignoring grp2Val")}
if(length(grp2Num) >0 && length(grp2Val) !=1) {grp2Num <- NULL; message(fxNa,paste(msg1[c(1,4,5,9)]))}
if(length(grp2Num) >0) {
if(any(sum(is.na(grp2Num)) >0, is.na(grp2Val))) stop(msg1[c(1:2,1,3)])
grp2ini <- if(length(grp2Num) >1) {
if(identical(sumMeth,"median")) stats::median(x[grp2Num],na.rm=TRUE) else mean(x[grp2Num], na.rm=TRUE)
} else x[grp2Num]
if(length(grep("^[[:digit:]]+$",grp2Num)) <1) grp2Num <- match(grp2Num, names(x))
grp2Num <- convToNum(grp2Num, remove=NULL)
grp2Num <- grp2Num[grp2Num <= length(x)]
msg2 <- c("'grp2Num' should be either numeric for positions in 'x' or character for names of 'x'"," ... ignoring")
if(length(grp2Num) <1) {grp2Num <- NULL; message(fxNa,msg1[1],msg2)} }
if(length(grp2Num) <1) {
x <- if(all(c(grp1Val, grp1ini) !=0)) grp1Val*x/grp1ini else x + grp1Val - grp1ini # set values
} else {
x <- x - grp1ini # set 1st val to 0
x <- grp1Val + x*(grp2Val -grp1Val)/grp2ini } }
x }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/checkStrictOrder.R
|
#' Check length of vector
#'
#' \code{checkVectLength} checks argument 'x' for expected length 'expeL' and return either message or error when expectation not met.
#' May be used for parameter ('sanity') checking in other user front-end functions.
#' @param x (numeric or charcter vector) input to check length
#' @param expeL (numeric) expected length
#' @param stopOnProblem (logical) continue on problems with message or stop (as error message)
#' @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 \code{NULL}; it produces either error-message if length is not OK or optional message if length is OK
#' @examples
#' aa <- 1:5; checkVectLength(aa,exp=3)
#' @export
checkVectLength <- function(x, expeL=1, stopOnProblem=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="checkVectLength")
argN <- deparse(substitute(x))
msg <- " argument 'expeL' should be numeric of length 1 ; resetting to default =1"
if(!is.finite(expeL)) {expeL <- 1; message(fxNa,msg)}
if(length(x) != expeL) {
msg <- paste(" Argument '",argN,"' doesn't fit to expected length of ",expeL,sep="")
if(stopOnProblem) stop(fxNa,msg) else {if(!silent) message(fxNa,msg)} }
}
#' Convert numeric vector to matrix
#'
#' Take (numeric) vector and return matrix, if 'colNa' given will be used as colname
#'
#' @param x (numeric or character) main input
#' @param colNa (integer) design the comumn-name to be given
#' @param rowsKeep (logical) is \code{TRUE} make matrix of 1 column, otherwise of 1 row
#' @return matrix
#' @seealso \code{\link[base]{matrix}}
#' @examples
#' .vector2Matr(c(3:6))
#' @export
.vector2Matr <- function(x, colNa=NULL, rowsKeep=TRUE) {
## take (numeric) vector and return matrix, if 'colNa' given will be used as colname
nameX <- deparse(substitute(x))
if(is.factor(x)) x <- as.character(x)
if(length(dim(x)) <2) x <- if(rowsKeep) matrix(x, ncol=1, dimnames=list(names(x), if(length(colNa) >0) colNa[1] else nameX)) else {
matrix(x, nrow=1, dimnames=list( if(length(colNa) >0) colNa[1] else nameX), names(x))}
x }
#' Convert numeric matrix to numeric
#'
#' Take matrix and return vector
#'
#' @param matr (matrix) main input
#' @param useCol (integer) design the comumns to be used
#' @return numeric vector
#' @seealso \code{\link[base]{matrix}}
#' @examples
#' .convertMatrToNum(matrix(1:6, ncol=2))
#' @export
.convertMatrToNum <- function(matr, useCol=NULL){
## convert all (or selected by 'useCol') colums of matrix (or data.frame) to matrix of numeric data
## by default ('useCol' as NULL) all columns will be used
## columns with text data will be returned as NAs
## columns not covered/mentioned in useCol will only be transformed to matrix
## for more elaborate function see convMatr2df()
if(is.null(useCol)) {
suplMa <- NULL
useCol <- 1:ncol(matr)
} else { # start with testing validity of values given
msg1 <- "'useCol' should design the columns of 'matr' to be used for conversion. Invalid entry"
if(is.numeric(useCol)) {
if(sum(is.finite(useCol)) < length(useCol) || max(useCol) > length(matr)) stop(msg1)
} else { # if real col-name given, convert to number
useCol <- naOmit(match(as.character(useCol), colnames(matr)))
if(length(useCol) <1) stop(" no valid columns-names found") }
suplMa <- matr[,-1*useCol]
}
dimNa <- dimnames(matr)
out <- matrix(as.numeric(as.character(as.matrix(matr[,useCol]))), nrow=length(dimNa[[1]]), ncol=length(useCol)) # robust to factors
if(!is.null(suplMa)) out <- cbind(as.matrix(suplMa), out)
dimnames(out) <- dimNa
out }
#' Check Factor
#'
#' This function was designed to check a factor object
#'
#' @param fac (factor) main input
#' @param facNa (character) level-names
#' @param minLev (integer) minium number of levels
#' @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 corrceted/adjusted factor
#' @seealso \code{\link[base]{factor}}
#' @examples
#' .checkFactor(gl(3,2))
#' @export
.checkFactor <- function(fac, facNa=NULL, minLev=2, silent=FALSE, debug=FALSE, callFrom=NULL){
## checking of factors (used for for limma model.matrix)
objNa <- deparse(substitute(fac))
fxNa <- .composeCallName(callFrom, newNa=".checkFactor")
if(is.null(facNa) | length(facNa) <1) facNa <- objNa
if(length(facNa) >1) facNa <- facNa[1]
if(!is.factor(fac)) {fac <- as.factor(fac)
if(!silent) message(fxNa," transforming ",facNa," to ",length(levels(fac))," level-factor (",
paste(utils::head(levels(fac)),collapse=", "),if(length(levels(fac)) >6) " ..",")")}
if(length(levels(fac)) < minLev & !silent) message(fxNa," NOTE : factor ",facNa," contains not required number of levels")
fac }
#' Add lower caps to character vector
#'
#' This function allows adding all content as lower caps to/of character vector
#'
#' @param x (character) main input
#' @return This function returns a elongated character vector
#' @seealso \code{\link[base]{chartr}}
#' @examples
#' .plusLowerCaps(c("Abc","BCD"))
#' @export
.plusLowerCaps <- function(x) unique(c(x,tolower(x))) # return original content of 'x' plus all in lower caps (non-redundant)
#' Replace Special Characters
#'
#' This function allows replacing special characters
#' Note that (most) special characters must be presented with protection for \code{grep} and \code{sub}.
#'
#' @param x (character) main input
#' @param findSp (character) special characters to replace (may have to be given as protected)
#' @param replBy (character) replace by
#' @return This function returns a corrceted/adjusted factor
#' @seealso \code{\link[base]{factor}}
#' @examples
#' .replSpecChar(c("jhjh(ab)","abc"))
#' @export
.replSpecChar <- function(x, findSp=c("\\(","\\)","\\$"), replBy="_") {
## in character vector 'x' replace special character 'findSp' and replace by 'replBy'
## note that spec characters must pe presented with protection for grep & sub
if(length(findSp) > 1 & length(replBy)==1) replBy <- rep(replBy, length(findSp))
for(i in 1:length(findSp)) { xx <- grep(findSp[i],x)
if(length(xx) >0) x <- gsub(findSp[i],replBy[i],x)}
x}
#' Check argument names
#'
#' This function allows checking of argument names
#'
#' @param x (character) main input
#' @param argNa (character) argument name
#' @param lazyEval (logical) decide if argument should be avaluated with abbreviated names, too
#' @return This function returns a elongated character vector
#' @seealso \code{\link[base]{chartr}}
#' @examples
#' .checkArgNa("Abc",c("ab","Ab","BCD"))
#' @export
.checkArgNa <- function(x, argNa, lazyEval=TRUE) {
## check character vector 'x' if any of its elements may be (lazy avaluation) argument names of vector 'argNa'
## potentially calling too many conflicts : eg will call conflict for single character even when saveral 'argNa' start with this letter (ie invalid for calling fx)
## return logical vector at length & names of 'x'
isArgNa <- sapply(x, nchar) <1
zz <- naOmit(match(argNa, x))
if(length(zz) >0) isArgNa[zz] <- TRUE
if(lazyEval) {
tmp <- .cutStr(argNa[1], startFr=1, reverse=TRUE)[-1]
tmp <- sapply(x, function(z) z %in% tmp)
if(any(tmp, na.rm=TRUE)) isArgNa[which(tmp)] <- TRUE
} else {zz <- naOmit(match(argNa,x)); if(length(zz)>0) isArgNa[zz] <- TRUE}
isArgNa }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/checkVectLength.R
|
#' Replace Most Distant Values by NA
#'
#' This procedures aims to streighten (clean) the most extreme values of noisy replicates by identifying the most distant points
#' (among a set of replicates). The input 'x' (matrix or data.frame) is supposed to come from multiple different measures taken
#' in replicates (eg weight of different individuals as rows taken as multiple replicate measures in subsequent columns).
#'
#' @details
#' With the argument \code{nOutl} the user chooses the total number of most extreme values to replace by \code{NA}.
#' how many of the most extreme replicates of the whole dataset will replaced by \code{NA}, ie with \code{nOutl=1}
#' only the single most extreme outlyer will be replaced by \code{NA}.
#' Outlier points are determined as point(s) with highest distance to (row) center (median and mean choice via argument 'centrMeth').
#' Thus function returns input data with "removed" points set to \code{NA}, or if \code{retOffPos=TRUE} the most extreme/outlier positions.
#'
#' @param x matrix (or data.frame)
#' @param centrMeth (character) method to summarize (mean or median)
#' @param nOutl (integer) determines how many points per line will be set to \code{NA} (with n=1 the worst row of replicates will be 'cleaned')
#' @param retOffPos (logical) if \code{TRUE}, replace the most extreme outlyer only
#' @param silent (logical) suppres messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @return This function returns a matrix of same dimensions as input \code{x}, data-points which were tagged/removed are set to \code{NA}, or if \code{retOffPos=TRUE} the most extreme/outlier positions
#' @examples
#' mat3 <- matrix(c(19,20,30, 18,19,28, 16,14,35),ncol=3)
#' cleanReplicates(mat3, nOutl=1)
#' @export
cleanReplicates <- function(x, centrMeth="median", nOutl=2, retOffPos=FALSE, silent=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="cleanReplicates")
if(!any(is.data.frame(x),is.matrix(x))) stop(" 'x' is assumed as matrix or data.frame")
if(length(dim(x)) !=2) stop(fxNa," Designed for 2dim 'x' (here ",if(is.null(ncol(x))) "none" else ncol(x),")")
if(nOutl >= ncol(x)) stop(fxNa," Argument 'nOutl' should not reach or exceed number of columns of 'x' (here ",ncol(x)," cols)")
if(is.data.frame(x)) x <- as.matrix(x)
if(length(table(table(rownames(x)))) != 1) {
if(!silent) message(fxNa," rownames of 'x' either NULL or not unique, replacing by row-numbers")
rownames(x) <- 1:nrow(x) }
xCV <- rowCVs(x)
xCV <- xCV[which(rowSums(!is.na(x)) >0)]
badCV <- which(xCV >= sort(xCV, decreasing=TRUE, na.last=TRUE)[nOutl])
if(!silent) message(fxNa,"removing ",length(badCV)," entries in lines ",paste(names(badCV),collapse=","))
centr <- if(identical(centrMeth, "median")) apply(x, 1, stats::median,na.rm=TRUE) else rowMeans(x, na.rm=TRUE)
di <- abs(x - matrix(rep(centr, ncol(x)), nrow=nrow(x)))
di[which(rowSums(!is.na(di)) <1), ] <- 0
if(!silent & sum(is.infinite(di)) >0) message(fxNa," Attention, ",sum(is.infinite(di))," distance values are infinite !")
for(i in 1:length(badCV)) {y <- badCV[i]
x[match(names(y), rownames(x)), which(di[y,] ==max(di[y,], na.rm=TRUE))[1]] <- NA }
x }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/cleanReplicates.R
|
#' Reorganize results of search for close (similar) values in matrix-view
#'
#' \code{closeMatchMatrix} reorganizes/refines results from simple search of similar values of 2 sets of data by \code{\link[wrMisc]{findCloseMatch}} (as list for one-to many relations) to more human friendly/readable matrix.
#' This function returns results combining two sets of data which were initially compared (eg measured and threoretical values) as matrix-view using output of \code{\link[wrMisc]{findCloseMatch}} and both original datastes
#' Additional information (covariables, annotation, ...) may be included as optional columns for either 'predMatr' or 'measMatr'.
#' Note : It is important to run \code{\link[wrMisc]{findCloseMatch}} with \code{sortMatch=FALSE} !
#' Note : Results presented based on view of 'predMatr', so if multiple 'measMatr' are at within tolared distance, lines of 'measMatr' will be repeated;
#' Note : Distances 'disToMeas' and 'ppmToPred' are oriented : neg value if measured is lower than predicted (and pos values if higher than predicted);
#' Note : Returns \code{NULL} when nothing within given limits of comparison;
#' @param closeMatch (list) output from \code{\link[wrMisc]{findCloseMatch}}, ie list with hits for each 'x' (1st argument) : named vectors of value & x index in name; run with 'sortMatch'=F
#' @param predMatr (vector or matrix) predicted values, the column 'colPred' indicates which column is used for matching from \code{\link[wrMisc]{findCloseMatch}}; if column 'id' present this column will be used as identifier for matching
#' @param measMatr (vector or matrix) measured values, the column 'colMeas' indicates which column is used for matching from \code{\link[wrMisc]{findCloseMatch}}; if column 'id' present this column will be used as identifier for matching
#' @param prefMatch (character, length=2) prefixes ('^x' and/or '^y') thay may have been added by \code{findCloseMatch}
#' @param colPred (integer or text, length=1) column of 'predMatr' with main values of comparison
#' @param colMeas (integer or text, length=1) column of 'measMatr' with main measures of comparison
#' @param limitToBest (integer) column of 'measMatr' with main measures of comparison
#' @param asDataFrame (logical) convert results to data.frame if non-numeric matrix produced (may slightly slow down big results)
#' @param origNa (logical) will try to use original names of objects 'predMatr','measMatr', if they are not multi-column and not conflicting other output-names (otherwise 'predMatr','measMatr' will appear)
#' @param silent (logical) suppress messages
#' @param callFrom (character) allows easier tracking of message(s) produced
#' @param debug (logical) for bug-tracking: more/enhanced messages
#' @return results as matrix-view based on initial results from \code{\link[wrMisc]{findCloseMatch}}, including optional columns of suppelemental data for both sets of data for comparison. Returns \code{NULL} when nothing within limits
#' @seealso \code{\link[wrMisc]{findCloseMatch}}, \code{\link[wrMisc]{checkSimValueInSer}}
#' @examples
#' aA <- c(11:17); bB <- c(12.001,13.999); cC <- c(16.2,8,9,12.5,15.9,13.5,15.7,14.1,5)
#' (cloMa <- findCloseMatch(aA,cC,com="diff",lim=0.5,sor=FALSE))
#' # all matches (of 2d arg) to/within limit for each of 1st arg ('x'); 'y' ..to 2nd arg = cC
#' (maAa <- closeMatchMatrix(cloMa,aA,cC,lim=TRUE)) #
#' (maAa <- closeMatchMatrix(cloMa,aA,cC,lim=FALSE,origN=TRUE)) #
#' (maAa <- closeMatchMatrix(cloMa,cbind(valA=81:87,aA),cbind(valC=91:99,cC),colM=2,
#' colP=2,lim=FALSE))
#' (maAa <- closeMatchMatrix(cloMa,cbind(aA,valA=81:87),cC,lim=FALSE,deb=TRUE)) #
#' a2 <- aA; names(a2) <- letters[1:length(a2)]; c2 <- cC; names(c2) <- letters[10+1:length(c2)]
#' (cloM2 <- findCloseMatch(x=a2,y=c2,com="diff",lim=0.5,sor=FALSE))
#' (maA2 <- closeMatchMatrix(cloM2,predM=cbind(valA=81:87,a2),measM=cbind(valC=91:99,c2),
#' colM=2,colP=2,lim=FALSE,asData=TRUE))
#' (maA2 <- closeMatchMatrix(cloM2,cbind(id=names(a2),valA=81:87,a2),cbind(id=names(c2),
#' valC=91:99,c2),colM=3,colP=3,lim=FALSE,deb=FALSE))
#' @export
closeMatchMatrix <- function(closeMatch, predMatr, measMatr, prefMatch=c("^x","^y"), colPred=1, colMeas=1, limitToBest=TRUE, asDataFrame=FALSE, origNa=TRUE,silent=FALSE,callFrom=NULL,debug=FALSE){
fxNa <- .composeCallName(callFrom,newNa="closeMatchMatrix")
namesMXY <- c(deparse(substitute(closeMatch)), deparse(substitute(predMatr)), deparse(substitute(measMatr)))
if(debug) silent <- FALSE
if(debug) {message(fxNa,".. xxidentToMatr2a\n")}
if(length(closeMatch) <1) message(fxNa," INPUT EMPTY, NOTHING TO DO !!")
if(length(dim(predMatr)) <2) {
predMatr <- cbind(id=if(is.null(names(predMatr))) 1:length(predMatr) else names(predMatr), predMatr)
if(is.character(colPred)) colnames(predMatr)[2] <- colPred
colPred <- 2
} else if(!is.matrix(predMatr)) predMatr <- as.matrix(predMatr)
if(is.character(colPred)) { chCol <- colnames(predMatr)==colPred
if(sum(chCol) <1) { if(!silent) message(fxNa," PROBLEM : '",colPred,"' not found in ",namesMXY[2]," !!")
colPred <- 2
} else colPred <- which(chCol)}
if("id" %in% colnames(predMatr)) {
if(colnames(predMatr)[1] != "id") {tmp <- colnames(predMatr)=="id"
predMatr <- predMatr[,c(which(tmp),which(!tmp))]}
} else { colPred <- colPred +1
predMatr <- cbind(id=if(is.null(rownames(predMatr))) 1:nrow(predMatr) else rownames(predMatr), predMatr)}
if(length(dim(measMatr)) <2) {
measMatr <- cbind(id=if(is.null(names(measMatr))) 1:length(measMatr) else names(measMatr), measMatr)
if(is.character(colMeas)) colnames(measMatr)[2] <- colMeas
colMeas <- 2
} else if(!is.matrix(measMatr)) measMatr <- as.matrix(measMatr)
if(is.character(colMeas)) colMeas <- which(colnames(measMatr)==colMeas)
if("id" %in% colnames(measMatr)) {
if(colnames(measMatr)[1] != "id") {tmp <- colnames(measMatr)=="id"
measMatr <- measMatr[,c(which(tmp),which(!tmp))]}
} else { colMeas <- colMeas +1
measMatr <- cbind(id=if(is.null(rownames(measMatr))) 1:nrow(measMatr) else rownames(measMatr), measMatr) }
txt <- c(" TROUBLE AHEAD : ", "elements of 'closeMatch' have no name !!")
chCloseM <- sub(prefMatch[1],"", names(closeMatch)) %in% predMatr[,"id"]
if(all(!chCloseM, na.rm=TRUE)) stop("None of (list-) names of 'closeMatch' fits to 'predMatr'")
if(any(!chCloseM, na.rm=TRUE) && !silent) message(fxNa,txt[1],sum(chCloseM)," out of ",length(chCloseM)," elements from 'closeMatch' not found in 'predMatr'")
chCloMaNa <- nchar(names(closeMatch)) # check for empty names
if(any(chCloMaNa <1, na.rm=TRUE)) message(fxNa,txt[1],sum(chCloMaNa <1)," out of ",length(closeMatch)," (list-)",txt[2])
chCloMaN2 <- nchar(unlist(sapply(closeMatch, names)))
if(any(chCloMaN2 <1, na.rm=TRUE)) message(fxNa,txt[1],sum(chCloMaN2 <1)," out of ",sum(sapply(closeMatch,length))," indiv ",txt[2]) ##if(is.null(colnames(predMatr))) colnames(predMatr) <- "predMatr"
nMatch <- sapply(closeMatch,length)
if(debug) {message(fxNa,".. xxidentToMatr2c\n")}
## main joining of predMatr & measMatr
measNa <- sub(prefMatch[2],"", unlist(lapply(closeMatch, names))) # names of measured (y) to each 'y'
if(length(grep("[[:alpha:]]", measNa)) <1) measNa <- as.integer(measNa)
prediNa <- sub(prefMatch[1],"", names(closeMatch)) # ..'x', ie predMatr
if(length(grep("[[:alpha:]]", prediNa)) <1) prediNa <- as.integer(prediNa)
txt <- c(fxNa," TROUBLE ahead, trouble matching names or NAs already in 'closeMatch' (see ")
if(any(is.na(prediNa))) message(txt,"'x'/predicted) !!")
if(any(is.na(measNa))) message(txt,"'y'/measured) !!")
chP <- match(rep(prediNa, nMatch), predMatr[,1])
partP <- if(length(chP)==1) matrix(predMatr[chP,], nrow=1, dimnames=list(rownames(predMatr)[chP], colnames(predMatr))) else predMatr[chP,]
partM <- if(length(measNa)==1) matrix(measMatr[measNa,], nrow=1, dimnames=list(rownames(measMatr)[measNa], colnames(measMatr))) else measMatr[measNa,]
if(origNa && length(grep(" = ",namesMXY[2:3])) >0) { origNa <- FALSE
if(!silent) message(fxNa,"Reset argument 'origNa' to FALSE since names of 'predMatr' and/or 'measMatr' result of formula and would be too long")}
if(origNa) {
colnames(partP)[1] <- paste("id",namesMXY[2],sep=".")
colnames(partM)[1] <- paste("id",namesMXY[3],sep=".")
if(ncol(partP)==2) colnames(partP)[colPred] <- namesMXY[2] else {
colnames(partP)[-1] <- paste(namesMXY[2],colnames(partP)[-1],sep=".")}
if(ncol(partM)==2) colnames(partM)[colMeas] <- namesMXY[3] else {
colnames(partM)[-1] <- paste(namesMXY[3],colnames(partM)[-1],sep=".")}
} else {
dupNa <- duplicated(c(colnames(partP), colnames(partM)))
if(any(dupNa)) {
dupNa <- c(colnames(partP), colnames(partM))[dupNa]
chNaP <- colnames(partP) %in% dupNa
chNaM <- colnames(partM) %in% dupNa
colnames(partP)[which(chNaP)] <- paste(colnames(partP)[which(chNaP)],"pred",sep=".")
colnames(partM)[which(chNaM)] <- paste(colnames(partM)[which(chNaM)],"meas",sep=".") }
}
out <- cbind(partP, partM)
colMeas <- colMeas + ncol(partP)
if(debug) {message(fxNa,".. xxidentToMatr2d\n")}
chOrd <- order(as.character(out[,colMeas])) # grouping done by measured mass; tapply will always sort by this alphabetically (so instead of repeated re-sorting...)
if(!identical(chOrd, 1:nrow(out))) out <- out[chOrd,]
## add suppelemental info (eg distance, if dist is closest, ...)
if(nrow(out) <1) {if(!silent) message(fxNa," nothing left"); return(NULL)} else {
di <- cbind(me=as.numeric(out[,colMeas]), pr=if(length(colPred) >0) as.numeric(out[,colPred]))
out <- cbind(out, disToPred=di[,2] -di[,1], ppmToPred=XYToDiffPpm(di[,2], di[,1], nSign=5, callFrom=fxNa), nByGrp=NA, isMin=NA, nBest=NA) # note : ppm as normalized difference 1e6*(meas - ref)/ref
if(debug) {message(fxNa,".. xxidentToMatr2e\n")}
## inspect groups for multiple values
ch1 <- table(out[,colPred])
out[,ncol(out) -2] <- rep(ch1, ch1) # nByGrp
tmp <- tapply(as.numeric(out[,"disToPred"]), out[,colPred], function(x) {if(length(unique(x))==1) rep(1,length(x)) else 0+(abs(x)==min(abs(x)))} )
out[,"isMin"] <- unlist(tmp)
tmp <- tapply(as.integer(out[,"isMin"]), out[,colPred], sum) # prepare nBest
out[,ncol(out)] <- rep(tmp, ch1) # nBest
ch3 <- out[,ncol(out) -1] =="0"
if(any(ch3)) out[which(ch3), ncol(out)] <- 0 # reset lines which are not best dist as nBest=0
chMax <- out[,ncol(out) -1] >0
if(limitToBest && any(!chMax)) out <- out[which(chMax),] # filter & add col for nBest
if(debug) { message(fxNa,".. xxidentToMatr2f \n")}
## re-sort
if(nrow(out) >1) {chOrd <- as.integer(order(out[,1])) #out[,"id.predMatr"]
out <- out[chOrd,]}
if(is.character(out) & asDataFrame) out <- convMatr2df(out)[,-1]
out }}
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/closeMatchMatrix.R
|
#' Compare means of two vectors by permutation test
#'
#' Run coin-flipping like permutation tests (to compare difference of 2 means: 'x1' and 'x2') without any distribution-assumptions.
#' This function uses the package \href{https://CRAN.R-project.org/package=coin}{coin}, if not installed, the function will return NULL and give a warning.
#'
#' @param x1 numeric vector (to be compared with vector 'x2')
#' @param x2 numeric vector (to be compared with vector 'x1')
#' @param orient (character) may be "two.sided","greater" or "less"
#' @param nPerm (integer) number of permutations
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @return This function returns an object of "MCp" class numeric output with p-values
#' @seealso \code{oneway_test} in \code{\link[coin]{LocationTests}}
#' @examples
#' coinPermTest(2, 3, nPerm=200)
#' @export
coinPermTest <- function(x1, x2, orient="two.sided", nPerm=5000, silent=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="coinPermTest")
if(!requireNamespace("coin", quietly=TRUE)) {
warning(fxNa,"Package 'coin' not found, please install from CRAN; retruning NULL")
} else {
tmp <- if(identical(orient,"greater")) try(coin::oneway_test(c(x1,x2) ~ factor(rep(c("A","B"), c(length(x1), length(x2)))),
alternative="greater", distribution=coin::approximate(B=nPerm)), silent=TRUE) else if(any(identical(orient, "fewer"), identical(orient, "less"))) {
try(coin::oneway_test(c(x1, x2) ~ factor(rep(c("A", "B"), c(length(x1), length(x2)))),
alternative="less", distribution=coin::approximate(B=nPerm)), silent=TRUE) } else {
try(coin::oneway_test(c(x1, x2) ~ factor(rep(c("A", "B"), c(length(x1), length(x2)))), distribution=coin::approximate(B=nPerm)),silent=TRUE) }
if(inherits(tmp, "try-error")) { warning(fxNa,"Unable to run coin::oneway_test() !"); out <- NULL
} else out <- coin::pvalue(tmp)
out } }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/coinPermTest.R
|
#' Standard error of median for each column by bootstrap
#'
#' Determine standard error (sd) of median by bootstraping for multiple sets of data (rows in input matrix 'dat').
#' Note: The package \href{https://CRAN.R-project.org/package=boot}{boot} must be installed from CRAN.
#' @param dat (numeric) matix
#' @param nBoot (integer) number if iterations
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @return This function 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)
#' colMedSds(dat1)
#' @export
colMedSds <- function(dat, nBoot=99, silent=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="colMedSds")
if(!isTRUE(silent)) silent <- FALSE
msg <- "'dat' should be matrix or data.frame with "
if(length(dat) <1) { warning(fxNa,"Argument 'dat' seems to be empty !"); out <- NULL
} else {
if(is.null(ncol(dat))) stop(msg,"multiple columns !") else if(ncol(dat) < 2) stop(msg,"at least 2 columns !")
chPa <- requireNamespace("boot", quietly=TRUE)
if(!chPa) { out - NULL
warning(fxNa,"Package 'boot' not found (please install first from CRAN), returning NULL")
} else {
median.fun <- function(dat,indices) stats::median(dat[indices], na.rm=TRUE)
out <- try(apply(dat, 2, function(x) stats::sd(boot::boot(data=x, statistic=median.fun, R=nBoot)$t)), silent=TRUE)
if(inherits(out, "try-error")) { warning(fxNa,"Unable to run boot::boot()"); out <- NULL } } }
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/colMedSds.R
|
#' sd for each column
#'
#' \code{colSds} is a speed optimized \code{sd} for matrix or data.frames.
#' It and treats each line as an independent set of data for calculating the sd (equiv to \code{apply(dat,1,sd)}).
#' NAs are ignored from data.
#' @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)),nc=10)
#' colSds(dat1)
#' @export
colSds <- 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)
out <- sqrt(rowSums(matrix(as.numeric(!is.na(t(dat))),ncol=nrow(dat))*(t(dat) - colMeans(dat,na.rm=TRUE))^2,na.rm=TRUE)/(colSums(!is.na(dat))-1)) # handels NA OK
out[is.nan(out)] <- NA # replace 'NaN' by NA for output
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/colSds.R
|
#' Transform numeric values to color-gradient
#'
#' This function helps making color-gradients for plotting a numerical variable.
#' It requires the package 'RColorBrewer' being installed from CRAN.
#' Note : RColorBrewer palettes were not integrated here, since they are not continuous.
#'
#' @param x (character) color input
#' @param gradTy (character) type of gradeint may be 'rainbow', 'heat.colors', 'terrain.colors', 'topo.colors', 'cm.colors', 'hcl.colors', 'grey.colors', 'gray.colorsW' or 'logGray'
#' @param nStartOmit (integer) omit n steps from begining of gradient range
#' @param nEndOmit (integer or "sep") omit n steps from end of gradient range, if \code{nEndOmit="sep"} 20 percent of initial grades will be removed to obtain 'separate' ie non-closing color-circles/gradients eg with \code{rainbow}
#' @param revCol (logical) reverse order
#' @param alpha (numeric) optional transparency value (1 for no transparency, 0 for complete opaqueness)
#' @param callFrom (character) allow easier tracking of message(s) produced
#' @return This function returns a character vector (of same length as x) with color encoding
#' @seealso \code{\link[base]{cut}}
#' @examples
#' set.seed(2015); dat1 <- round(runif(15),2)
#' plot(1:15,dat1,pch=16,cex=2,col=colorAccording2(dat1))
#' plot(1:15,dat1,pch=16,cex=2,col=colorAccording2(dat1,nStartO=0,nEndO=4,revCol=TRUE))
#' plot(1:9,pch=3)
#' points(1:9,1:9,col=transpGraySca(st=0,en=0.8,nSt=9,trans=0.3),cex=42,pch=16)
#' @export
colorAccording2 <- function(x, gradTy="rainbow", nStartOmit=NULL, nEndOmit=NULL, revCol=FALSE,alpha=1,callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="colorAccording2")
x <- convToNum(x, remove=NULL, sciIncl=TRUE, callFrom=fxNa)
if(revCol) x <- -1*x
ind <- round(1 +(.scale01(x) *(sum(!is.na(x)) -1)) )
stFro <- if(is.null(nStartOmit)) 1 else nStartOmit +1 # + test/convert as integer
if(identical(nEndOmit,"sep")) nEndOmit <- floor(length(x) *0.2)
upTo <- sum(!is.na(x)) +stFro -1
nCol <- sum(!is.na(x)) +stFro-1 +if(is.null(nEndOmit)) 0 else nEndOmit # + test/convert as integer
switch(gradTy,
rainbow=grDevices::rainbow(nCol, alpha=alpha)[stFro:upTo][ind],
heat.colors=grDevices::heat.colors(nCol, alpha=alpha)[stFro:upTo][ind],
terrain.colors=grDevices::terrain.colors(nCol, alpha=alpha)[stFro:upTo][ind],
topo.colors=grDevices::topo.colors(nCol, alpha=alpha)[stFro:upTo][ind],
cm.colors=grDevices::cm.colors(nCol, alpha=alpha)[stFro:upTo][ind],
hcl.colors=grDevices::hcl.colors(nCol, alpha=alpha)[stFro:upTo][ind],
gray.colors=grDevices::grey.colors(nCol, start=0.2, end=0.9, alpha=alpha)[stFro:upTo][ind],
gray.colorsW=transpGraySca(startGray=0.9, endGrey=0.2, nSteps=5, transp=alpha) [stFro:upTo][ind],
logGray=transpGraySca(0, 1, nSteps=sum(!is.na(x)), transp=alpha)[stFro:upTo][ind]
) }
#' Automatic choice of colors
#'
#' This function allows to do automatic choice of colors: if single-> grey, if few -> RColorBrewer, if many : gradient green -> grey/red
#'
#' @param nGrp (numeric vector) main input
#' @param paired (logical)
#' @param alph (numeric vector)
#' @return character vector with color codes
#' @seealso \code{\link[grDevices]{rgb}}; \code{\link{colorAccording2}}
#' @examples
#' .chooseGrpCol(4)
#' @export
.chooseGrpCol <- function(nGrp, paired=FALSE, alph=0.2) {
## automatic choice of colors: if single-> grey, if few -> RColorBrewer, if many : gradient green -> grey/red
## if max groups =8 (or max 2x6 paired groups) choose contrasting colors from RColorBrewer
## requires (RColorBrewer)
finCol <- grDevices::rgb(0.2,0.2,0.2, alpha=alph) # dark grey
if(nGrp >1 & nGrp < (9+4*paired)) {
if(paired) {
chPa <- requireNamespace("RColorBrewer", quietly=TRUE)
if(!chPa) stop("package 'RColorBrewer' not found ! Please install first from CRAN")}
finCol <- if(paired) RColorBrewer::brewer.pal(12,"Paired")[c(5:6,1:4,7:12)] else RColorBrewer::brewer.pal(8,"Accent")[c(6,5,1:3,4,7:8)] # red, blue,green,purple,orange,yellow,brown,grey
if(nGrp < length(finCol)) finCol <- finCol[1:nGrp]
if(alph <1 & alph >0) finCol <- convColorToTransp(finCol,alph=alph)}
if(nGrp > (8+4*paired)) { # gradient bright green -> dark olive -> bright red
finCol <- grDevices::rgb(seq(0,0.9,length.out=nGrp), seq(0.9,0,length.out=nGrp), 0.2, alpha=alph)
}
finCol }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/colorAccording2.R
|
#' Planing for making all multiplicative combinations
#'
#' Provide all combinations for each of n elements of vector 'nMax' (positive integer, eg number of max multiplicative value).
#' For example, imagine, we have 3 cities and the (maximum) voting participants per city.
#' Results must be read vertically and allow to see all total possible compositons.
#'
#' @param nMax (positive integer) could be max number of voting participants form different cities, eg Paris max 2 persons, Lyon max 1 person ...
#' @param include0 (logical) include 0 occurances, ie provide al combinations starting from 0 or from 1 up to nMax
#' @param asList (logical) return result as list or as array
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @return 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 \code{\link[utils]{combn}}
#' @examples
#' combinatIntTable(c(1,1,1,2), include0=TRUE, asList=FALSE, silent=TRUE)
#' ## Imagine we have 3 cities and the (maximum) voting participants per city :
#' nMa <- c(Paris=2, Lyon=1, Strasbourg=1)
#' combinatIntTable(nMa, include0=TRUE, asList=TRUE, silent=TRUE)
#' @export
combinatIntTable <- function(nMax,include0=TRUE,asList=FALSE,callFrom=NULL,silent=TRUE){
## used by .parCombinateAllAndSum(), combinateAllAndSum()
fxNa <- .composeCallName(callFrom, newNa="combinatIntTable")
iniNa <- names(nMax)
ch <- as.integer(nMax)
msg <- "'nMax' should be positive integer (numeric) of length >1"
if(!is.integer(ch) | length(nMax) <1) stop(msg) else nMax <- ch
ch <- is.na(nMax) | nMax <1
if(any(ch)) {if(sum(!ch) >0) {nMax <- nMax[!ch]; iniNa <- iniNa[!ch]} else stop(msg)
if(!silent) message(fxNa,"trimming to ",sum(!ch)," positive non-NA")}
## main
k <- if(include0) 0:1 else 1:0
if(length(nMax) <2) {out <- as.matrix(k[1]:nMax); return(if(!asList) out else list(out))} # case of single valid nMax (improve ?)
diM <- c(k[2] +nMax[2], prod(nMax[-2] +k[2]))
out <- list(matrix(rep(k[1]:nMax[1], each=diM[1]), nrow=diM[1], ncol=diM[2]))
if(length(nMax) >1) out[[2]] <- matrix((k[1]:nMax[2]), nrow=diM[1], ncol=diM[2])
if(length(nMax) >2) for(i in 3:length(nMax)) out[[i]] <- matrix(rep(k[1]:nMax[i], each=prod(k[2]+nMax[1:(i-1)])), nrow=diM[1], ncol=diM[2])
if(!asList) {
out <- array(unlist(out), dim=c(dim(out[[1]]), length(nMax)))
dimnames(out)[[3]] <- iniNa } else names(out) <- iniNa
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/combinatIntTable.R
|
#' Combine Vectors From List And Return Basic Count Statistics
#'
#' The aim of this function is to choose a fixed number (\code{nCombin}) of list-elments from \code{lst} and count the number of common values/words.
#' Furthermore, one can define levels to fine-tune the types of combinations to examine.
#' In case multiple combinations for a given level are possible, some basic summary statistics are provided, too.
#'
#' @details
#' Note of caution :
#' With very long lists and/or high numbers of repeats of given levels, however, the computational effort incerases very much (like it does when using \code{table}).
#' Thus, when exploring all different combinations of large data-sets may easily result in queries consuming many ressources (RAM and processing time) !
#' It is recommended to start testing with test smaller sub-groups.
#'
#' The main idea of this function is to count frequency of terms when combining different drawings.
#' For example, you ask students from different cities which are their preferred hobbies, they may have different preference depending on the city ( defined by \code{lev}).
#' Now, if you want to make groups of 3 students, possibly with one from each city (A ,B and C), you want to count (/estimate) the frequency of different combinations possible.
#' Thus, using this function all combinations of the students from city A with the students from city B and C will be made when counting the number of common hobbies (by \code{nCombin} students).
#' Then, all counting results will be summarized to the average count for the various categories (which hobbies were seen once, twice or 3 times...),
#' sem (standard error of the mean) and CI (95% confidence interval), as well as sd.
#'
#' Of course, the number of potential combinations may quickly get very large. Using the argument \code{remDouble=TRUE} you can limit the search to
#' either finding all students giving the same answer plus all student giving different answers.
#' In this case, when a given level appears multiple times, all possible combinations using one of the respective entries will be be made with the other levels.
#'
#'
#' @param lst (list of character or integer vectors) main input
#' @param lev (character) define groups of \code{lst}
#' @param nCombin (integer) number of list-elements to combine from \code{lst}
#' @param remDouble (logical) remove intra-duplicates (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 an array with 3 dimensions : i) ii) the combinations of \code{nCombin} list-elements,
#' iii) the number of counts (n), sem (standard error of the mean), CI (confidence interval) and sd
#' @seealso \code{\link[base]{table}}, \code{\link[wrMisc]{replicateStructure}}
#' @examples
#' ## all list-elements are considered equal
#' tm1 <- list(a1=LETTERS[1:17], a2=LETTERS[3:19], a3=LETTERS[6:20], a4=LETTERS[8:22])
#' combineAsN(tm1, lev=gl(1,4))[,1,]
#'
#' ## different levels/groups in list-elements
#' tm4 <- list(a1=LETTERS[1:15], a2=LETTERS[3:16], a3=LETTERS[6:17], a4=LETTERS[8:19],
#' b1=LETTERS[5:19], b2=LETTERS[7:20], b3=LETTERS[11:24], b4=LETTERS[13:25], c1=LETTERS[17:26],
#' d1=LETTERS[4:12], d2=LETTERS[5:11], d3=LETTERS[6:12], e1=LETTERS[7:10])
#' te4 <- combineAsN(tm4, nCombin=4, lev=substr(names(tm4),1,1))
#' str(te4)
#' te4[,,1]
#'
#' @export
combineAsN <- function(lst, lev=NULL, nCombin=3, remDouble=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL) {
## count combinatorics
## 'remDouble' .. idea to remove mixed auto&hetero-combinations (but leave auto.only and hetero.only combinations)
## combine 'nCombin' combinations of the (same level of) vectors in list 'lst' and search how may instances of the elements are found/counted on average, as total ('any'), single, double, triple or min2
## Example : There are 4 independent drawings of a variable number of letters from the alphabet.
## Note double-repeats may be quite frequent and are eliminated by default, triple- (and higher) repeats are kept.
## if multiple ways of making sets of 'nCombin' vetors exist, summary statistics will be added in 3rd dimension of resulting array
fxNa <- .composeCallName(callFrom, newNa="combineAsN")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
reqPa <- c("utils","wrMisc")
chPa <- sapply(reqPa, requireNamespace, quietly=TRUE)
if(any(!chPa)) stop("package(s) '",paste(reqPa[which(!chPa)], collapse="','"),"' not found ! Please install first from CRAN")
## sanity checks
if(length(lev) <1) { if(length(names(lst)) >0) { lev <- substr(names(lst),1,1)
if(!silent) message(fxNa,"Note : Argument 'lev' is missing; trying to recuperate as 1st character of names of 'lst' : ",pasteC(utils::head(lev,7),quoteC="'"), if(length(lev) >7) "...")
} else stop("Argument 'lev' (for levels of list-elements) MUST be provided when 'lst' has no names !")}
if(length(lst) != length(lev)) stop("Length of 'lst' and 'lev' must match ! Was ",length(lst)," and ",length(lev)," !")
colNaSep <- c("_","-","\\.","\\+","__","--","\\+\\+") # separators to test/for choice when combining
inclMono <- TRUE # complementary to remDouble (realy useful ?)
if(length(nCombin) <1) { nCombin <- length(levels(as.factor(lev)))
if(debug) message(fxNa,"Setting nCombin to ",nCombin)
} else if(length(nCombin) >1) { nCombin <- nCombin[1]
if(!silent) message(fxNa,"'nCombin' should be of length=1 (using only 1st)")}
if(any(is.na(nCombin))) { nCombin <- length(levels(as.factor(lev)))
if(!silent) message(fxNa,"'nCombin' has NA, resetting to default")}
if(any(sapply(c("all","def"), identical, nCombin))) nCombin <- length(levels(as.factor(lev)))
if(length(lst) <2 || nCombin <2) { datOK <- FALSE; if(!silent) message(fxNa,"Nothing to do")
} else datOK <- TRUE
if(datOK & nCombin ==2 & remDouble) { remDouble <- FALSE
if(debug) message(fxNa,"Setting 'nCombin=2' AND 'remDouble=TRUE' makes no sense (nothing will match), running as 'remDouble=FALSE' ")}
if(datOK) {
## check levels
levNo <- try(suppressWarnings(as.numeric(unique(lev))), silent=TRUE) # level-indexes
if(inherits(levNo, "try-error") || any(is.na(levNo))) levNo <- unique(suppressWarnings(as.numeric(as.factor(lev))))
if(debug) message(fxNa," levNo (",class(levNo),") = ",pasteC(levNo))
if(nCombin > length(lev) -1) { nCombin <- length(lev) -1
if(!silent) message(fxNa," Argument 'nCombin' is too high for given data, re-setting to ",nCombin)
}
outDiNa <- list( c("sing","doub","trip","min2","any"), "x", c("n","sem","CI","sd"))
}
if(datOK) {
if(nCombin ==length(lev)) {
out <- table(table(unlist(lst)))[c("1","2","3")]
out <- array(c(out, sum(out[c(1:2)]), sum(out), rep(NA,5*3)), dim=c(5,1,4), dimnames=outDiNa)
} else {
## MAIN, prepare matrix of combin
## Setup combinations to try
if(isTRUE(remDouble) && length(unique(levNo)) >1) { nCombin <- min(nCombin, length(levels(as.factor(lev))), na.rm=TRUE)
if(!silent) message(fxNa," argument 'nCombin' combined to 'remDouble'=TRUE is too high for given data, re-setting to ",nCombin)}
combOfN <- utils::combn((1:length(lst)), nCombin) # the combinations (all) ..
## prepare separator for names of combinations
chSep <- sapply(colNaSep, function(x) length(grep(x, levNo)) >0)
sep <- if(any(!chSep)) colNaSep[which(!chSep)[1]] else "_"
colnames(combOfN) <- apply(combOfN, 2, function(x) paste(sort(lev[x]), collapse=sep))
if(debug) {message(fxNa,"cA3a")}
## FILTER
## idea : remove all multi-intra exect all-intra
if(remDouble) { # remove mixed repeats (double-same + other) but keep all-same (or higher n-mers)
chD <- sapply( strsplit(colnames(combOfN), sep), function(x) length(unique(x)))
chD <- chD %in% c(nCombin, if(inclMono) 1 else NULL)
if(any(!chD)) { combOfN <- if(sum(chD) >1) combOfN[,which(chD)] else matrix(combOfN[,which(chD)], ncol=1, dimnames=list(NULL, colnames(combOfN)[which(chD)]))
if(debug) {message(fxNa,"Removing ",sum(!chD)," poly-repeats but not auto-repeats (out of ",ncol(combOfN),
") combinations since argument 'remDouble=",remDouble,"' cA3b")}
}
}
if(debug) { message(fxNa,"cA3c")}
## main part, extract elements and count frequencies
com3c <- apply(combOfN, 2, function(x) sortByNRepeated(lst[x], silent=silent, debug=debug, callFrom=fxNa)) # make list of number of times found: 1x, 2x, 3x ... takes a few sec
forceN <- 3 # ?? for extracting (no more than) c("sing","doub","trip")
if(debug) {message(fxNa,"cA3d")}
maxLev <- max(sapply(com3c, length))
tmp <- matrix(0, ncol=length(com3c), nrow=max(forceN, maxLev), dimnames=list(1:max(maxLev, forceN), names(com3c)))
for(i in 1:length(com3c)) {tm2 <- if(is.matrix(com3c[[i]])) rep(nrow(com3c[[i]]), ncol(com3c[[i]])) else sapply(com3c[[i]], length)
tmp[if(length(names(tm2)) >0) as.integer(names(tm2)) else 1:length(tm2), i] <- tm2 }
rownames(tmp) <- c("sing","doub","trip", if(nrow(tmp) > 3) paste0("_",c(4:nrow(tmp)),"x"))
## adhere to previous structure (sing, doub, min2, any & rest), ie adjust number of indv x-counts to forceN
comCou2 <- rbind(tmp[1:forceN,], min2=colSums(tmp[1:2,]), any=colSums(tmp))
dupNa <- duplicated(colnames(comCou2), fromLast=FALSE)
if(debug) {message(fxNa,"cA3e Found ",sum(dupNa)," 'redundant' level-combinations out of ",length(dupNa))}
## which contain repeated combinations of groups: calculate sd & derivatives, organize as array
if(any(dupNa)) {
grTy <- unique(colnames(comCou2))
sumMatr <- function(x) { avX <- rowMeans(x); sdX <- rowSds(x); c(nAv=avX, sem=sdX/sqrt(ncol(x)), CI=apply(x, 1, confInt), sd=sdX)} # seems OK
comCou3 <- sapply(grTy, function(x) { y <- comCou2[,which(colnames(comCou2) %in% x)]; if(length(dim(y)) >1) sumMatr(y) else c(y, rep(NA,length(y)*3))} )
if(length(dim(comCou3)) <2) comCou3 <- matrix(comCou3, ncol=1, dimnames=list(NULL, colnames(comCou2)))
allNa <- colnames(comCou3)
faRep <- findRepeated(colnames(comCou3), nonRepeated=TRUE) # correct object (note: all colnames are already different)
out <- array(NA, dim=c(nrow(comCou2), length(faRep$rep) +length(faRep$nonrep), 4), dimnames=list(rownames(comCou2), allNa,c("n","sem","CI","sd")))
#isMult <- match(names(faRep$rep), allNa) # needed ?
if(debug) {message(fxNa,"cA3g")}
for(i in 1:(dim(out)[3])) out[,,i] <- comCou3[(i-1)*nrow(out) +(1:nrow(out)),]
} else {
out <- array(c(comCou2, rep(NA, nrow(comCou2)*ncol(comCou2)*3)), dim=c(nrow(comCou2),ncol(comCou2),4),
dimnames=list(rownames(comCou2), colnames(comCou2),c("n","sem","CI","sd")))
}
}
}
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/combineAsN.R
|
#' Create factor-like column regrouping data regrouping simultaneaously by two factors
#'
#' This function aims to address the situation when two somehow different groupins (of the same data) exist and need to be joined.
#' It is not necessary that both alternative groupings use the same labels, neither.
#' \code{combineByEitherFactor} adds new (last) column named 'grp' to input matrix representing the combined factor
#' relative to 2 specified columns from input matrix \code{mat} (via 'refC1','refC2'). Optionally, the output may be
#' sorted and a column giving n per factor-level may be added.
#' The function treats selected columns of \code{mat}
#' as pairwise combination of 2 elements (that may occur multiple times over all lines of \code{mat})
#' and sorts/organizes all instances of such combined elements (ie from both selected columns) as repeats of a given group,
#' who's class number is given in output column 'grp', the (total) number of repeats may be displayed in column 'nGrp' ( \code{nByGrp=TRUE}).
#' If groups are overlapping (after re-ordering), an iterative process of max 3x2 passes will be launched after initial matching.
#' Works on numeric as well as character input.
#'
#' @param mat main input matrix
#' @param refC1 (integer) column-number of 'mat' to use as 1st set
#' @param refC2 (integer) column-number of 'mat' to use as 2nd set
#' @param nByGrp (logical) add last col with n by group
#' @param convergeMax (logical) if \code{TRUE}, run 2 add'l iteartive steps to search convergence to stable result
#' @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 containing both selected columns plus additional column(s) indicating group-number of the pair-wise combination
#' (and optional the total n by group)
#' @examples
#' nn <- rep(c("a","e","b","c","d","g","f"),c(3,1,2,2,1,2,1))
#' qq <- rep(c("m","n","p","o","q"),c(2,1,1,4,4))
#' nq <- cbind(nn,qq)[c(4,2,9,11,6,10,7,3,5,1,12,8),]
#' combineByEitherFactor(nq,1,2,nBy=TRUE); combineByEitherFactor(nq,1,2,nBy=FALSE)
#' combineByEitherFactor(nq,1,2,conv=FALSE); combineByEitherFactor(nq,1,2,conv=TRUE)
#' ##
#' mm <- rep(c("a","b","c","d","e"),c(3,4,2,3,1)); pp <- rep(c("m","n","o","p","q"),c(2,2,2,2,5))
#' combineByEitherFactor(cbind(mm,pp), 1, 2, con=FALSE, nBy=TRUE)
#' combineByEitherFactor(cbind(mm,pp), 1, 2, con=TRUE, nBy=TRUE)
#' @export
combineByEitherFactor <- function(mat, refC1, refC2, nByGrp=FALSE, convergeMax=TRUE, callFrom=NULL, debug=FALSE, silent=FALSE) {
fxNa <- .composeCallName(callFrom,newNa="combineByEitherFactor")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(length(mat) <1) stop(fxNa," nothing found in 'mat'")
if(length(dim(mat)) !=2) stop("'mat' must be matrix with min 2 columns")
msg <- "Arguments 'refC1' & 'refC1' should be of length=1 (truncating)"
if(length(refC1) >1) {if(!silent) message(fxNa,msg); refC1 <- refC1[1]}
if(length(refC2) >1) {if(!silent) message(fxNa,msg); refC2 <- refC1[2]}
if(nrow(mat) <2) return(cbind(mat, grp=1, nGrp=if(nByGrp) 1 else NULL))
mat <- cbind(mat, iniOrder=1:nrow(mat)) # add col initial order
mat <- mat[order(mat[,refC1], mat[,refC2]),] # reorder by 1st fact & 2nd fact
## express 1st index as 2nd :
mat <- cbind(mat, grp=unlist(tapply(mat[,refC1],mat[,refC2], function(x) rep(x[1],length(x))))[rank(mat[,refC2],ties.method="first")])
sup1 <- unlist(tapply(mat[,ncol(mat)],mat[,refC1], function(x) rep(x[1],length(x))))[order(mat[,refC1])]
msg <- c(" did not reach convergence at ","2nd","4th"," pass, continuing ..","6th pass (stop iterating)"," pass")
if(convergeMax & !all(sup1==mat[,ncol(mat)])) {
if(!silent && nrow(mat) >999) message(fxNa,msg[c(1,2,4)])
sup2 <- unlist(tapply(sup1,mat[,refC2], function(x) rep(x[1],length(x))))[order(mat[,refC2])]
sup3 <- unlist(tapply(sup2,mat[,refC1], function(x) rep(x[1],length(x))))[order(mat[,refC1])]
if(!all(sup3==sup2) & !silent) { message(fxNa,msg[c(1,2,4)])
sup2 <- unlist(tapply(sup3,mat[,refC2], function(x) rep(x[1],length(x))))[order(mat[,refC2])]
sup3 <- unlist(tapply(sup2,mat[,refC1], function(x) rep(x[1],length(x))))[order(mat[,refC1])]
if(!all(sup3==sup2) && !silent) message(fxNa,msg[c(1,5)]) }
mat[,ncol(mat)] <- sup3 } else if(!silent && !convergeMax) message(fxNa,msg[c(1,2,6)])
mat[,ncol(mat)] <- as.numeric(as.factor(mat[,ncol(mat)])) # reset grp names
if(nByGrp) { mTa <- table(mat[,ncol(mat)])
mat <- cbind(mat,nGrp=mTa[match(mat[,ncol(mat)],names(mTa))]) }
mat[as.numeric(mat[,ncol(mat) -1 -nByGrp]), -ncol(mat) +1 +nByGrp] }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/combineByEitherFactor.R
|
#' Find and combine points located very close in x/y space
#'
#' Search points in x,y space that are located very close and thus likely to overlap.
#' In case of points close enough, various options for joining names (and shortening longer descriptions) are available.
#'
#' @param dat (matrix) matrix or data.frame with 2 cols (used ONLY 1st & 2nd column !), used as x & y coordinates
#' @param suplInfo (NULL or character) when points are considered overlapping the text from 'suplInfo' will be reduced to fragment before 'txtSepChar' and combined (with others from overlapping text) using 'combSym', if NULL $combInf will appear with row-numbers
#' @param disThr (numeric) distance-thrshold for considering as similar via searchDataPairs()
#' @param addNsimil (logical) include number of fused points
#' @param txtSepChar (character) for use with .retain1stPart(): where to cut (& keep 1st part) text from 'suplInfo' to return in out$CombInf; only 1st element used !
#' @param combSym (character) concatenation symbol (character, length=1) for points considered overlaying, see also 'suplInfo'
#' @param maxOverl (integer) if NULL no limit or max limit of group/clu size (avoid condensing too many neighbour points to single cloud)
#' @param debug (logical) additional messages for debugging
#' @param silent (logical) suppres messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @return matrix with fused (condensed) information for cluster of overapping points
#' @examples
#' set.seed(2013)
#' datT2 <- matrix(round(rnorm(200)+3,1),ncol=2,dimnames=list(paste("li",1:100,sep=""),
#' letters[23:24]))
#' # (mimick) some short and longer names for each line
#' inf2 <- cbind(sh=paste(rep(letters[1:4],each=26),rep(letters,4),1:(26*4),sep=""),
#' lo=paste(rep(LETTERS[1:4],each=26),rep(LETTERS,4),1:(26*4),",",rep(letters[sample.int(26)],4),
#' rep(letters[sample.int(26)],4),sep=""))[1:100,]
#' head(datT2,n=10)
#' head(combineOverlapInfo(datT2,disThr=0.03),n=10)
#' head(combineOverlapInfo(datT2,suplI=inf2[,2],disThr=0.03),n=10)
#' @export
combineOverlapInfo <- function(dat,suplInfo=NULL,disThr=0.01,addNsimil=TRUE,txtSepChar=",",combSym="+",maxOverl=50,callFrom=NULL,debug=FALSE,silent=FALSE){
fxNa <- .composeCallName(callFrom,newNa="combineOverlapInfo")
if(length(dim(dat)) !=2) stop("expecting matrix or data.frame with 2 cols as 'dat'")
if(!is.null(suplInfo)){
suplInfo <- as.character(suplInfo)
if(length(suplInfo) != nrow(dat)) { message(fxNa," number of rows of 'dat' (",nrow(dat),
") should match length of 'suplInfo' (",length(suplInfo),") .. ignoring")
suplInfo <- NULL }}
datOverl <- searchDataPairs(dat[,1:2], disThr=disThr, byColumn=FALSE, realDupsOnly=FALSE, callFrom=fxNa)
txt <- " overlap-pairs: making condensed groups via fusePairs() will take "
if(!silent & nrow(datOverl) >1800) message(fxNa,nrow(datOverl),txt, if(nrow(datOverl) >5000) "VERY (!) " else "","MUCH TIME !")
modDatLi0 <- sort(unique(naOmit( as.character(as.matrix(datOverl[,1:2]))))) # get all line-numbers with (potentially) close points
modDatLi2 <- unique(convToNum(modDatLi0, remove=NULL, sciIncl=TRUE))
modDatLi <- if(length(modDatLi2)==length(modDatLi0)) modDatLi2 else match(modDatLi0,rownames(dat)) # convert to numeric if possible, otherwise as rownames
if(length(modDatLi) <2) {
if(!silent) message(fxNa,"all entries seem non-overlapping, no need to combine overlapping ones")
return(cbind(dat, clu=1:nrow(dat), combInf=if(length(suplInfo) <1) 1:nrow(dat) else suplInfo, clu=1:nrow(dat), isComb=FALSE))
} else { # aggregate points considered potentially overlapping to 'clusters'
datOverl[,1] <- as.character(datOverl[,1])
datOverl[,2] <- as.character(datOverl[,2])
if(debug) {message(fxNa,"combOI\n")}
tmp <- fusePairs(datOverl, refDatNames=rownames(dat), inclRepLst=TRUE, maxFuse=maxOverl, callFrom=fxNa, debug=FALSE)
if(is.na(txtSepChar)) txtSepChar <- "_" else if(txtSepChar %in% c("+",".")) txtSepChar <- paste("\\",txtSepChar,sep="")
if(is.null(suplInfo)) suplInfo <- 1:nrow(dat)
redInfo <- suplInfo
if(debug) {message(fxNa,"xxComb3\n")}
if(!all(is.na(suplInfo))) for(i in unique(tmp$clu)) { # loop along cluster-names
j <- match(names(tmp$clu)[which(tmp$clu==i)],rownames(dat)) # ie, at these locations
if(length(j) >1 & length(txtSepChar)==1) redInfo[j] <- paste(.retain1stPart(
suplInfo[j],sep=txtSepChar,offSet=1), collapse=sub("\\\\","",combSym)) }
out <- data.frame(dat, combInf=NA, clu=NA, isComb=FALSE, stringsAsFactors=FALSE)
if(length(suplInfo) ==nrow(dat)) { out$combInf <- redInfo }
out[,"clu"] <- tmp$clu[match(rownames(dat),names(tmp$clu))]
if(any(is.na(out[,"clu"]))) out[which(is.na(out[,"clu"])),"clu"] <- max(out[,"clu"],na.rm=TRUE)+(1:sum(is.na(out[,"clu"]))) # in case of NAs, attribue new no
cluTab <- table(out[,"clu"])
out[which(!is.na(match(out[,"clu"],names(cluTab)[which(cluTab >1)]))),"isComb"] <- TRUE
out }}
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/combineOverlapInfo.R
|
#' Combine/reduce redundant lines based on specified column
#'
#' This function works similar to \code{unique}, but it takes a matrix as input and considers one specified column to find unique instances.
#' It identifies 'repeated' lines of the input-matrix (or data.frame) 'mat' based on (repeated) elements in/of column with name 'colNa' (or column-number).
#' Redundant lines (ie repeated lines) will disappear in output.
#' Eg used with extracted annotation where 1 gene has many lines for different GO annotation.
#'
#' @param mat input matrix or data.frame
#' @param colNa character vector (length 1) macting 1 column name (if mult only 1st will be used), in case of mult matches only 1st used
#' @param sep (character) separator (default=",")
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @return matrix containing the input matrix without lines considered repeated (unique-like)
#' @seealso \code{\link{findRepeated}}, \code{\link{firstOfRepLines}}, \code{\link{organizeAsListOfRepl}}, \code{\link{combineRedundLinesInList}}
#' @examples
#' matr <- matrix(c(letters[1:6],"h","h","f","e",LETTERS[1:5]),ncol=3,
#' dimnames=list(letters[11:15],c("xA","xB","xC")))
#' combineRedBasedOnCol(matr,colN="xB")
#' combineRedBasedOnCol(rbind(matr[1,],matr),colN="xB")
#' @export
combineRedBasedOnCol <- function(mat, colNa, sep=",", silent=FALSE, callFrom=NULL){
## combine lines of matrix (or data.frame) 'mat' based on (repeated) elements in/of column with name 'colNa' (or column-number).
## 'colNa' ...
## 'sep' ... character vector (length 1) as separator when concatenating text-fields
## redundant lines (ie repeated lines) will disappear in output
## eg used with extracted annotation where 1 gene has many lines for different GO annot
fxNa <- .composeCallName(callFrom,newNa="combineBasedOnCol")
argN <- deparse(substitute(mat))
msg <- paste(" expecting matrix or data.frame with min 2 columns in '",argN,"'")
if(length(dim(mat)) <2) stop(msg) else if(ncol(mat) <2) stop(msg)
if(is.data.frame(mat)) mat <- as.matrix(mat)
msg <- c(fxNa,"argument 'colNa'"," longer than 1"," not found","using only 1st element")
if(length(colNa) >1) {if(!silent) message(msg[-4]); colNa <- colNa[1]}
if(is.numeric(colNa)) { if(colNa > ncol(mat)) stop else colNa <- which(colnames(mat) ==colNa)[1]
} else if(!colNa %in% colnames(mat)) {colNa <- which(colnames(mat) ==colNa)[1]; message(msg[-3])}
if(length(sep) <1) {sep <- ","} else if(length(sep) >1) {sep <- sep[1]}
chCol <- which(colnames(mat) %in% colNa)
if(length(chCol) <0) stop(" no columns in '",argN,"' corresponding to '",colNa,"' found")
refCo <- chCol[1]
chRef <- table(mat[,refCo])
if(any(is.na(mat[,refCo])) &!silent) {message(fxNa," trouble ahead : column ",colnames(mat)[chRef]," in '",argN,"' contains NAs !!")}
if(length(chRef) <nrow(mat)) { # has repeated elements
matLst <- by(mat,as.numeric(as.factor(mat[,refCo])),as.matrix)
out <- t(sapply(matLst,apply,2,function(y) paste(unique(y),collapse=",")))
out <- out[match(unique(mat[,refCo]),unique(out[,refCo])),] # bring in order of (non-red) initial
if(length(dim(out)) <2) out <- matrix(out,nrow=1,dimnames=list("1",names(out)))
} else out <- mat
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/combineRedBasedOnCol.R
|
#' Combine Redundant Lines In List
#'
#' This function provides help for combining/summarizing lines of numeric data which may be summaried according to reference vector or matrix of annotation (part of the same input-list).
#' The data and reference will be aligned and data corresponding to redundant information be combined/summarized.
#'
#'
#' @details
#' All input data should be in a list, ie one or multipl matrix or data.frame for numeric data (see argument \code{datNa}), as well as the reference (see argument \code{refNa}).
#' The refgerence may be a named character vecor or a matrix for which the column to be used should be specified using the argument \code{refColNa}.
#' In case the annotation is a matrix, the rownames will be used as unique/independent identifyers to adjust potentially different order of numeric data and annotation.
#' In absence of rownames, an additional column \code{supRefColNa} of the annotation may be designed for adjusting the order of annotation and numeric data.
#'
#' The numeric list may contain multiple matrixes or data.frames which will all be summarized by the same procedure as long as they have the same initial dimensions and are specified by \code{refNa}.
#'
#' Please note that all other list elements from input not specified by \code{refNa} (or \code{datNa}) will be maintained in the output just as they are.
#'
#' @param lst (list) main input, containing matrix or data.frame of numeric data (see \code{datNa} and annotation (see \code{refNa}) and possibly unrelated stuff
#' @param refNa (character) name of list-element containing annotation
#' @param datNa (character) name(s) of list-element(s) containing numeric/quantitation data
#' @param refColNa (character) in case the list-element to be used as reference is \code{matrix} or \code{data.frame}, the column to be used must be specified here
#' @param supRefColNa (character) in case the \code{lst$refNa} has no rownames, the content of column \code{lst$supRefColNa} will be used instead
#' @param summarizeType (character) the summarization method gets specified here; so far 'sum','av','med','first' and 'last' are implemented
#' @param NA.rm (logical) pass to summarizing functions order to omit \code{NA}s, 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
#'
#' @seealso \code{\link{findRepeated}}, \code{\link{firstOfRepLines}}, \code{\link{organizeAsListOfRepl}}, \code{\link{combineRedBasedOnCol}}
#' @return This function returns a list of same length as input
#' @examples
#' x1 <- list(quant=matrix(11:34, ncol=3, dimnames=list(letters[8:1], LETTERS[11:13])),
#' annot=matrix(paste0(LETTERS[c(1:4,6,3:5)],LETTERS[c(1:4,6,3:5)]), ncol=1,
#' dimnames=list(paste(letters[1:8]),"xx")) )
#' combineRedundLinesInList(lst=x1, refNa="annot", datNa="quant", refColNa="xx")
#' @export
combineRedundLinesInList <- function(lst, refNa="ref", datNa="quant", refColNa="GeneName", supRefColNa=NULL, summarizeType="av",
NA.rm=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL) {
## combine lines of (matrix) list-elements according to (line-) grouping given by reference (also part of list x);
## name of reference should be in refNa; in case reference is matrix, a specific column (refColNa) may be chosen
fxNa <- .composeCallName(callFrom, newNa="combineRedundLinesInList")
namesXY <- deparse(substitute(lst))
out <- NULL
datOK <- length(lst) >0
if(debug) message(fxNa, "cRLL0")
if(length(refNa) >1) {refNa <- refNa[1]} else if(length(refNa) <1) {datOK <- FALSE
stop("Argument 'refNa' should design list-element of '",namesXY,"' (index or name)") }
if(length(datNa) >1) {datNa <- datNa[1]} else if(length(datNa) <1) {datOK <- FALSE
stop("Argument 'datNa' should design list-element of '",namesXY,"' (index or name)") }
.chLstNa <- function(x, lst, colName=NULL, lstArgNa, datOK, fxNa, silent) {
## check if x (refNa, etc) is valid element of lst, optional check if including column named colName (for 'refNa')
## returns $lstMatch ie position of x in names of lst
if(is.numeric(x)) { if(x >= 1 && x <= length(lst)) { lstMatch <- as.integer(x)
} else { if(!silent) message(fxNa,"Invalid numeric entry for list-element"); datOK <- FALSE}
} else { ## check if given name exists in lst
lstMatch <- which(names(lst) %in% x)
if(length(lstMatch) >0) {
names(lstMatch) <- x
} else { datOK <- FALSE
if(!silent) message(fxNa,"Can't find ",x," in names of ",lstArgNa)}
}
## check if lstMatch corresponds to matrix or data.frame with named columns
if(datOK) { datOK <- length(colnames(lst[[lstMatch]])) ==ncol(lst[[lstMatch]])
if(!datOK) { if(!silent) message(fxNa," ",lstArgNa,"$",names(lst)[refNa]," does not seem to be suitable matrix or data.frame") }}
if(datOK && length(colName)==1) { ## check if colName part of colnames
if(is.integer(colName)) { datOK <- colName <= ncol(lst[[lstMatch]]) && colName >=1
if(!datOK && !silent) message(fxNa,"Invalid numeric entry for 'colName")
} else {
chRefCol <- colName %in% colnames(lst[[x]])
if(!chRefCol) { datOK <- FALSE
if(!silent) message(fxNa,"Can't find '",colName,"' in names of ",lstArgNa)
} }
}
list(datOK=datOK, lstMatch=lstMatch)
}
if(length(refColNa) < 1) refColNa <- "GeneName"
if(length(refColNa) > 1) { refColNa <- refColNa[1]
if(!silent) message(fxNa, "Argument 'refColNa' should be of length 1, trimming ..") }
xx <- .chLstNa(x=refNa, lst, colName=refColNa, lstArgNa=namesXY[1], datOK=datOK, fxNa, silent)
datOK <- xx$datOK
refNa <- xx$lstMatch # as index (+name)
xx <- .chLstNa(x=datNa, lst, colName=NULL, lstArgNa=namesXY[1], datOK=datOK, fxNa, silent)
datOK <- xx$datOK
datNa <- xx$lstMatch # as index (+name)
if(debug) { message(fxNa, "cRLL1"); cRLL1 <- list(lst=lst, refNa=refNa,datNa=datNa,refColNa=refColNa, NA.rm=NA.rm, summarizeType=summarizeType,supRefColNa=supRefColNa,datOK=datOK) }
## check if redundant data
if(datOK) {
datOK <- any(duplicated(if(length(dim(lst[[refNa]])) > 1) lst[[refNa]][,refColNa] else lst[[refNa]]), na.rm=TRUE)
if(!datOK && debug) message(fxNa,"No redundant values foound, nothing to do ...")
}
## check rownames of annot
## when annotation (ie lst[[refNa]]) has no (row)names, supRefColNa will be used instead (must give unique IDs)
if(datOK) {
if(length(dim(lst[[refNa]])) > 1) {
if(length(rownames(lst[[refNa]])) <1) {
chSupTRef <- supRefColNa[1] %in% colnames(lst[[refNa]])
if(isTRUE(chSupTRef)) chSupTRef <- isTRUE(sum(duplicated(lst[[refNa]][,chSupTRef])) <1)
if(!chSupTRef) { datOK <- FALSE
if(!silent) message(fxNa," 'supRefColNa' either not in annotation-data or not unique !") }
}
} else {
if(length(names(lst[[refNa]])) <1) { datOK <- FALSE
if(!silent) message(fxNa," annotation has no names, can't use 'supRefColNa' (annotation is not matrix) !") }
} }
if(debug) { message(fxNa, "cRLL1a"); cRLL1a <- list() }
if(datOK) {
## pick annotation concerned : if ..
## problem : lst[[refNa]] may be matrix wo rownames !!! (proteomics example)
## strategy : option to specify 2nd column (supRefColNa) to use instead of rownames for collapsing all names or picking 1st
annS <- if(length(dim(lst[[refNa]])) > 1) lst[[refNa]][,refColNa] else lst[[refNa]]
out <- lst # keep also non-concerned data, instead of : list()
newNa <- if(length(dim(annS)) > 1) tapply(rownames(annS), annS[, refColNa], paste, collapse=",") else tapply(names(annS), annS, paste, collapse=",")
newNFi <- if(length(dim(annS)) > 1) tapply(rownames(annS), annS[, refColNa], function(z) z[1]) else tapply(names(annS), annS, function(z) z[1])
## check if any duplicated items exist
chDu <- duplicated(if(length(dim(annS)) >1) annS[, refColNa] else annS)
if(all(!chDu, na.rm=TRUE)) datOK <- FALSE
}
if(debug) { message(fxNa, "cRLL2"); cRLL2 <- list(lst=lst, out=out,refNa=refNa,datNa=datNa,refColNa=refColNa, NA.rm=NA.rm, summarizeType=summarizeType,datOK=datOK) }
if(datOK) {
## prepare for multiple summarizing options/functions via argument summarizeType
sumFx <- function(z, meth) {
if(length(dim(z)) < 2) stop("Invalid entry 'z' (should be matrix)")
if(any(c("aver", "average", "mean") %in% meth)) meth <- "av"
if(any(c("median") %in% meth)) meth <- "med"
out <- try(switch(meth,
sum=colSums(z, na.rm=NA.rm),
av=colMeans(z, na.rm=NA.rm),
med=apply(z, 2, stats::median, na.rm=NA.rm),
first=z[1,], last=z[nrow(z), ]), silent=TRUE)
if(inherits(out, "try-error")) out <- NULL
out }
if(debug) { message(fxNa, "cRLL2a"); cRLL2a <- list() }
## prepare $annot
if(length(dim(annS)) > 1) {
out[[refNa]] <- annS[which(!duplicated(annS[, refColNa])), ]
out[[refNa]] <- out[[refNa]][order(out[[refNa]][, refColNa]), ]
} else out[[refNa]] <- sort(annS[which(!duplicated(annS))]) # , fromLast=TRUE
if(debug) { message(fxNa, "cRLL2b") }
out[[refNa]] <- by(lst[[refNa]], if(length(dim(lst[[refNa]])) > 1) lst[[refNa]][, refColNa] else names(lst[[refNa]]),
function(x) if(length(dim(x)) > 1) cbind(x[1, ], allIniNames=paste(rownames(x), collapse=",")) else cbind(x[1], allIniNames=paste(names(x), collapse=",")))
if(debug) { message(fxNa, "cRLL2c") }
out[[refNa]] <- matrix(unlist(out[[refNa]]), nrow=length(out[[refNa]]), byrow=TRUE)
colNa <- colnames(lst[[refNa]])
if(length(colNa) < 1) colNa <- paste0("X.", 1:ncol(out[[refNa]]))
dimnames(out[[refNa]]) <- list(rownames(out[[refNa]]), if(length(colNa) ==ncol(out[[refNa]])) colNa else c(colNa[1], paste0(colNa[1], 2:(ncol(out[[refNa]])))))
if(debug) { message(fxNa, "cRLL2d") }
if(is.null(colnames(out[[refNa]]))) {
colnames(out[[refNa]]) <- c(if(length(refColNa) ==1) refColNa else "ref", paste("x", 1:(ncol(out[[refNa]] -1)))) } else if(colnames(out[[refNa]])[1] == "")
colnames(lst[[refNa]])[1] <- if(length(refColNa) ==1) refColNa else "ref"
if(debug) { message(fxNa, "cRLL3; ready to combine data of ", length(datNa)," table(s) (element(s) of 'lst') as ", summarizeType)
cRLL3 <- list(lst=lst, out=out,sumFx=sumFx,annS=annS,refNa=refNa,datNa=datNa,refColNa=refColNa,NA.rm=NA.rm,summarizeType=summarizeType) }
## now summarize
for(i in datNa) { yy <- lst[[i]]
yz <- unlist(by(yy, if(length(dim(annS)) > 1) annS[, refColNa] else annS, sumFx, summarizeType))
if(length(yz) > 0) out[[i]] <- matrix(yz, byrow=TRUE, ncol=ncol(yy), dimnames=list(sort(unique(if(length(dim(annS)) >1) annS[, refColNa] else annS)), colnames(yy)))
}
if(debug) { message(fxNa, "cRLL3b"); cRLL3b <- list()}
names(out) <- names(lst)
out
} else { if(debug) message(fxNa, "Invalid entry OR no redundant ref/annnot found, nothing to do ...")
lst
}
}
#' Combine Redundant Lines In List, Deprecated
#'
#' The function combineRedundLinesInListAcRef() has been deprecated and replaced by combineRedundLinesInList() from the same package
#'
#' @param lst (list) main input
#' @param listNa (character) names of list-elements containing quantitation data (1st position) and protein/line annotation (2nd position)
#' @param refColNa (character) in case the list-element to be used as reference is \code{matrix} or \code{data.frame}, the column to be used must be specified here
#' @param summarizeType (character) the summarization method gets specified here; so far 'sum','av','med','first' and 'last' are implemented
#' @param NA.rm (logical) pass to summarizing functions order to omit \code{NA}s, 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
#' @seealso \code{\link{combineRedundLinesInList}}
#' @return This function returns a list of same length as input
#' @examples
#' x1 <- list(quant=matrix(11:34, ncol=3, dimnames=list(letters[8:1], LETTERS[11:13])),
#' annot=matrix(paste0(LETTERS[c(1:4,6,3:5)],LETTERS[c(1:4,6,3:5)]), ncol=1,
#' dimnames=list(paste(letters[1:8]),"xx")) )
#' ## please use combineRedundLinesInList()
#' combineRedundLinesInList(lst=x1, refNa="annot", datNa="quant", refColNa="xx")
#' @export
combineRedundLinesInListAcRef <- function(lst, listNa=c("ref","quant"), refColNa="xx", summarizeType="av", NA.rm=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL) {
.Deprecated(new="combineRedundLinesInList", package="wrMisc", msg="The function combineRedundLinesInListAcRef() has been deprecated and replaced by combineRedundLinesInList()")
#combineRedundLinesInList(lst=lst, listNa=listNa, refColNa=refColNa, summarizeType=summarizeType, NA.rm=NA.rm, silent=silent, debug=debug, callFrom=callFrom)
fxNa <- .composeCallName(callFrom, newNa="combineRedundLinesInList")
namesXY <- deparse(substitute(lst))
out <- NULL
datOK <- TRUE
if(debug) message(fxNa, "cRLL0")
msg1 <- c(" entry for 'listNa' (must design at least 2 list-elements of '", namesXY, "', 1st sould be annotation, others numeric matrix)")
if(length(listNa) > 1) {
if(is.numeric(listNa)) {
listNa <- as.integer(listNa)
if(any(listNa < 1 | listNa > length(lst)))
stop(fxNa, "Invalid (numeric)", msg1)
} else {
lstMatch <- match(listNa, names(lst))
chNA <- is.na(lstMatch)
if(sum(!chNA) < 2 || chNA[1]) stop(fxNa, msg1)
if(any(chNA)) { refColNa <- naOmit(refColNa)
if(!silent) message(fxNa, "Removing ", sum(chNA), " element(s) not found in 'refColNa'") }
}
} else stop(fxNa, "Insufficient", msg1)
chUni <- unique(lst[[listNa[1]]])
if(length(chUni) < 2) datOK <- FALSE
if(datOK) {
if(length(refColNa) < 1) refColNa <- "GeneName"
if(length(refColNa) > 1) { refColNa <- refColNa[1]
if(!silent) message(fxNa, "Argument 'refColNa' should be of length 1, trimming ..") }
## sort listNa to have annot at beginning
if(length(names(listNa)) == length(listNa)) {
chO <- naOmit(match(c("ref", "reference", "annot"), tolower(names(listNa))))
if(length(chO) > 0) {
if(chO[1] != 1) {
if(debug) message(fxNa, "Changing order of 'listNa' based on names of 'listNa'")
listNa <- listNa[c(chO[1], (1:length(listNa))[-chO[1]])] }
}
}
if(debug) { message(fxNa, "cRLL1"); cRLL1 <- list(lst=lst, listNa=listNa, refColNa=refColNa, NA.rm=NA.rm, summarizeType=summarizeType) }
## re-order listNa to have annotation as 1st
nuI <- naOmit(match(listNa[-1], names(lst)))
## check presence of 'refColNa' in lst
if(length(dim(lst[[listNa[1]]])) > 1) {
ch1 <- refColNa %in% colnames(lst[[listNa[1]]])
if(!any(ch1)) stop(fxNa, "Missing column '", refColNa, "' in ", namesXY[1], "$", listNa[1])
}
chDuRef <- duplicated(if(length(dim(lst[[listNa[1]]])) > 1) lst[[listNa[1]]][, refColNa] else lst[[listNa[1]]])
datOK <- any(chDuRef, na.rm=TRUE)
if(debug) { message(fxNa, "cRLL1b"); cRLL1b <- list()
}
}
if(datOK) {
chNa <- is.na(nuI)
if(length(listNa) < 2 || all(chNa)) stop("Invalid entry for 'listNa' (must design at least one numeric matrix of 'lst')")
if(any(chNa)) message(fxNa, "Elements ", pasteC(listNa[which(chNa)]),"missing")
xAnn <- which(names(lst) == listNa[1])
annS <- if(length(dim(lst[[xAnn]])) > 1) lst[[xAnn]][match(rownames(lst[[xAnn]]), rownames(lst[[nuI[1]]])), ] else lst[[xAnn]][match(names(lst[[xAnn]]), rownames(lst[[nuI[1]]]))]
out <- list()
newNa <- if(length(dim(annS)) > 1) tapply(rownames(annS), annS[, refColNa], paste, collapse=",") else tapply(names(annS), annS, paste, collapse=",")
newNFi <- if(length(dim(annS)) > 1) tapply(rownames(annS), annS[, refColNa], function(z) z[1]) else tapply(names(annS), annS, function(z) z[1])
## prepare for multiple summarizing options/functions via argument summarizeType
sumFx <- function(z, meth) {
if(length(dim(z)) < 2) stop("Invalid entry 'z' (should be matrix)")
if(any(c("aver", "average", "mean") %in% meth)) meth <- "av"
if(any(c("median") %in% meth)) meth <- "med"
out <- try(switch(meth,
sum=colSums(z, na.rm=NA.rm),
av=colMeans(z, na.rm=NA.rm),
med=apply(z, 2, stats::median, na.rm=NA.rm),
first=z[1,], last=z[nrow(z), ]), silent=TRUE)
if(inherits(out, "try-error")) out <- NULL
out }
if(debug) { message(fxNa, "cRLL2") }
## prepare $annot
if(length(dim(annS)) > 1) {
out[[xAnn]] <- annS[which(!duplicated(annS[, refColNa], fromLast=TRUE)), ]
out[[xAnn]] <- out[[xAnn]][order(out[[xAnn]][, refColNa]), ]
} else out[[xAnn]] <- sort(annS[which(!duplicated(annS, fromLast=TRUE))])
if(debug) { message(fxNa, "cRLL2b"); cRLL2b <- list() }
out[[xAnn]] <- by(lst[[xAnn]], if(length(dim(lst[[xAnn]])) > 1) lst[[xAnn]][, refColNa] else names(lst[[xAnn]]),
function(x) if(length(dim(x)) > 1) cbind(x[1, ], allIniNames=paste(rownames(x), collapse=",")) else cbind(x[1], allIniNames=paste(names(x), collapse=",")))
if(debug) { message(fxNa, "cRLL2c") }
out[[xAnn]] <- matrix(unlist(out[[xAnn]]), nrow=length(out[[xAnn]]), byrow=TRUE)
colNa <- colnames(lst[[xAnn]])
if(length(colNa) < 1) colNa <- paste0("X.", 1:ncol(out[[xAnn]]))
dimnames(out[[xAnn]]) <- list(names(out[[xAnn]]), if(length(colNa) ==ncol(out[[xAnn]])) colNa else c(colNa[1], paste0(colNa[1], 2:(ncol(out[[xAnn]])))))
if(debug) { message(fxNa, "cRLL2d") }
if(is.null(colnames(out[[xAnn]]))) {
colnames(out[[xAnn]]) <- c(if(length(refColNa) ==1) refColNa else "ref", paste("x", 1:(ncol(out[[xAnn]] -1)))) } else if(colnames(out[[xAnn]])[1] == "")
colnames(lst[[xAnn]])[1] <- if(length(refColNa) ==1) refColNa else "ref"
if(debug) { message(fxNa, "cRLL3; Summarizing ", length(nuI)," elements as ", summarizeType)
cRLL3 <- list(lst=lst, out=out,sumFx=sumFx,annS=annS, xAnn=xAnn,listNa=listNa,refColNa=refColNa,NA.rm=NA.rm,summarizeType=summarizeType) }
## now summarize
for(i in nuI) { yy <- lst[[i]]
yz <- unlist(by(yy, if(length(dim(annS)) > 1) annS[, refColNa] else annS, sumFx, summarizeType))
if(length(yz) > 0) out[[i]] <- matrix(yz, byrow=TRUE, ncol=ncol(yy), dimnames=list(sort(unique(if(length(dim(annS)) >1) annS[, refColNa] else annS)), colnames(yy)))
}
names(out) <- names(lst)
rownames(out[[xAnn]]) <- rownames(out[[nuI[1]]])
out
} else { if(debug) message(fxNa, "No redundant ref/annnot found, nothing to do ...")
lst
}
}
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/combineRedundLinesInList.R
|
#' Combine replicates from list to matrix
#'
#' Suppose multiple measures (like multiple chanels) are taken for subjects and these measures are organized as groups in a list,
#' like muliple parameters (= channels) or types of measurements (typically many paramters are recorded when screeinig compounds in microtiter plates).
#' Within one parameter/channel all replicate-data from separate list-entries ('lst') will get combined according to names of list-elements.
#' The function will trim any redundant text in names of list-elements, try to isolate separator (may vary among replicate-groups, but should be 1 character long).
#' eg names "hct116 1.1.xlsx" & "hct116 1.2.xlsx" will be combined as replicates, "hct116 2.1.xlsx" will be considered as new group.
#' @param lst (list) list of arrays (typically multi-parameter measures of micortiterplate data)
#' @param callFrom (character) allows easier tracking of message(s) produced
#' @return list of arrays now with same dimension of arrays (but shorter, since replicate-arrays were combined)
#' @seealso \code{\link{extr1chan}}, \code{\link{organizeAsListOfRepl}}
#' @examples
#' lst2 <- list(aa_1x=matrix(1:12,nrow=4,byrow=TRUE),ab_2x=matrix(24:13,nrow=4,byrow=TRUE))
#' combineReplFromListToMatr(lst2)
#' @export
combineReplFromListToMatr <- function(lst,callFrom=NULL){
fxNa <- .composeCallName(callFrom,newNa="combineReplFromListToMatr")
varNa <- .trimFromEnd(.trimFromStart(names(lst)))
varSep <- gsub("[[:alnum:]]","",varNa)
if(any(nchar(varSep) <1)) stop(" Manually EDIT file-names, can't find separator between group/plate-name and replicate-number !")
if(any(nchar(varSep) >1)) message(" so far designed for single separator character; use gregexpr & unlist",
"\ Here :",paste(varSep,collapse=" "))
varSep[which(varSep== ".")] <- "\\."
varNa2 <- apply(cbind(varNa,varSep),1,function(x) unlist(strsplit(x[1],x[2])) )
arrTy <- table(varNa2[1,])[rank(unique(varNa2[1,]))]
out <- list()
iniFi <- 0
for(i in 1:length(arrTy)) {
check <- sapply(lst[iniFi+(1:arrTy[i])],length)
if(length(unique(check)) !=1) {
message(fxNa," plate-type ",i," : Trouble ahead : Dimensions of plates not constant ! files ",paste(names(lst)[iniFi+(1:arrTy[i])],collapse=" "))
} else {
out[[i]] <- as.matrix(sapply(lst[iniFi+(1:arrTy[i])],as.numeric))
dimNa <- dimnames(lst[[1+iniFi]])
dimnames(out[[i]]) <- list(paste(dimNa[[1]],rep(sub("^X","",dimNa[[2]]),each=length(dimNa[[1]])),sep=""),varNa2[2,iniFi+(1:arrTy[i])] )
iniFi <- iniFi + arrTy[i]
} }
names(out) <- unique(varNa2[1,])
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/combineReplFromListToMatr.R
|
#' Get all combinations with TRUE from each column
#'
#' This function addresses the case when multiple alternatove ways exit to combine two elements.
#' \code{combineSingleT} makes combinatory choices : if multiple \code{TRUE} in given column of 'mat' make all multiple selections with always one \code{TRUE} from each column
#' The resultant output contains index for first and second input columns elements to be combined.
#' @param mat 2-column matrix of logical values
#' @return matrix with indexes of conbinations of \code{TRUE}
#' @examples
#' ## Example: Fist column indicates which boys want to dance and second column
#' ## which girls want to dance. So if several boys want to dance each of the girls
#' ## will have the chance to dance with each of them.
#' matr <- matrix(c(TRUE,FALSE,TRUE,FALSE,TRUE,FALSE),ncol=2)
#' combineSingleT(matr)
#' @export
combineSingleT <- function(mat){
msg <- "Expecting matrix of logical entries with 2 columns and at least 1 'TRUE' per column "
if(length(dim(mat)) !=2) stop(msg) else if(nrow(mat) <1 | ncol(mat)<2) stop(msg)
if(!is.logical(mat)) msg <- matrix(as.logical(mat),ncol=ncol(mat))
chMu <- apply(mat,2,which)
if(any(sapply(chMu,length)<1)) stop(msg)
if(is.matrix(chMu)) chMu <- list(chMu[,1],chMu[,2])
out <- matrix(c(rep(chMu[[1]],sum(mat[,2])),rep(chMu[[2]],each=sum(mat[,1]))),ncol=2)
colnames(out) <- if(is.null(colnames(mat))) paste("de",1:2,sep="") else colnames(mat)
out}
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/combineSingleT.R
|
#' Complete list of arrays for same dimensions
#'
#' This functions aims to inspect repeating structues of data given as list of arrays and will try to complete
#' arrays with fewer lines or columns (as this may appear eg with the very last set of high-thourput sceening data
#' if fewer measures remain in the last set). Thus, the dimensions of the arrays are compared and
#' cases with fewer (lost) columns (eg fewer experimental replicates) will be adjust/complete by adding column(s) of NA.
#' Used eg when at reading mircotiterplate data the last set is not complete.
#' @param arrLst (list) list of arrays (typically 1st and 2nd dim for specific genes/objects, 3rd for different measures associated with)
#' @param silent (logical) suppress messages
#' @return list of arrays, now with same dimension of arrays
#' @param callFrom (character) allows easier tracking of message(s) produced
#' @seealso \code{\link[wrMisc]{organizeAsListOfRepl}}, \code{\link[wrMisc]{extr1chan}}
#' @examples
#' arr1 <- array(1:24,dim=c(4,3,2),dimnames=list(c(LETTERS[1:4]),
#' paste("col",1:3,sep=""),c("ch1","ch2")))
#' arr3 <- array(81:96,dim=c(4,2,2),dimnames=list(c(LETTERS[1:4]),
#' paste("col",1:2,sep=""),c("ch1","ch2")))
#' arrL3 <- list(pl1=arr1,pl3=arr3)
#' completeArrLst(arrL3)
#' @export
completeArrLst <- function(arrLst,silent=FALSE,callFrom=NULL){
## adjust/complete cases with fewer (lost) columns (replicates) by adding column(s) of NA
## to obtain same dimension of arrays in list
fxNa <- .composeCallName(callFrom,newNa="completeArrLst")
dims <- sapply(arrLst,dim)
corPos <- apply(dims,1,function(x) which(x < max(x,na.rm=TRUE)))
maxDim <- apply(dims,1,max,na.rm=TRUE)
if(!silent) message(fxNa," max dimensions ",paste(maxDim,collapse=" "))
if(length(corPos[[1]]) >0) for(i in corPos[[1]]) message("filling along rows not yet implemented")
if(length(corPos[[2]]) >0) for(i in corPos[[2]]) {
if(!silent) message(fxNa," +filling ",names(arrLst)[i]," from ",paste(dim(arrLst[[i]]),collapse=" ")," to ",paste(maxDim,collapse=" "))
add <- array(NA,dim=c(maxDim[1],maxDim[2]-dim(arrLst[[i]])[2],maxDim[3]))
orgDimNa <- dimnames(arrLst[[i]])
arrLst[[i]] <- .fuse2ArrBy2ndDim(arrLst[[i]],add)
dimnames(arrLst[[i]]) <- list(orgDimNa[[1]],c(orgDimNa[[2]],paste("NA",1:(maxDim[2]-length(orgDimNa[[2]])),sep=".")),orgDimNa[[3]])
}
if(length(corPos[[3]]) >0) for(i in corPos[[3]]) message(fxNa,"filling along channels not yet implemented")
arrLst }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/completeArrLst.R
|
#' Value Matching With Option For Concatenated Terms
#'
#' This is a _match()_-like function allowing to serach among concatenated terms/IDs, additional options to remove text pattern like terminal lowercase extesion are available.
#' The function returns a named vector indicating the positions of (first) matches similar to \code{\link[base]{match}}.
#'
#' @details
#' The main motivation to create this function was to be able to treat concatenated entries and to look if \code{any} of the concatenated values match to 'x'.
#' This function offers additional options for trimming values before running the main comparison.
#'
#' Of course, the concatenation strategy must be known and only a single concatenation separator (which may be multiple characters long) may be used for both \code{x} and \code{match}.
#' Thus result will only indicate that at least one of the concatenated terms had a match, but not which one.
#' Finally, both vectors \code{x} and \code{table} may contain concatenated terms.
#' In this case this function will require much more computational ressources due to the increased combinatorics when comparing larger vectors.
#'
#' Please note, that in case of multiple to multiple matches, only the first hit gets reported.
#'
#' The argument \code{globalPat="digitExtension"} allows eg reducing 'A1234-4' to 'A1234'.
#'
#' @param x (vector) the values to be matched
#' @param table (vector) the values to be matched against (ie reference)
#' @param sep (character) separator character in case concatenation of entries is tested
#' @param sepPattern (character or \code{NULL}) optional custom pattern for splitting concatenations of \code{x}) and \code{table}) (in case \code{NULL}) is not sufficient)
#' @param globalPat (character) pattern for additional trimming of serach-terms. If \code{globalPat="digitExtension"} all terminal digits will not be considered when matching
#' @param nomatch (vector) similar to \code{\link[base]{match}} the value to be returned in the case when no match is found
#' @param incomparables (vector) similar to \code{\link[base]{match}}, a vector of values that cannot be matched. Any value in x matching a value in this vector is assigned the nomatch value.
#' @param extensPat (logical) similar to \code{\link[base]{match}} the value to be returned in the case when no match is found
#' @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 with verified path and file-name(s), returns \code{NULL} if nothing
#' @seealso \code{\link[base]{match}} (for two simple vectors without concatenated terms), \code{\link[base]{grep}}
#' @examples
#' tab1 <- c("AA","BB-5","CCab","FF")
#' tab2 <- c("AA","WW,Vde,BB-5,E","CCab","FF,Uef")
#' x1 <- c("ZZ","YY","AA","BB-2","DD","CCdef","Dxy") # modif of single ID (no concat)
#' concatMatch(x1, tab2)
#' x2 <- c("ZZ,Z","YY,Y","AA,Z,Y","BB-2","DD","X,CCdef","Dxy") # conatenated in 'x'
#' concatMatch(x2, tab2)
#' tab1 <- c("AA","BB-5","CCab","FF") # no conatenated in 'table'
#' concatMatch(x2, tab1) # simple case of no concat anywhere
#' concatMatch(x1, tab1)
#' @export
concatMatch <- function(x, table, sep=",", sepPattern=NULL, globalPat="digitExtension", nomatch=NA_integer_, incomparables=NULL, extensPat=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL) {
## move to wrMisc ?
## idea : find where x (eg fasta) matche(s) IN table (MQresult, has concat)
## both \code{x} and \code{table} may contain concatenated IDs
## match-like function including each of concatenated terms/IDss, add'l option to remove add'l pattern like terminal lowercase extension
## strategy A : few concatenations : run match() on 1st set of table, 2nd set etc
## strategy B : many concat & short x : grep each x in table (as heading, sep+x+sep, as term)
## globalPat (character, 'digitExtension') regular expression for searching eg reduce 'A1234-4' to 'A1234'
## extensPat (charcter) \code{TRUE} for removing terminal lower case eg ('AB1234ups')
## need to find if any of concatenated 'x' in 'table'
## prepare
fxNa <- wrMisc::.composeCallName(callFrom, newNa="concatMatch")
if(isTRUE(debug)) silent <- FALSE
if(!isTRUE(silent)) silent <- FALSE
xIni <- x; tableIni <- table # initialize backup
chDux <- duplicated(x)
if(length(x) <1) stop("Invalid entry, 'x' must be at least of length=1")
if(length(table) <1) stop("Invalid entry, 'table' must be at least of length=1")
if(!any(c("numeric", "character", "logical") %in% class(x))) stop("Invalid entry, 'x' must be numeric, character or logical vector")
if(!any(c("numeric", "character", "logical") %in% class(table))) stop("Invalid entry, 'table' must be numeric, character or logical vector")
if(any(chDux) && !silent) message(fxNa,"Note, some entries of 'x' are not unique !")
chDut <- duplicated(table)
if(any(chDut) && !silent) message(fxNa,"Note, some entries of 'table' are not unique !")
if(debug) {message(fxNa,"cMa1"); cMa1 <- list(x=x,table=table, sep=sep,sepPattern=sepPattern,globalPat=globalPat,extensPat=extensPat)}
## rm term sep
chSep <- grep(paste0(sep,"$"), x)
if(length(chSep) >0) {x <- sub(paste0(sep,"$"), "", x)}
chSep <- grep(paste0(sep,"$"), table)
if(length(chSep) >0) {table <- sub(paste0(sep,"$"), "", table)}
## however - possibility that x or table become non-unique due to manipulation !!
if(length(sepPattern) <1) sepPattern <- sep
## remove terinal extensions (eg AB1234ups)
if(length(extensPat) ==1) {
if(isTRUE(extensPat)) { # remove terminal lower case eg ('AB1234ups')
chPatXt <- grep("[A-Z0-9][[:lower:]]+$", x) # tailing pattern
chPatXc <- grep(paste0("[A-Z0-9][[:lower:]]+",sep,"."), x) # center pattern
chPatTt <- grep("[A-Z0-9][[:lower:]]+$", table)
chPatTc <- grep(paste0("[A-Z0-9][[:lower:]]+",sep,"."), table)
if(length(chPatXt) >0) x[chPatXt] <- sub("[[:lower:]]+$","", x[chPatXt])
if(length(chPatXc) >0) x[chPatXc] <- sub(paste0("[[:lower:]]+",sep), sep, x[chPatXc])
if(length(chPatTt) >0) table[chPatTt] <- sub("[[:lower:]]+$","", table[chPatTt])
if(length(chPatTc) >0) table[chPatTc] <- sub(paste0("[[:lower:]]+",sep), sep, table[chPatTc])
} else {
chExt <- grep(extensPat, x)
if(length(chExt) >0) x <- sub(extensPat, "", x)}
chDux <- duplicated(x)
if(any(chDux) && !silent) message(fxNa,"Note, some entries of 'x' are not unique ! (after cleaning by 'extensPat')")
chDut<- duplicated(table)
if(any(chDut) && !silent) message(fxNa,"Note, some entries of 'table' are not unique ! (after cleaning by 'extensPat')")
}
## global pattern modif
if(length(globalPat) >0) {
## however - possibility that x or table become non-unique due to manipulation !!
if(identical(globalPat, "digitExtension")) { ## remove all after '-' eg ('P1234-5')
chPatXt <- grep("[A-Z0-9]\\-[[:digit:]]{1,4}$", x) # tailing pattern
chPatXc <- grep(paste0("[A-Z0-9]\\-[[:digit:]]{1,4}",sep,"."), x) # center pattern
chPatTt <- grep("[A-Z0-9]\\-[[:digit:]]{1,4}$", table)
chPatTc <- grep(paste0("[A-Z0-9]\\-[[:digit:]]{1,4}",sep,"."), table)
if(length(chPatXt) >0) x[chPatXt] <- sub("\\-[[:digit:]]{1,4}$","", x[chPatXt])
if(length(chPatXc) >0) x[chPatXc] <- sub(paste0("\\-[[:digit:]]{1,4}",sep), sep, x[chPatXc])
if(length(chPatTt) >0) table[chPatTt] <- sub("\\-[[:digit:]]{1,4}$","", table[chPatTt])
if(length(chPatTc) >0) table[chPatTc] <- sub(paste0("\\-[[:digit:]]{1,4}",sep), sep, table[chPatTc])
} else {
chPat <- grep(globalPat, x)
if(length(chPat) >0) x[chPat] <- sub(globalPat, sep, x[chPat])
chPat <- grep(globalPat, table)
if(length(chPat) >0) table[chPat] <- sub(globalPat, sep, table[chPat])}
chDux <- duplicated(x)
if(any(chDux) && !silent) message(fxNa,"Note, some entries of 'x' are not unique ! (after cleaning by 'globalPat')")
chDut<- duplicated(table)
if(any(chDut) && !silent) message(fxNa,"Note, some entries of 'table' are not unique ! (after cleaning by 'globalPat')")
}
if(debug) { message(fxNa,"cMa2"); cMa2 <- list(x=x,table=table, sep=sep,sepPattern=sepPattern,globalPat=globalPat,extensPat=extensPat,chSep=chSep)}
## MAIN :
## start with regular match
out <- match(x, table, nomatch=nomatch, incomparables=incomparables)
x1 <- x; table1 <- table
names(out) <- x
chMa <- is.na(out)
if(any(chMa)) {
## not all items of 'x' found in 'table' ==> try complementing missing
## now work only on x not prevusouly found !
if(debug) {message(fxNa,sum(chMa)," ID/term of 'x' not found so far : ", wrMisc::pasteC(utils::head(x[which(chMa)], quoteC="'")))}
## check for separators
chSepT <- grep(sepPattern, table) # which 'table' are concatented => useful for splitting
chSepX <- grep(sepPattern, x[which(chMa)]) # don't use truncation (strat A) when x has concatenation
if(debug) { message(fxNa,"cMa3"); cMa3 <- list(x=x,table=table,out=out,chMa=chMa,chSepT=chSepT,chSepX=chSepX, sep=sep,sepPattern=sepPattern,globalPat=globalPat,extensPat=extensPat,chSep=chSep)}
if(length(chSepT) >0 || length(chSepX) >0) {
if(debug) message(fxNa,"Found ",length(chSepT)," cases of conatenated IDs in 'table' -> split; ",length(chSepX)," cases of conatenated 'x'")
## has separators
## now devide strat A and B
nCharX <- nchar(x)
nSepX <- (nCharX - nchar(gsub(sepPattern,"", x))) /nchar(sep)
nCharTab <- nchar(table)
nSepTab <- (nCharTab - nchar(gsub(sepPattern,"", table))) /nchar(sep) # number of concatenated terms for each 'table'
if(length(chSepX) <1 && max(nSepTab, na.rm=TRUE) / length(x) < 0.5 && max(nSepTab, na.rm=TRUE) < 15) {
## strategy A :
## few concatenations : run match() on 1st set of table, 2nd set etc
if(debug) message(fxNa,"Choose strategy A : few concatenations : run match() on 1st set of table, 2nd set etc")
if(debug) { message(fxNa,"cMa4"); cMa4 <- list(x=x,table=table,out=out,chSepT=chSepT,chMa=chMa,chSepT=chSepT, sep=sep,sepPattern=sepPattern,globalPat=globalPat,extensPat=extensPat,chSep=chSep)}
##
for(i in 0:max(nSepTab, na.rm=TRUE)) {
if(length(chSepT) >0 && any(is.na(out))) { # yes, need to go further and split
if(i >0) {chSepT <- grep(sepPattern, table) # update (which 'table' are concatented => use for splitting)
table <- substring(table, nchar(tabT) +2) } # removve 1st element from left (already treated)
tabT <- sub(paste0(sep,".+"), "", table[chSepT]) # truncate from right, ie leave only 1st
outNa <- which(is.na(out))
maT <- match(x[outNa], tabT, nomatch=nomatch, incomparables=incomparables)
names(maT) <- x[which(is.na(out))]
chNa <- !is.na(maT)
if(any(chNa)) { out[outNa[which(chNa)]] <- chSepT[maT[which(chNa)]]
if(debug) message(fxNa,"Found ",sum(chNa)," add'l matches in i=",i+1) }
}
}
} else {
## strategy B :
## many concat & short x : grep each 'x' in table (as heading, sep+x+sep, as term) ==> may be slow when 'x' is long
## also works if 'x' has concatenations
if(debug) message(fxNa," ++ Strategy B : use grep for terminal 'x' or 'x' combined with 'sep'")
.sepGrep <- function(xx, sep, table) grep(paste0("^",xx,"$|","^",xx,sep,"|",sep,xx,sep,"|",sep,xx,"$"), table) # terminal & separator-grep
if(length(chSepX) <1) {
out2 <- lapply(x[which(chMa)], .sepGrep, sep, table)
out2 <- sapply(out2, function(y) if(length(y) >0) y[1] else NA)
} else {
## double concatenated (x & table) => strsplit x for grep of each !
if(debug) { message(fxNa,"cMa5"); cMa5 <- list(x=x,table=table,out=out,chSepT=chSepT,chMa=chMa,chSepT=chSepT, sep=sep,sepPattern=sepPattern,globalPat=globalPat,extensPat=extensPat,chSep=chSep)}
spl <- strsplit(x[which(chMa)], sep)
naOm3 <- function(zz, sep, table) {zz <- unlist(lapply(zz, .sepGrep, sep, table)); isNa <- is.na(zz); if(any(!isNa)) zz[which(!isNa)[1]] else NA } # return 1st non-NA or NA from sepGrep search
out2 <- sapply(spl, naOm3, sep, table)
}
chLe <- sapply(out2, length)
if(any(chLe) >1) {
if(!silent) message(fxNa,"Found ",sum(chLe >1)," cased of multiple matching after split & grep, using only first") }
out[which(chMa)] <- unlist(out2)
}
} else {if(debug) message(fxNa,"Remain with match-approach (no concatenations found)")
}
} else if(debug) message(fxNa,"All initial 'x' were found in 'table'")
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/concatMatch.R
|
#' Confidence Interval To Given Alpha
#'
#' This little function returns the confidence interval associated to a given significance level \code{alpha} under the hypothesis of the Normal distribution is valid.
#'
#' @param x (numeric) main input
#' @param alpha (numeric) significance level, accepted type I error
#' @param distrib (character) distribution, so far only \code{Normal} is implemented
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of message(s) produced
#' @return This function returns the confidence interval to a given \code{alpha} under the hypothesis of the Normal distribution.
#' @seealso \code{\link[stats]{TDist}}; \code{\link[stats]{confint}}
#' @examples
#'
#' confInt(c(5,2:6))
#'
#' @export
confInt <- function(x, alpha=0.05, distrib="Normal", silent=FALSE, callFrom=NULL) { ## return Confidence Interval (CI) (range) based on sd ('x')
fxNa <- .composeCallName(callFrom, newNa="confInt")
if(!"normal" %in% tolower(distrib)) warning(fxNa,"So far only distrib='Normal' has been implemented, all data will be considered as originating from Normal distribution")
tVal <- stats::qt((1 -alpha)/2 + 0.5, length(x) -1)
tVal*stats::sd(x, na.rm=TRUE) / sqrt(length(x))}
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/confInt.R
|
#' Characterize individual contribution of single edges in tree-structures
#'
#' This function helps investigating tree-like structures with the aim of indicating how much individual tree components contribute
#' to compose long stretches.
#' \code{contribToContigPerFrag} characterizes individual (isolated) contribution of single edges in tree-structures.
#' Typically used to process/exploit summarized trees (as matrix) made by \code{\link{buildTree}} which makes use of the package \href{https://CRAN.R-project.org/package=data.tree}{data.tree}.
#' For example if A,B and C can be joined aa well and B +D, this function will check if A+B+C is longer and if A contributes to the longest tree.
#' @param joinMat (matrix) matrix with concatenated edges as rownames (separated by slashes), column \code{sumLen} for total length and column \code{n} for number of edges
#' @param fullLength (integer) custom total length (useful if the concatenated edges do not cover 100 percent of the original precursor whose fragments are studied)
#' @param nDig (integer) rounding: number of digits for 3rd column \code{len.rat} in output
#' @return matrix of 3 columns: with length of longest tree-branches where given edge participates (column \code{sumLen}), the (total) number of edges therein (col \code{n.frag}) and a relative value (\code{len.rat})
#' @seealso to build tree \code{\link{buildTree}}
#' @examples
#' path1 <- matrix(c(17,19,18,17, 4,4,2,3),ncol=2,
#' dimnames=list(c("A/B/C/D","A/B/G/D","A/H","A/H/I"),c("sumLen","n")))
#' contribToContigPerFrag(path1)
#' @export
contribToContigPerFrag <- function(joinMat,fullLength=NULL,nDig=3){
argN <- deparse(substitute(joinMat))
msg <- c("Unknown input-format in '",argN,"'")
if(is.list(joinMat)) {if("paths" %in% names(joinMat)) joinMat <- joinMat$paths else stop(msg)}
if(length(dim(joinMat)) <2) stop(msg) else if(!"sumLen" %in% colnames(joinMat)) stop("Need column 'sumLen' in ",argN)
if(is.null(fullLength)) fullLength <- max(joinMat[,"sumLen"])
joinMat <- joinMat[sort.list(joinMat[,"sumLen"],decreasing=FALSE),]
jLi <- lapply(rownames(joinMat),strsplit,"/")
frags <- sort(unique(unlist(jLi)))
out <- t(sapply(frags,function(x) {z <- grep(x,rownames(joinMat))
w <- max(joinMat[z,"sumLen"])
c(w, min(joinMat[z[which(joinMat[z,"sumLen"]==w)],"n"]) )
} ))
colnames(out) <- c("sumLe","n.frag")
out <- cbind(out,len.rat=round(out[,"sumLe"]/fullLength,nDig))
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/contribToContigPerFrag.R
|
#' Convert matrix of integer to matrix of x-times repeated column-names
#'
#' \code{conv01toColNa} transforms matrix of integers (eg 0 and 1) to repeated & concatenated text from argument \code{colNa},
#' the character string for 0 occurances of argument \code{zeroTex} may be customized.
#' Used eg when specifying (and concatenating) various counted elements (eg properties) along a vector like variable peptide modifications in proteomics.
#'
#' @param mat input matrix (with integer values)
#' @param colNa alternative (column-)names to the ones from 'mat' (default colnames of 'mat')
#' @param zeroTex text to display if 0 (default "")
#' @param pasteCol (logical) allows to collapse all columns to single chain of characters in output
#' @return character vector
#' @examples
#' (ma1 <- matrix(sample(0:3,40,repl=TRUE), ncol=4, dimnames=list(NULL, letters[11:14])))
#' conv01toColNa(ma1)
#' conv01toColNa(ma1, colNa=LETTERS[1:4], ze=".")
#' conv01toColNa(ma1, colNa=LETTERS[1:4], pasteCol=TRUE)
#' @export
conv01toColNa <- function(mat,colNa=NULL,zeroTex="",pasteCol=FALSE){
txt <- "'mat' should be matrix"
collTx <- ""
if(length(dim(mat)) !=2) stop(txt) else if(any(dim(mat)==0)) stop(txt," with >0 rows & cols")
if(is.data.frame(mat)) {ch <- as.numeric(as.matrix(mat))
if(!is.numeric(ch)) stop(txt," cannot transform to matrix of numeric")
mat <- matrix(ch, nrow=nrow(mat), dimnames=dimnames(mat))}
if(is.null(colNa)) colNa <- colnames(mat) else {if(length(colNa) != ncol(mat)) colNa <- colnames(mat)}
out <- matrix(zeroTex, nrow=nrow(mat), ncol=ncol(mat), dimnames=dimnames(mat))
for(j in 1:ncol(mat)) { tmp <- which(mat[,j] >0)
if(length(tmp) >0) out[tmp,j] <- if(max(mat[tmp,j]) >1) sapply(mat[tmp,j], function(x) paste(rep(colNa[j],x),collapse=collTx)) else colNa[j]}
if(pasteCol & ncol(mat) >1) { sepPa <- ""
tmp <- if(ncol(mat)==2) paste(out[,1],out[,2],sep=sepPa) else paste(out[,1],out[,2],out[,3],sep=sepPa)
if(ncol(mat) >3) for(j in 4:ncol(mat)) tmp <- paste(tmp,out[,j], sep=sepPa)
out <- as.matrix(tmp)}
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/conv01toColNa.R
|
#' Assign new transparency to given colors
#'
#' This function alows (re-)defining a new transparency. A color encoding vector will be transformed to the same color(s) but with new transparency (alpha).
#' @param color (character) color input
#' @param alph (numeric) transparency value (1 for no transparency, 0 for complete opaqueness), values <1 will be treated as percent-values
#' @return character vector (of same length as input) with color encoding for new transparency
#' @seealso \code{\link[grDevices]{rgb}}, \code{\link[graphics]{par}}
#' @examples
#' col0 <- c("#998FCC","#5AC3BA","#CBD34E","#FF7D73")
#' col1 <- convColorToTransp(col0,alph=0.7)
#' layout(1:2)
#' pie(rep(1,length(col0)),col=col0)
#' pie(rep(1,length(col1)),col=col1,main="new transparency")
#' @export
convColorToTransp <- function(color,alph=1){
## set given colors to specific transparency
## convert standard color vector to same color but with specific transparency 'alph'
if(any(alph <1)) alph <- round(alph*100)
col1 <- grDevices::col2rgb(color,alpha=TRUE)
col1[4,] <- rep(alph,ncol(col1))[1:ncol(col1)]
apply(col1,2,function(x) grDevices::rgb(x[1],x[2],x[3],alpha=x[4],maxColorValue=255)) }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/convColorToTransp.R
|
#' Convert matrix (eg with redundant) row-names to data.frame
#'
#' This function provides flexible converting of matrix to data.frame.
#' For example repeated/redundant rownames are not allowed in data.frame(), thus the corresponding column-names have to be renamed using a counter-suffix.
#' In case of non-redundant rownames, a new column 'addIniNa' will be introduced at beginning to document the initial (redundant) rownames,
#' non-redundant rownames will be created.
#' Finally, this functions converts the corrected matrix to data.frame and checks/converts columns for transforming character to numeric if possible.
#' If the input is a data.frame containing factors, they will be converted to character before potential conversion.
#' Note: for simpler version (only text to numeric) see from this package \code{.convertMatrToNum} .
#' @param mat matrix (or data.frame) to be converted
#' @param addIniNa (logical) if \code{TRUE} an additional column ('ID') with rownames will be added at beginning
#' @param duplTxtSep (character) separator for enumerating replicated names
#' @param silent (logical) suppres messages
#' @param callFrom (character) allow easier tracking of message(s) produced
#' @return This functions returns a data.frame equivalent to the input matrix, an additional column named 'ID' will be added for initial rownames
#' @seealso \code{\link[base]{numeric}}, for simpler version (only text to numeric) see from this package \code{.convertMatrToNum}
#' @examples
#' dat1 <- matrix(1:10, ncol=2)
#' rownames(dat1) <- letters[c(1:3,2,5)]
#' ## as.data.frame(dat1) ... would result in an error
#' convMatr2df(dat1)
#'
#' df1 <- data.frame(a=as.character((1:3)/2), b=LETTERS[1:3], c=1:3)
#' str(convMatr2df(df1))
#'
#' df2 <- df1; df2$b <- as.factor(df2$b)
#' str(convMatr2df(df2))
#' @export
convMatr2df <- function(mat, addIniNa=TRUE, duplTxtSep="_", silent=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="convMatr2df")
iniNa <- rownames(mat)
chNR <- any(duplicated(iniNa)) & length(iniNa) >0 # non-redundant ?
out <- NULL
## check&treat duplicated rownames
if(is.matrix(mat)) {
if(chNR){
nrNa <- treatTxtDuplicates(iniNa, onlyCorrectToUnique=TRUE, sep=duplTxtSep, silent=silent,callFrom=fxNa)
rownames(mat) <- NULL
mat <- data.frame(ID=iniNa, mat, stringsAsFactors=FALSE)
rownames(mat) <- nrNa
} else {
mat <- data.frame(ID=if(is.null(iniNa)) rep(NA,nrow(mat)) else iniNa, mat, stringsAsFactors=FALSE) }
}
## try converting columns from factor or text to numeric
if(is.data.frame(mat)) {
chFa <- sapply(mat, inherits, "factor")
if(any(chFa)) for(i in which(chFa)) mat[,i] <- as.character(mat[,i])
chNum <- sapply(mat, inherits, c("integer","numeric"))
chTx <- sapply(mat, inherits, "character")
if(colnames(mat)[1]=="ID") chTx[1] <- FALSE
## limit trying to columns conataining digits in all elements
if(any(chTx)) chTx[which(chTx)] <- if(sum(chTx)==1) all(grepl("[[:digit:]]",mat[,which(chTx)])) else grepl("[[:digit:]]",mat[,which(chTx)])
if(any(chTx)) for(i in which(chTx)) { tmp <- try(suppressWarnings(as.numeric(mat[,i])), silent=TRUE)
if(!inherits(tmp, "try-error")) if(!all(is.na(tmp))) mat[,i] <- tmp }
} else { mat <- NULL
if(!silent) message(fxNa,"Can't convert object of class ",pasteC(class(mat), quoteC="'")," to data.frame, returning NULL") }
mat }
#' Check if vector may be numeric content
#'
#' This function allows to checking if a given vector may be numeric content
#'
#' @param x (numeric vector) main input
#' @param pattern (character) custom pattern to check
#' @return This functions returns a logical/boolean vector for each of the elements of 'x'
#' @seealso \code{\link[base]{numeric}}; \code{\link{convMatr2df}}
#' @examples
#' .mayBeNum(c(3:6))
#' @export
.mayBeNum <- function(x, pattern=NULL) {
## test if values of (simple) char vector may be numeric; return index of suitable values
## 'pattern' .. pattern of regular expressions (default for pos & neg values incl '.' as decimal)
## won't work with scientif annotations or heading or tailing spaces !!
if(is.factor(x)) x <- as.character(x)
if(is.null(pattern)) pattern <- "(^([0-9]+)|(^[+-][0-9]+)|(^\\.[0-9]+)|(^0\\.[0-9]+))((\\.[0-9]+)?)(([eE][+-]?[0-9]+)?)$" #"(^([0-9]+)|(^[+-][0-9]+)|(^\\.[0-9]+))((\\.[0-9]+)?)(([eE][+-]?[0-9]+)?)$"
all(grepl(pattern, x)) }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/convMatr2df.R
|
#' Convert vector to numeric
#'
#' This function checks if input vector/character string contains numbers (with or without comma) and attempts converting to numeric.
#' This functions was designed for extracting the numeric part of character-vectors (or matrix) containing both numbers and character-elements.
#' Depending on the parameters \code{convert} and \code{remove} text-entries can be converted to NA (in resulting numeric objects) or removed (the number of elements/lines gets reduced, in consequece).
#' Note: if 'x' is a matrix, its matrix-dimensions & -names will be preserved.
#' Note: so far Inf and -Inf do not get recognized as numeric.
#'
#' @param x vector to be converted
#' @param autoConv (logical) simple automatic conversion based on \code{as.numeric}; if \code{TRUE} all other arguments exept \code{spaceRemove} will not be considered
#' @param spaceRemove (logical) to remove all heading and trailing (white) space (until first non-space character)
#' @param convert (character) define which type of non-conform entries to convert to NAs. Note, if \code{remove} is selected to eliminate character-entries they cannot be converted any more. Use 'allChar' for all character-entries; 'sparseChar' sparse (ie rare) character entries; \code{NA} for converting 'Na' or 'na' to \code{NA}; if 'none' or \code{NULL} no conversions at all.
#' @param remove (character) define which type of non-conform entries to remove, removed items cannot be converted to \code{NA} any more. Use 'allChar' for removing all character entries; \code{NA} for removing all instances of \code{NA} (execept thise created by converting text); all elements will be kept if 'none' or \code{NULL}.
#' @param euroStyle (logical) if \code{TRUE} will convert all ',' (eg used as European decimal-separator) to '.' (as internally used by R as decimal-separator), thus allowing converting the European decimal format.
#' @param sciIncl (logical) include recognizing scientific notation (eg 2e-4)
#' @param callFrom (character) allow easier tracking of messages produced
#' @param silent (logical) suppress messages
#'
#' @details This function may be used in two modes, depening if argument \code{autoConv} is \code{TRUE} or \code{FALSE}.
#' The first options allows accessing an automatic mode based on \code{as.numeric},
#' while the second options investigates all characters if they may belong to numeric expressions and allows removing specific text-elements.
#'
#' @return This function returns a numeric vector (or matrix (if 'x' is matrix))
#' @seealso \code{\link[base]{numeric}} and \code{as.numeric} (on same help-page)
#' @examples
#' x1 <- c("+4"," + 5","6","bb","Na","-7")
#' convToNum(x1)
#' convToNum(x1, autoConv=FALSE, convert=c("allChar"))
#' convToNum(x1, autoConv=FALSE) # too many non-numeric instances for 'sparseChar'
#'
#' x2 <- c("+4"," + 5","6","-7"," - 8","1e6","+ 2.3e4","-3E4","- 4E5")
#' convToNum(x2)
#' convToNum(x2, autoConv=FALSE, convert=NA,remove=c("allChar",NA))
#' convToNum(x2, autoConv=FALSE, convert=NA,remove=c("allChar",NA),sciIncl=FALSE)
#' @export
convToNum <- function(x, autoConv=TRUE, spaceRemove=TRUE, convert=c(NA,"sparseChar"),remove=NULL,euroStyle=TRUE,sciIncl=TRUE,callFrom=NULL,silent=TRUE) {
fxNa <- .composeCallName(callFrom,newNa="convToNum")
if(!is.numeric(x)) {
if(isTRUE(autoConv)) {
if(isTRUE(spaceRemove)) x <- gsub(" ","",x)
ini <- list(class=class(x), mode=mode(x), len=length(x), dim=dim(x))
if(length(ini$dim) ==2) ini$dimnames=dimnames(x)
if(!any(c("numeric","integer") %in% ini$class)) { # thus non-numeric
if(isFALSE(silent)) message(fxNa,"length(x) ",ini$len," class(x) ",class(x)," mode(x) ", mode(x),
" head ",paste(utils::head(x),collapse=" "))
if("data.frame" %in% ini$class | "list" %in% ini$mode) x <- unlist(x)
x <- try(suppressWarnings(as.numeric(if(inherits(x, "factor")) as.character(x) else x)), silent=TRUE)
if(inherits(x, "try-error")) x <- rep(NA,ini$len)
if(length(ini$dim) ==2) {x <- matrix(x, nrow=ini$dim[1], ncol=ini$dim[2], dimnames=ini$dimnames)
if("data.frame" %in% ini$class) x <- as.data.frame(x)}
}
} else {
## old version of this function
if(is.factor(x)) x <- as.character(x)
if(isTRUE(spaceRemove)) x <- sub("^ +","",sub(" +$","",x))
if(isTRUE(euroStyle)) x <- sub(",",".",x)
if("none" %in% convert) convert <- NULL
if("none" %in% remove) remove <- NULL
## convert NA-like text (if specified via 'convert')
if(length(convert) >0) if("na" %in% tolower(convert)) convert[which(tolower(convert) %in% "na")] <- NA
if(length(remove) >0) if("na" %in% tolower(remove)) convert[which(tolower(remove) %in% "na")] <- NA
if(any(is.na(convert))) { naCh <- tolower(x) %in% "na" | tolower(x) %in% "nan"
if(any(naCh)) x[which(naCh)] <- NA}
if("NA" %in% remove | any(is.na(remove))) {chNa <- is.na(x); if(any(chNa)) x <- x[-1*which(chNa)]}
aa <- c("[[:digit:]]+\\.[[:digit:]]+$","[[:digit:]]+$")
ab <- paste0("^",rep(c("","\\+ *","\\- *"),each=2),rep(aa,3))
check <- grep(paste(ab,collapse="|"),x)
if(sciIncl) {
ac <- c("[[:digit:]]+","[[:digit:]]+\\.[[:digit:]]+")
ac <- matrix(c(rep("^",24),rep(c("","\\+ *","\\- *"),8),rep(ac,12),rep(c("E","e"),each=12),rep(c("","","-","-"),6),rep(ac[1],24),rep("$",24)),nrow=24)
ac <- apply(ac,1,paste,collapse="")
check2 <- unlist(sapply(ac,grep,x))
check <- sort(unique(c(check,check2))) }
## include NAs to check (unless specified to remove)
chNa <- is.na(x)
if(!any(is.na(remove)) & any(chNa)) check <- sort(unique(c(check,which(chNa))))
## option remove all character entries
if(length(remove) >0) {
msg <- NULL
if(any(is.na(remove))) { chNa <- is.na(x)
if(any(chNa)) {x <- x[-1*which(chNa)]
msg <- c(" remove ",sum(chNa)," NAs !")
check <- check[-1*which(check %in% which(chNa))]} }
if("allChar" %in% remove) { x <- if(length(check) >0) x[check] else NULL
if(length(x) -length(check) >0) msg <- c(if(length(msg) >0) c(msg," ;")," remove 'allChar': ",
length(x) -length(check)," text-elements removed allowing conversion to numeric !")
check <- if(length(x) >0) 1:length(x) else NULL }
if(isFALSE(silent) & length(msg) >0) if(paste(nchar(msg),collapse="") >3) message(fxNa,msg)
}
## option: convert (sparse) character entries to NA
if(length(x) >0) {if(any(c("allChar","sparseChar") %in% convert) & !"allChar" %in% remove) {
msg <- conv <- NULL
if("allChar" %in% convert) { conv <- if(length(check) >0) (1:length(x))[-1*check] else 1:length(x)
if(length(x) >length(check)) msg <- c(" option convert='allChar': replacing ",length(x)-length(check)," character-entries by NA !")
} else if("sparseChar" %in% convert & length(check) > ceiling(length(x)*0.7)) {
conv <- (1:length(x))[-1*check] }
if(length(conv) >0) {
msg <- c(" replacing ",length(conv)," 'sparse' character-entries by NA !")
x[conv] <- NA; check <- sort(unique(c(check,conv))) }
if(length(msg) >0 & isFALSE(silent)) if(paste(nchar(msg),collapse="") >3) message(fxNa,msg)
}
if(length(check) >0) x[check] <- sub(" ","",x[check])
chNa <- is.na(x)
x <- if(length(x) <1) NULL else { if(identical(1:length(x),check)) as.numeric(x) else {
if(identical(1:length(x), sort(unique(check,which(chNa))))) as.numeric(x) else x}}}
} }
x }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/convToNum.R
|
#' get coordinates of values/points in matrix according to filtering condition
#'
#' Get coordinates of values/points in matrix according to filtering condition
#'
#' @param mat (matrix or data.frame) matrix or data.frame
#' @param cond (logical or integer) condition/test to see which values of \code{mat} fulfull test, or integer of index passing
#' @param sortByRows (logical) optional sorting of results by row-index
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of message(s) produced
#' @return matrix columns 'row' and 'col'
#' @seealso \code{\link[base]{which}}
#' @examples
#' set.seed(2021); ma1 <- matrix(sample.int(n=40,size=27,replace=TRUE), ncol=9)
#' ## let's test which values are >37
#' which(ma1 >37) # doesn't tell which row & col
#' coordOfFilt(ma1, ma1 >37)
#'
#' @export
coordOfFilt <- function(mat, cond, sortByRows=FALSE, silent=FALSE, callFrom=NULL) {
## get coordinates of values/points in matrix according to filtering condition
fxNa <- .composeCallName(callFrom, newNa="coordOfFilt")
if(any(length(dim(mat)) !=2, dim(mat) < 2:1)) stop("Invalid argument 'mat'; must be matrix or data.frame with min 2 lines and 1 col")
cond <- if(is.logical(cond)) which(cond) else as.integer(cond)
chNa <- is.na(cond)
if(any(chNa)) cond <- cond[which(!chNa)]
if(min(cond) <1 | max(cond) > prod(dim(mat))) stop("invalid entry for 'cond'")
## main
out <- cbind(row=cond %% nrow(mat), col=(cond +nrow(mat) -1) %/% nrow(mat))
ch0 <- out[,1]==0 # need to replace row=0
if(any(ch0)) out[which(ch0)] <- nrow(mat)
if(length(unique(names(cond)))==length(cond)) rownames(out) <- names(cond)
if(sortByRows) out <- out[order(out[,1], decreasing=FALSE), ]
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/coordOfFilt.R
|
#' Correct vector to unique
#'
#' \code{correctToUnique} checks 'x' for unique entries, while maintaining the original length. If necessary a counter will added to non-unique entries.
#' @param x input character vector
#' @param sep (character) separator used when adding counter
#' @param atEnd (logical) decide location of placing the counter (at end or at beginning of initial text)
#' @param maxIter (numeric) max number of iterations
#' @param NAenum (logical) if \code{TRUE} all \code{NA}s will be enumerated (NA_1,NA_2,...)
#' @param silent (logical) suppress messages
#' @param callFrom (character) for better tracking of use of functions
#' @return This function returns a character vector
#' @seealso \code{\link[base]{unique}} will simply remove repeated elements, ie length of 'x' won't remain constant, \code{\link{filtSizeUniq}} is more complex and slower, \code{\link{treatTxtDuplicates}}
#' @examples
#' correctToUnique(c("li0","n",NA,NA,rep(c("li2","li3"),2),rep("n",4)))
#' @export
correctToUnique <- function(x, sep="_", atEnd=TRUE, maxIter=4, NAenum=TRUE, silent=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="correctToUnique")
chNA <- is.na(x)
if(length(NAenum) >1) NAenum <- as.logical(NAenum[1])
if(NAenum && any(chNA)) x[which(chNA)] <- "NA"
dupR <- duplicated(x, fromLast=FALSE)
dupL <- duplicated(x, fromLast=TRUE)
anyDu <- anyDx <- dupL | dupR
if(any(anyDu)) { anyDu <- which(anyDu)
xIni <- x
x[which(!dupR & dupL)] <- if(atEnd) paste(x[which(!dupR & dupL)],"1",sep=sep) else paste("1",x[which(!dupR & dupL)],sep=sep)
dupRx0 <- dupR[anyDu]
iter <- 2
finished <- FALSE
while(iter <= maxIter & !finished){
dupRX <- duplicated(x[anyDu], fromLast=FALSE)
if(any(dupRX)) {sel <- which(!dupRX & dupRx0); x[anyDu[sel]] <- if(atEnd) paste(x[anyDu[sel]],iter,sep=sep) else paste(iter,x[anyDu[sel]],sep=sep)
iter <- iter + 1
dupRx0 <- dupRX
} else {x[anyDu[which(dupRx0)]] <- if(atEnd) paste(x[anyDu[which(dupRx0)]],iter,sep=sep) else paste(iter,x[anyDu[which(dupRx0)]],sep=sep)
finished <- TRUE} }
if(!NAenum) if(any(chNA)) x[which(chNA)] <- NA
if(!finished) {
xTab <- table(xIni[anyDu])[rank(unique(xIni[anyDu]))]
if(any(xTab >maxIter)) for(i in names(xTab)[which(xTab > maxIter)]) {
z <- which(x==i); x[z] <- if(atEnd) paste(x[z],(maxIter +1):xTab[which(names(xTab)==i)],sep=sep) else paste((maxIter +1):xTab[i],x[z],sep=sep)}}}
x }
#' Check regression arguments
#'
#' This function is an enhanced version of \code{unique}, names of elements are maintained
#'
#' @param x (numeric or character vector) main input
#' @param splitSameName (logical)
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @param debug (logical) additional messages for debugging
#' @return vector like input
#' @seealso \code{\link[base]{unique}}
#' @examples
#' aa <- c(a=11, b=12,a=11,d=14, c=11)
#' .uniqueWName(aa)
#' .uniqueWName(aa[-1]) # value repeated but different name
#' @export
.uniqueWName <- function(x, splitSameName=TRUE, silent=TRUE, debug=FALSE, callFrom=NULL){
## enhanced version of unique(): return unique of vector 'x' with names (if multiple names fit to same value of 'x', use 1st of names)
## assumes that names of 'x' are redundant to value of 'x'
## 'splitSameName' .. allows keeping different names, even if with same value in 'x' (which would disappear with unique(x))
fxNa <- .composeCallName(callFrom, newNa=".uniqueWName")
argNa <- deparse(substitute(x))
inv <- FALSE
if(length(unique(x)) < length(unique(names(x)))) {
if(splitSameName){
if(!silent) message(fxNa,"'",argNa,"' has more names than different values, maintaining different names")
tmp <- names(x)
names(tmp) <- x
x <- tmp
inv <- TRUE
} else if(!silent) message(fxNa,"Names of '",argNa,"' don't fit to its values, ",
"result not representative, rather use argument 'splitSameName'=TRUE")
}
out <- sapply(unique(x), function(z) x[which(x==z)[1]])
if(is.character(x)) names(out) <- substr(names(out), nchar(out) +2, nchar(names(out)))
if(inv){
tmp <- names(out)
names(tmp) <- out
out <- tmp }
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/correctToUnique.R
|
#' Correct mixed slash and backslash in file path
#'
#' @description
#' This function corrects paths character strings for mixed slash and backslash in file path.
#' In Windows the function \code{tempdir()} will use double backslashes as separator while \code{file.path()} uses regular slashes.
#' So when combining these two one might encounter a mix of slashes and double backslashes which may cause trouble, unless this is streightened out to a single separator used.
#' When pointig to given files inside html-files, paths need to have a prefix, this can be added using the argument \code{asHtml}.
#'
#' @param x (character) input path to test and correct
#' @param asHtml (logical) option for use in html : add prefix "file:/"
#' @param anyPlatf (logical) if \code{TRUE}, checking will only be performed in Windows environement
#' @param silent (logical) suppress messages
#' @param callFrom (character) allows easier tracking of message(s) produced
#' @return character vector with corrected path
#' @seealso \code{\link[base]{tempfile}}, \code{\link[base]{file.path}}
#' @examples
#' path1 <- 'D:\\temp\\Rtmp6X8/working_dir\\RtmpKC/example.txt'
#' (path1b <- correctWinPath(path1, anyPlatf=TRUE))
#' (path1h <- correctWinPath(path1, anyPlatf=TRUE, asHtml=TRUE))
#' @export
correctWinPath <- function(x, asHtml=FALSE, anyPlatf=FALSE, silent=TRUE, callFrom=NULL) {
## correct mixed slash and backslash in file path
fxNa <- .composeCallName(callFrom,newNa="correctWinPath")
if(anyPlatf | length(grep("ming.32", R.Version()$platform)) >0) {
x <- gsub("\\\\","/",x) #"
if(asHtml & length(grep("[[:upper:]]:", substr(x,1,2))) >0) {
x <- paste("file:///",x,sep="") }
}
if(asHtml & length(grep("^/",x)) >0) x <- paste("file:///", x, sep="")
x }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/correctWinPath.R
|
#' Count from two vectors number of values close within given limits
#'
#' This functions summarizes the serach of similar (or identical) numeric values from 2 initial vectors, it
#' evaluates the result from initial search run by findCloseMatch(), whose output is a less convenient list.
#' \code{countCloseToLimits} checks furthermore how many results within additional (more stringent)
#' distance-limits may be found and returns the number of distance values within the limits tested.
#' Designed for checking if threshold used with findCloseMatch() may be set more stringent, eg when searching reasonable FDR limits ...
#'
#' @param closeMatch (list) output from findCloseMatch(), ie list indicating which instances of 2 series of data have close matches
#' @param limitIdent (numeric) max limit or panel of threshold values to test (if single value, in addtion a panel with values below will be tested)
#' @param prefix (character) prefix for names of output
#' @return integer vector with counts for number of list-elements with at least one absolue value below threshold, names
#' @seealso \code{\link[wrMisc]{findCloseMatch}}
#' @examples
#' set.seed(2019); aa <- sample(12:15,20,repl=TRUE) +round(runif(20),2)-0.5
#' bb <- 11:18
#' match1 <- findCloseMatch(aa,bb,com="diff",lim=0.65)
#' head(match1)
#' (tmp3 <- countCloseToLimits(match1,lim=c(0.5,0.35,0.2)))
#' (tmp4 <- countCloseToLimits(match1,lim=0.7))
#' @export
countCloseToLimits <- function(closeMatch,limitIdent=5,prefix="lim_") {
limitIdent <- unique(limitIdent)
if(length(limitIdent) ==1) {x <- floor(log10(signif(limitIdent,1)))
x <- c(10^c((x-1):x),10^c((x-1):x)/5,4*round(seq(limitIdent/40,limitIdent/4,length.out=20),2),limitIdent) # default series of limits
limitIdent <- unique(signif(sort(x),digits=5)) }
if(length(closeMatch) <1 | length(limitIdent) <1) { out <- rep(NA,length(limitIdent))
} else {
out <- rowSums(sapply(closeMatch,function(z) (min(abs(z)) <= limitIdent)))}
if(is.null(names(out))) names(out) <- paste(prefix,limitIdent,sep="")
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/countCloseToLimits.R
|
#' Count same start- and end- sites of edges (or fragments)
#'
#' Suppose a parent sequence/string 'ABCDE' gets cut in various fragments (eg 'ABC','AB' ...).
#' \code{countSameStartEnd} counts how many (ie re-occuring) start- and end- sites of edges do occur in the input-data.
#' The input is presented as matrix of/indicating start- and end-sites of edges.
#' The function is used to characterize partially redundant edges and accumulation of cutting/breakage sites.
#' @param frag (matrix) 1st column \code{beg} start-sites, 2nd column \code{end} end-sites of edges, rownames to precise fragment identities are recommended
#' @param minFreq (integer) min number of accumulated sites for taking into account (allows filtering with large datasets)
#' @param nDig (integer) rounding: number of digits for columns \code{beg.rat} and \code{end.rat} in output
#' @return matrix of 6 columns: input (beg and end), beg.n, beg.rat, end.n, end.rat
#' @seealso to build initial tree \code{\link{buildTree}}, \code{\link{contribToContigPerFrag}}, \code{\link{simpleFragFig}}
#' @examples
#' frag1 <- cbind(beg=c(2,3,7,13,13,15,7,9,7, 3,3,5), end=c(6,12,8,18,20,20,19,12,12, 4,5,7))
#' rownames(frag1) <- letters[1:nrow(frag1)]
#' countSameStartEnd(frag1)
#' simpleFragFig(frag1)
#' @export
countSameStartEnd <- function(frag,minFreq=2,nDig=4) {
if(!is.matrix(frag)) frag <- as.matrix(frag)
if(is.null(rownames(frag))) rownames(frag) <- paste("li",1:nrow(frag),sep="") else {
frag <- frag[sort.list(rownames(frag)),]}
chTab <- function(tab) {chT <- tab > minFreq-1; if(any(chT)) tab[which(chT)] else NULL}
headT <- chTab(table(frag[,1]))
tailT <- chTab(table(frag[,2]))
out <- matrix(nrow=nrow(frag),ncol=2)
if(length(headT) >0) { tmp <- which(frag[,1] %in% names(headT)); out[tmp,1] <- as.integer(as.character(factor(frag[tmp,1],labels=headT)))}
if(length(tailT) >0) { tmp <- which(frag[,2] %in% names(tailT)); out[tmp,2] <- as.integer(as.character(factor(frag[tmp,2],labels=tailT)))}
cbind(frag,beg.n=out[,1],beg.rat=signif(out[,1]/nrow(frag),digits=nDig), end.n=out[,2],end.rat=signif(out[,2]/nrow(frag),digits=nDig))
}
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/countSameStartEnd.R
|
#' Cut 3-dim array in list of matrixes (or arrays) similar to organizing into clusters
#'
#' \code{cutArrayInCluLike} cuts 'dat' (matrix,data.frame or 3-dim array) in list (of appended lines) according to 'cluOrg',
#' which serves as instruction which line of 'dat' should be placed in which list-element (like sorting according to cluster-numbers).
#' @param dat array (3 dim)
#' @param cluOrg (factor) organization of lines to 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 retruns a list of matrixes (or arrays)
#' @examples
#' mat1 <- matrix(1:30,nc=3,dimnames=list(letters[1:10],1:3))
#' cutArrayInCluLike(mat1,cluOrg=factor(c(2,rep(1:4,2),5)))
#' @export
cutArrayInCluLike <- function(dat, cluOrg, silent=FALSE, debug=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="cutArrayInCluLike")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
msg2 <- " 'cluOrg' should be factor or numeric vector corresponding to lines of 'dat', ie instruction which line of 'dat' to put in which list-element (cluster)"
che <- dim(dat)
if(!length(che) %in% c(2,3)) stop(fxNa,"Expecting matrix or data.frame of 2 or array of 3 dimensions")
if(is.null(cluOrg)) stop(fxNa,msg2)
if(length(cluOrg) != nrow(dat)) stop(fxNa,msg2)
uniqNa <- unique(naOmit(cluOrg))
out <- list()
for(i in 1:length(uniqNa)) out[[i]] <- if(length(che) ==3){
dat[which(cluOrg==uniqNa[i]),,]
} else {
dat[which(cluOrg==uniqNa[i]),] }
names(out) <- uniqNa
out }
#' Combine annotation information from list of matrixes
#'
#' This function allows to combine information (annotation) from list of matrixes (ie replace when NA), using always the columns specified in 'useCol' (numeric)
#'
#' @param lst (list) main input
#' @param useCol (numeric vector) which columns should be used
#' @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 single matrix of combined (non-redundant) info
#' @seealso used in \code{\link{cutArrayInCluLike}}
#' @examples
#' .datSlope(c(3:6))
#' @export
.combineListAnnot <- function(lst, useCol=1:2, silent=FALSE, debug=FALSE, callFrom=NULL){
## combine information (annotation) from list of matrixes (ie replace when NA), using always the columns specified in 'useCol' (numeric)
## the 1st elment of 'useCol' will be used as to select column used as key for merging
## return single matrix of combined (non-redundant) info
fxNa <- .composeCallName(callFrom, newNa=".combineListAnnot")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(length(useCol) <2) stop(fxNa,"Need at least 2 columns numbers in 'useCol' (1st col specified used as key)")
cheDim <- sapply(lst, dim)
if(is.list(cheDim)) {
lst <- lst[sapply(cheDim, length) >1]
cheDim <- sapply(lst, dim)}
if(is.list(cheDim)) {
cheDim3 <- sapply(cheDim, length)
if(any(cheDim3 >2)) message(fxNa,"So far not coded for arrays with >2 dims")
lst <- lst[sapply(cheDim,length) <3] }
if(length(lst) <1) stop(fxNa,"No (valuable) matrixes or data.frames found in 'lst'")
cheDim <- sapply(lst, dim)
if(any(cheDim[1,] <0)) {message(fxNa,"Omiting 0-row elements"); lst <- lst[cheDim[1,] >0]}
if(any(max(useCol) > cheDim[2,])) stop(fxNa,"Column no specified in 'useCol' seems not to exist")
## main
colNa1 <- colnames(lst[[1]])[useCol]
if(!silent) message(fxNa," .combineListAnnot() .. checking ",length(lst)," list-elements; '",
colNa1[1],"' will be used as key")
out <- as.matrix(lst[[1]][,useCol])
if(length(lst) >1) for(i in 2:length(lst)) {
compColNa <- sort(colnames(lst[[i]])[useCol]) == sort(colNa1) # compare col-names (too strict ??)
if(all(compColNa)) { # for optional testing if col-names do indeed match
out <- as.matrix(merge(out,lst[[i]][,useCol], by=colNa1[1],all=TRUE))
NaLi <- which(is.na(out[,2]))
for(j in 2:length(useCol)) out[NaLi,j] <- out[NaLi,length(useCol)+j-1] }
out <- out[,1:length(useCol)] }
stripColNa <- sub(".x$","",colnames(out))
if(length(unique(stripColNa)) ==ncol(out)) colnames(out) <- stripColNa
out }
#' Check list of arrays for consistent dimensions of all arrays
#'
#' This function allows to check list of arrays for consistent dimensions of all arrays
#'
#' @param arrLst (list) main input
#' @param arrNDim (integer) number of dimensions for arrays
#' @param fxName (character) this name will be given in message
#' @param varName (character)
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @param debug (logical) additional messages for debugging
#' @return list
#' @seealso used in \code{\link{cutArrayInCluLike}}
#' @examples
#' .datSlope(c(3:6))
#' @export
.checkConsistentArrList <- function(arrLst, arrNDim=3, fxName=NULL, varName=NULL, silent=FALSE, debug=FALSE, callFrom=NULL) {
## check list of arrays for consistent dimensions of all arrays
## arrNDim .. number of dimensions for arrays
## fxName will be given in message
fxNa <- .composeCallName(callFrom, newNa=".checkConsistentArrList")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
che <- sapply(arrLst, dim)
if(!is.null(fxName)) fxName <- paste(fxName,": ")
if(!is.null(varName)) varName <- "'arrLst'"
if(is.list(che)) stop(fxName,"Format of '",varName,"' seems not consistent")
if(any(nrow(che) != arrNDim)) stop(fxName,"Expecting list of ",paste(arrNDim,collapse=", ")," dim arrays in ",varName)
if(any(apply(che, 1, function(x) length(unique(x)))) !=1) message(fxName,"Format of ",varName," seems not consistent")
}
#' Summarize along columns of multiple arrays in list
#'
#' This function allows summarizing along columns of multiple arrays in list
#'
#' @param arrLst (list) main input
#' @param sumType (character)
#' @param arrOutp (logical)
#' @param signifDig (integer)
#' @param formatCheck (logical)
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @param debug (logical) additional messages for debugging
#' @return array (1st dim will be summary along cols, rows will be layers of 3rd array-dim
#' @seealso used in \code{\link{cutArrayInCluLike}}
#' @examples
#' .datSlope(c(3:6))
#' @export
.arrLstMean <- function(arrLst, sumType="mean", arrOutp=FALSE, signifDig=3,formatCheck=FALSE,silent=FALSE, debug=FALSE, callFrom=NULL){
## summarize along columns of mult arrays in list
## can summarize as median or mean
## resultant 1st dim will be summary along cols, rows will be layers of 3rd array-dim ie dim(arrLst[[1]])[3]
## eg expr data as clusters (list-elements)
fxNa <- .composeCallName(callFrom, newNa=".arrLstMean")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(formatCheck) .checkConsistentArrList(arrLst, fxName=fxNa)
diNa <- dimnames(arrLst[[1]])
out <- if(sumType=="median") {
lapply(arrLst, function(x) t(signif(apply(x,c(2,3), stats::median, na.rm=TRUE), signifDig)) )
} else {
lapply(arrLst, function(x) t(signif(apply(x, 3, colMeans, signifDig))) ) }
if(is.list(out)) names(out) <- names(arrLst)
if(arrOutp) out <- aperm(array(unlist(lapply(out,t)), dim=c(dim(arrLst[[1]])[-1], length(arrLst)),
dimnames=list(diNa[[2]], diNa[[3]], names(arrLst))), c(2,1,3))
out }
#' Summarize along columns of mult arrays in list
#'
#' This function allows summarizing along columns of mult arrays in list
#'
#' @param arrLst (list) main input
#' @param arrOutp (logical)
#' @param signifDig (integer)
#' @param formatCheck (logical)
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @param debug (logical) additional messages for debugging
#' @return array (1st dim will be summary along cols, rows will be layers of 3rd array-dim ie dim(arrLst[[1]])[3])
#' @seealso used in \code{\link{cutArrayInCluLike}}
#' @examples
#' .datSlope(c(3:6))
#' @export
.arrLstSEM <- function(arrLst, arrOutp=FALSE, signifDig=3, formatCheck=FALSE, silent=FALSE, debug=FALSE, callFrom=NULL){
## summarize along columns of mult arrays in list
## can summarize as median or mean
## resultant 1st dim will be summary along cols, rows will be layers of 3rd array-dim ie dim(arrLst[[1]])[3]
## eg expr data as clusters (list-elements)
fxNa <- .composeCallName(callFrom, newNa=".arrLstSEM")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(formatCheck) .checkConsistentArrList(arrLst, fxName=fxNa)
diNa <- dimnames(arrLst[[1]])
out <- lapply(arrLst, function(x) t(apply(aperm(x,c(2,1,3)), 3, rowSEMs)) )
if(is.list(out)) names(out) <- names(arrLst)
if(arrOutp) out <- aperm(array(unlist(lapply(out,t)), dim=c(dim(arrLst[[1]])[-1],length(arrLst)),
dimnames=list(diNa[[2]], diNa[[3]], names(arrLst))), c(2,1,3))
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/cutArrayInCluLike.R
|
#' Cut character-vector at multiple sites
#'
#' This function cuts character vector after 'cutAt' (ie keep the search subtsting 'cutAt', different to \code{strsplit}).
#' Used for theoretical enzymatic digestion (eg in proteomics)
#' @param y character vector (better if of length=1, otherwise one won't know which fragment stems from which input)
#' @param cutAt (character) search subtsting, ie 'cutting rule'
#' @return modified (ie cut) character vector
#' @seealso \code{\link[base]{strsplit}}, \code{\link[wrMisc]{nFragments0}}, \code{\link[wrMisc]{nFragments}}
#' @examples
#' tmp <- "MSVSRTMEDSCELDLVYVTERIIAVSFPSTANEENFRSNLREVAQMLKSKHGGNYLLFNLSERRPDITKLHAKVLEFGWPDLHTPALEKI"
#' cutAtMultSites(c(tmp,"ojioRij"),c("R","K"))
#' @export
cutAtMultSites <- function(y,cutAt) {
for(i in cutAt) {y <- strsplit(y,i); y <- as.character(unlist(sapply(y, .addLetterWoLast, addChr=i)))}; y}
#' Add letter to all elements but not last
#'
#' This function allows to add 'addChr' to all entries, without the last entry
#'
#' @param x (character) main input
#' @param addChr (character)
#' @return This function returns a modified character vector
#' @seealso \code{\link[base]{paste}}; used in \code{\link{cutAtMultSites}}
#' @examples
#' .addLetterWoLast(c("abc","efgh"),"Z")
#' @export
.addLetterWoLast <- function(x, addChr) paste0(x,rep(c(addChr,""),c(length(x)-1,1))) # add 'addChr' to all entries wo last entry
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/cutAtMultSites.R
|
#' Cut numeric vector to n groups (ie convert to factor)
#'
#' \code{cutToNgrp} is a more elaborate version of \code{\link[base]{cut}} for cutting a the content of a
#' numeric vector '\code{x}' into a given number of groups, taken from the length of '\code{lev}'.
#' Besides, this function provides the group borders/limits for convention use with legends.
#'
#' @param x numeric vector
#' @param lev (character or numeric), the length of this argument tells the number of groups to be used for cutting
#' @param NAuse (logical) include NAs as separate group
#' @param callFrom (character) for better tracking of use of functions
#' @return list with \code{$grouped} telling which element of '\code{x}' goes in which group and \code{$legTxt} with gourp-borders for convenient use with legends
#' @seealso \code{\link[base]{cut}}
#' @examples
#' set.seed(2019); dat <- runif(30) +(1:30)/2
#' cutToNgrp(dat,1:5)
#' plot(dat,col=(1:5)[as.numeric(cutToNgrp(dat,1:5)$grouped)])
#' @export
cutToNgrp <- function (x, lev, NAuse=FALSE,callFrom=NULL) {
##
fxNa <- .composeCallName(callFrom,newNa="cutToNgrp")
ra <- range(x, na.rm=TRUE)
if(length(lev) <2) message(fxNa," 'lev' indicates to make only ",length(lev)," groups, do you really want this ?")
if(diff(ra) > 0) {
ndig <- round(1.5+log(length(lev)))
br <- signif(seq(ra[1] -diff(ra)*0.001, ra[2]+diff(ra)*0.001, length.out=length(lev) +1), digits=ndig)
if(max(br) < ra[2]) br[length(br)] <- signif(br[length(br)] +(br[2] -br[1])/12, digits=ndig)
chBr <- duplicated(br,fromLast=FALSE)
if(any(chBr)) {
br <- signif(seq(ra[1] -diff(ra)*0.001, ra[2], length.out=length(lev) +1), digits=ndig +1)
chBr <- duplicated(br,fromLast=FALSE)
if(any(chBr)) {
whRep <- !chBr
br[which(chBr)] <- br[which(chBr)] +ra[1]/1e6 }}
intGrp <- cut(x, br)
} else intGrp <- rep(1, length(x))
legTx <- matrix(sub("\\]", "", sub("\\(","", unlist(sapply(levels(intGrp), strsplit, ",")))), ncol=2, byrow=TRUE)
lowVa <- signif(ra[1], 1)
if(lowVa <= ra[1]) legTx[1,1] <- lowVa
legTx <- matrix(signif(as.numeric(legTx), digits=round(0.5+log(length(lev)))), ncol=2, dimnames=list(lev,c("from","to")))
if(NAuse) if (any(is.na(x))) {
levels(intGrp) <- c(levels(intGrp), "NA")
intGrp[which(is.na(intGrp))] <- "NA"
legTx <- rbind(legTx, c("NA", "NA"))
}
list(grouped=intGrp, legTxt=legTx)
}
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/cutToNgrp.R
|
#' Compute matrix of differences for all pairwise combinations of numeric vector
#'
#' \code{diffCombin} returns matrix of differences (eg resulting from subsititution) for all pairwise combinations of numeric vector 'x'.
#'
#' @param x numeric vector to compute differences for all combinations
#' @param diagAsNA (logical) return all self-self combinations as NA (otherwise 0)
#' @param prefix (logical) if TRUE, dimnames of output will specify orientation (prefix='from.' and 'to.')
#' @param callFrom (character) allow easier tracking of message(s) produced
#' @param silent (logical) suppress messages
#' @return numeric matrix of all pairwise differences
#' @seealso \code{\link[base]{diff}} for simple differences
#' @examples
#' diffCombin(c(10,11.1,13.3,16.6))
#' @export
diffCombin <- function(x,diagAsNA=FALSE,prefix=TRUE,silent=FALSE,callFrom=NULL) {
fxNa <- .composeCallName(callFrom,newNa="diffCombin")
if(!is.numeric(x)) x <- convToNum(x,remove=NULL,sciIncl=TRUE,callFrom=fxNa,silent=silent)
if(is.null(names(x))) names(x) <- sprintf(paste("%0",nchar(length(x)),"d",sep=""),1:length(x))
diNa <- if(prefix) list(paste("to",names(x),sep="."),paste("from",names(x),sep=".")) else list(names(x),names(x))
out <- matrix(rep(x,length(x)),nrow=length(x),dimnames=diNa) -matrix(rep(x,each=length(x)),nrow=length(x))
if(diagAsNA) diag(out) <- NA
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/diffCombin.R
|
#' Difference in ppm between numeric values
#'
#' This is a \code{diff()}-like function to return difference in ppm between subsequent values.
#' Result is oriented, ie neg ppm value means decrease (from higher to lower value). Note that if the absolute difference remains the same the difference in ppm will not remain same.
#' Any difference to NA is returned as NA, thus a single NA will result in two NAs in output (unless NA is 1st or last).
#'
#' @param dat (numeric) vector for calculating difference to preceeding/following value in ppm
#' @param toPrev (logical) determine oriention
#' @param silent (logical) suppress messages
#' @param callFrom (character) allows easier tracking of messages produced
#' @return This function returns a 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)
#' @seealso \code{\link{checkSimValueInSer}} and (from this package) \code{.compareByDiff}, \code{\link[base]{diff}}
#' @examples
#' aa <- c(1000.01, 1000.02, 1000.05, 1000.08, 1000.09, 1000.08)
#' .compareByPPM(list(aa,aa), 30, TRUE) # tabular 'long' version
#' diffPPM(aa)
#' @export
diffPPM <- function(dat, toPrev=FALSE, silent=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom,newNa="diffPPM")
if(!is.numeric(dat)) dat <- try(as.numeric(if(is.factor(dat)) as.character(dat) else dat), silent=TRUE)
if(inherits(dat, "try-error")) { if(!silent) message(fxNa,"Can't convert 'dat' to numeric !"); return(NULL)
} else {
rat <- if(toPrev) dat[-1]/dat[-length(dat)] else dat[-length(dat)]/dat[-1]
(2*(dat[-1] > dat[-length(dat)])-1)*abs(rat -1)/1e-6}}
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/diffPPM.R
|
#' Eliminate close (overlapping) points (in x & y space)
#'
#' \code{elimCloseCoord} reduces number of rows in 'dat' by eliminating lines where x & y coordinates (columns of matrix '\code{dat}' defined by '\code{useCol}') are identical (overlay points) or very close.
#' The stringency for 'close' values may be fine-tuned using \code{nDig}), this function uses internally \code{\link{firstOfRepeated}}.
#'
#' @param dat matrix (or data.frame) with main numeric input
#' @param useCol (numeric) index for numeric columns of 'dat' to use/consider
#' @param elimIdentOnly (logical) if TRUE, eliminate real duplicated points only (ie identical values only)
#' @param refine (numeric) allows increasing stringency even further (higher 'refine' .. more lines considered equal)
#' @param nDig (integer) number of significant digits used for rounding, if two 'similar' values are identical after this rounding the second will be eliminated.
#' @param silent (logical) suppress messages
#' @param callFrom (character) allows easier tracking of message(s) produced
#' @return resultant matrix/data.frame
#' @seealso \code{\link{findCloseMatch}}, \code{\link{firstOfRepeated}}
#' @examples
#' da1 <- matrix(c(rep(0:4,5),0.01,1.1,2.04,3.07,4.5),nc=2); da1[,1] <- da1[,1]*99; head(da1)
#' elimCloseCoord(da1)
#' @export
elimCloseCoord <- function(dat,useCol=1:2,elimIdentOnly=FALSE,refine=2,nDig=3,callFrom=NULL,silent=FALSE){
fxNa <- .composeCallName(callFrom,newNa="elimCloseCoord")
argN <- deparse(substitute(x))
refine <- 1/refine
if(is.null(rownames(dat))) rownames(dat) <- 1:nrow(dat)
firstOfRep <- firstOfRepeated(paste(dat[,useCol[1]],dat[,useCol[2]],sep="_"))$indUniq
if(!elimIdentOnly) {
if(nDig <3) message(fxNa," the stringency chosen (of ",nDig," significant digits) is very high, you may consider using 'nDig' values higher than 2 !")
dat1 <- as.matrix(dat[,useCol])
if(is.character(dat1)) dat1 <- matrix(as.numeric(dat1),ncol=2)
nDig <- lapply(as.data.frame(dat1), function(x) signif(max(x,na.rm=TRUE),nDig) ) # numb of digits after decimal for max
nDig <- sapply(nDig,function(x) nchar(x)-nchar(round(x))-1)
nDig[nDig <0] <- 0
firstOfRep <- firstOfRepeated(paste(round(refine*dat1[,1],nDig[1]),
round(refine*dat1[,2],nDig[2]),sep="_"))$indUniq
if(!silent) message(fxNa," reducing '",argN,"' from ",nrow(dat)," to ",length(firstOfRep)," lines")
dat <- dat[firstOfRep,] }
dat }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/elimCloseCoord.R
|
#' Equal character-length number
#'
#' \code{equLenNumber} convert numeric entry 'x' to text, with all elements getting the same number of characters (ie by adding preceeding or tailing 0s, if needed).
#' So far, the function cannot handle scientific annotations.
#'
#' @param x (caracter) input vector
#' @param silent (logical) suppress messages
#' @param debug (logical) additional messages for debugging
#' @param callFrom (character) allow easier tracking of messages produced
#' @return character vector formated as equal number of characters per value
#' @seealso \code{\link[base]{sprintf}}
#' @examples
#' equLenNumber(c(12,-3,321))
#' equLenNumber(c(12,-3.3,321))
#' @export
equLenNumber <- function(x, silent=FALSE, callFrom=NULL, debug=FALSE){
fxNa <- .composeCallName(callFrom, newNa="equLenNumber")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
x <- sub("^ +","",sub(" +$","",x)) # remove heading or tailing spaces
check1 <- grep("^[[:digit:]]+$|^\\-[[:digit:]]+$",x) # use as integer
check2 <- grep("^[[:digit:]]+\\.[[:digit:]]+$|^[[:digit:]]+$|^-[[:digit:]]+$|^-[[:digit:]]+\\.[[:digit:]]+$",x) # other numeric (wo exponent)
if(length(check2) < length(x) && !silent) message(fxNa," ",length(x)-length(check2)," out of ",length(x)," entries can't be transformed to numeric")
x <- as.numeric(x)
if(length(check1) ==length(x)) sprintf(paste("%0",max(nchar(as.character(x))),"d",sep=""),x) else {
sprintf(paste("%0",max(nchar(as.character(x))+1),".",max(nchar(gsub("\\.","",gsub("^[[:digit:]]+","",gsub("^-","",x))))),"f",sep=""),x)}
}
#' Convert to simple vector (similar to unlist)
#'
#' This function allows converting 'dat' (may be list, data.frame etc) to simple vector, more elaborate than unlist()
#'
#' @param dat (list, data.frame) main input
#' @param toNumeric (logical)
#' @return character (or numeric) vector
#' @seealso \code{\link[base]{unlist}}; used in \code{\link{equLenNumber}}
#' @examples
#' aa <- matrix(11:14, ncol=2)
#' .checkConvt2Vect(aa)
#' @export
.checkConvt2Vect <- function(dat, toNumeric=TRUE) {
## convert 'dat' (may be list, data.frame etc) to simple vector, more elaborate unlist()
## if 'toNumeric'=FALSE only the 1st column of a matrix or data.frame will be extracted !!
## list names will be passed on (list-elements longer than 1 will get number-extesions)
if(is.data.frame(dat)) dat <- as.matrix(dat)
if(is.list(dat)) {
datNa <- names(dat)
dat <- unlist(dat)
if(length(dat) ==length(datNa)) names(dat) <- datNa}
if(is.matrix(dat)) {
rowNa <- rownames(dat)
dat <- if(toNumeric) as.numeric(dat) else dat[,1]
if(!is.null(rowNa)) names(dat) <- rowNa }
dat }
#' Compose sequence of (function-)calls
#'
#' This function was designed for tracing the hierarchy of function-calls.
#' It allows to remove any tailing space or ': ' from 'callFrom' (character vector) and return with added 'newNa' (+ 'add2Tail')
#'
#' @param newNa (character vector) main input
#' @param add2Head (character)
#' @param add2Tail (character)
#' @param callFrom (character) may also contain multiple separate names (ie length >1), will be concatenated using ' -> '
#' @return character vector (history of who called whom)
#' @seealso \code{\link[base]{paste}}
#' @examples
#' .composeCallName("newFunction", callFrom="initFunction")
#' @export
.composeCallName <- function(newNa, add2Head="", add2Tail=" : ", callFrom=NULL) {
## remove any tailing space or ': ' from 'callFrom' (character vector) and return with added 'newNa' (+ 'add2Tail')
## 'callFrom' may also contain multiple separate names (ie length >1), will be concatenated using ' -> '
## used for building history of who called whom ...
if(length(callFrom) >0) {
callFrom <- sub("[[:blank:]]+$","", callFrom)
callFrom <- sub("^[[:blank:]]+","", callFrom)
callFrom <- sub("[[:blank:]]:+$","", callFrom)
paste(callFrom, collapse=" -> ")}
fxNa <- paste(c(add2Head, callFrom, if(!is.null(callFrom)) " -> ", newNa, add2Tail), collapse="")
fxNa }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/equLenNumber.R
|
#' Exclude extreme values (based on distance to mean)
#'
#' This function aims to identify extreme values (values most distant to mean, thus potential outlyers), mark them as NA or directely exclude them (depending on '\code{showNAs}').
#' Note that every set of non-identical values will have at least one most extreme value. Extreme values are part of many distributions, they are not necessarily true outliers.
#'
#' @param dat numeric vector, main input
#' @param result (character) may be 'val' for returning data without extreme values or 'pos' for returning position/index of extreme values
#' @param CVlim (NULL or numeric) allows to retain extreme values only if a certain CV (for all 'dat') is exceeded (to avoid calling extreme values form homogenous data-sets)
#' @param maxExcl (integer) max number of elments to explude
#' @param showNA (logical) will display extrelme values as NA
#' @param goodValues (logical) allows to display rather the good values instead of the extreme values
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of message(s) produced
#' @return numeric vector wo extremle values or index-position of extreme values
#' @seealso \code{\link{firstOfRepLines}}, \code{\link{get1stOfRepeatedByCol}} for treatment of matrix
#' @examples
#' x <- c(rnorm(30),-6,20)
#' exclExtrValues(x)
#' @export
exclExtrValues <- function(dat,result="val",CVlim=NULL,maxExcl=1,showNA=FALSE,goodValues=TRUE,silent=FALSE,callFrom=NULL) {
## return position of extreme value (potential outlyer)
## results may be given as position of extreme values ('pos') or as values ('val') without the extremes identified
fxNa <- .composeCallName(callFrom,newNa="exclExtrValues")
extrVal <- which(abs(dat-sum(dat,na.rm=TRUE)/sum(!is.na(dat))) == max(abs(dat-mean(dat,na.rm=TRUE))))
if(length(extrVal) == length(dat) & !silent) message(" all values are equidistant, not possible to distinguish one/some as 'extreme'")
if(length(extrVal) > maxExcl & !silent) message(" more extreme values are equidistant than available for display with 'maxExcl' = ",maxExcl)
if(!is.null(CVlim)) if(!is.finite(as.numeric(CVlim))) {
warning(" 'CVlim' should be numeric of length 1, ignoring current value of 'CVlim'"); CVlim <- NULL}
if(!is.null(CVlim)) {
if(stats::sd(as.numeric(dat),na.rm=TRUE)/mean(as.numeric(dat),na.rm=TRUE) < as.numeric(CVlim)[1]) extrVal <- NA }
extrVal <- naOmit(extrVal)[1:maxExcl]
if(tolower(result) %in% c("val","value")) {
if(showNA) {out <- dat; out[extrVal] <- NA } else out <- dat[-1*extrVal]}
if(tolower(result) %in% c("pos","position")) out <- if(goodValues) (1:length(dat))[-1*extrVal] else extrVal
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/exclExtrValues.R
|
#' Normalize by adjusting exponent
#'
#' This function normalizes 'dat' by optimizing exponent function (ie dat ^exp) to fit best to 'ref' (default: average of each line of 'dat').
#'
#' @param dat matrix or data.frame of numeric data to be normalized
#' @param useExpon (numeric vector or matrix) exponent values to be tested
#' @param dynExp (logical) require 'useExpon' as 2 values (matrix), will gradually increase exponent from 1st to 2nd; may be matrix or data.frame for dynamic,
#' in this case 1st line for exp for lowest data, 2nd line for highest
#' @param nStep (integer) number of exponent variations (steps) when testing range from-to
#' @param startExp (numeric)
#' @param simMeas (character) similarity metric to be used (so far only "cor"), if rSquare=TRRUE, the r-squared will be returned
#' @param refDat (matrix or data.frame) if null average of each line from 'dat' will be used as reference in similarity measure
#' @param refGrp (factor) designing which col of 'ref' should be used with which col of 'dat' (length equal to number of cols in 'dat').
#' Note: 'refGrp' not yet coded optimally to extract numeric part of character vector, protential problems when all lines or cols of dat are NA
#' @param refLines (NULL or integer) optional subset of lines to be considered (only) when determining normalization factors
#' @param rSquare (logical) if \code{TRUE}, add r-squared
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of messages produced
#' @return This functuion returns a matrix of normalized data
#' @seealso more eveolved than \code{\link[wrMisc]{normalizeThis}} with arugment set to 'exponent'
#' @examples
#' set.seed(2016); dat1 <- matrix(c(runif(200)+rep(1:10,20)),nc=10)
#' head(rowGrpCV(dat1,gr=gl(4,3,labels=LETTERS[1:4])[2:11]))
#' set.seed(2016); dat1 <- c(0.1,0.2,0.3,0.5)*rep(c(1,10),each=4)
#' dat1 <- matrix(round(c(sqrt(dat1),dat1^1.5,3*dat1+runif(length(dat1))),2),nc=3)
#' dat2a <- exponNormalize(dat1[,1],useExpon=2,nSte=1,refD=dat1[,3])
#' layout(matrix(1:2,nc=2))
#' plot(dat1[,1],dat1[,3],type="b",main="init",ylab="ref")
#' plot(dat2a$datNor[,1],dat1[,3],type="b",main="norm",ylab="ref")
#' dat2b <- exponNormalize(dat1[,1],useExpon=c(1.7,2.3),nSte=5,refD=dat1[,3])
#' plot(dat1[,1],dat1[,3],type="b",main="init",ylab="ref")
#' plot(dat2b$datNor[,1],dat1[,3],type="b",main="norm",ylab="ref")
#'
#' dat2c <- exponNormalize(dat1[,-3],useExpon=matrix(c(1.7,2.3,0.6,0.8),nc=2),nSte=5,refD=dat1[,3]);
#' plot(dat1[,1],dat1[,3],type="b",main="init",ylab="ref ")
#' plot(dat2c$datNor[,1],dat1[,3],type="b",main="norm 1",ylab="ref")
#' plot(dat1[,2],dat1[,3],type="b",main="init",ylab="ref")
#' plot(dat2c$datNor[,2],dat1[,3],type="b",main="norm 2",ylab="ref");
#' @export
exponNormalize <- function(dat, useExpon, dynExp=TRUE, nStep=20, startExp=1, simMeas="cor", refDat=NULL, refGrp=NULL, refLines=NULL,rSquare=FALSE,silent=FALSE,callFrom=NULL) {
fxNa <- .composeCallName(callFrom,newNa="exponNormalize")
dimDat <- dim(dat)
if(!is.matrix(dat)) dat <- as.matrix(dat)
if(is.null(refDat)) refDat <- matrix(rowMeans(if(length(refLines) < nrow(dat) & !is.null(refLines)) dat[refLines,] else dat, na.rm=TRUE),
ncol=1,dimnames=list(NULL,colnames(dat))) else { message(fxNa,"adj 'refDat to matrix' \n")
if(length(dim(refDat)) <2) refDat <- as.matrix(as.numeric(refDat)) }
if(is.null(refGrp)) refGrp <- rep(1,ncol(dat))
if(length(refGrp) != ncol(dat)) message(fxNa," 'refGrp' (",length(refGrp),") doesn't fit to 'dat' (",ncol(dat)," cols)")
if(max(as.numeric(refGrp),na.rm=TRUE) > ncol(dat)) {
message(fxNa," 'refGrp' suggests columns not found in 'dat' !") }
useExpon <- unique(naOmit(useExpon))
## main
.sw <- function(useExpon,startExp,nStep) { # function for defining new series of 'useExpon'
meth <- paste("m",0 +(length(useExpon) >1) + 2*all(startExp <1),sep="")
switch(meth,
m0=seq(useExpon, startExp, length.out=nStep),
m1=seq(useExpon[1], useExpon[2], length.out=nStep),
m2=seq(startExp, useExpon, length.out=nStep),
m3=seq(useExpon[1], useExpon[2], length.out=nStep) ) }
if(length(dim(useExpon)) >1 & dynExp & nStep >1) { # diff/indep expon series for each col of data
useExpon <- apply(useExpon,2,.sw,startExp,nStep)
if(!silent) message(fxNa," column-specific exponent testing of ",nrow(useExpon)," x ",ncol(useExpon)," exponents")
} else {
if(nStep >1) useExpon <- .sw(useExpon,startExp,nStep)
if(!silent) message(fxNa," static exponent series (length ",length(useExpon),")")}
if(!is.matrix(useExpon)) useExpon <- matrix(rep(useExpon,ncol(dat)), ncol=ncol(dat))
expoNor <- list()
for(i in 1:nrow(useExpon)) expoNor[[i]] <- dat^matrix(rep(useExpon[i,], each=nrow(dat)), ncol=ncol(dat))
corVal <- if(identical(simMeas,"cor")) sapply(expoNor, function(x) apply(x,2,stats::cor, y=refDat, use="complete.obs")) else {
corVal <- NULL; message(fxNa," PROBLEM : unknown similarity measure !!")}
if(!is.matrix(corVal)) corVal <- matrix(corVal, ncol=ncol(dat))
if(all(dim(corVal) == dim(t(useExpon)))) corVal <- t(corVal)
dimnames(corVal) <- list(paste("exp",useExpon[,1],sep="_"), colnames(dat))
bestExpPo <- apply(corVal, 2, which.max)
bestExp <- apply(rbind(bestExpPo, useExpon), 2, function(x) x[-1][x[1]])
datNor <- matrix(nrow=nrow(dat), ncol=ncol(dat), dimnames=dimnames(dat))
for(i in 1:ncol(dat)) datNor[,i] <- dat[,i]^bestExp[i]
out <- list(bestExp=bestExp, datNor=datNor, allSimil = if(rSquare) corVal^2 else corVal)
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/exponNormalize.R
|
#' Flexible extraction of columns
#'
#' This function provides flexible checking if a set of columns may be extracted from a matrix or data.frame 'x'.
#' If argument \code{extrCol} is list of character vectors, this allows to search among given options, the first matching name for each vector will be identified.
#'
#' @param x (matrix or data.frame) main input (where data should be extracted from)
#' @param extrCol (character, integer or list) columns to be extracted, may be column-names or column index; if is \code{list} each first-level element will be considered as options for one choice
#' @param doExtractCols (logical) if default \code{FALSE} only the column indexes will be returned
#' @param silent (logical) suppress messages
#' @param callFrom (character) allows easier tracking of message(s) produced
#' @return integer-vector (if\code{doExtractCols=FALSE} return depending on input \code{matrix} or \code{data.frame})
#' @seealso \code{\link[utils]{read.table}}, \code{\link{filterList}}
#' @examples
#' dFr <- data.frame(a=11:14, b=24:21, cc=LETTERS[1:4], dd=rep(c(TRUE,FALSE),2))
#' extrColsDeX(dFr,c("b","cc","notThere"))
#' extrColsDeX(dFr,c("b","cc","notThere"), doExtractCols=TRUE)
#' extrColsDeX(dFr, list(c("nn","b","a"), c("cc","a"),"notThere"))
#' @export
extrColsDeX <- function(x, extrCol, doExtractCols=FALSE, callFrom=NULL, silent=FALSE) {
## flexible extraction of columns from x
## remove any NA
fxNa <- .composeCallName(callFrom, newNa="extrColsDeX")
nameX <- deparse(substitute(x))
nameCol <- deparse(substitute(extrCol))
if(length(dim(x)) <2) stop("argument ",nameX," should be matrix or data.frame")
if(any(dim(x) <1)) stop("nothing to do, ",nameX," has no lines or columns")
chNa <- is.na(extrCol)
if(any(chNa)) extrCol <- extrCol[which(!chNa)]
## check if use as integer (or match)
chExtrCol <- sub("^[[:digit:]]+", "", extrCol)
chExtrCol <- nchar(chExtrCol) >0
if(length(chExtrCol) <1) stop("nothing to do")
if(all(!chExtrCol)) extrCol <- as.integer(extrCol) else { ## try to find text in colnames
if(is.null(colnames(x))) stop(" Problem: ",nameX," has no colnames !")
if(!is.list(extrCol)) {
## single choice for each column to extract
extrCo2 <- match(extrCol, colnames(x))
} else {
## try to locate first of multi-choices
extrCo2 <- unlist(lapply(extrCol, function(z) naOmit(match(z,colnames(x)))[1]))
}
## check for NA due to match
chNa <- is.na(extrCo2)
if(any(chNa)) {
if(all(chNa)) stop(fxNa," Did not find ANY of the names given in ",nameCol," for extracting !")
if(isFALSE(silent)) message(fxNa," Can't find column(s) ",pasteC(extrCol[which(chNa)],quote="'")," in ",nameCol)
extrCo2 <- extrCo2[which(!chNa)] }
extrCol <- extrCo2
}
if(isTRUE(doExtractCols)) {
if(length(extrCol) >1 | is.data.frame(x)) x[,extrCol] else if(length(extrCol)==1) {
matrix(x[,extrCol], ncol=1, dimnames=list(rownames(x), colnames(x)[extrCol]))} else NULL
} else extrCol }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/extrColsDeX.R
|
#' Extract numeric part of matrix or data.frame
#'
#' \code{extrNumericFromMatr} extracts numeric part of matrix or data.frame, removing remaining non-numeric elements if \code{trimToData} is set to \code{TRUE}.
#' Note, that cropping entire lines where a (single) text element appeared may quickly reduce the overal content of the input data.
#'
#' @param dat matrix (or data.frame) for extracting numeric parts
#' @param trimToData (logical) default to remove (crop) lines and cols contributing to NA, non-numeric data is transfomed to NA
#' @param silent (logical) suppress messages
#' @param callFrom (character) allow easier tracking of message(s) produced
#' @return matrix of numeric data
#' @examples
#' mat <- matrix(c(letters[1:7],14:16,LETTERS[1:6]),nrow=4,dimnames=list(1:4,letters[1:4]))
#' mat; extrNumericFromMatr(mat)
#' mat <- matrix(c(letters[1:4],1,"e",12:19,LETTERS[1:6]),nr=5,dimnames=list(11:15,letters[1:4]))
#' mat; extrNumericFromMatr(mat)
#' @export
extrNumericFromMatr <- function(dat,trimToData=TRUE,silent=FALSE,callFrom=NULL) {
fxNa <- .composeCallName(callFrom,newNa="extrNumericFromMatr")
dimNa <- dimnames(dat)
chDat <- is.data.frame(dat)
if(is.data.frame(dat)) {
facCol <- sapply(1:ncol(dat),function(x) is.factor(dat[,x]))
if(sum(facCol,na.rm=TRUE) >0) for(i in which(facCol)) dat[,i] <- as.character(dat[,i])
dat <- gsub("\x5E[[:blank:]]+","",as.matrix(dat)) }
out <- matrix(NA,nrow=nrow(dat),ncol=ncol(dat))
for(i in 1:ncol(dat)) {x <- .mayBeNum(dat[,i]); if(length(x)>0) out[x,i] <- dat[x,i]}
out <- matrix(as.numeric(out),nrow=nrow(dat),ncol=ncol(dat),dimnames=dimnames(dat))
if(trimToData) {
useLi <- table(unlist(apply(out,2,function(x) (1:length(x))[!is.na(x)])))
useLi <- which(useLi==max(useLi))
useCo <- table(unlist(apply(out,1,function(x) (1:length(x))[!is.na(x)])))
useCo <- which(useCo==max(useCo))
## primary cropping
ou2 <- out[useLi,useCo]
if(length(dim(ou2)) <1) ou2 <- matrix(ou2,nrow=length(useLi),dimnames=list(rownames(dat)[useLi],colnames(dat)[useCo]))
## final/add'l cropping of lines with NAs
out <- ou2[which(rowSums(is.na(ou2)) <1),]
if(length(dim(out)) <1) out <- matrix(out,ncol=ncol(ou2),dimnames=list(rownames(ou2)[which(rowSums(is.na(ou2)) <1)],colnames(ou2)))
txt <- c("Nothing remains when cropping for numeric part !","Removed "," out of "," columns and "," rows")
if(!silent) message(fxNa, if(length(out) <1) txt[1] else c(txt[2],ncol(dat)-ncol(out),
txt[3],ncol(dat),txt[4],nrow(dat)-nrow(out),txt[3],nrow(dat),txt[5]))
}
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/extrNumericFromMatr.R
|
#' Extract specific text
#'
#' This function extracts/cuts text-fragments out of \code{txt} following specific anchors defined by arguments \code{cutFrom} and \code{cutTo}.
#'
#' @details
#' In case \code{cutFrom} is not found \code{missingAs} will be returned.
#' In case \code{cutTo} is not found, text gets extracted with \code{chaMaxEl} characters.
#'
#' @param txt character vector to be treated
#' @param cutFrom (character) text where to start cutting
#' @param cutTo (character) text where to stop cutting
#' @param missingAs (character) specific content of output at line/location of 'exclLi'
#' @param exclFromTag (logical) to exclude text given in 'cutFrom' from result
#' @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 modified character vector
#' @seealso \code{\link[base]{substr}}
#' @examples
#' extrSpcText(c(" ghjg GN=thisText PE=001"," GN=_ PE=", NA, "abcd"))
#' extrSpcText(c("ABCDEF.3-6","05g","bc.4-5"), cutFr="\\.", cutT="-")
#' @export
extrSpcText <- function(txt, cutFrom=" GN=", cutTo=" PE=", missingAs=NA, exclFromTag=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="extrSpcText")
if(!isTRUE(silent)) silent <- FALSE
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(!isTRUE(silent)) silent <- FALSE
seFr <- gregexpr(cutFrom, txt)
seTo <- gregexpr(cutTo, txt)
chOc <- cbind(fr=sapply(seFr, length), to=sapply(seTo, length))
chaFr <- if(all(chOc[,1]==1)) unlist(seFr) else sapply(seFr, function(x) x[1]) # if search-term found mult times, take 1st
chaTo <- if(all(chOc[,2]==1)) unlist(seTo) else sapply(seTo, function(x) x[1]) # if search-term found mult times, take 1st
exclLi <- which(chaFr <0 | is.na(txt))
if(exclFromTag) chaFr[which(chaFr >0)] <- chaFr[which(chaFr >0)] +nchar(sub("\\\\","",cutFrom))
if(any(chaTo <0)) { # gregexpr returns -1 if term not found -> not usable index
if(!silent) message(fxNa,sum(chaTo <0,na.rm=TRUE)," 'cutTo' tags not found !")
}
out <- substr(txt, chaFr, chaTo-1)
if(length(exclLi) >0) out[exclLi] <- missingAs
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 x character vector to be treated
#' @param searchChar (character) text to look for
#' @param after (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 a modified character vector
#' @seealso \code{\link[base]{grep}}
#' @examples
#' .cutAtSearch("abcdefg","de")
#' @export
.cutAtSearch <- function(x, searchChar, after=TRUE, silent=TRUE, debug=FALSE, callFrom=NULL) {
## search 'searchChar' within x (character vector) and cut either before or after values of 'x'
## for simple cutting before searchCharacter use .retain1stPart()
## 'after' =TRUE means that all text BEFORE 'searchChar' will be returned
searArg <- if(!silent) deparse(substitute(searchChar)) else "searchChar"
fxNa <- .composeCallName(callFrom, newNa=".cutAtSearch")
pos <- gregexpr(searchChar, x)
ch <- pos <0
if(any(ch)) pos[which(ch)] <- -1*nchar(searchChar)
if(max(sapply(pos, length),na.rm=TRUE) >1) {
if(!silent) message(fxNa," multiple occurances of '",searArg,"' found")
pos <- sapply(pos,function(z) z[1])
} else pos <- unlist(pos)
out <- if(after) substr(x, pos +nchar(searchChar), nchar(x)) else substr(x, 1, pos -1)
if(!after) {ch <- out=="" & pos <0; if(any(ch)) out[which(ch)] <- x[which(ch)]}
names(out) <- x
out }
#' Trim character string: keep only text before 'sep'
#'
#' Trim character string: keep only text before 'sep' (length=1 !)
#'
#' @param chr character vector to be treated
#' @param sep (character) saparator
#' @param offSet (integer) off-set
#' @return This function returns a modified character vector
#' @seealso \code{\link[base]{substr}}
#' @examples
#' .retain1stPart("abc = def")
#' @export
.retain1stPart <- function(chr, sep=" = ", offSet=1){
## trim character string: keep only text before 'sep' (length=1 !)
## offSet allows to cut n characteres before occurance of 'sep' (character of length=1 or neg value for cut after)
## error if all 'chr' NA !
## attention special characters as sep ('+' or '.') need to be protected !! eg # if(sep %in% c("+",".")) sep <- paste("\\",sep,sep="")
## see also volcDat .cutAtSearch() for cutting after ...
chrCh <- regexpr(sep[1], chr)
if(any(naOmit(chrCh >0))) { trimNo <- which(chrCh >0)
chr[trimNo] <- substr(chr[trimNo], 1, chrCh[trimNo] -offSet)}
chr }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/extrSpcText.R
|
#' Extract just one series, ie channel, of list of arrays
#'
#' This function was designed for handeling measurements stored as list of multiple arrays, like eg compound-screens using microtiter-plates where multiple parameters ('channels')
#' were recorded for each well (element).
#' The elements (eg compounds screened) are typcally stored in the 1st dimension of the arrays, the replicated in the secon dimension and different measure types/parameters in the 3rd chanel.
#' In order to keep the structure of of individual microtiter-plates, typically each plate forms a separate array (of same dimensions) in a list.
#' The this function allows extracting a single channel of the list of arrays (3rd dim of each array) and return row-appended matrix.
#' @param arrLst (list) list of arrays (typically 1st and 2nd dim for specific genes/objects, 3rd for different measures associated with)
#' @param cha (integer) channel number
#' @param na.rm (logical) default =TRUE to remove NAs
#' @param rowSep (character) separator for rows
#' @return list with just single channel extracted
#' @seealso \code{\link[wrMisc]{organizeAsListOfRepl}}
#' @examples
#' arr1 <- array(1:24,dim=c(4,3,2),dimnames=list(c(LETTERS[1:4]),
#' paste("col",1:3,sep=""),c("ch1","ch2")))
#' arr2 <- array(74:51,dim=c(4,3,2),dimnames=list(c(LETTERS[1:4]),
#' paste("col",1:3,sep=""),c("ch1","ch2")))
#' arrL1 <- list(pl1=arr1,pl2=arr2)
#' extr1chan(arrL1,ch=2)
#' @export
extr1chan <- function(arrLst,cha,na.rm=TRUE,rowSep="__"){
## extract single channel of list of arrays (3rd dim of each array) and return row-appended matrix
msg <- "'cha' should be numeric of length 1"
for(pl in 1:length(arrLst)) out <- if(pl ==1) arrLst[[pl]][,,cha] else rbind(out,arrLst[[pl]][,,cha])
plNa <- names(arrLst)
if(is.null(plNa)) plNa <- as.character(1:length(arrLst))
if(!is.null(rowSep)) rownames(out) <- paste(rep(plNa,sapply(arrLst,nrow)), rownames(out),sep=rowSep)
if(na.rm) out <- out[ which(rowSums(is.na(out)) < ncol(arrLst[[1]])),]
out }
|
/scratch/gouwar.j/cran-all/cranData/wrMisc/R/extract1chan.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.