content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
#' @export
#' @name Generate_data
#' @title Generate_data
#'
#' @description This function generates data (X,y) with specified correlation and noise standard deviation.
#'
#' @param truth.beta A vector of active beta's (s * 1, with s the number of active coordinates).
#' @param p Number of covariates.
#' @param n Number of observations.
#' @param truth.sigma Noise standard deviation.
#' @param rho Correlation Coefficient.
#' @param correlation Correlation structure. Correlation = "block" means predictors are grouped into equi-size blocks where each block contains one active predictor, and the within-block correlation coefficient is rho; predictors in different blocks are mutually independent. Correlation = "all" means all predictors are equi-correlated with coefficient rho.
#' @param NumOfBlock Number of blocks, used only when correlation = 'block'.
#'
#' @return A list, including vector 'y' (n1), matrix 'X' (np), vector 'beta' (p1).
Generate_data = function(truth.beta, p, n, truth.sigma, rho, correlation=c("block","all"), NumOfBlock){
s = length(truth.beta)
if (correlation == "block"){
block = rho + diag(1-rho, p/NumOfBlock, p/NumOfBlock)
Sigma = kronecker(diag(NumOfBlock), block) # block diagonal matrix
trueId = 1 + p/NumOfBlock * (1:s-1)
beta = rep(0, p)
beta[trueId] = truth.beta
}else if (correlation == 'all'){
Sigma = rho + diag(1-rho, p, p)
trueId = 1:s
beta = c(truth.beta, rep(0, p-s))
}else {
print("unknown correlation structure!")
}
X = mvnfast::rmvn(n = n, mu = rnorm(p, 0, 1), sigma = Sigma)
s = length(truth.beta)
# standardize X so that each column has l2-norm sqrt(n)
X <- scale(X, center = TRUE, scale = FALSE)
Xnorm = apply(X^2, 2, sum)
X = X * matrix(sqrt(n)/sqrt(Xnorm), byrow = T, nrow = n, ncol = p)
y = X[,trueId] %*% truth.beta + rnorm(n, 0, truth.sigma)
return(list(y=y, X=X, beta = beta))
}
| /scratch/gouwar.j/cran-all/cranData/BBSSL/R/Generate_data.R |
#' @export
#' @name Gibbs
#' @title Gibbs
#' @description This function runs SSVS for linear regression with Spike-and-Slab LASSO prior.
#' By default, this function uses the speed-up trick in Bhattacharya et al., 2016 when p > n.
#'
#' @param y A vector of continuous responses (n x 1).
#' @param X The design matrix (n x p), without an intercept.
#' @param a,b Parameters of the prior.
#' @param lambda A two-dim vector = c(lambda0, lambda1).
#' @param maxiter An integer which specifies the maximum number of iterations for MCMC.
#' @param burn.in An integer which specifies the maximum number of burn-in iterations for MCMC.
#' @param initial.beta A vector of initial values of beta to used. If set to NULL, the LASSO solution with 10-fold cross validation is used. Default is NULL.
#' @param sigma Noise standard deviation. Default is 1.
#'
#' @return A list, including matrix 'beta' ((maxiter-burn.in) x p), matrix 'tau2' ((maxiter-burn.in) x p),
#' matrix 'gamma' ((maxiter-burn.in) x p), vector 'theta' ((maxiter-burn.in) x 1).
#' @examples
#' n = 100; p = 1000;
#' truth.beta = c(2, 3, -3, 4); # high-dimensional case
#' truth.sigma = 1
#' data = Generate_data(truth.beta, p, n, truth.sigma = 1, rho = 0.6,"block",100)
#' y = data$y; X = data$X; beta = data$beta
#'
#' # --------------- set parameters -----------------
#' lambda0 = 50; lambda1 = 0.05; lambda = c(lambda0, lambda1)
#' a = 1; b = p #beta prior for theta
#' MCchain1 = Gibbs(y, X, a, b, lambda, maxiter = 15001, burn.in = 5001)
Gibbs = function(y, X, a, b, lambda, maxiter, burn.in, initial.beta = NULL, sigma = 1){
n = nrow(X)
p = ncol(X)
lambda1 = lambda[2]
lambda0 = lambda[1]
X = apply(X, 2, function(t) (t-mean(t)))
y = y - mean(y)
# -------------- Initialization -----------------
if (is.null(initial.beta)){
cvlambda = glmnet::cv.glmnet(X,y)$lambda.min
cvfit = glmnet::glmnet(X, y, lambda = cvlambda)
initial.beta = cvfit$beta
initial.beta = matrix(initial.beta, nrow = 1)
}
prob1 = greybox::dlaplace(initial.beta, mu = 0, scale = 1/lambda1)
prob0 = greybox::dlaplace(initial.beta, mu = 0, scale = 1/lambda0)
prob = prob1 / (prob1 + prob0)
initial.gamma = rep(NA, p)
initial.tau2 = rep(NA, p)
for (i in 1:p){
initial.gamma[i] = rbinom(1, size = 1, prob = prob[i])
mu = lambda[initial.gamma[i]+1] / abs(initial.beta[i] + 0.5)
lamb = lambda[initial.gamma[i]+1]^2
inv.tau = statmod::rinvgauss(n=1, mean = mu, shape = lamb)
initial.tau2[i] = 1 / inv.tau
}
initial.theta = rbeta(1, sum(initial.gamma) + a, p - sum(initial.gamma) + b)
# ------------- Create data --------------------
n = length(y)
p = length(initial.beta)
beta = matrix(NA, nrow = maxiter, ncol = p)
tau2 = matrix(NA, nrow = maxiter, ncol = p)
gamma = matrix(NA, nrow = maxiter, ncol = p)
theta = rep(NA, maxiter)
beta[1,] = initial.beta
tau2[1,] = initial.tau2
gamma[1,] = initial.gamma
theta[1] = initial.theta
# -------------- SSVS --------------------------
for (i in 2:maxiter){
start_time <- Sys.time()
#update beta
if (p>n){ # p^2n
d = tau2[i-1,] # d is 1-by-p
u = as.matrix(rnorm(p) * sqrt(d), nrow = 1) # u is 1-by-p
delta = rnorm(n)
XD = X * matrix(d, byrow = T, ncol = p, nrow = n) # complexity O(np)
v = X %*% u / sigma + delta # complexity O(np)
H = XD %*% t(X) / sigma^2 + diag(rep(1,n)) # complexity O(n^2p), this is the main bottleneck
w = Matrix::solve(H, y/sigma-v) # complexity O(n^3)
beta[i,] = u + (t(XD) / sigma) %*% w # complexity O(np)
} else { # p^2n
D = diag(1/tau2[i-1,])
H = Matrix::solve(t(X) %*% X/sigma^2 + D) # complexity O(p^2n+p^3)
beta[i,] = mvnfast::rmvn(1, mu = H %*% t(X) %*% y / sigma^2, sigma = H)
}
for (j in 1:p){
#update tau
mu = lambda[gamma[i-1,j]+1] / abs(beta[i, j])
lamb = lambda[gamma[i-1,j]+1]^2
inv.tau = statmod::rinvgauss(n=1, mean = mu, shape = lamb)
tau2[i,j] = 1 / inv.tau
#update gamma
tmp = lambda[2]^2 / lambda[1]^2 * exp( - (lambda[2]^2 - lambda[1]^2) * tau2[i,j] / 2) * theta[i-1] / (1 - theta[i-1])
prob = 1 - 1 / (tmp + 1)
gamma[i,j] = rbinom(1, 1, prob)
}
#update theta
active = sum(gamma[i,])
theta[i] = rbeta(1, active + a, p - sum(gamma[i,]) + b)
end_time <- Sys.time()
svMisc::progress(i, maxiter, progress.bar = T)
if (i == maxiter) cat("Done!\n")
}
# ------------ output ------------------------
return(list(beta = beta[-(1:burn.in),], tau2 = tau2[-(1:burn.in),], gamma = gamma[-(1:burn.in),], theta = theta[-(1:burn.in)]))
}
| /scratch/gouwar.j/cran-all/cranData/BBSSL/R/Gibbs.R |
#' @export
#' @name Gibbs2
#' @title Gibbs2
#' @description This function runs one-site Gibbs sampler for linear regression with Spike-and-Slab LASSO prior.
#'
#' @param y A vector of continuous responses (n x 1).
#' @param X The design matrix (n x p), without an intercept.
#' @param a,b Parameters of the prior.
#' @param lambda A two-dim vector = c(lambda0, lambda1).
#' @param maxiter An integer which specifies the maximum number of iterations for MCMC.
#' @param burn.in An integer which specifies the number of burn-in iterations for MCMC.
#' @param initial.beta A vector of initial values of beta to used. If set to NULL, the LASSO solution with 10-fold cross validation is used. Default is NULL.
#' @param sigma Noise standard deviation. Default is 1.
#'
#' @return A list, including matrix beta and gamma of dimension (maxiter-burn.in) x p, vector theta ((maxiter-burn.in) x 1)
#'
#' @examples
#' n = 100; p = 1000;
#' truth.beta = c(2, 3, -3, 4); # high-dimensional case
#' truth.sigma = 1
#' data = Generate_data(truth.beta, p, n, truth.sigma = 1, rho = 0.6,"block",100)
#' y = data$y; X = data$X; beta = data$beta
#'
#' # --------------- set parameters -----------------
#' lambda0 = 50; lambda1 = 0.05; lambda = c(lambda0, lambda1)
#' a = 1; b = p #beta prior for theta
#' MCchain2 = Gibbs2(y, X, a, b, lambda, maxiter = 15001, burn.in = 5001)
Gibbs2 = function(y, X, a, b, lambda, maxiter, burn.in, initial.beta = NULL, sigma = 1){
n = nrow(X)
p = ncol(X)
lambda1 = lambda[2]
lambda0 = lambda[1]
X = apply(X, 2, function(t) (t-mean(t)))
y = y - mean(y)
# -------------- Initialization -----------------
if (is.null(initial.beta)){
cvlambda = glmnet::cv.glmnet(X,y)$lambda.min
cvfit = glmnet::glmnet(X, y, lambda = cvlambda)
initial.beta = cvfit$beta
initial.beta = matrix(initial.beta, nrow = 1)
}
prob1 = greybox::dlaplace(initial.beta, mu = 0, scale = 1/lambda1)
prob0 = greybox::dlaplace(initial.beta, mu = 0, scale = 1/lambda0)
prob = prob1 / (prob1 + prob0)
initial.gamma = rep(NA, p)
for (i in 1:p){
initial.gamma[i] = rbinom(1, size = 1, prob = prob[i])
}
initial.theta = rbeta(1, sum(initial.gamma) + a, p - sum(initial.gamma) + b)
# ------------- Create data --------------------
n = length(y)
p = length(initial.beta)
beta = matrix(NA, nrow = maxiter, ncol = p)
gamma = matrix(NA, nrow = maxiter, ncol = p)
theta = rep(NA, maxiter)
beta[1,] = initial.beta
gamma[1,] = initial.gamma
theta[1] = initial.theta
XTX = rep(NA, p)
for (j in 1:p){
XTX[j] = sum(X[,j]^2)
}
res = y - X %*% as.matrix(c(initial.beta), ncol=1)
# -------------- SSVS --------------------------
for (i in 2:maxiter){
start_time <- Sys.time()
#res = y - X %*% as.matrix(beta[i-1,], ncol=1)
for (j in 1:p){
res = res + X[,j] * beta[i-1,j]
resprod = sum( res * X[,j] )
s = sigma / sqrt(XTX[j])
mu10 = (resprod + sigma^2 * lambda1) / XTX[j]
mu11 = (resprod - sigma^2 * lambda1) / XTX[j]
mu00 = (resprod + sigma^2 * lambda0) / XTX[j]
mu01 = (resprod - sigma^2 * lambda0) / XTX[j]
p01 = 1-pnorm(q=0, mean=mu01, sd=s)
p00 = pnorm(q=0, mean=mu00, sd=s)
p11 = 1-pnorm(q=0, mean=mu11, sd=s)
p10 = pnorm(q=0, mean=mu10, sd=s)
if(resprod >=0 ){
c1_div_c0 = lambda1 / lambda0 * exp( ( sigma^2*(lambda1^2-lambda0^2)+2*resprod*(lambda1-lambda0) ) / 2/XTX[j] )
c1_div_c0 = c1_div_c0 * ( p10 + p11 * exp( -lambda1*2*resprod/XTX[j] ) ) / ( p00 + p01 * exp( -lambda0*2*resprod/XTX[j] ) )
if(is.na(c1_div_c0)){
c1_div_c0 = lambda1 / lambda0 * exp( ( sigma^2*(lambda1^2-lambda0^2)+2*resprod*(lambda1-lambda0) ) / 2/XTX[j] -
lambda0*2*resprod/XTX[j] ) * ( p10 + p11 * exp( -lambda1*2*resprod/XTX[j] ) )
}
} else {
c1_div_c0 = lambda1 / lambda0 * exp( ( sigma^2*(lambda1^2-lambda0^2)-2*resprod*(lambda1-lambda0) ) / 2/XTX[j] )
c1_div_c0 = c1_div_c0 * ( p11 + p10 * exp( lambda1*2*resprod/XTX[j] ) ) / ( p01 + p00 * exp( lambda0*2*resprod/XTX[j] ) )
if(is.na(c1_div_c0)){
c1_div_c0 = lambda1 / lambda0 * exp( ( sigma^2*(lambda1^2-lambda0^2)-2*resprod*(lambda1-lambda0) ) / 2/XTX[j] -
lambda0*2*resprod/XTX[j]) * ( p11 + p10 * exp( lambda1*2*resprod/XTX[j] ) )
}
}
# update gamma
tmp = theta[i-1] * c1_div_c0 / (1-theta[i-1])
prob = 1 - 1 / (tmp + 1)
gamma[i,j] = rbinom(1, 1, prob)
# update beta
thislambda = lambda[gamma[i,j]+1]
uu = runif(1);
if (gamma[i,j]==0){
uu0 = p00 / ( p00 + p01 * exp(- 2*resprod*thislambda / XTX[j] ) )
if(is.na(uu0)){
uu0 = 1 / ( 1 + p01 / s * exp(- 2*resprod*thislambda / XTX[j] + mu00^2/2/s^2 )*sqrt(2*pi)*mu00 )
}
} else {
uu0 = p10 / ( p10 + p11 * exp(- 2*resprod*thislambda / XTX[j] ) )
if(is.na(uu0)){
uu0 = 1 / ( 1 + p11 / s * exp(- 2*resprod*thislambda / XTX[j] + mu10^2/2/s^2 )*sqrt(2*pi)*mu10 )
}
}
mu0 = (resprod + sigma^2 * thislambda) / XTX[j]
mu1 = (resprod - sigma^2 * thislambda) / XTX[j]
if (uu <= uu0){
beta[i,j] = truncnorm::rtruncnorm( n=1, a=-Inf, b=0, mean=mu0, sd = s )
}else{
beta[i,j] = truncnorm::rtruncnorm( n=1, a=0, b=Inf, mean=mu1, sd = s )
}
# update residual
res = res - X[,j] * beta[i,j]
}
# update theta
theta[i] = rbeta( n=1, shape1=a+sum(gamma[i,]), shape2=b+n-sum(gamma[i,]) )
end_time <- Sys.time()
svMisc::progress(i, maxiter, progress.bar = T)
if (i == maxiter) cat("Done!\n")
}
# ------------ output ------------------------
return(list(beta = beta[-(1:burn.in),], gamma = gamma[-(1:burn.in),], theta = theta[-(1:burn.in)]))
}
| /scratch/gouwar.j/cran-all/cranData/BBSSL/R/Gibbs2.R |
SSLASSO_2 <- function(X,
y,
initial.beta,
penalty = c("adaptive", "separable"),
variance = c("fixed", "unknown"),
lambda1,
lambda0,
nlambda = 100,
theta = 0.5,
sigma = 1,
a = 1, b,
eps = 0.001,
max.iter = 500,
counter = 10,
warn = FALSE) {
# Coersion
penalty <- match.arg(penalty)
variance <- match.arg(variance)
if (!is(X, "matrix")) {
tmp <- try(X <- model.matrix(~0+., data=X), silent=TRUE)
if (is(tmp, "try-error")) {
stop("X must be a matrix or able to be coerced to a matrix")
}
}
if (storage.mode(X) == "integer") {
storage.mode(X) <- "double"
}
if (!is(y, "numeric")) {
tmp <- try(y <- as.numeric(y), silent=TRUE)
if (is(tmp,"try-error")) {
stop("y must numeric or able to be coerced to numeric")
}
}
if (any(is.na(y)) | any(is.na(X))) {
stop("Missing data (NA's) detected. Take actions (e.g., removing cases, removing features, imputation) to eliminate missing data before passing X and y to SSLASSO")
}
## Standardize
XX <- standard(X) # this function has been modified and now it does NOT standardize it!
ns <- attr(XX, "nonsingular")
p <- ncol(XX)
yy <- y - mean(y)
n <- length(yy)
if (missing(lambda0)) {
lambda0 <- seq(1, n, length = nlambda)
lambda1 <- lambda0[1]
} else {
nlambda <- length(lambda0)
if (missing(lambda1)) {
lambda1 <- lambda0[1]
}
}
# Lambda0 should be an increasing sequence
monotone <- sum((lambda0[-1] - lambda0[-nlambda]) > 0)
if (monotone != nlambda - 1){
stop("lambda0 must be a monotone increasing sequence")
}
if (lambda1 > min(lambda0) ) {
stop("lambda1 must be smaller than lambda0")
}
if(missing(b)) {
b <- p
}
# get initial value for sigma
df = 3
sigquant = 0.9
sigest <- sd(yy)
qchi <- qchisq(1 - sigquant, df)
ncp <- sigest^2 * qchi / df
min_sigma2 <- sigest^2 / n
if (variance == "unknown") {
if (missing(sigma)) {
sigma <- sqrt(df * ncp / (df + 2))
}
} else {
if (missing(sigma)) {
sigma <- sqrt(df * ncp / (df - 2))
}
}
## Fit
res <- .Call("SSL_gaussian", XX, yy, initial.beta, penalty, variance, as.double(lambda1), as.numeric(lambda0),
as.double(theta), as.double(sigma), as.double(min_sigma2), as.double(a), as.double(b),
eps, as.integer(max.iter), as.integer(counter), PACKAGE = "BBSSL")
bb <- matrix(res[[1]], p, nlambda)
iter <- res[[3]]
thetas<-res[[4]]
sigmas <- res[[5]]
## Warning
if (warn & any(iter == max.iter)) {
warning("Algorithm did not converge for the ABOVE MENTIONED values of lambda0")
print(lambda0[iter == max.iter])
}
if (iter[nlambda] == max.iter) {
warning("Algorithm did not converge")
}
## Unstandardize
beta <- matrix(0, nrow = ncol(X), ncol = nlambda)
bbb <- bb/attr(XX, "scale")[ns]
beta[ns, ] <- bbb
intercept <- rep(mean(y), nlambda) - crossprod(attr(XX, "center")[ns], bbb)
## Names
varnames <- if (is.null(colnames(X))) paste("V", 1:ncol(X), sep = "") else colnames(X)
varnames <- c(varnames)
dimnames(beta) <- list(varnames, round(lambda0,digits=4))
## Select
select <- apply(beta, 2, function(x){as.numeric(x!=0)})
## Model
model<-(1:p)[select[,nlambda]==1]
## Output
val <- structure(list(beta = beta,
intercept = intercept,
iter = iter,
lambda0 = lambda0,
penalty = penalty,
lambda1 = lambda1,
thetas = thetas,
sigmas = sigmas,
select = select,
model = model,
n = n),
class = "SSLASSO")
val
}
| /scratch/gouwar.j/cran-all/cranData/BBSSL/R/SSLASSO_2.R |
plot.SSLASSO<-function(x, ...){
betas <-t(x$beta)
v0s <-x$lambda0
select <-apply(betas,2,function(x){as.numeric(x!=0)})
matplot(v0s,betas,xlab=expression(lambda[0]),ylab=expression(hat(beta)),lwd=1,col="grey",lty=2,type="l")
betas[select==F]=NA
matpoints(v0s,betas*select,xlab=expression(lambda[0]),ylab=expression(hat(beta)),lwd=1,col=4,lty=2,pch=19)
matpoints(v0s,betas*(1-select),xlab=expression(lambda[0]),ylab=expression(hat(beta)),lwd=1,col=2,lty=2,pch=19)
title("Spike-and-Slab LASSO")
oldpar <- par(no.readonly = TRUE) # ensure settings are reset when the function is exited
on.exit(par(oldpar))
par(xpd=T)
labels=paste("X",1:ncol(betas),sep="")
labels[select[length(v0s),]==0]<-""
text(max(v0s)*(1.1),betas[length(v0s),],labels=labels,col=4)
}
| /scratch/gouwar.j/cran-all/cranData/BBSSL/R/plot.SSLASSO.R |
standard <- function(X) {
if (!is(X, "matrix")) {
tmp <- try(X <- model.matrix(~0+., data=X), silent=TRUE)
if (is(tmp, "try-error")) stop("X must be a matrix or able to be coerced to a matrix")
}
STD <- .Call("standardize", X, PACKAGE = "BBSSL")
dimnames(STD[[1]]) <- dimnames(X)
ns <- which(STD[[3]] > 1e-6)
if (length(ns) == ncol(X)) {
val <- STD[[1]]
} else {
val <- STD[[1]][, ns, drop=FALSE]
}
attr(val, "center") <- STD[[2]]
attr(val, "scale") <- STD[[3]]
attr(val, "nonsingular") <- ns
val
}
| /scratch/gouwar.j/cran-all/cranData/BBSSL/R/standard.R |
#' A caching wrapper around load2.
#'
#' This closure returns a wrapper around \code{\link{load2}} which per
#' default caches loaded objects and returns the cached version
#' in subsequent calls.
#'
#' @param use.cache [\code{logical(1)}]\cr
#' Enable the cache?
#' Default is \code{TRUE}.
#' @return [\code{function()}] with argument \code{slot}
#' (name of the slot to cache the object in, default is \dQuote{default}).
#' All other arguments are passed down to \code{\link{load2}}.
#' @export
makeFileCache = function(use.cache = TRUE) {
assertFlag(use.cache)
.cache = list()
function(file, slot = "default", ...) {
if (use.cache) {
if (is.null(.cache[[slot]]) || .cache[[slot]]$file != file)
.cache[[slot]] = list(file = file, obj = load2(file = file, ...))
return(.cache[[slot]]$obj)
}
return(load2(file = file, ...))
}
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/FileCache.R |
#' A wrapper to add to the class attribute.
#'
#' @param x [any]\cr
#' Your object.
#' @param classes [\code{character}]\cr
#' Classes to add. Will be added in front (specialization).
#' @return Changed object \code{x}.
#' @export
#' @examples
#' x = list()
#' print(class(x))
#' x = addClasses(x, c("foo1", "foo2"))
#' print(class(x))
addClasses = function(x, classes) {
class(x) = c(classes, class(x))
x
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/addClasses.R |
#' Parses \code{...} arguments to a named list.
#'
#' The deparsed name will be used for arguments with missing names.
#' Missing names will be set to \code{NA}.
#'
#' @param ...
#' Arbitrary number of objects.
#' @return [\code{list}]: Named list with objects.
#' @export
#' @examples
#' z = 3
#' argsAsNamedList(x = 1, y = 2, z)
argsAsNamedList = function(...) {
args = list(...)
ns = names2(args)
ns.missing = is.na(ns)
if (any(ns.missing)) {
ns.sub = as.character(substitute(deparse(...)))[-1L]
ns[ns.missing] = ns.sub[ns.missing]
}
setNames(args, replace(ns, ns %in% c("NA", "NULL", ""), NA_character_))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/argsAsNamedList.R |
#' Extracts a named element from a list of lists.
#'
#' @param xs [\code{list}]\cr
#' A list of vectors of the same length.
#' @param row.names [\code{character} | \code{integer} | \code{NULL}]\cr
#' Row names of result.
#' Default is to take the names of the elements of \code{xs}.
#' @param col.names [\code{character} | \code{integer} | \code{NULL}]\cr
#' Column names of result.
#' Default is to take the names of the elements of \code{xs}.
#' @return [\code{matrix}].
#' @export
asMatrixCols = function(xs, row.names, col.names) {
assertList(xs)
n = length(xs)
if (n == 0L)
return(matrix(0, nrow = 0L, ncol = 0L))
assertList(xs, types = "vector")
m = unique(viapply(xs, length))
if (length(m) != 1L)
stopf("Vectors must all be of the same length!")
if (missing(row.names)) {
row.names = names(xs[[1L]])
}
if (missing(col.names)) {
col.names = names(xs)
}
xs = unlist(xs)
dim(xs) = c(m, n)
rownames(xs) = row.names
colnames(xs) = col.names
return(xs)
}
#' @rdname asMatrixCols
#' @export
asMatrixRows = function(xs, row.names, col.names) {
t(asMatrixCols(xs, row.names = col.names, col.names = row.names))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/asMatrix.R |
#' Converts a string into a quoted expression.
#'
#' Works the same as if you would have entered the expression and called
#' \code{\link{quote}} on it.
#'
#' @param s [\code{character(1)}]\cr
#' Expression as string.
#' @param env [\code{numeric(1)}]\cr
#' Environment for expression.
#' Default is \code{parent.frame()}
#' @return Quoted expression.
#' @export
#' @examples
#' asQuoted("x == 3")
asQuoted = function(s, env = parent.frame()) {
assertString(s)
structure(parse(text = s)[1L], env = env, class = "quoted")[[1L]]
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/asQuoted.R |
#' Simple bin packing.
#'
#' Maps numeric items in \code{x} into groups with sum
#' less or equal than \code{capacity}.
#' A very simple greedy algorithm is used, which is not really optimized
#' for speed. This is a convenience function for smaller vectors, not
#' a competetive solver for the real binbacking problem.
#' If an element of \code{x} exceeds \code{capacity}, an error
#' is thrown.
#'
#' @param x [\code{numeric}]\cr
#' Numeric vector of elements to group.
#' @param capacity [\code{numeric(1)}]\cr
#' Maximum capacity of each bin, i.e., elements will be grouped
#' so their sum does not exceed this limit.
#' @return [\code{integer}]. Integer with values \dQuote{1} to \dQuote{n.bins}
#' indicating bin membership.
#' @export
#' @examples
#' x = 1:10
#' bp = binPack(x, 11)
#' xs = split(x, bp)
#' print(xs)
#' print(sapply(xs, sum))
binPack = function(x, capacity) {
assertNumeric(x, min.len = 1L, lower = 0, any.missing = FALSE)
assertNumber(capacity)
too.big = which.first(x > capacity, use.names = FALSE)
if (length(too.big))
stopf("Capacity not sufficient. Item %i (x=%f) does not fit", too.big, x[too.big])
if (any(is.infinite(x)))
stop("Infinite elements found in 'x'")
ord = order(x, decreasing = TRUE)
grp = integer(length(x))
sums = vector(typeof(x), 1L)
bin.count = 1L
for(j in ord) {
new.sums = sums + x[j]
pos = which.first(new.sums <= capacity, use.names = FALSE)
if (length(pos)) {
grp[j] = pos
sums[pos] = new.sums[pos]
} else {
bin.count = bin.count + 1L
grp[j] = bin.count
sums[bin.count] = x[j]
}
}
grp
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/binPack.R |
#' Check if some values are covered by the range of the values in a second vector.
#'
#' @param x [\code{numeric(n)}]\cr
#' Value(s) that should be within the range of \code{y}.
#' @param y [\code{numeric}]\cr
#' Numeric vector which defines the range.
#' @return [\code{logical(n)}]. For each value in \code{x}: Is it in the range of \code{y}?
#' @usage x \%btwn\% y
#' @rdname btwn
#' @examples
#' x = 3
#' y = c(-1,2,5)
#' x %btwn% y
#' @export
`%btwn%` = function(x, y) {
r = range(y)
x <= r[2] & x >= r[1]
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/btwn.R |
#' @title Capitalize strings in a vector
#'
#' @description
#' Capitalise first word or all words of a character vector.
#' Lower back of vector element or word, respectively.
#'
#' @param x [\code{character(n)}]\cr
#' Vector of character elements to capitalize.
#' @param all.words [\code{logical(1)}]\cr
#' If \code{TRUE} all words of each vector element are capitalized.
#' \code{FALSE} capitalizes the first word of each vector element.
#' @param lower.back [\code{logical(1)}]\cr
#' \code{TRUE} lowers the back of each word or vector element (depends on \code{all.words}).
#' @return Capitalized vector: [\code{character(n)}].
#' @export
#' @examples
#' capitalizeStrings(c("the taIl", "wags The dOg", "That looks fuNny!"))
#' capitalizeStrings(c("the taIl", "wags The dOg", "That looks fuNny!")
#' , all.words = TRUE, lower.back = TRUE)
capitalizeStrings = function(x, all.words = FALSE, lower.back = FALSE) {
assertCharacter(x)
assertLogical(all.words, any.missing = FALSE, len = 1L)
assertLogical(lower.back, any.missing = FALSE, len = 1L)
if (all.words) {
pattern = "([[:alnum:]])([[:alnum:]]*)"
replacement = "\\U\\1"
if (lower.back) {
replacement = paste0(replacement, "\\L\\2")
} else {
replacement = paste0(replacement, "\\E\\2")
}
} else {
pattern = "^([[:alnum:]])"
replacement = "\\U\\1"
if (lower.back) {
pattern = paste0(pattern, "(.*)")
replacement = paste0(replacement, "\\L\\2")
}
}
return(gsub(pattern, replacement, x, perl = TRUE))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/capitalizeStrings.R |
#' Wrapper for cat and sprintf.
#'
#' A simple wrapper for \code{cat(sprintf(...))}.
#'
#' @param ... [any]\cr
#' See \code{\link{sprintf}}.
#' @param file [\code{character(1)}]\cr
#' See \code{\link{cat}}.
#' Default is \dQuote{}.
#' @param append [\code{logical(1)}]\cr
#' See \code{\link{cat}}.
#' Default is \code{FALSE}.
#' @param newline [\code{logical(1)}]\cr
#' Append newline at the end?
#' Default is \code{TRUE}.
#' @return Nothing.
#' @export
#' @examples
#' msg = "a message."
#' catf("This is %s", msg)
catf = function(..., file = "", append = FALSE, newline = TRUE) {
cat(sprintf(...), ifelse(newline, "\n", ""), sep = "", file = file, append = append)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/catf.R |
#' @title Check for a function argument.
#'
#' @description
#' Throws exception if checks are not passed. Note that argument is evaluated when checked.
#'
#' This function is superseded by the package \pkg{checkmate} and might get deprecated
#' in the future. Please
#'
#' @param x [any]\cr
#' Argument.
#' @param cl [\code{character}]\cr
#' Class that argument must \dQuote{inherit} from.
#' If multiple classes are given, \code{x} must \dQuote{inherit} from at least one of these.
#' See also argument \code{s4}.
#' @param s4 [\code{logical(1)}]\cr
#' If \code{TRUE}, use \code{is} for checking class \code{cl}, otherwise use \code{\link{inherits}}, which
#' implies that only S3 classes are correctly checked. This is done for speed reasons
#' as calling \code{\link{is}} is pretty slow.
#' Default is \code{FALSE}.
#' @param len [\code{integer(1)}]\cr
#' Length that argument must have.
#' Not checked if not passed, which is the default.
#' @param min.len [\code{integer(1)}]\cr
#' Minimal length that argument must have.
#' Not checked if not passed, which is the default.
#' @param max.len [\code{integer(1)}]\cr
#' Maximal length that argument must have.
#' Not checked if not passed, which is the default.
#' @param choices [any]\cr
#' Discrete number of choices, expressed by a vector of R objects.
#' If passed, argument must be identical to one of these and nothing else is checked.
#' @param subset [any]\cr
#' Discrete number of choices, expressed by a vector of R objects.
#' If passed, argument must be identical to a subset of these and nothing else is checked.
#' @param lower [\code{numeric(1)}]\cr
#' Lower bound for numeric vector arguments.
#' Default is \code{NA}, which means not required.
#' @param upper [\code{numeric(1)}]\cr
#' Upper bound for numeric vector arguments.
#' Default is \code{NA}, which means not required.
#' @param na.ok [\code{logical(1)}]\cr
#' Is it ok if a vector argument contains NAs?
#' Default is \code{TRUE}.
#' @param formals [\code{character}]\cr
#' If this is passed, \code{x} must be a function.
#' It is then checked that \code{formals} are the names of the
#' (first) formal arguments in the signature of \code{x}.
#' Meaning \code{checkArg(function(a, b), formals = "a")} is ok.
#' Default is missing.
#' @return Nothing.
#' @export
checkArg = function(x, cl, s4 = FALSE, len, min.len, max.len, choices, subset, lower = NA, upper = NA, na.ok = TRUE, formals) {
s = deparse(substitute(x))
if (missing(x))
stop("Argument ", s, " must not be missing!")
cl2 = class(x)[1]
len2 = length(x)
matchEl = function(x, xs) any(sapply(xs, function(y) identical(y, x)))
# choices must be done first
if (!missing(choices)) {
if (!matchEl(x, choices))
stop("Argument ", s, " must be any of: ", collapse(choices), "!")
} else if (!missing(subset)) {
if (!all(sapply(x, matchEl, xs = subset)))
stop("Argument ", s, " must be subset of: ", collapse(subset), "!")
} else if (!missing(formals)) {
if (!is.function(x))
stop("Argument ", s, " must be of class ", "function", " not: ", cl2, "!")
fs = names(formals(x))
if (length(fs) < length(formals) || !all(formals == fs[seq_along(formals)]))
stop("Argument function must have first formal args: ", paste(formals, collapse = ","), "!")
} else {
mycheck = function(x, cc)
if(identical(cc, "numeric"))
is.numeric(x)
else if(identical(cc, "integer"))
is.integer(x)
else if(identical(cc, "vector"))
is.vector(x)
else if (!s4)
inherits(x, cc)
else if (s4)
is(x, cc)
if (!any(sapply(cl, mycheck, x = x)))
stop("Argument ", s, " must be of class ", collapse(cl, " OR "), ", not: ", cl2, "!")
if (!missing(len) && len2 != len)
stop("Argument ", s, " must be of length ", len, " not: ", len2, "!")
if (!missing(min.len) && len2 < min.len)
stop("Argument ", s, " must be at least of length ", min.len, " not: ", len2, "!")
if (!missing(max.len) && len2 > max.len)
stop("Argument ", s, " must be at most of length ", max.len, " not: ", len2, "!")
if (!na.ok && any(is.na(x)))
stop("Argument ", s, " must not contain any NAs!")
if (is.numeric(x) && !is.na(lower) && ((any(is.na(x)) && !na.ok) || (!any(is.na(x)) && any(x < lower))))
stop("Argument ", s, " must be greater than or equal ", lower, "!")
if (is.numeric(x) && !is.na(upper) && ((any(is.na(x)) && !na.ok) || (!any(is.na(x)) && any(x > upper))))
stop("Argument ", s, " must be less than or equal ", upper, "!")
}
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/checkArg.R |
#' Check that a list contains only elements of a required type.
#'
#' Check that argument is a list and contains only elements of a required type.
#' Throws exception if check is not passed.
#' Note that argument is evaluated when checked.
#'
#' @param xs [\code{list}]\cr
#' Argument.
#' @param cl [\code{character(1)}]\cr
#' Class that elements must have. Checked with \code{is}.
#' @return Nothing.
#' @export
#' @examples
#' xs = as.list(1:3)
#' checkListElementClass(xs, "numeric")
checkListElementClass = function(xs, cl) {
assertList(xs)
s = deparse(substitute(xs))
lapply(seq_along(xs), function(i) {
x = xs[[i]]
if(!(is(x, cl)))
stop("List ", s, " has element of wrong type ", class(x)[1L], " at position ", i, ". Should be: ", cl)
})
invisible(NULL)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/checkListElementClass.R |
#' Chunk elements of vectors into blocks of nearly equal size.
#'
#' In case of shuffling and vectors that cannot be chunked evenly,
#' it is chosen randomly which levels / chunks will receive 1 element less.
#' If you do not shuffle, always the last chunks will receive 1 element less.
#'
#' @param x [ANY]\cr
#' Vector, list or other type supported by \code{\link[base]{split}}.
#' @param chunk.size [\code{integer(1)}]\cr
#' Requested number of elements in each chunk.
#' Cannot be used in combination with \code{n.chunks} or \code{props}.
#' If \code{x} cannot be evenly chunked, some chunks will have less elements.
#' @param n.chunks [\code{integer(1)}]\cr
#' Requested number of chunks.
#' If more chunks than elements in \code{x} are requested, empty chunks are
#' dropped.
#' Can not be used in combination with \code{chunks.size} or \code{props}.
#' @param props [\code{numeric}]\cr
#' Vector of proportions for chunk sizes.
#' Empty chunks may occur, depending on the length of \code{x} and the given
#' proportions.
#' Cannot be used in combination with \code{chunks.size} or \code{n.chunks}.
#' @param shuffle [\code{logical(1)}]\cr
#' Shuffle \code{x}?
#' Default is \code{FALSE}.
#' @return [unnamed \code{list}] of chunks.
#' @export
#' @examples
#' xs = 1:10
#' chunk(xs, chunk.size = 3)
#' chunk(xs, n.chunks = 2)
#' chunk(xs, n.chunks = 2, shuffle = TRUE)
#' chunk(xs, props = c(7, 3))
chunk = function(x, chunk.size, n.chunks, props, shuffle = FALSE) {
assertFlag(shuffle)
method = c("chunk.size", "n.chunks", "props")
method = method[!c(missing(chunk.size), missing(n.chunks), missing(props))]
if (length(method) != 1L)
stop("You must provide exactly one of 'chunk.size', 'n.chunks' or 'props'")
nx = length(x)
ch = switch(method,
chunk.size = {
chunk.size = convertInteger(chunk.size)
assertCount(chunk.size, positive = TRUE)
getNChunks(nx, nx %/% chunk.size + (nx %% chunk.size > 0L), shuffle)
},
n.chunks = {
n.chunks = convertInteger(n.chunks)
assertCount(n.chunks, positive = TRUE)
getNChunks(nx, n.chunks, shuffle)
},
props = {
assertNumeric(props, min.len = 1L, any.missing = FALSE, lower = 0)
props = props / sum(props)
ch = factor(rep.int(seq_along(props), round(props * nx, digits = 0L)),
levels = seq_along(props))
if (shuffle) sample(ch) else ch
})
unname(split(x, ch))
}
getNChunks = function(nx, n.chunks, shuffle) {
n.chunks = min(n.chunks, nx)
if (shuffle) {
c(sample(seq(0L, (nx %/% n.chunks) * n.chunks - 1L) %% n.chunks),
sample(n.chunks, nx %% n.chunks) - 1L)
} else {
sort(seq.int(0L, nx - 1L) %% n.chunks)
}
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/chunk.R |
#' Shortens strings to a given length.
#'
#' @param x [\code{character}]\cr
#' Vector of strings.
#' @param len [\code{integer(1)}]\cr
#' Absolute length the string should be clipped to, including \code{tail}.
#' Note that you cannot clip to a shorter length than \code{tail}.
#' @param tail [\code{character(1)}]\cr
#' If the string has to be shortened at least 1 character, the final characters will be \code{tail}.
#' Default is \dQuote{...}.
#' @return [\code{character(1)}].
#' @export
#' @examples
#' print(clipString("abcdef", 10))
#' print(clipString("abcdef", 5))
clipString = function(x, len, tail = "...") {
assertCharacter(x, any.missing = TRUE)
len = asInteger(len, len = 1L, lower = nchar(tail))
assertString(tail)
ind = (!is.na(x) & nchar(x) > len)
replace(x, ind, paste(substr(x[ind], 1L, len - nchar(tail)), tail, sep = ""))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/clipString.R |
#' @title Returns first non-missing, non-null argument.
#'
#' @description
#' Returns first non-missing, non-null argument, otherwise \code{NULL}.
#'
#' We have to perform some pretty weird \code{\link{tryCatch}} stuff internally,
#' so you should better not pass complex function calls into the arguments that can throw exceptions,
#' as these will be completely muffled, and return \code{NULL} in the end.
#'
#' @param ... [any]\cr
#' Arguments.
#' @return [any].
#' @export
#' @examples
#' f = function(x,y) {
#' print(coalesce(NULL, x, y))
#' }
#' f(y = 3)
coalesce = function(...) {
dots = match.call(expand.dots = FALSE)$...
for (arg in dots) {
ismissing = if (is.symbol(arg)) {
eval(substitute(missing(symbol), list(symbol = arg)), envir = parent.frame())
} else {
FALSE
}
if (!ismissing) {
value = tryCatch(eval(arg, envir = parent.frame()), error = function(...) NULL)
if (!is.null(value)) {
return(value)
}
}
}
NULL
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/coalesce.R |
#' Collapse vector to string.
#'
#' A simple wrapper for \code{paste(x, collapse)}.
#'
#' @param x [\code{vector}]\cr
#' Vector to collapse.
#' @param sep [\code{character(1)}]\cr
#' Passed to \code{collapse} in \code{\link{paste}}.
#' Default is \dQuote{,}.
#' @return [\code{character(1)}].
#' @export
#' @examples
#' collapse(c("foo", "bar"))
#' collapse(c("foo", "bar"), sep = ";")
collapse = function(x, sep = ",") {
paste0(x, collapse = sep)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/collapse.R |
#' Collapse vector to string.
#'
#' A simple wrapper for \code{collapse(sprintf, ...)}.
#'
#' Useful for vectorized call to \code{\link{sprintf}}.
#'
#' @param ... [any]\cr
#' See \code{\link{sprintf}}.
#' @param sep [\code{character(1)}]\cr
#' See \code{\link{collapse}}.
#' @return [\code{character(1)}].
#' @export
collapsef = function(..., sep = ",") {
paste0(sprintf(...), collapse = sep)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/collapsef.R |
#' Compute statistical mode of a vector (value that occurs most frequently).
#'
#' Works for integer, numeric, factor and character vectors.
#' The implementation is currently not extremely efficient.
#'
#' @param x [\code{vector}]\cr
#' Factor, character, integer, numeric or logical vector.
#' @param na.rm [\code{logical(1)}]\cr
#' If \code{TRUE}, missing values in the data removed.
#' if \code{FALSE}, they are used as a separate level and this level could therefore
#' be returned as the most frequent one.
#' Default is \code{TRUE}.
#' @param ties.method [\code{character(1)}]\cr
#' \dQuote{first}, \dQuote{random}, \dQuote{last}: Decide which value to take in case of ties.
#' Default is \dQuote{random}.
#' @return Modal value of length 1, data type depends on data type of \code{x}.
#' @export
#' @examples
#' computeMode(c(1,2,3,3))
computeMode = function(x, ties.method = "random", na.rm = TRUE) {
assertAtomicVector(x)
assertChoice(ties.method, c("first", "random", "last"))
assertFlag(na.rm)
tab = as.data.table(x)[, .N, by = x]
if (na.rm) tab = na.omit(tab)
ind = (tab$N == max(tab$N))
mod = tab$x[ind]
if (is.factor(mod))
mod = as.character(mod)
if (length(mod) > 1L)
ind = switch(ties.method, first = mod[1L], random = sample(mod, 1L), last = mod[length(mod)])
else mod
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/computeMode.R |
#' Converts columns in a data frame to characters, factors or numerics.
#'
#' @param df [\code{data.frame}]\cr
#' Data frame.
#' @param chars.as.factor [\code{logical(1)}]\cr
#' Should characters be converted to factors?
#' Default is \code{FALSE}.
#' @param factors.as.char [\code{logical(1)}]\cr
#' Should characters be converted to factors?
#' Default is \code{FALSE}.
#' @param ints.as.num [\code{logical(1)}]\cr
#' Should integers be converted to numerics?
#' Default is \code{FALSE}.
#' @param logicals.as.factor [\code{logical(1)}]\cr
#' Should logicals be converted to factors?
#' Default is \code{FALSE}.
#' @export
#' @return [\code{data.frame}].
convertDataFrameCols = function(df, chars.as.factor = FALSE, factors.as.char = FALSE, ints.as.num = FALSE, logicals.as.factor = FALSE) {
assertDataFrame(df)
assertFlag(chars.as.factor)
assertFlag(factors.as.char)
assertFlag(ints.as.num)
assertFlag(logicals.as.factor)
df = x = as.list(df)
if (chars.as.factor) {
i = vlapply(df, is.character)
if (any(i))
x[i] = lapply(x[i], factor)
}
if (factors.as.char) {
i = vlapply(df, is.factor)
if (any(i))
x[i] = lapply(x[i], as.character)
}
if (ints.as.num) {
i = vlapply(df, is.integer)
if (any(i))
x[i] = lapply(x[i], as.double)
}
if (logicals.as.factor) {
i = vlapply(df, is.logical)
if (any(i))
x[i] = lapply(x[i], factor, levels = c("TRUE", "FALSE"))
}
as.data.frame(x, stringsAsFactors = FALSE)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/convertDataFrameCols.R |
#' Conversion for single integer.
#'
#' Convert single numeric to integer only if the numeric represents a single integer,
#' e.g. 1 to 1L.
#' Otherwise the argument is returned unchanged.
#'
#' @param x [any]\cr
#' Argument.
#' @return Either a single integer if conversion was done or \code{x} unchanged.
#' @export
#' @examples
#' str(convertInteger(1.0))
#' str(convertInteger(1.3))
#' str(convertInteger(c(1.0, 2.0)))
#' str(convertInteger("foo"))
convertInteger = function(x) {
if (is.integer(x) || length(x) != 1L)
return(x)
if (is.na(x))
return(as.integer(x))
if (is.numeric(x)) {
xi = as.integer(x)
if (isTRUE(all.equal(x, xi)))
return(xi)
}
return(x)
}
#' Conversion for integer vector.
#'
#' Convert numeric vector to integer vector if the numeric vector fully represents
#' an integer vector,
#' e.g. \code{c(1, 5)} to \code{c(1L, 5L)}.
#' Otherwise the argument is returned unchanged.
#'
#' @param x [any]\cr
#' Argument.
#' @return Either an integer vector if conversion was done or \code{x} unchanged.
#' @export
#' @examples
#' str(convertIntegers(1.0))
#' str(convertIntegers(1.3))
#' str(convertIntegers(c(1.0, 2.0)))
#' str(convertIntegers("foo"))
convertIntegers = function(x) {
if (is.integer(x))
return(x)
if (length(x) == 0L || (is.atomic(x) && all(is.na(x))))
return(as.integer(x))
if (is.numeric(x)) {
xi = as.integer(x)
if (isTRUE(all.equal(x, xi, check.names = FALSE)))
return(setNames(xi, names(x)))
}
return(x)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/convertInteger.R |
#' @title Convert a list of row-vector of equal structure to a data.frame.
#'
#' @description
#' Elements are arranged in columns according to their name in each
#' element of \code{rows}.
#' Variables that are not present in some row-lists, or encoded as \code{NULL}, are filled using NAs.
#'
#' @param rows [\code{list}]\cr
#' List of rows. Each row is a list or vector of the same structure,
#' where all corresponding elements must have the same class.
#' It is allowed that in some rows some elements are not present, see above.
#' @param strings.as.factors [\code{logical(1)}]\cr
#' Convert character columns to factors?
#' Default is \code{default.stringsAsFactors()} for R < "4.1.0" and \code{FALSE} otherwise.
#' @param row.names [\code{character} | \code{integer} | \code{NULL}]\cr
#' Row names for result.
#' By default the names of the list \code{rows} are taken.
#' @param col.names [\code{character} | \code{integer}]\cr
#' Column names for result.
#' By default the names of an element of \code{rows} are taken.
#' @return [\code{data.frame}].
#' @export
#' @examples
#' convertListOfRowsToDataFrame(list(list(x = 1, y = "a"), list(x = 2, y = "b")))
convertListOfRowsToDataFrame = function(rows, strings.as.factors = NULL,
row.names, col.names) {
assertList(rows)
assertList(rows, types = "vector")
if (!length(rows))
return(makeDataFrame(0L, 0L))
if (is.null(strings.as.factors)) {
if(getRversion() < "4.1.0")
strings.as.factors = default.stringsAsFactors()
else
strings.as.factors = FALSE
}
assertFlag(strings.as.factors)
if (missing(row.names))
row.names = names(rows)
# make names
rows = lapply(rows, function(x) setNames(x, make.names(names2(x, ""), unique = TRUE)))
cols = unique(unlist(lapply(rows, names2)))
if (anyMissing(cols))
stop("All row elements must be named")
if (!length(cols))
return(makeDataFrame(length(rows), 0L))
extract = function(cn) {
tmp = lapply(rows, function(x) if (is.list(x)) x[[cn]] else unname(x[cn]))
if (any(viapply(tmp, length) > 1L))
stop("Rows may only contain a single value per name")
simplify2array(replace(tmp, vlapply(tmp, is.null), NA))
}
d = data.frame(setNames(lapply(cols, extract), cols), row.names = row.names, stringsAsFactors = strings.as.factors)
if (!missing(col.names))
colnames(d) = col.names
return(d)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/convertListOfRowsToDataFrame.R |
#' Converts storage type of a matrix.
#'
#' Works by setting \code{\link{mode}}.
#'
#' @param x [\code{matrix}]\cr.
#' Matrix to convert.
#' @param type [\code{character(1)}]\cr
#' New storage type.
#' @return [\code{matrix}].
#' @note \code{as.mytype} drops dimension when used on a matrix.
#' @export
convertMatrixType = function(x, type) {
assertMatrix(x)
assertChoice(type, c("integer", "numeric", "complex", "character", "logical"))
storage.mode(x) = type
return(x)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/convertMatrixType.R |
#' Convert rows (columns) of data.frame or matrix to lists.
#'
#' For each row, one list/vector is constructed, each entry of
#' the row becomes a list/vector element.
#'
#' @param x [\code{matrix} | \code{data.frame}]\cr
#' Object to convert.
#' @param name.list [\code{logical(1)}]\cr
#' Name resulting list with names of rows (cols) of \code{x}?
#' Default is \code{FALSE}.
#' @param name.vector [\code{logical(1)}]\cr
#' Name vector elements in resulting list with names of cols (rows) of \code{x}?
#' Default is \code{FALSE}.
#' @param factors.as.char [\code{logical(1)}]\cr
#' If \code{x} is a data.frame, convert factor columns to
#' string elements in the resulting lists?
#' Default is \code{TRUE}.
#' @param as.vector [\code{logical(1)}]\cr
#' If \code{x} is a matrix, store rows as vectors in the resulting list - or otherwise as lists?
#' Default is \code{TRUE}.
#' @return [\code{list} of lists or vectors].
#' @export
convertRowsToList = function(x, name.list = TRUE, name.vector = FALSE,
factors.as.char = TRUE, as.vector = TRUE) {
assert(checkMatrix(x), checkDataFrame(x))
assertFlag(name.list)
assertFlag(name.vector)
assertFlag(factors.as.char)
assertFlag(as.vector)
ns.list = if (name.list) rownames(x) else NULL
ns.vector = if (name.vector) colnames(x) else NULL
if (is.matrix(x)) {
if (as.vector)
res = lapply(seq_row(x), function(i) setNames(x[i, ], ns.vector))
else
res = lapply(seq_row(x), function(i) setNames(as.list(x[i, ]), ns.vector))
} else if (is.data.frame(x)) {
if (factors.as.char)
x = convertDataFrameCols(x, factors.as.char = TRUE)
res = rowLapply(x, function(row) setNames(as.list(row), ns.vector))
}
setNames(res, ns.list)
}
#' @rdname convertRowsToList
#' @export
convertColsToList = function(x, name.list = FALSE, name.vector= FALSE,
factors.as.char = TRUE, as.vector = TRUE) {
# we need a special case for df and can ignore as.vector in it
if (is.data.frame(x)) {
if (factors.as.char)
x = convertDataFrameCols(x, factors.as.char = TRUE)
y = as.list(x)
if (name.vector) {
ns.vector = if (name.vector) colnames(x) else NULL
y = lapply(y, function(z) setNames(z, ns.vector))
}
colnames(y) = if (name.list) colnames(x) else NULL
return(y)
}
convertRowsToList(t(x), name.list = name.list, name.vector = name.vector,
factors.as.char = factors.as.char, as.vector = as.vector)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/convertRowsToList.R |
#' @title Converts any R object to a descriptive string so it can be used in messages.
#'
#' @description
#' Atomics: If of length 0 or 1, they are basically printed as they are.
#' Numerics are formated with \code{num.format}.
#' If of length greater than 1, they are collapsed witd \dQuote{,} and clipped.
#' so they do not become excessively long.
#' Expressions will be converted to plain text.
#'
#' All others: Currently, only their class is simply printed
#' like \dQuote{<data.frame>}.
#'
#' Lists: The mechanism above is applied (non-recursively) to their elements.
#' The result looks like this:
#' \dQuote{a=1, <unamed>=2, b=<data.frame>, c=<list>}.
#'
#' @param x [any]\cr
#' The object.
#' @param num.format [\code{character(1)}]\cr
#' Used to format numerical scalars via \code{\link{sprintf}}.
#' Default is \dQuote{\%.4g}.
#' @param clip.len [\code{integer(1)}]\cr
#' Used clip atomic vectors via \code{\link{clipString}}.
#' Default is 15.
#' @return [\code{character(1)}].
#' @export
#' @examples
#' convertToShortString(list(a = 1, b = NULL, "foo", c = 1:10))
convertToShortString = function(x, num.format = "%.4g", clip.len = 15L) {
# convert non-list object to string
convObj = function(x) {
cl = getClass1(x)
string =
if (is.atomic(x) && !is.null(x) && length(x) == 0L)
sprintf("%s(0)", getClass1(x))
else if (cl == "numeric")
paste(sprintf(num.format, x), collapse=",")
else if (cl == "integer")
paste(as.character(x), collapse=",")
else if (cl == "logical")
paste(as.character(x), collapse=",")
else if (cl == "character")
collapse(x)
else if (cl == "expression")
as.character(x)
else
sprintf("<%s>", cl)
clipString(string, clip.len)
}
# handle only lists and not any derived data types
if (getClass1(x) == "list") {
if (length(x) == 0L)
return("list()")
ns = names2(x, missing.val = "<unnamed>")
ss = lapply(x, convObj)
collapse(paste(ns, "=", ss, sep = ""), ", ")
} else {
convObj(x)
}
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/convertToShortString.R |
#' Call \code{lapply} on an object and return a data.frame.
#'
#' Applies a function \code{fun} on each element of input \code{x}
#' and combines the results as \code{data.frame} columns.
#' The results will get replicated to have equal length
#' if necessary and possible.
#'
#' @param x [\code{data.frame}]\cr
#' Data frame.
#' @param fun [\code{function}]\cr
#' The function to apply.
#' @param ... [any]\cr
#' Further arguments passed down to \code{fun}.
#' @param col.names [\code{character(1)}]\cr
#' Column names for result.
#' Default are the names of \code{x}.
#' @export
#' @return [\code{data.frame}].
dapply = function(x, fun, ..., col.names) {
assertFunction(fun)
x = lapply(x, fun, ...)
if (missing(col.names)) {
ns = names2(x)
missing = which(is.na(ns))
if (length(missing))
names(x) = replace(ns, missing, paste0("Var.", missing))
} else {
assertCharacter(col.names, len = length(x), any.missing = FALSE)
names(x) = col.names
}
n = unique(viapply(x, length))
if (length(n) > 1L) {
max.n = max(n)
if (any(max.n %% n))
stop("Arguments imply differing number of rows: ", collapse(n, ", "))
x = lapply(x, rep_len, length.out = max.n)
n = max.n
}
attr(x, "row.names") = seq_len(n)
attr(x, "class") = "data.frame"
return(x)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/dapply.R |
#' Is one / are several files a directory?
#'
#' If a file does not exist, \code{FALSE} is returned.
#'
#' @param ... [\code{character(1)}]\cr
#' File names, all strings.
#' @return [\code{logical}].
#' @export
#' @examples
#' print(isDirectory(tempdir()))
#' print(isDirectory(tempfile()))
isDirectory = function(...) {
paths = c(...)
if (.Platform$OS.type == "windows" && getRversion() < "3.0.2")
paths = sub("^([[:alpha:]]:)[/\\]*$", "\\1//", paths)
x = file.info(paths)$isdir
!is.na(x) & x
}
#' Is one / are several directories empty?
#'
#' If file does not exist or is not a directory, \code{FALSE} is returned.
#'
#' @param ... [\code{character(1)}]\cr
#' Directory names, all strings.
#' @return [\code{logical}].
#' @export
#' @examples
#' print(isEmptyDirectory(tempdir()))
#' print(isEmptyDirectory(tempfile()))
isEmptyDirectory = function(...) {
vapply(list(...), FUN.VALUE = TRUE, FUN = function(x) {
isDirectory(x) && length(list.files(x, all.files = TRUE, include.dirs = TRUE)) == 2L
})
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/directory.R |
#' Execute a function call similar to \code{do.call}.
#'
#' This function is supposed to be a replacement for \code{\link[base]{do.call}} in situations
#' where you need to pass big R objects.
#' Unlike \code{\link[base]{do.call}}, this function allows to pass objects via \code{...}
#' to avoid a copy.
#'
#' @param fun [\code{character(1)}]\cr
#' Name of the function to call.
#' @param ... [any]\cr
#' Arguments to \code{fun}. Best practice is to specify them in a \code{key = value} syntax.
#' @param .args [\code{list}]\cr
#' Arguments to \code{fun} as a (named) list. Will be passed after arguments in \code{...}.
#' Default is \code{list()}.
#' @return Return value of \code{fun}.
#' @export
#' @examples \dontrun{
#' library(microbenchmark)
#' x = 1:1e7
#' microbenchmark(do.call(head, list(x, n = 1)), do.call2("head", x, n = 1))
#' }
do.call2 = function(fun, ..., .args = list()) {
assertString(fun)
ddd = match.call(expand.dots = FALSE)$...
expr = as.call(c(list(as.name(fun)), ddd, lapply(substitute(.args)[-1L], identity)))
eval.parent(expr, n = 1L)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/do.call2.R |
#' Drop named elements of an object.
#'
#' @param x [any]\cr
#' Object to drop named elements from.
#' For a matrix or a data frames this function drops named columns via
#' the second argument of the binary index operator \code{[,]}.
#' Otherwise, the unary index operator \code{[]} is used for dropping.
#' @param drop [\code{character}]\cr
#' Names of elements to drop.
#' @return Subset of object of same type as \code{x}. The object is not simplified,
#' i.e, no dimensions are dropped as \code{[,,drop = FALSE]} is used.
#' @export
dropNamed = function(x, drop = character(0L)) {
assertCharacter(drop, any.missing = FALSE)
if (length(drop) == 0L)
return(x)
if (is.matrix(x) || is.data.frame(x))
x[, setdiff(colnames(x), drop), drop = FALSE]
else
x[setdiff(names(x), drop)]
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/dropNamed.R |
#' Blow up single scalars / objects to vectors / list by replication.
#'
#' Useful for standard argument conversion where a user can input a single
#' element, but this has to be replicated now n times for a resulting vector or list.
#'
#' @param x [any]\cr
#' Input element.
#' @param n [\code{integer(1)}]\cr
#' Desired length.
#' Default is 1 (the most common case).
#' @param cl [\code{character}*]\cr
#' Only do the operation if \code{x} inherits from this one of these classes,
#' otherwise simply let \code{x} pass.
#' Default is \code{NULL} which means to always do the operation.
#' @param names [\code{character}*] \cr
#' Names for result.
#' Default is \code{NULL}, which means no names.
#' @param ensure.list [\code{logical(1)}]\cr
#' Should \code{x} be wrapped in a list in any case?
#' Default is \code{FALSE}, i.e., if \code{x} is a scalar value, a vector is
#' returned.
#' @return Ether a vector or list of length \code{n} with replicated \code{x} or \code{x} unchanged..
#' @export
ensureVector = function(x, n = 1L, cl = NULL, names = NULL, ensure.list = FALSE) {
n = convertInteger(n)
assertCount(n)
assertFlag(ensure.list)
doit = isScalarValue(x) || !is.atomic(x)
if (!is.null(cl)) {
assertCharacter(cl, min.len = 1L, any.missing = FALSE, all.missing = FALSE)
doit = doit && inherits(x, cl)
}
if (doit) {
if (isScalarValue(x) && !ensure.list) {
xs = rep(x, n)
} else {
xs = replicate(n, x, simplify = FALSE)
}
if (!is.null(names)) {
assertCharacter(names, len = n, any.missing = FALSE)
names(xs) = names
}
return(xs)
} else {
return(x)
}
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/ensureVector.R |
#' Split up a string into substrings.
#'
#' Split up a string into substrings according to a seperator.
#'
#' @param x [\code{character}]\cr
#' Source string.
#' @param sep [\code{character}]\cr
#' Seperator whcih is used to split \code{x} into substrings.
#' Default is \dQuote{ }.
#' @return [\code{vector}]
#' Vector of substrings.
#' @export
#' @examples
#' explode("foo bar")
#' explode("comma,seperated,values", sep = ",")
explode = function(x, sep = " ") {
assertString(x)
assertString(sep)
#FIXME: why perl?
x.exploded = strsplit(x, sep, perl = TRUE)
return(x.exploded[[1L]])
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/explode.R |
#' Extracts a named element from a list of lists.
#'
#' @param xs [\code{list}]\cr
#' A list of named lists.
#' @param element [\code{character}]\cr
#' Name of element(s) to extract from the list elements of \code{xs}.
#' What happens is this: \code{x$el1$el2....}.
#' @param element.value [any]\cr
#' If given, \code{\link{vapply}} is used and this argument is passed to \code{FUN.VALUE}.
#' Note that even for repeated indexing (if length(element) > 1) you only
#' pass one value here which refers to the data type of the final result.
#' @param simplify [\code{logical(1)} | character(1)]\cr
#' If \code{FALSE} \code{\link{lapply}} is used, otherwise \code{\link{sapply}}.
#' If \dQuote{cols}, we expect the elements to be vectors of the same length and they are
#' arranged as the columns of the resulting matrix.
#' If \dQuote{rows}, likewise, but rows of the resulting matrix.
#' Default is \code{TRUE}.
#' @param use.names [\code{logical(1)}]\cr
#' If \code{TRUE} and \code{xs} is named, the result is named as \code{xs},
#' otherwise the result is unnamed.
#' Default is \code{TRUE}.
#' @return [\code{list} | simplified \code{vector} | \code{matrix}]. See above.
#' @export
#' @examples
#' xs = list(list(a = 1, b = 2), list(a = 5, b = 7))
#' extractSubList(xs, "a")
#' extractSubList(xs, "a", simplify = FALSE)
extractSubList = function(xs, element, element.value, simplify = TRUE, use.names = TRUE) {
assertList(xs)
assert(checkFlag(simplify), checkChoice(simplify, c("cols", "rows")))
assertFlag(use.names)
# we save some time here if we only do the for loop in the complicated case
# the whole function is still not very nice due to the loop
# extractSubList should be C code anyway i guess....
doindex = if (length(element) == 1L) {
function(x) x[[element]]
} else {
function(x) {
for (el in element)
x = x[[el]]
return(x)
}
}
if (!missing(element.value)) {
ys = vapply(xs, doindex, FUN.VALUE = element.value)
} else if (isTRUE(simplify)) {
ys = sapply(xs, doindex, USE.NAMES = use.names)
} else {
ys = lapply(xs, doindex)
if (simplify == "rows")
ys = asMatrixRows(ys)
else if (simplify == "cols")
ys = asMatrixCols(ys)
}
ns = names(xs)
if (use.names && !is.null(ns)) {
if (isTRUE(simplify))
names(ys) = ns
else if (simplify == "rows")
rownames(ys) = ns
else if (simplify == "cols")
colnames(ys) = ns
} else {
if (simplify %in% c("rows", "rows"))
dimnames(ys) = NULL
else
names(ys) = NULL
}
return(ys)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/extractSubList.R |
#' Combine multiple factors and return a factor.
#'
#' Note that function does not inherit from \code{\link{c}} to not change R semantics behind your back when this
#' package is loaded.
#'
#' @param ... [\code{factor}]\cr
#' The factors.
#' @return [\code{factor}].
#' @export
#' @examples
#' f1 = factor(c("a", "b"))
#' f2 = factor(c("b", "c"))
#' print(c(f1, f2))
#' print(cFactor(f1, f2))
cFactor = function(...) {
args = lapply(list(...), as.factor)
newlevels = sort(unique(unlist(lapply(args, levels))))
ans = unlist(lapply(args, function(x) {
m = match(levels(x), newlevels)
m[as.integer(x)]
}))
levels(ans) = newlevels
setClasses(ans, "factor")
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/factor.R |
#' Filter a list for NULL values
#'
#' @param li [\code{list}]\cr
#' List.
#' @return [\code{list}].
#' @export
filterNull = function(li) {
assertList(li)
li[!vlapply(li, is.null)]
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/filterNull.R |
#' Helper function for determining the vector of attribute names
#' of a given object.
#'
#' @param obj [any]\cr
#' Source object.
#' @return [\code{character}]
#' Vector of attribute names for the source object.
#' @export
getAttributeNames = function(obj) {
names(attributes(obj))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/getAttributeNames.R |
#' Wrapper for \code{class(x)[1]}.
#'
#' @param x [any]\cr
#' Input object.
#' @return [\code{character(1)}].
#' @note \code{getClass} is a function in \code{methods}. Do not confuse.
#' @export
getClass1 = function(x) {
class(x)[1L]
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/getClass1.R |
#' Get the first/last element of a list/vector.
#'
#' @param x [\code{list} | \code{vector}]\cr
#' The list or vector.
#' @return Selected element. The element name is dropped.
#' @export
getFirst = function(x) {
assertVector(x, min.len = 1L)
x[[1L]]
}
#' @rdname getFirst
#' @export
getLast = function(x) {
assertVector(x, min.len = 1L)
x[[length(x)]]
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/getFirstLast.R |
#' Find row- or columnwise the index of the maximal / minimal element in a matrix.
#'
#' \code{getMaxIndexOfRows} returns the index of the maximal element of each row.
#' \code{getMinIndexOfRows} returns the index of the minimal element of each row.
#' \code{getMaxIndexOfCols} returns the index of the maximal element of each col.
#' \code{getMinIndexOfCols} returns the index of the minimal element of each col.
#' If a corresponding vector (row or col) is empty, possibly after NA removal, -1 is returned
#' as index.
#'
#' @param x [\code{matrix(n,m)}] \cr
#' Numerical input matrix.
#' @param weights [\code{numeric}]\cr
#' Weights (same length as number of rows/cols).
#' If these are specified, the index is selected from the weighted elements
#' (see \code{\link{getMaxIndex}}).
#' Default is \code{NULL} which means no weights.
#' @param ties.method [\code{character(1)}]\cr
#' How should ties be handled?
#' Possible are: \dQuote{random}, \dQuote{first}, \dQuote{last}.
#' Default is \dQuote{random}.
#' @param na.rm [\code{logical(1)}]\cr
#' If \code{FALSE}, NA is returned if an NA is encountered in \code{x}.
#' If \code{TRUE}, NAs are disregarded.
#' Default is \code{FALSE}
#' @return [\code{integer(n)}].
#' @export
#' @useDynLib BBmisc c_getMaxIndexOfRows c_getMaxIndexOfCols
#' @examples
#' x = matrix(runif(5 * 3), ncol = 3)
#' print(x)
#' print(getMaxIndexOfRows(x))
#' print(getMinIndexOfRows(x))
getMaxIndexOfRows = function(x, weights = NULL, ties.method = "random", na.rm = FALSE) {
mode(x) = "numeric"
ties.method = switch(ties.method, random = 1L, first = 2L, last = 3L,
stop("Unknown ties method"))
assertFlag(na.rm)
assertNumeric(weights, null.ok = TRUE, len = ncol(x))
.Call(c_getMaxIndexOfRows, x, as.numeric(weights), ties.method, na.rm, PACKAGE = "BBmisc")
}
#' @export
#' @rdname getMaxIndexOfRows
getMinIndexOfRows = function(x, weights = NULL, ties.method = "random", na.rm = FALSE) {
getMaxIndexOfRows(-x, weights, ties.method, na.rm)
}
#' @export
#' @rdname getMaxIndexOfRows
getMaxIndexOfCols = function(x, weights = NULL, ties.method = "random", na.rm = FALSE) {
mode(x) = "numeric"
ties.method = switch(ties.method, random = 1L, first = 2L, last = 3L,
stop("Unknown ties method"))
assertFlag(na.rm)
assertNumeric(weights, null.ok = TRUE, len = nrow(x))
.Call(c_getMaxIndexOfCols, x, as.numeric(weights), ties.method, na.rm, PACKAGE = "BBmisc")
}
#' @export
#' @rdname getMaxIndexOfRows
getMinIndexOfCols = function(x, weights = NULL, ties.method = "random", na.rm = FALSE) {
getMaxIndexOfCols(-x, weights, ties.method, na.rm)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/getMaxColIndex.R |
#' Return index of maximal/minimal/best element in numerical vector.
#'
#' If \code{x} is empty or only contains NAs which are to be removed,
#' -1 is returned.
#'
#' @note
#' Function \code{getBestIndex} is a simple wrapper for \code{getMinIndex} or
#' \code{getMaxIndex} respectively depending on the argument \code{minimize}.
#'
#' @param x [\code{numeric}]\cr
#' Input vector.
#' @param weights [\code{numeric}]\cr
#' Weights (same length as \code{x}).
#' If these are specified, the index is selected from \code{x * w}.
#' Default is \code{NULL} which means no weights.
#' @param ties.method [\code{character(1)}]\cr
#' How should ties be handled?
#' Possible are: \dQuote{random}, \dQuote{first}, \dQuote{last}.
#' Default is \dQuote{random}.
#' @param na.rm [\code{logical(1)}]\cr
#' If \code{FALSE}, NA is returned if an NA is encountered in \code{x}.
#' If \code{TRUE}, NAs are disregarded.
#' Default is \code{FALSE}
#' @param minimize [\code{logical(1)}]\cr
#' Minimal element is considered best?
#' Default is \code{TRUE}.
#' @param ... [any]\cr
#' Further arguments passed down to the delegate.
#' @return [\code{integer(1)}].
#' @export
#' @useDynLib BBmisc c_getMaxIndex
getMaxIndex = function(x, weights = NULL, ties.method = "random", na.rm = FALSE) {
ties.method = switch(ties.method, random = 1L, first = 2L, last = 3L,
stop("Unknown ties method"))
assertFlag(na.rm)
assertNumeric(weights, null.ok = TRUE, len = length(x))
.Call(c_getMaxIndex, as.numeric(x), as.numeric(weights), ties.method, na.rm, PACKAGE = "BBmisc")
}
#' @export
#' @rdname getMaxIndex
getMinIndex = function(x, weights = NULL, ties.method = "random", na.rm = FALSE) {
getMaxIndex(-as.numeric(x), weights, ties.method, na.rm)
}
#' @export
#' @rdname getMaxIndex
getBestIndex = function(x, weights = NULL, minimize = TRUE, ...) {
assertFlag(minimize)
getIndex = if (minimize) getMinIndex else getMaxIndex
getIndex(x, weights, ...)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/getMaxIndex.R |
#' Functions to determine the operating system.
#'
#' \itemize{
#' \item{getOperatingSystem}{Simple wrapper for \code{.Platform$OS.type}, returns \code{character(1)}.}
#' \item{isUnix}{Predicate for OS string, returns \code{logical(1)}. Currently this would include Unix, Linux and Mac flavours.}
#' \item{isLinux}{Predicate for sysname string, returns \code{logical(1)}.}
#' \item{isDarwin}{Predicate for sysname string, returns \code{logical(1)}.}
#' \item{isWindows}{Predicate for OS string, returns \code{logical(1)}.}
#' }
#'
#' @return See above.
#' @export
getOperatingSystem = function() {
.Platform$OS.type
}
#' @rdname getOperatingSystem
#' @export
isWindows = function() {
.Platform$OS.type == "windows"
}
#' @rdname getOperatingSystem
#' @export
isUnix = function() {
.Platform$OS.type == "unix"
}
#' @rdname getOperatingSystem
#' @export
isLinux = function() {
isUnix() && grepl("linux", Sys.info()["sysname"], ignore.case = TRUE)
}
#' @rdname getOperatingSystem
#' @export
isDarwin = function() {
isUnix() && grepl("darwin", Sys.info()["sysname"], ignore.case = TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/getOperatingSystem.R |
#' Construct a path relative to another
#'
#' Constructs a relative path from path \code{from} to path \code{to}.
#' If this is not possible (i.e. different drive letters on windows systems),
#' \code{NA} is returned.
#'
#' @param to [\code{character(1)}]\cr
#' Where the relative path should point to.
#' @param from [\code{character(1)}]\cr
#' From which part to start.
#' Default is \code{\link[base]{getwd}}.
#' @param ignore.case [\code{logical(1)}]\cr
#' Should path comparisons be made case insensitve?
#' Default is \code{TRUE} on Windows systems and \code{FALSE} on other systems.
#' @return [character(1)]: A relative path.
#' @export
getRelativePath = function(to, from = getwd(), ignore.case = isWindows()) {
numberCommonParts = function(p1, p2) {
for (i in seq_len(min(length(p1), length(p2)))) {
if (p1[i] != p2[i])
return(i - 1L)
}
return(if (is.null(i)) 0L else i)
}
from = splitPath(from)
to = splitPath(to)
assertFlag(ignore.case)
if (length(from$drive) != length(to$drive))
return(NA_character_)
if (length(from$drive) > 0L && length(to$drive) > 0L && from$drive != to$drive)
return(NA_character_)
if (ignore.case)
i = numberCommonParts(tolower(from$path), tolower(to$path))
else
i = numberCommonParts(from$path, to$path)
res = c(rep.int("..", length(from$path) - i), tail(to$path, ifelse(i == 0L, Inf, -i)))
if (length(res) == 0L)
res = "."
collapse(res, .Platform$file.sep)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/getRelativePath.R |
#' Current time in seconds.
#'
#' Simple wrapper for \code{as.integer(Sys.time())}.
#'
#' @return [\code{integer(1)}].
#' @export
getUnixTime = function() {
as.integer(Sys.time())
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/getUnixTime.R |
#' Determines used factor levels.
#'
#' Determines the factor levels of a factor type vector
#' that are actually occuring in it.
#'
#' @param x [\code{factor}]\cr
#' The factor.
#' @return [\code{character}]
#' @export
getUsedFactorLevels = function(x) {
intersect(levels(x), unique(x))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/getUsedFactorLevels.R |
#' Check if given object has certain attributes.
#'
#' @param obj [mixed]\cr
#' Arbitrary R object.
#' @param attribute.names [\code{character}]\cr
#' Vector of strings, i.e., attribute names.
#' @return [\code{logical(1)}]
#' \code{TRUE} if object \code{x} contains all attributes from \code{attributeNames}
#' and \code{FALSE} otherwise.
#' @export
hasAttributes = function(obj, attribute.names) {
isSubset(attribute.names, getAttributeNames(obj))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/hasAttributes.R |
#' Insert elements from one list/vector into another list/vector.
#'
#' Inserts elements from \code{xs2} into \code{xs1} by name,
#' overwriting elements of equal names.
#'
#' @param xs1 [\code{list}]\cr
#' First list/vector.
#' @param xs2 [\code{list}]\cr
#' Second vector/list. Must be fully and uniquely named.
#' @param elements [\code{character}]\cr
#' Elements from \code{xs2} to insert into \code{xs1}.
#' Default is all.
#' @return \code{x1} with replaced elements from \code{x2}.
#' @export
#' @examples
#' xs1 = list(a = 1, b = 2)
#' xs2 = list(b = 1, c = 4)
#' insert(xs1, xs2)
#' insert(xs1, xs2, elements = "c")
insert = function(xs1, xs2, elements) {
if (length(xs2) > 0L) {
if (missing(elements)) {
xs1[names(xs2)] = xs2
} else {
elements = intersect(elements, names(xs2))
xs1[elements] = xs2[elements]
}
}
return(xs1)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/insert.R |
#' Conditional checking for expensive examples.
#'
#' Queries environment variable \dQuote{R_EXPENSIVE_EXAMPLE_OK}.
#' Returns \code{TRUE} iff set exactly to \dQuote{TRUE}.
#' This allows conditional checking of expensive examples in packages
#' via R CMD CHECK, so they are not run on CRAN, but at least
#' on your local computer.
#' A better option than \dQuote{dont_run} in many cases, where such examples
#' are not checked at all.
#'
#' @return [\code{logical(1)}].
#' @export
#' @examples
#' # extremely costly random number generation, that we dont want checked on CRAN
#' if (isExpensiveExampleOk()) {
#' runif(1)
#' }
isExpensiveExampleOk = function() {
Sys.getenv("R_EXPENSIVE_EXAMPLE_OK") == "TRUE"
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/isExpensiveExampleOk.R |
#' A wrapper for \code{identical(x, FALSE)}.
#'
#' @param x [any]\cr
#' Your object.
#' @return [\code{logical(1)}].
#' @export
#' @examples
#' isFALSE(0)
#' isFALSE(FALSE)
isFALSE = function(x) {
identical(x, FALSE)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/isFALSE.R |
#' Are all elements of a list / vector uniquely named?
#'
#' \code{NA} or \dQuote{} are not allowed as names.
#'
#' @param x [\code{vector}]\cr
#' The vector or list.
#' @return [\code{logical(1)}].
#' @export
#' @examples
#' isProperlyNamed(list(1))
#' isProperlyNamed(list(a = 1))
#' isProperlyNamed(list(a = 1, 2))
isProperlyNamed = function(x) {
ns = names2(x)
length(x) == 0L || !(any(is.na(ns)) || anyDuplicated(ns))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/isProperlyNamed.R |
#' Checks whether an object is a scalar NA value.
#'
#' Checks whether object is from \code{(NA, NA_integer, NA_real_, NA_character_, NA_complex_)}.
#' @param x [any]\cr
#' Object to check.
#' @return [\code{logical(1)}].
#' @export
isScalarNA = function(x) {
is.atomic(x) && length(x) == 1L && is.na(x)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/isScalarNA.R |
#' Is given argument an atomic vector or factor of length 1?
#'
#' More specific functions for scalars of a given type exist, too.
#'
#' @param x [any]\cr
#' Argument.
#' @param na.ok [\code{logical(1)}]\cr
#' Is \code{NA} considered a scalar?
#' Default is \code{TRUE}.
#' @param null.ok [\code{logical(1)}]\cr
#' Is \code{NULL} considered a scalar?
#' Default is \code{FALSE}.
#' @param type [\code{character(1)}]\cr
#' Allows to restrict to specific type, e.g., \dQuote{numeric}?
#' But instead of this argument you might want to consider using \code{isScalar<Type>}.
#' Default is \dQuote{atomic}, so no special restriction.
#' @return [\code{logical(1)}].
#' @export
isScalarValue = function(x, na.ok = TRUE, null.ok = FALSE, type = "atomic") {
if (is.null(x))
return(null.ok)
# not really cool switch, but maybe fastest option
istype = switch(type,
"atomic" = is.atomic,
"logical" = is.logical,
"numeric" = is.numeric,
"integer" = is.integer,
"complex" = is.complex,
"chararacter" = is.character,
"factor" = is.factor
)
istype(x) && length(x) == 1L && (na.ok || !is.na(x))
}
#' @rdname isScalarValue
#' @export
isScalarLogical = function(x, na.ok = TRUE, null.ok = FALSE) {
isScalarValue(x, na.ok, null.ok, "logical")
}
#' @rdname isScalarValue
#' @export
isScalarNumeric = function(x, na.ok = TRUE, null.ok = FALSE) {
isScalarValue(x, na.ok, null.ok, "numeric")
}
#' @rdname isScalarValue
#' @export
isScalarInteger = function(x, na.ok = TRUE, null.ok = FALSE) {
isScalarValue(x, na.ok, null.ok, "integer")
}
#' @rdname isScalarValue
#' @export
isScalarComplex = function(x, na.ok = TRUE, null.ok = FALSE) {
isScalarValue(x, na.ok, null.ok, "complex")
}
#' @rdname isScalarValue
#' @export
isScalarCharacter = function(x, na.ok = TRUE, null.ok = FALSE) {
isScalarValue(x, na.ok, null.ok, "chararacter")
}
#' @rdname isScalarValue
#' @export
isScalarFactor = function(x, na.ok = TRUE, null.ok = FALSE) {
isScalarValue(x, na.ok, null.ok, "factor")
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/isScalarValue.R |
#' Check subset relation on two vectors.
#'
#' @param x [\code{vector}]\cr
#' Source vector.
#' @param y [\code{vector}]\cr
#' Vector of the same mode as \code{x}.
#' @param strict [\code{logical(1)}]\cr
#' Checks for strict/proper subset relation.
#' @return [\code{logical(1)}]
#' \code{TRUE} if each element of \code{x} is also contained in \code{y}, i. e.,
#' if \code{x} is a subset of \code{y} and \code{FALSE} otherwise.
#' @export
isSubset = function(x, y, strict = FALSE) {
assertFlag(strict)
if (length(x) == 0L)
return(TRUE)
res = all(x %in% y)
if (strict)
res = res & !isSubset(y, x)
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/isSubset.R |
#' Check superset relation on two vectors.
#'
#' @param x [\code{vector}]\cr
#' Source vector.
#' @param y [\code{vector}]\cr
#' Vector of the same mode as \code{x}.
#' @param strict [\code{logical(1)}]\cr
#' Checks for strict/proper superset relation.
#' @return [\code{logical(1)}]
#' \code{TRUE} if each element of \code{y} is also contained in \code{x}, i. e.,
#' if \code{y} is a subset of \code{x} and \code{FALSE} otherwise.
#' @export
isSuperset = function(x, y, strict = FALSE) {
isSubset(y, x, strict)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/isSuperset.R |
#' Can some strings be used for column or list element names without problems?
#'
#' @param x [\code{character}]\cr
#' Character vector to check.
#' @param unique [\code{logical(1)}]\cr
#' Should the names be unique?
#' Default is \code{TRUE}.
#' @return [\code{logical}]. One Boolean entry for each string in \code{x}.
#' If the entries are not unique and \code{unique} is enabled, the first duplicate will
#' be \code{FALSE}.
#' @export
isValidName = function(x, unique = TRUE) {
if (!is.character(x))
x = as.character(x)
# check that make.names does not change the string (otherwise it would be invalid),
# names are unique (for e.g. colnames) and stuff like ..1 is disallowed
x == make.names(x, isTRUE(unique)) & !grepl("^\\.\\.[0-9]$", x)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/isValidName.R |
#' Is return value of try an exception?
#'
#' Checks if an object is of class \dQuote{try-error} or
#' \dQuote{error}.
#'
#' @param x [any]\cr
#' Any object, usually the return value of \code{\link[base]{try}},
#' \code{\link[base]{tryCatch}}, or a function which may return a
#' \code{\link[base]{simpleError}}.
#' @return [\code{logical(1)}].
#' @export
#' @examples
#' x = try(stop("foo"))
#' print(is.error(x))
#' x = 1
#' print(is.error(x))
is.error = function(x) {
inherits(x, c("try-error", "error"))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/is_error.R |
#' Convert Integers to Strings
#'
#' This is the counterpart of \code{\link[base]{strtoi}}.
#' For a base greater than \sQuote{10}, letters \sQuote{a} to \sQuote{z}
#' are used to represent \sQuote{10} to \sQuote{35}.
#'
#' @param x [\code{integer}]\cr
#' Vector of integers to convert.
#' @param base [\code{integer(1)}]\cr
#' Base for conversion. Values between 2 and 36 (inclusive) are allowed.
#' @return \code{character(length(x))}.
#' @export
#' @examples
#' # binary representation of the first 10 natural numbers
#' itostr(1:10, 2)
#'
#' # base36 encoding of a large number
#' itostr(1e7, 36)
itostr = function(x, base = 10L) {
x = asInteger(x, any.missing = FALSE, lower = 0L)
base = asInt(base, na.ok = FALSE, lower = 2L, upper = 36L)
.Call("itostr", x, base, PACKAGE = "BBmisc")
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/itostr.R |
#' A wrapper for \code{library}.
#'
#' Tries to load packages. If the packages are not found, they will be installed from
#' the default repository. This function is intended for use in interactive sessions
#' and should not be used by other packages.
#'
#' @param ... [any]\cr
#' Package names.
#' @return [\code{logical}]: Named logical vector determining the success
#' of package load.
#' @export
#' @examples \dontrun{
#' lib("BBmisc", "MASS", "rpart")
#' }
lib = function(...) {
getLib = function(pkg) {
ok = suppressWarnings(require(pkg, character.only = TRUE))
if (!ok && !is.error(try(install.packages(pkg)))) {
ok = require(pkg, character.only = TRUE)
}
ok
}
pkgs = unique(c(...))
assertCharacter(pkgs, any.missing = FALSE)
vlapply(pkgs, getLib)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/lib.R |
#' Load RData file and return objects in it.
#'
#' @param file [\code{character(1)}]\cr
#' File to load.
#' @param parts [\code{character}]\cr
#' Elements in file to load.
#' Default is all.
#' @param simplify [\code{logical(1)}]\cr
#' If \code{TRUE}, a list is only returned if \code{parts} and the file contain both more
#' than 1 element, otherwise the element is directly returned.
#' Default is \code{TRUE}.
#' @param envir [\code{environment(1)}]\cr
#' Assign objects to this environment.
#' Default is not to assign.
#' @param impute [\code{ANY}]\cr
#' If \code{file} does not exists, return \code{impute} instead.
#' Default is missing which will result in an exception if \code{file} is not found.
#' @return Either a single object or a list.
#' @export
#' @examples
#' fn = tempfile()
#' save2(file = fn, a = 1, b = 2, c = 3)
#' load2(fn, parts = "a")
#' load2(fn, parts = c("a", "c"))
load2 = function(file, parts, simplify = TRUE, envir, impute) {
assertFlag(simplify)
ee = new.env()
if (!missing(impute) && !file.exists(file))
return(impute)
load(file, envir = ee)
ns = ls(ee, all.names = TRUE)
if (!missing(parts)) {
assertCharacter(parts, any.missing = FALSE)
d = setdiff(parts, ns)
if (length(d) > 0L)
stopf("File %s does not contain: %s", file, collapse(d))
} else {
parts = ns
}
if (!missing(envir)) {
lapply(ns, function(x) assign(x, ee[[x]], envir = envir))
}
if (simplify) {
if (length(ns) == 1L)
return(ee[[ns]])
if (length(parts) == 1L)
return(ee[[parts]])
}
mget(parts, envir = ee)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/load2.R |
#' A wrapper for \code{\link{sort}} to sort using the \dQuote{C} collating rules.
#'
#' @param ...
#' Options passed to sort.
#' @return See \code{\link{sort}}.
#' @export
lsort = function(...) {
cur = Sys.getlocale("LC_COLLATE")
if (cur != "C") {
Sys.setlocale("LC_COLLATE", "C")
on.exit(Sys.setlocale("LC_COLLATE", cur))
}
sort(...)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/lsort.R |
#' Initialize data.frame in a convenient way.
#'
#' @param nrow [\code{integer(1)}]\cr
#' Nubmer of rows.
#' @param ncol [\code{integer(1)}]\cr
#' Number of columns.
#' @param col.types [\code{character(ncol)} | \code{character(1)}]\cr
#' Data types of columns.
#' If you only pass one type, it will be replicated.
#' Supported are all atomic modes also supported by
#' \code{\link[base]{vector}}, i.e. all common data frame types except factors.
#' @param init [any]\cr
#' Scalar object to initialize all elements of the data.frame.
#' You do not need to specify \code{col.types} if you pass this.
#' @param row.names [\code{character} | \code{integer} | \code{NULL}]\cr
#' Row names.
#' Default is \code{NULL}.
#' @param col.names [\code{character} | \code{integer}]\cr
#' Column names.
#' Default is \dQuote{V1}, \dQuote{V2}, and so on.
#' @export
#' @examples
#' print(makeDataFrame(3, 2, init = 7))
#' print(makeDataFrame(3, 2, "logical"))
#' print(makeDataFrame(3, 2, c("logical", "numeric")))
makeDataFrame = function(nrow, ncol, col.types, init, row.names = NULL, col.names = sprintf("V%i", seq_len(ncol))) {
nrow = asCount(nrow)
ncol = asCount(ncol)
if (!missing(col.types))
assertCharacter(col.types, min.len = 1L, any.missing = FALSE)
if (!missing(init)) {
if(!isScalarValue(init))
stop("'init' must be a scalar value!")
if (!missing(col.types)) {
if (length(col.types) > 1L)
stop("If 'init' is given, length of col.types must be 1!")
if (identical(class(init)[1L], "col.types"))
stop("Class of 'init' must match given column type!")
}
}
if (!missing(col.types) && length(col.types) == 1L)
col.types = rep.int(col.types, ncol)
if (!is.null(row.names))
assert(checkIntegerish(row.names, len = nrow), checkCharacter(row.names, len = nrow))
assert(checkIntegerish(col.names, len = ncol), checkCharacter(col.names, len = ncol))
if (nrow == 0L && ncol == 0L)
df = data.frame()
else if (ncol == 0L)
df = data.frame(matrix(nrow = nrow, ncol = 0))
else if (missing(init))
df = lapply(col.types, vector, length = nrow)
else
df = replicate(ncol, rep.int(init, nrow), simplify = FALSE)
df = as.data.frame(df, stringsAsFactors = FALSE)
rownames(df) = row.names
colnames(df) = col.names
return(df)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/makeDataFrame.R |
#' @title Create a progress bar with estimated time.
#'
#' @description
#' Create a progress bar function that displays the estimated time till
#' completion and optional messages. Call the returned functions \code{set} or
#' \code{inc} during a loop to change the display.
#' Note that you are not allowed to decrease the value of the bar.
#' If you call these function without setting any of the arguments
#' the bar is simply redrawn with the current value.
#' For errorhandling use \code{error} and have a look at the example below.
#'
#' You can globally change the behavior of all bars by setting the option
#' \code{options(BBmisc.ProgressBar.style)} either to \dQuote{text} (the default)
#' or \dQuote{off}, which display no bars at all.
#'
#' You can globally change the width of all bars by setting the option
#' \code{options(BBmisc.ProgressBar.width)}. By default this is \code{getOption("width")}.
#'
#' You can globally set the stream where the output of the bar is directed by setting the option
#' \code{options(BBmisc.ProgressBar.stream)} either to \dQuote{stderr} (the default)
#' or \dQuote{stdout}. Note that using the latter will result in the bar being shown in
#' reports generated by Sweave or knitr, what you probably do not want.
#'
#' @param min [\code{numeric(1)}]\cr
#' Minimum value, default is 0.
#' @param max [\code{numeric(1)}]\cr
#' Maximum value, default is 100.
#' @param label [\code{character(1)}]\cr
#' Label shown in front of the progress bar.
#' Note that if you later set \code{msg} in the progress bar function,
#' the message will be left-padded to the length of this label, therefore
#' it should be at least as long as the longest message you want to display.
#' Default is \dQuote{}.
#' @param char [\code{character(1)}]\cr
#' A single character used to display progress in the bar.
#' Default is \sQuote{+}.
#' @param style [\code{character(1)}]\cr
#' Style of the progress bar. Default is set via options (see details).
#' @param width [\code{integer(1)}]\cr
#' Width of the progress bar. Default is set via options (see details).
#' @param stream [\code{character(1)}]\cr
#' Stream to use. Default is set via options (see details).
#' @return [\code{\link{ProgressBar}}]. A list with following functions:
#' \item{set [function(value, msg = label)]}{Set the bar to a value and possibly display a message instead of the label.}
#' \item{inc [function(value, msg = label)]}{Increase the bar and possibly display a message instead of the label.}
#' \item{kill [function(clear = FALSE)]}{Kill the bar so it cannot be used anymore. Cursor is moved to new line. You can also erase its display.}
#' \item{error [function(e)]}{Useful in \code{tryCatch} to properly display error messages below the bar. See the example.}
#' @export
#' @aliases ProgressBar
#' @examples
#' bar = makeProgressBar(max = 5, label = "test-bar")
#' for (i in 0:5) {
#' bar$set(i)
#' Sys.sleep(0.2)
#' }
#' bar = makeProgressBar(max = 5, label = "test-bar")
#' for (i in 1:5) {
#' bar$inc(1)
#' Sys.sleep(0.2)
#' }
#' # display errors properly (in next line)
#' \dontrun{
#' f = function(i) if (i>2) stop("foo")
#' bar = makeProgressBar(max = 5, label = "test-bar")
#' for (i in 1:5) {
#' tryCatch ({
#' f(i)
#' bar$set(i)
#' }, error = bar$error)
#' }
#' }
makeProgressBar = function(min = 0, max = 100, label = "", char = "+",
style = getOption("BBmisc.ProgressBar.style", "text"),
width = getOption("BBmisc.ProgressBar.width", getOption("width")),
stream = getOption("BBmisc.ProgressBar.stream", "stderr")) {
assertNumber(min)
assertNumber(max)
assertString(label)
assertChoice(style, c("text", "off"))
assertInt(width, lower = 30L)
assertChoice(stream, c("stderr", "stdout"))
if (style == "off")
return(structure(list(
set = function(value, msg = label) invisible(NULL),
inc = function(inc, msg = label) invisible(NULL),
kill = function(clear = FALSE) invisible(NULL),
error = function(e) stop(e)
), class = "ProgressBar"))
mycat = if (stream == "stdout")
function(...) cat(...)
else
function(...) cat(..., file = stderr())
## label |................................| xxx% (hh:mm:ss)
label.width = nchar(label)
bar.width = width - label.width - 21L
bar = rep(" ", bar.width)
start.time = as.integer(Sys.time())
delta = max - min
kill.line = "\r"
killed = FALSE
cur.value = min
draw = function(value, inc, msg) {
if (!missing(value) && !missing(inc))
stop("You must not set value and inc!")
else if (!missing(value))
assertNumber(value, lower = max(min, cur.value), upper = max)
else if (!missing(inc)) {
assertNumber(inc, lower = 0, upper = max - cur.value)
value = cur.value + inc
} else {
value = cur.value
}
if (!killed) {
# special case for min == max, weird "empty" bar, but might happen...
if (value == max)
rate = 1
else
rate = (value - min) / delta
bin = round(rate * bar.width)
bar[seq(bin)] <<- char
delta.time = as.integer(Sys.time()) - start.time
if (value == min)
rest.time = 0
else
rest.time = (max - value) * (delta.time / (value - min))
rest.time = splitTime(rest.time, "hours")
# as a precaution, so we can _always_ print in the progress bar cat
if (rest.time["hours"] > 99)
rest.time[] = 99
mycat(kill.line)
msg = sprintf(sprintf("%%%is", label.width), msg)
mycat(sprintf("%s |%s| %3i%% (%02i:%02i:%02i)", msg, collapse(bar, sep = ""), round(rate*100),
rest.time["hours"], rest.time["minutes"], rest.time["seconds"]))
if (value == max)
kill()
flush.console()
}
cur.value <<- value
}
clear = function(newline = TRUE) {
mycat(kill.line)
mycat(rep(" ", width))
if (newline)
mycat("\n")
}
kill = function(clear = FALSE) {
if (clear)
clear(newline = TRUE)
else
mycat("\n")
killed <<- TRUE
}
makeS3Obj("ProgressBar",
set = function(value, msg = label) draw(value = value, msg = msg),
inc = function(inc, msg = label) draw(inc = inc, msg = msg),
kill = kill,
error = function(e) {
kill(clear = FALSE)
stop(e)
}
)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/makeProgressBar.R |
#' Simple constructor for S3 objects based on lists.
#'
#' Simple wrapper for \code{as.list} and \code{\link{setClasses}}.
#'
#' @param classes [\code{character}]\cr
#' Class(es) for constructed object.
#' @param ... [any]\cr
#' Key-value pairs for class members.
#' @return Object.
#' @export
#' @examples
#' makeS3Obj("car", speed = 100, color = "red")
makeS3Obj = function(classes, ...) {
assertCharacter(classes, min.len = 1L, any.missing = FALSE)
setClasses(list(...), classes = classes)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/makeS3Obj.R |
#' Simple logger which outputs to a file.
#'
#' Creates a simple file logger closure to log to a file, including time stamps.
#' An optional buffer holds the last few log messages.
#'
#' @param logfile [\code{character(1)}]\cr
#' File to log to.
#' @param touch [\code{logical(1)}]\cr
#' Should the file be created before the first log message?
#' Default is \code{FALSE}.
#' @param keep [\code{integer(1)}]\cr
#' Number of log messages to keep in memory for quick access.
#' Default is \code{10}.
#' @return [\code{\link{SimpleFileLogger}}]. A list with following functions:
#' \item{log [function(msg)]}{Send log message.}
#' \item{getMessages [function(n)]}{Get last \code{n} log messages.}
#' \item{clear [function()]}{Resets logger and deletes log file.}
#' \item{getSize [function()]}{Returns the number of logs written.}
#' \item{getLogfile [function()]}{Returns the full file name logs are written to.}
#' @export
#' @aliases SimpleFileLogger
makeSimpleFileLogger = function(logfile, touch = FALSE, keep = 10L) {
assertString(logfile)
assertFlag(touch)
keep = asCount(keep)
assertDirectoryExists(dirname(logfile), "w")
if (touch && !file.create(logfile))
stopf("Could not create file '%s'", logfile)
if (keep)
buffer = circularBuffer("character", keep)
n.lines = 0L
makeS3Obj("SimpleFileLogger",
log = function(msg) {
if (keep)
buffer$push(msg)
if (!touch && n.lines == 0L && !file.create(logfile))
stopf("Could not create file '%s'", logfile)
catf("<%s> %s", as.character(Sys.time()), msg, file = logfile, append = TRUE, newline = TRUE)
n.lines <<- n.lines + 1L
},
getMessages = function(n) {
if (!keep || n > keep)
return(sub("^<.+> (.*)", "\\1", tail(readLines(logfile), n)))
buffer$get(n)
},
clear = function() {
if (keep)
buffer$clear()
n.lines <<- 0L
file.remove(logfile)
},
getSize = function() {
n.lines
},
getLogfile = function() {
logfile
}
)
}
circularBuffer = function(type, capacity) {
st = vector(type, capacity)
stored = 0L
pos = 0L
list(
push = function(x) {
pos <<- pos %% capacity + 1L
stored <<- min(capacity, stored + 1L)
st[[pos]] <<- x
},
get = function(n = 1L) {
head(st[rev((seq_len(stored) + pos - 1L) %% stored + 1L)], n)
},
stored = function() {
stored
},
clear = function() {
st <<- vector(type, capacity)
stored <<- 0
pos <<- 0
}
)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/makeSimpleFileLogger.R |
#' Replace values in atomic vectors
#'
#' @details
#' Replaces values specified in \code{from} with values in \code{to}.
#' Regular expression matching can be enabled which calls \code{\link[base]{gsub}} iteratively
#' on \code{x} to replace all patterns in \code{from} with replacements in \code{to}.
#'
#' @param x [\code{atomic}]\cr
#' Atomic vector. If \code{x} is a factor, all replacements work on the levels.
#' @param from [\code{atomic}]\cr
#' Atomic vector with values to replace, same length as \code{to}.
#' @param to [\code{atomic}]\cr
#' Atomic vector with replacements, same length as \code{from}.
#' @param regex [\code{logical}]\cr
#' Use regular expression matching? Default is \code{FALSE}.
#' @param ignore.case [\code{logical}]\cr
#' Argument passed to \code{\link[base]{gsub}}.
#' @param perl [\code{logical}]\cr
#' Argument passed to \code{\link[base]{gsub}}.
#' @param fixed [\code{logical}]\cr
#' Argument passed to \code{\link[base]{gsub}}.
#' @return [\code{atomic}].
#' @export
#' @examples
#' # replace integers
#' x = 1:5
#' mapValues(x, c(2, 3), c(99, 100))
#'
#' # replace factor levels using regex matching
#' x = factor(c("aab", "aba", "baa"))
#' mapValues(x, "a.a", "zzz", regex = TRUE)
mapValues = function(x, from, to, regex = FALSE, ignore.case = FALSE, perl = FALSE, fixed = FALSE) {
assertAtomic(x)
assertAtomic(from)
assertAtomic(to, len = length(from))
assertFlag(regex)
map = function(x, from, to) {
if (regex) {
for (i in seq_along(from))
x = gsub(from[i], to[i], x, ignore.case = ignore.case, perl = perl, fixed = fixed)
} else {
m = match(x, from, nomatch = NA_integer_)
found = !is.na(m)
x[found] = to[m[found]]
}
return(x)
}
if (is.factor(x)) {
levels(x) = map(levels(x), from, to)
return(x)
}
return(map(x, from, to))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/mapValues.R |
# FIXME: not used anywhere?
matchDataFrameSubset = function(df, ss, factors.as.chars = TRUE) {
# checkArg(df, c("list", "data.frame"))
# checkArg(ss, c("list", "data.frame"))
if (!isProperlyNamed(df))
stop("'df' is not proberbly named")
if (!isProperlyNamed(ss))
stop("'ss' is not proberbly named")
if (any(names(ss) %nin% names(df)))
stop("Names of 'ss' not found in 'df'")
if (is.list(df))
df = as.data.frame(df, stringsAsFactors = FALSE)
if (is.list(ss))
ss = as.data.frame(ss, stringsAsFactors = FALSE)
df = subset(df, select = names(ss))
if (factors.as.chars) {
df = convertDataFrameCols(df, factors.as.char = TRUE)
ss = convertDataFrameCols(ss, factors.as.char = TRUE)
}
conv = function(x) rawToChar(serialize(x, connection = NULL, ascii = TRUE))
match(rowSapply(ss, conv, use.names = FALSE), rowSapply(df, conv, use.names = FALSE))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/matchDataFrameSubset.R |
#' Wrapper for message and sprintf.
#'
#' A simple wrapper for \code{message(sprintf(...))}.
#'
#' @param ... [any]\cr
#' See \code{\link{sprintf}}.
#' @param .newline [logical(1)]\cr
#' Add a newline to the message. Default is \code{TRUE}.
#' @return Nothing.
#' @export
#' @examples
#' msg = "a message"
#' warningf("this is %s", msg)
messagef = function(..., .newline = TRUE) {
message(sprintf(...), appendLF = .newline)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/messagef.R |
#' @title Create named list, possibly initialized with a certain element.
#'
#' @description
#' Even an empty list will always be named.
#'
#' @param names [\code{character}]\cr
#' Names of elements.
#' @param init [valid R expression]\cr
#' If given all list elements are initialized to this, otherwise
#' \code{NULL} is used.
#' @return [\code{list}].
#' @export
#' @examples
#' namedList(c("a", "b"))
#' namedList(c("a", "b"), init = 1)
namedList = function(names, init) {
if (missing(names))
return(setNames(list(), character(0L)))
n = length(names)
if (missing(init))
xs = vector("list", n)
else
xs = replicate(n, init, simplify = FALSE)
setNames(xs, names)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/namedList.R |
#' Replacement for names which always returns a vector.
#'
#' A simple wrapper for \code{\link[base]{names}}.
#' Returns a vector even if no names attribute is set.
#' Values \code{NA} and \code{""} are treated as missing and
#' replaced with the value provided in \code{missing.val}.
#'
#' @param x [\code{ANY}]\cr
#' Object, probably named.
#' @param missing.val [\code{ANY}]\cr
#' Value to set for missing names. Default is \code{NA_character_}.
#' @return [\code{character}]: vector of the same length as \code{x}.
#' @export
#' @examples
#' x = 1:3
#' names(x)
#' names2(x)
#' names(x[1:2]) = letters[1:2]
#' names(x)
#' names2(x)
names2 = function(x, missing.val = NA_character_) {
n = names(x)
if (is.null(n))
return(rep.int(missing.val, length(x)))
replace(n, is.na(n) | n == "", missing.val)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/names2.R |
#' Simply a negated \code{in} operator.
#'
#' @param x [\code{vector}]\cr
#' Values that should not be in \code{y}.
#' @param y [\code{vector}]\cr
#' Values to match against.
#' @usage x \%nin\% y
#' @rdname nin
#' @export
`%nin%` = function(x, y) {
!match(x, y, nomatch = 0L)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/nin.R |
#' @title Normalizes numeric data to a given scale.
#'
#' @description
#' Currently implemented for numeric vectors, numeric matrices and data.frame.
#' For matrixes one can operate on rows or columns
#' For data.frames, only the numeric columns are touched, all others are left unchanged.
#' For constant vectors / rows / columns most methods fail, special behaviour for this
#' case is implemented.
#'
#' The method also handles NAs in in \code{x} and leaves them untouched.
#'
#' @param x [\code{numeric} | \code{matrix} | \code{data.frame}]\cr
#' Input vector.
#' @param method [\code{character(1)}]\cr
#' Normalizing method. Available are:\cr
#' \dQuote{center}: Subtract mean.\cr
#' \dQuote{scale}: Divide by standard deviation.\cr
#' \dQuote{standardize}: Center and scale.\cr
#' \dQuote{range}: Scale to a given range.\cr
#' @param range [\code{numeric(2)}]\cr
#' Range for method \dQuote{range}.
#' The first value represents the replacement for the min value, the second is the substitute for the max value.
#' So it is possible to reverse the order by giving \code{range = c(1,0)}.
#' Default is \code{c(0,1)}.
#' @param margin [\code{integer(1)}]\cr
#' 1 = rows, 2 = cols.
#' Same is in \code{\link{apply}}
#' Default is 1.
#' @param on.constant [\code{character(1)}]\cr
#' How should constant vectors be treated? Only used, of \dQuote{method != center},
#' since this methods does not fail for constant vectors. Possible actions are:\cr
#' \dQuote{quiet}: Depending on the method, treat them quietly:\cr
#' \dQuote{scale}: No division by standard deviation is done, input values.
#' will be returned untouched.\cr
#' \dQuote{standardize}: Only the mean is subtracted, no division is done.\cr
#' \dQuote{range}: All values are mapped to the mean of the given range.\cr
#' \dQuote{warn}: Same behaviour as \dQuote{quiet}, but print a warning message.\cr
#' \dQuote{stop}: Stop with an error.\cr
#' @return [\code{numeric} | \code{matrix} | \code{data.frame}].
#' @seealso \code{\link{scale}}
#' @export
normalize = function(x, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet") {
assertChoice(method, c("range", "standardize", "center", "scale"))
assertNumeric(range, len = 2L, any.missing = FALSE)
assertChoice(on.constant, c("quiet", "warn", "stop"))
UseMethod("normalize")
}
#' @export
normalize.numeric = function(x, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet") {
y = normalize2(x, method, range, on.constant = on.constant)
# scale call below returns matrices
if (is.matrix(y))
y = y[,1L]
return(y)
}
#' @export
normalize.matrix = function(x, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet") {
x = apply(x, margin, normalize2, method = method, range = range, on.constant = on.constant)
if (margin == 1L)
x = t(x)
return(x)
}
#' @export
normalize.data.frame = function(x, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet") {
isnum = sapply(x, is.numeric)
if (any(isnum))
x[, isnum] = as.data.frame(lapply(x[, isnum, drop = FALSE], normalize2, method = method,
range = range, on.constant = on.constant))
return(x)
}
normalize2 = function(x, method, range, on.constant) {
# is x a constant vector?
if (length(unique(x[!is.na(x)])) == 1L) {
switch(on.constant,
warn = warning("Constant vector in normalization."),
stop = stop("Constant vector in normalization."))
switch(method,
center = scale(x, center = TRUE, scale = FALSE),
range = ifelse(is.na(x), NA, mean(range)),
standardize = scale(x, center = TRUE, scale = FALSE),
scale = x
)
} else {
switch(method,
range = (x - min(x, na.rm = TRUE)) / diff(range(x, na.rm = TRUE)) * diff(range) + range[1L],
standardize = scale(x, center = TRUE, scale = TRUE),
center = scale(x, center = TRUE, scale = FALSE),
scale = scale(x, center = FALSE, scale = sd(x, na.rm = TRUE))
)
}
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/normalize.R |
#' @title Naive multi-start version of \code{\link{optimize}} for global optimization.
#'
#' @description
#' The univariate \code{\link{optimize}} can stop at arbitrarily bad points when
#' \code{f} is not unimodal. This functions mitigates this effect in a very naive way:
#' \code{interval} is subdivided into \code{nsub} equally sized subintervals,
#' \code{\link{optimize}} is run on all of them (and on the original big interval) and
#' the best obtained point is returned.
#'
#' @param f See \code{\link{optimize}}.
#' @param interval See \code{\link{optimize}}.
#' @param ... See \code{\link{optimize}}.
#' @param lower See \code{\link{optimize}}.
#' @param upper See \code{\link{optimize}}.
#' @param maximum See \code{\link{optimize}}.
#' @param tol See \code{\link{optimize}}.
#' @param nsub [\code{integer(1)}]\cr
#' Number of subintervals. A value of 1 implies normal \code{\link{optimize}} behavior.
#' Default is 50L.
#' @return See \code{\link{optimize}}.
#' @export
optimizeSubInts = function(f, interval, ..., lower = min(interval), upper = max(interval),
maximum = FALSE, tol = .Machine$double.eps^0.25, nsub = 50L) {
nsub = asCount(nsub, positive = TRUE)
interval = c(lower, upper)
# run on normal interval
best = optimize(f = f, interval = interval, maximum = maximum, tol = tol)
# run on smaller partitions
if (nsub > 1L) {
mult = ifelse(maximum, -1, 1)
grid = seq(lower, upper, length.out = nsub + 1L)
for (j in seq_len(length(grid)-1L)) {
res = optimize(f = f, interval = c(grid[j], grid[j+1L]), maximum = maximum, tol = tol)
if (mult * res$objective < mult * best$objective)
best = res
}
}
return(best)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/optimizeSubInts.R |
#' Pause in interactive mode and continue on <Enter>.
#' @export
pause = function() {
if (interactive())
readline("Pause. Press <Enter> to continue.")
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/pause.R |
#' More meaningful \code{head(df)} output.
#'
#' The behaviour is similar to \code{print(head(x, n))}. The difference is, that if
#' the number of rows in a data.frame/matrix or the number of elements in a list
#' or vector is larger than \code{n}, additional information is printed about
#' the total number of rows or elements respectively.
#'
#' @param x [\code{data.frame} | \code{matrix} | \code{list} | \code{vector}]\cr
#' Object.
#' @param n [\code{integer(1)}]\cr
#' Single positive integer: number of rows for a matrix/data.frame or number of
#' elements for vectors/lists respectively.
#' @return Nothing.
#' @export
printHead = function(x, n = 6L) {
assertCount(n, positive = TRUE)
print(head(x, n = n))
if ((is.data.frame(x) || is.matrix(x)) && nrow(x) > n)
catf("... (#rows: %i, #cols: %i)", nrow(x), ncol(x))
else if (length(x) > n)
catf("... (#elements: %i)", length(x))
invisible(NULL)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/printHead.R |
#' Print \code{str(x)} of an object to a string / character vector.
#'
#' @param x [any]\cr
#' Object to print
#' @param collapse [\code{character(1)}]\cr
#' Used to collapse multiple lines.
#' \code{NULL} means no collapsing, vector is returned.
#' Default is \dQuote{\\n}.
#' @return [\code{character}].
#' @export
#' @examples
#' printStrToChar(iris)
printStrToChar = function(x, collapse = "\n") {
d = printToChar(str(x), collapse = NULL)
# remove NULL from str
collapse(d[-length(d)], collapse)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/printStrToChar.R |
#' Prints object to a string / character vector.
#'
#' @param x [any]\cr
#' Object to print
#' @param collapse [\code{character(1)}]\cr
#' Used to collapse multiple lines.
#' \code{NULL} means no collapsing, vector is returned.
#' Default is \dQuote{\\n}.
#' @return [\code{character}].
#' @export
#' @examples
#' x = data.frame(a = 1:2, b = 3:4)
#' str(printToChar(x))
printToChar = function(x, collapse = "\n") {
rval = NULL
con = textConnection("rval", "w", local = TRUE)
sink(con)
on.exit({
sink()
close(con)
})
print(x)
if (!is.null(collapse))
paste(rval, collapse = collapse)
else
rval
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/printToChar.R |
#' Calculate range statistic.
#'
#' A simple wrapper for \code{diff(range(x))}, so \code{max(x) - min(x)}.
#'
#' @param x [\code{numeric}]\cr
#' The vector.
#' @param na.rm [\code{logical(1)}]\cr
#' If \code{FALSE}, NA is returned if an NA is encountered in \code{x}.
#' If \code{TRUE}, NAs are disregarded.
#' Default is \code{FALSE}
#' @return [\code{numeric(1)}].
#' @export
rangeVal = function(x, na.rm = FALSE) {
assertNumeric(x, min.len = 1L, any.missing = TRUE)
assertFlag(na.rm)
if (allMissing(x))
return(NA_real_)
diff(range(x, na.rm = na.rm))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/rangeVal.R |
#' @title Require some packages.
#'
#' @description
#' Packages are loaded either via \code{\link{requireNamespace}} or \code{\link{require}}.
#'
#' If some packages could not be loaded and \code{stop} is \code{TRUE}
#' the following exception is thrown:
#' \dQuote{For <why> please install the following packages: <missing packages>}.
#' If \code{why} is \code{NULL} the message is:
#' \dQuote{Please install the following packages: <missing packages>}.
#'
#' @param packs [\code{character}]\cr
#' Names of packages.
#' If a package name is prefixed with \dQuote{!}, it will be attached using \code{\link[base]{require}}.
#' If a package name is prefixed with \dQuote{_}, its namespace will be loaded using \code{\link[base]{requireNamespace}}.
#' If there is no prefix, argument \code{default.method} determines how to deal with package loading.
#' @param min.versions [\code{character}]\cr
#' A char vector specifying required minimal version numbers for a subset of packages in \code{packs}.
#' Must be named and all names must be in \code{packs}.
#' The only exception is when \code{packs} is only a single string, then you are allowed to pass
#' an unnamed version string here.
#' Default is \code{NULL}, meaning no special version requirements
#' @param why [\code{character(1)}]\cr
#' Short string explaining why packages are required.
#' Default is an empty string.
#' @param stop [\code{logical(1)}]\cr
#' Should an exception be thrown for missing packages?
#' Default is \code{TRUE}.
#' @param suppress.warnings [\code{logical(1)}]\cr
#' Should warnings be supressed while requiring?
#' Default is \code{FALSE}.
#' @param default.method [\code{character(1)}]\cr
#' If the packages are not explicitly prefixed with \dQuote{!} or \dQuote{_},
#' this arguments determines the default. Possible values are \dQuote{attach} and
#' \dQuote{load}.
#' Note that the default is \dQuote{attach}, but this might/will change in a future version, so
#' please make sure to always explicitly set this.
#' @return [\code{logical}]. Named logical vector describing which packages could be loaded (with required version).
#' Same length as \code{packs}.
#' @export
#' @examples
#' requirePackages(c("BBmisc", "base"), why = "BBmisc example")
requirePackages = function(packs, min.versions = NULL, why = "", stop = TRUE, suppress.warnings = FALSE, default.method = "attach") {
assertCharacter(packs, any.missing = FALSE)
if (!is.null(min.versions)) {
assertCharacter(min.versions)
if (length(packs) == 1L && length(min.versions) == 1L && is.null(names(min.versions)))
names(min.versions) = packs
else
assertSubset(names(min.versions), packs)
}
assertFlag(stop)
assertFlag(suppress.warnings)
assertChoice(default.method, choices = c("load", "attach"))
char = substr(packs, 1L, 1L)
force.attach = (char == "!")
force.load = (char == "_")
ns.only = if (default.method == "load") !force.attach else force.load
packs = substr(packs, 1L + (force.load | force.attach), nchar(packs))
suppressor = if (suppress.warnings) suppressWarnings else identity
packs.ok = unlist(Map(function(pack, ns.only) {
if (ns.only) {
suppressor(requireNamespace(pack, quietly = TRUE))
} else {
suppressor(require(pack, character.only = TRUE))
}
}, pack = packs, ns.only = ns.only))
if (stop && !all(packs.ok)) {
ps = collapse(packs[!packs.ok])
if (nzchar(why))
stopf("For %s please install the following packages: %s", why, ps)
else
stopf("Please install the following packages: %s", ps)
}
if (!is.null(min.versions)) {
packs.wrong.version = character(0L)
for (j in seq_along(min.versions)) {
pn = names(min.versions)[j]
mv = min.versions[j]
if (packageVersion(pn) < mv) {
packs.ok[pn] = FALSE
packs.wrong.version = c(packs.wrong.version, sprintf("%s >= %s", pn, mv))
}
}
if (stop && length(packs.wrong.version) > 0L) {
ps = collapse(packs.wrong.version)
if (nzchar(why))
stopf("For %s the package version requirements are not fulfilled: %s", why, ps)
else
stopf("The package version requirements are not fulfilled: %s", ps)
}
}
return(packs.ok)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/requirePackages.R |
#' Apply function to rows of a data frame.
#'
#' Just like an \code{\link[base]{lapply}} on data frames,
#' but on the rows.
#'
#' @param df [\code{data.frame}]\cr
#' Data frame.
#' @param fun [\code{function}]\cr
#' Function to apply. Rows are passed as list or vector,
#' depending on argument \code{unlist}, as first argument.
#' @param ... [\code{ANY}]\cr
#' Additional arguments for \code{fun}.
#' @param unlist [\code{logical(1)}]\cr
#' Unlist the row? Note that automatic conversion may be triggered for
#' lists of mixed data types
#' Default is \code{FALSE}.
#' @param simplify [\code{logical(1)} | character(1)]\cr
#' Should the result be simplified?
#' See \code{\link{sapply}}.
#' If \dQuote{cols}, we expect the call results to be vectors of the same length and they are
#' arranged as the columns of the resulting matrix.
#' If \dQuote{rows}, likewise, but rows of the resulting matrix.
#' Default is \code{TRUE}.
#' @param use.names [\code{logical(1)}]\cr
#' Should result be named by the row names of \code{df}?
#' Default is \code{TRUE}.
#' @return [\code{list} or simplified object]. Length is \code{nrow(df)}.
#' @export
#' @examples
#' rowLapply(iris, function(x) x$Sepal.Length + x$Sepal.Width)
rowLapply = function(df, fun, ..., unlist = FALSE) {
assertDataFrame(df)
fun = match.fun(fun)
assertFlag(unlist)
if (unlist) {
.wrap = function(.i, .df, .fun, ...)
.fun(unlist(.df[.i, , drop = FALSE], recursive = FALSE, use.names = TRUE), ...)
} else {
.wrap = function(.i, .df, .fun, ...)
.fun(as.list(.df[.i, , drop = FALSE]), ...)
}
lapply(seq_row(df), .wrap, .fun = fun, .df = df, ...)
}
#' @export
#' @rdname rowLapply
rowSapply = function(df, fun, ..., unlist = FALSE, simplify = TRUE, use.names = TRUE) {
assert(checkFlag(simplify), checkChoice(simplify, c("cols", "rows")))
assertFlag(use.names)
ys = rowLapply(df, fun, ..., unlist = unlist)
# simplify result
if (length(ys) > 0L) {
if (isTRUE(simplify)) {
ys = simplify2array(ys)
} else if (simplify == "rows") {
ys = asMatrixRows(ys)
} else if (simplify == "cols") {
ys = asMatrixCols(ys)
}
}
# set names
if (use.names) {
if (is.matrix(ys)) {
colnames(ys) = rownames(df)
rownames(ys) = NULL
} else {
names(ys) = rownames(df)
}
} else {
names(ys) = NULL
}
return(ys)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/rowLapply.R |
#' Save multiple objects to a file.
#'
#' A simple wrapper for \code{\link[base]{save}}. Understands key = value syntax to save
#' objects using arbitrary variable names. All options of \code{\link[base]{save}},
#' except \code{list} and \code{envir}, are available and passed to
#' \code{\link[base]{save}}.
#'
#' @param file
#' File to save.
#' @param ... [\code{any}]\cr
#' Will be converted to an environment and then passed to \code{\link[base]{save}}.
#' @param ascii
#' See help of \code{\link[base]{save}}.
#' @param version
#' See help of \code{\link[base]{save}}.
#' @param compress
#' See help of \code{\link[base]{save}}.
#' @param compression_level
#' See help of \code{\link[base]{save}}.
#' @param eval.promises
#' See help of \code{\link[base]{save}}.
#' @param precheck
#' See help of \code{\link[base]{save}}.
#' @return See help of \code{\link[base]{save}}.
#' @export
#' @examples
#' x = 1
#' save2(y = x, file = tempfile())
save2 = function(file, ..., ascii = FALSE, version = NULL, compress = !ascii,
compression_level, eval.promises = TRUE, precheck = TRUE) {
args = tryCatch(as.environment(argsAsNamedList(...)), error = function(e) stopf("Unable to convert to environment (%s)", as.character(e)))
save(list = ls(args, all.names = TRUE), envir = args, file = file, ascii = ascii, version = version, compress = compress,
compression_level = compression_level, eval.promises = eval.promises, precheck = precheck)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/save2.R |
#' Generate sequences along rows or cols.
#'
#' A simple convenience wrapper around \code{\link[base]{seq_len}}.
#'
#' @param x [\code{data.frame} | \code{matrix}]\cr
#' Data frame, matrix or any object which supports \code{\link[base]{nrow}}
#' or \code{\link[base]{ncol}}, respectively.
#' @return Vector of type [\code{integer}].
#' @export
#' @examples
#' data(iris)
#' seq_row(iris)
#' seq_col(iris)
seq_row = function(x) {
seq_len(nrow(x))
}
#' @export seq_col
#' @rdname seq_row
seq_col = function(x) {
seq_len(ncol(x))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/seq.R |
#' A wrapper for \code{attr(x, which) = y}.
#'
#' @param x [any]\cr
#' Your object.
#' @param which [\code{character(1)}]\cr
#' Name of the attribute to set
#' @param value [\code{ANY}]\cr
#' Value for the attribute.
#' @return Changed object \code{x}.
#' @export
#' @examples
#' setAttribute(list(), "foo", 1)
setAttribute = function(x, which, value) {
attr(x, which) = value
x
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/setAttribute.R |
#' A wrapper for \code{class(x) = classes}.
#'
#' @param x [any]\cr
#' Your object.
#' @param classes [\code{character}]\cr
#' New classes.
#' @return Changed object \code{x}.
#' @export
#' @examples
#' setClasses(list(), c("foo1", "foo2"))
setClasses = function(x, classes) {
class(x) = classes
x
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/setClasses.R |
#' Wrapper for \code{rownames(x) = y}, \code{colnames(x) = y}.
#'
#' @param x [\code{matrix} | \code{data.frame}]\cr
#' Matrix or data.frame.
#' @param names [\code{character}]\cr
#' New names for rows / columns.
#' @return Changed object \code{x}.
#' @export
#' @examples
#' setColNames(matrix(1:4, 2, 2), c("a", "b"))
setRowNames = function(x, names) {
rownames(x) = names
x
}
#' @rdname setRowNames
#' @export
setColNames = function(x, names) {
colnames(x) = names
x
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/setRowColNames.R |
#' Set a list element to a new value.
#'
#' This wrapper supports setting elements to \code{NULL}.
#'
#' @param obj [\code{list}]\cr
#' @param index [\code{character} | \code{integer}]\cr
#' Index or indices where to insert the new values.
#' @param newval [any]\cr
#' Inserted elements(s).
#' Has to be a list if \code{index} is a vector.
#' @return [\code{list}]
#' @export
setValue = function(obj, index, newval) {
assertList(obj)
assert(checkCharacter(index, any.missing = FALSE), checkIntegerish(index, any.missing = FALSE))
if (length(index) == 1L) {
if (is.null(newval))
obj[index] = list(NULL)
else
obj[index] = newval
} else {
assertList(newval, len = length(index))
obj[index] = newval
}
return(obj)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/setValue.R |
#' Sort the rows of a data.frame according to one or more columns.
#'
#' @param x [\code{data.frame}]\cr
#' Data.frame to sort.
#' @param col [\code{character}]\cr
#' One or more column names to sort \code{x} by.
#' In order of preference.
#' @param asc [\code{logical}]\cr
#' Sort ascending (or descending)?
#' One value per entry of \code{col}.
#' If a scalar logical is passed, it is replicated.
#' Default is \code{TRUE}.
#' @return [\code{data.frame}].
#' @export
sortByCol = function(x, col, asc = TRUE) {
assertDataFrame(x)
assertSubset(col, colnames(x))
m = length(col)
assertLogical(asc, min.len = 1L, any.missing = FALSE)
if (length(asc) == 1L)
asc = rep(asc, m)
asc = ifelse(asc, 1, -1)
args = as.list(x[, col, drop = FALSE])
# convert col to orderable numeric and multiply with factor
args = Map(function(a, b) xtfrm(a) * b, args, asc)
# now order the numerics and permute df
o = do.call(order, args)
return(x[o, , drop = FALSE])
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/sortByCol.R |
#' Split a path into components
#'
#' The first normalized path is split on forward and backward slashes and its components returned as
#' character vector. The drive or network home are extracted separately on windows systems and
#' empty on all other systems.
#'
#' @param path [\code{character(1)}]\cr
#' Path to split as string
#' @return \code{named list}: List with components \dQuote{drive} (\code{character(1)}
#' and \dQuote{path} (\code{character(n)}.
#' @export
splitPath = function(path) {
assertString(path)
path = normalizePath(path, mustWork = FALSE)
if (isWindows()) {
pattern = "^([[:alpha:]]:)|(\\\\[[:alnum:]]+)"
m = regexpr(pattern, path)
if (length(m) == 1L && m == -1L)
stop("Error extracting the drive letter")
drive = regmatches(path, m)
regmatches(path, m) = ""
} else {
drive = character(0L)
}
list(drive = drive, path = Filter(nzchar, strsplit(path, "[/\\]+")[[1L]]))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/splitPath.R |
#' Split seconds into handy chunks of time.
#'
#' Note that a year is simply defined as exactly 365 days.
#'
#' @param seconds [\code{numeric(1)}]\cr
#' Number of seconds. If not an integer, it is rounded down.
#' @param unit [\code{character(1)}]\cr
#' Largest unit to split seconds into.
#' Must be one of: \code{c("years", "days", "hours", "minutes", "seconds")}.
#' Default is \dQuote{years}.
#' @return [\code{numeric(5)}]. A named vector containing the
#' \dQuote{years}, \dQuote{days}, \dQuote{hours}, \dQuote{minutes}
#' and \dQuote{seconds}. Units larger than the given \code{unit} are
#' \code{NA}.
#' @export
#' @examples
#' splitTime(1000)
splitTime = function(seconds, unit = "years") {
assertNumber(seconds)
assertChoice(unit, c("years", "days", "hours", "minutes", "seconds"))
divider = c(31536000L, 86400L, 3600L, 60L, 1L)
res = setNames(rep.int(NA_integer_, 5L),
c("years", "days", "hours", "minutes", "seconds"))
start = which(names(res) == unit)
for (i in start:length(divider)) {
res[i] = seconds %/% divider[i]
seconds = seconds - res[i] * divider[i]
}
## Make sure all values are integral and do _not_ strip names:
viapply(res, as.integer)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/splitTime.R |
#' Wrapper for stop and sprintf.
#'
#' A wrapper for \code{\link{stop}} with \code{\link{sprintf}} applied to the arguments.
#' Notable difference is that error messages are not truncated to 1000 characters
#' by default.
#'
#' @param ... [any]\cr
#' See \code{\link{sprintf}}.
#' @param warning.length [\code{integer(1)}]\cr
#' Number of chars after which the error message
#' gets truncated, see ?options.
#' Default is 8170.
#' @return Nothing.
#' @export
#' @examples
#' err = "an error."
#' try(stopf("This is %s", err))
stopf = function(..., warning.length = 8170L) {
msg = sprintf(...)
obj = simpleError(msg, call = sys.call(sys.parent()))
old.opt = getOption("warning.length")
on.exit(options(warning.length = old.opt))
options(warning.length = warning.length)
stop(obj)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/stopf.R |
#' Repeat and join a string
#'
#' @param x [character]\cr
#' Vector of characters.
#' @param n [\code{integer(1)}]\cr
#' Times the vector \code{x} is repeated.
#' @param sep [\code{character(1)}]\cr
#' Separator to use to collapse the vector of characters.
#' @return \code{character(1)}.
#' @export
#' @examples
#' strrepeat("x", 3)
strrepeat = function(x, n, sep = "") {
paste0(rep.int(x, n), collapse = sep)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/strrepeat.R |
#' Suppresses all output except for errors.
#'
#' Evaluates an expression and suppresses all output except for errors,
#' meaning: prints, messages, warnings and package startup messages.
#'
#' @param expr [valid R expression]\cr
#' Expression.
#' @return Return value of expression invisibly.
#' @export
#' @examples
#' suppressAll({
#' print("foo")
#' message("foo")
#' warning("foo")
#' })
suppressAll = function(expr) {
capture.output({
z = suppressWarnings(
suppressMessages(
suppressPackageStartupMessages(force(expr))
)
)
})
invisible(z)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/suppressAll.R |
#' Calculates symmetric set difference between two sets.
#'
#' @param x [\code{vector}]\cr
#' Set 1.
#' @param y [\code{vector}]\cr
#' Set 2.
#' @return [\code{vector}].
#' @export
symdiff = function(x, y) {
setdiff(union(x, y), intersect(x, y))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/symdiff.R |
#' Wrapper for system2 with better return type and errorhandling.
#'
#' Wrapper for \code{\link{system2}} with better return type and errorhandling.
#'
#' @param command See \code{\link{system2}}.
#' @param args See \code{\link{system2}}.
#' @param stdout See \code{\link{system2}}.
#' @param stderr See \code{\link{system2}}.
#' @param wait See \code{\link{system2}}.
#' @param ... Further arguments passed to \code{\link{system2}}.
#' @param stop.on.exit.code [\code{logical(1)}]\cr
#' Should an exception be thrown if an exit code greater 0 is generated?
#' Can only be used if \code{wait} is \code{TRUE}.
#' Default is \code{wait}.
#' @return [\code{list}].
#' \item{exit.code [integer(1)]}{Exit code of command. Given if wait is \code{TRUE}, otherwise \code{NA}. 0L means success. 127L means command was not found}
#' \item{output [character]}{Output of command on streams. Only given is \code{stdout} or \code{stderr} was set to \code{TRUE}, otherwise \code{NA}.}
#' @export
system3 = function(command, args = character(0L), stdout = "", stderr = "", wait = TRUE, ..., stop.on.exit.code = wait) {
if (stop.on.exit.code && !wait)
stopf("stop.on.exit.code is TRUE but wait is FALSE!")
output = NA_character_
if (isTRUE(stdout) || isTRUE(stderr)) {
wait = TRUE
# here we wait anyway and output of cmd is returned
ec = 0L
suppressWarnings({
withCallingHandlers({
op = system2(command = command, args = args, stdout = stdout, stderr = stderr, wait = wait, ...)
}, warning = function(w) {
g = gregexpr("\\d+", w$message)[[1L]]
start = tail(g, 1L)
len = tail(attr(g, "match.length"), 1L)
ec <<- as.integer(substr(w$message, start, start + len - 1L))
})
})
} else {
ec = system2(command = command, args = args, stdout = stdout, stderr = stderr, wait = wait, ...)
}
if (wait) {
if (isTRUE(stdout) || isTRUE(stderr))
output = op
}
if (stop.on.exit.code && ec > 0L) {
args = collapse(args, " ")
if (length(output) == 0L)
output = ""
else
output = collapse(output, "\n")
stopf("Command: %s %s; exit code: %i; output: %s", command, args, ec, output)
}
list(exit.code = ec, output = output)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/system3.R |
#' Convert a numerical vector into a range string.
#'
#' @param x [\code{integer}]\cr
#' Vector to convert into a range string.
#' @param range.sep [\code{character(1)}]\cr
#' Separator between the first and last element of a range of consecutive
#' elements in \code{x}.
#' Default is \dQuote{ - }.
#' @param block.sep [\code{character(1)}]\cr
#' Separator between non consecutive elements of \code{x} or ranges.
#' Default is \dQuote{, }.
#' @return [\code{character(1)}]
#' @examples
#' x = sample(1:10, 7)
#' toRangeStr(x)
#' @export
toRangeStr = function(x, range.sep = " - ", block.sep = ", ") {
if (testIntegerish(x))
x = as.integer(x)
else
assertNumeric(x, any.missing = FALSE)
assertString(range.sep)
assertString(block.sep)
findRange = function(x) seq_len(max(which(x == x[1L] + 0:(length(x)-1L))))
x = sort(unique(x))
x = unname(split(x, c(0L, cumsum(diff(x) > 1L))))
combine = function(x)
if (length(x) == 1L)
as.character(x)
else
sprintf("%i%s%i", x[1L], range.sep, x[length(x)])
collapse(vapply(x, combine, character(1L), USE.NAMES = FALSE), block.sep)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/toRangeStr.R |
#' Apply a function with a predefined return value
#'
#' @description
#' These are just wrappers around \code{\link[base]{vapply}} with
#' argument \code{FUN.VALUE} set.
#' The function is expected to return a single \code{logical}, \code{integer},
#' \code{numeric} or \code{character} value, depending on the second letter
#' of the function name.
#'
#' @param x [\code{vector} or \code{list}]\cr
#' Object to apply function on.
#' @param fun [\code{function}]\cr
#' Function to apply on each element of \code{x}.
#' @param ... [\code{ANY}]\cr
#' Additional arguments for \code{fun}.
#' @param use.names [\code{logical(1)}]\cr
#' Should result be named?
#' Default is \code{TRUE}.
#' @export
vlapply = function(x, fun, ..., use.names = TRUE) {
vapply(X = x, FUN = fun, ..., FUN.VALUE = NA, USE.NAMES = use.names)
}
#' @rdname vlapply
#' @export
viapply = function(x, fun, ..., use.names = TRUE) {
vapply(X = x, FUN = fun, ..., FUN.VALUE = NA_integer_, USE.NAMES = use.names)
}
#' @rdname vlapply
#' @export
vnapply = function(x, fun, ..., use.names = TRUE) {
vapply(X = x, FUN = fun, ..., FUN.VALUE = NA_real_, USE.NAMES = use.names)
}
#' @rdname vlapply
#' @export
vcapply = function(x, fun, ..., use.names = TRUE) {
vapply(X = x, FUN = fun, ..., FUN.VALUE = NA_character_, USE.NAMES = use.names)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/vapply.R |
#' Wrapper for warning and sprintf.
#'
#' A wrapper for \code{\link{warning}} with \code{\link{sprintf}} applied to the arguments.
#'
#' @param ... [any]\cr
#' See \code{\link{sprintf}}.
#' @param immediate [\code{logical(1)}]\cr
#' See \code{\link{warning}}.
#' Default is \code{TRUE}.
#' @param warning.length [\code{integer(1)}]\cr
#' Number of chars after which the warning message
#' gets truncated, see ?options.
#' Default is 8170.
#' @return Nothing.
#' @export
#' @examples
#' msg = "a warning"
#' warningf("this is %s", msg)
warningf = function(..., immediate = TRUE, warning.length = 8170L) {
msg = sprintf(...)
if (immediate) {
old = getOption("warn")
# dont change warn setting if it is 2 (= error)
if (old <= 0L) {
on.exit(options(warn = old))
options(warn = 1L)
}
}
obj = simpleWarning(msg, call = sys.call(sys.parent()))
warning(obj)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/warningf.R |
#' Find the index of first/last \code{TRUE} value in a logical vector.
#'
#' @param x [\code{logical}]\cr
#' Logical vector.
#' @param use.names [\code{logical(1)}]\cr
#' If \code{TRUE} and \code{x} is named, the result is also
#' named.
#' @return [\code{integer(1)} | \code{integer(0)}].
#' Returns the index of the first/last \code{TRUE} value in \code{x} or
#' an empty integer vector if none is found.
#' @export
#' @examples
#' which.first(c(FALSE, TRUE))
#' which.last(c(FALSE, FALSE))
which.first = function(x, use.names = TRUE) {
wf(x, use.names)
}
#' @rdname which.first
#' @export
which.last = function(x, use.names = TRUE) {
wl(x, use.names)
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/which.first.R |
#' @import stats
#' @import checkmate
#' @import utils
#' @import data.table
#' @importFrom methods is
.onLoad = function(libname, pkgname) {
options(BBmisc.ProgressBar.stream = getOption("BBmisc.ProgressBar.stream", "stderr"))
options(BBmisc.ProgressBar.style = getOption("BBmisc.ProgressBar.style", "text"))
options(BBmisc.ProgressBar.width = getOption("BBmisc.ProgressBar.width", getOption("width")))
}
| /scratch/gouwar.j/cran-all/cranData/BBmisc/R/zzz.R |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.