code
stringlengths
1
13.8M
tar_rep_map_raw <- function( name, command, targets, tidy_eval = targets::tar_option_get("tidy_eval"), packages = targets::tar_option_get("packages"), library = targets::tar_option_get("library"), format = targets::tar_option_get("format"), iteration = targets::tar_option_get("iteration"), error = targets::tar_option_get("error"), memory = targets::tar_option_get("memory"), garbage_collection = targets::tar_option_get("garbage_collection"), deployment = targets::tar_option_get("deployment"), priority = targets::tar_option_get("priority"), resources = targets::tar_option_get("resources"), storage = targets::tar_option_get("storage"), retrieval = targets::tar_option_get("retrieval"), cue = targets::tar_option_get("cue") ) { targets::tar_warn_deprecate( "tar_rep_map() in tarchetypes is deprecated ", "(version 0.4.0, 2021-12-06). Please use tar_rep2() instead." ) do.call(tar_rep2_raw, rlang::call_args(match.call())) }
JDSI<-function (X,Y,ts=6,type=1) { X=matrix(X,ncol=1) Y=matrix(Y,ncol=1) if ((length(X)/12 != round(length(X)/12))) { return("ERROR: The input data should be the vector of the monthly data for a few years") } AX=ACCU(X,ts) AY=ACCU(Y,ts) JDSI_A=matrix(NA,nrow=length(X)/12,ncol=12,byrow=T) JDSI_K=matrix(NA,nrow=length(X)/12,ncol=12,byrow=T) for (k in 1:12) { mdx=AX[,k] mdy=AY[,k] if (k<ts) { xd=mdx[2:length(mdx)] yd=mdy[2:length(mdy)] p=BiEmp(xd,yd) u=copula::pobs(cbind(xd,yd)) p1=p p2=copula::Kn(p,u)*length(xd)/(length(xd)+1) JDSI_A[2:length(mdx),k]=stats::qnorm(p1) JDSI_K[2:length(mdx),k]=stats::qnorm(p2) } else { xd=mdx yd=mdy p=BiEmp(xd,yd) u=copula::pobs(cbind(xd,yd)) p1=p p2=copula::Kn(p,u)*length(xd)/(length(xd)+1) JDSI_A[,k]=stats::qnorm(p1) JDSI_K[,k]=stats::qnorm(p2) } } if (type==1) {result<-list(JDSI=JDSI_A) } else if (type==2) { {result<-list(JDSI=JDSI_K) } } else { stop("Only the type =1 and 2 are included. Others will be included in the future ") } return(result) }
getHyperPars = function(learner, for.fun = c("train", "predict", "both")) { assertSubset(for.fun, choices = c("train", "predict", "both")) UseMethod("getHyperPars") } getHyperPars.Learner = function(learner, for.fun = c("train", "predict", "both")) { assertClass(learner, classes = "Learner") pars = learner$par.set$pars pv = learner$par.vals ns = Filter(function(x) pars[[x]]$when %in% for.fun, names(pv)) pv[ns] } getHyperParsString = function(learner, show.missing.values = TRUE) { if ("fw.base.methods" %in% names(learner$par.set$pars)) { learner$par.set$pars$fw.base.methods = NULL learner$par.set$pars$fw.method = NULL learner$par.vals$fw.method = NULL learner$par.vals$fw.base.methods = NULL } if ("fw.base.methods" %in% names(learner$next.learner$par.set$pars)) { learner$next.learner$par.set$pars$fw.base.methods = NULL learner$next.learner$par.set$pars$fw.method = NULL learner$next.learner$par.vals$fw.method = NULL learner$next.learner$par.vals$fw.base.methods = NULL } hps = getHyperPars(learner) ns = names(hps) pars = getParamSet(learner)$pars[ns] s = mapply(paramValueToString, pars, hps, MoreArgs = list(show.missing.values = show.missing.values)) stri_paste(ns, s, sep = "=", collapse = ",") }
rlevel=function(fit,var,oldrf,newrf,cl=NA){ if(is.null(fit$call)){ type=as.character(fit$glmnet.fit$call) }else{ type=as.character(fit$call) } w=paste(var,newrf,sep="") if(type[1]=="glm"|type[1]=="lm"){ cv=vcov(fit) fit_sum=summary(fit) c=fit_sum$coefficients c=as.data.frame(c) for(i in 1:length(oldrf)){ x=c[substr(rownames(c),1,nchar(var[i]))==var[i],] y=c[substr(rownames(c),1,nchar(var[i]))!=var[i],] if(nrow(x)==1){ y[1,1]=y[1,1]+x[1,1] x[1,1]=-x[1,1] x[1,3]=-x[1,3] rownames(x)=paste(var[i],oldrf[i],sep="") }else{ n=which(substr(rownames(x),nchar(var[i])+1,nchar(rownames(x)))==newrf[i]) rownames(x)[n]=paste(var[i],oldrf[i],sep="") y[1,1]=y[1,1]+x[n,1] x[n,1]=-x[n,1] x[n,3]=-x[n,3] for(j in 1:nrow(x)){ if(j==n){ x[j,1]=x[j,1] }else{ x[j,1]=x[j,1]+x[n,1] x[j,2]=sqrt((x[j,2])^2+(x[n,2])^2-2*cv[which(rownames(cv)==rownames(x[j,])),which(colnames(cv)==paste(var[i],newrf[i],sep=""))]) x[j,3]=x[j,1]/x[j,2] if(type[1]=="glm"){ x[j,4]=2*pnorm(-abs(x[j,3])) }else{ x[j,4]=2*pt(abs(x[j,3]),fit$df.residual,lower.tail = FALSE) } } } } if(i==1){ e=which(colnames(cv)==paste(var[i],newrf[i],sep="")) vr=cv[1,1]+cv[which(rownames(cv)==paste(var[i],newrf[i],sep="")),which(colnames(cv)==paste(var[i],newrf[i],sep=""))]+ 2*cv[which(rownames(cv)==w[i]),1] }else{ vr=vr+cv[which(rownames(cv)==paste(var[i],newrf[i],sep="")),which(colnames(cv)==paste(var[i],newrf[i],sep=""))]+ 2*sum(cv[which(rownames(cv)==w[i]),c(1,e)]) e=c(e,which(colnames(cv)==paste(var[i],newrf[i],sep=""))) } c=rbind(y,x) } c[1,2]=sqrt(vr) c[1,3]=c[1,1]/c[1,2] if(type[1]=="glm"){ c[1,4]=2*pnorm(-abs(c[1,3])) }else{ c[1,4]=2*pt(abs(c[1,3]),fit$df.residual,lower.tail = FALSE) } return(c) } if(type[1]=="glmnet"){ if(is.na(cl)){ cl=1 } if(is.null(fit$call)){ c=coef(fit$glmnet.fit)[,cl] }else{ c=coef(fit)[,cl] } c=as.data.frame(c) c$p=1 for(i in 1:length(oldrf)){ x=c[substr(rownames(c),1,nchar(var[i]))==var[i],] y=c[substr(rownames(c),1,nchar(var[i]))!=var[i],] if(nrow(x)==1){ y[1,1]=y[1,1]+x[1,1] x[1,1]=-x[1,1] rownames(x)=paste(var[i],oldrf[i],sep="") }else{ n=which(substr(rownames(x),nchar(var[i])+1,nchar(rownames(x)))==newrf[i]) rownames(x)[n]=paste(var[i],oldrf[i],sep="") y[1,1]=y[1,1]+x[n,1] x[n,1]=-x[n,1] for(j in 1:nrow(x)){ if(j==n){ x[j,1]=x[j,1] }else{ x[j,1]=x[j,1]+x[n,1] } } } c=rbind(y,x) } name=rownames(c) c=c[,1] names(c)=name return(c) } }
library(scoper) library(dplyr) results <- identicalClones(ExampleDb, method="nt") results_db <- as.data.frame(results) glimpse(results_db) plot(results, binwidth=0.02) glimpse(summary(results)) results <- hierarchicalClones(ExampleDb, threshold=0.15) results_db <- as.data.frame(results) glimpse(results_db) plot(results, binwidth=0.02) glimpse(summary(results)) results <- spectralClones(ExampleDb, method="novj") plot(results, binwidth=0.02) results <- spectralClones(ExampleDb, method="novj", threshold=0.15) plot(results, binwidth=0.02) results <- spectralClones(ExampleDb, method="vj", threshold=0.15, germline="germline_alignment_d_mask") results_db <- as.data.frame(results) glimpse(results_db) plot(results, binwidth=0.02) glimpse(summary(results))
setAs("denseMatrix", "symmetricMatrix", function(from) .Call(dense_to_symmetric, from, "U", TRUE)) setAs("matrix", "symmetricMatrix", function(from) .Call(dense_to_symmetric, from, "U", TRUE)) setMethod("forceSymmetric", signature(x = "matrix", uplo="ANY"), function(x, uplo) .Call(dense_to_symmetric, x, if(missing(uplo)) "U" else uplo, FALSE)) symCls <- names(getClass("symmetricMatrix")@subclasses) for(cls in symCls) { setMethod("forceSymmetric", signature(x = cls, uplo="missing"), function(x, uplo) x) setMethod("forceSymmetric", signature(x = cls, uplo="character"), function(x, uplo) { if(uplo == x@uplo) x else t(x) }) } setMethod("forceSymmetric", signature(x = "denseMatrix", uplo="character"), function(x, uplo) .Call(dense_to_symmetric, x, uplo, FALSE)) setMethod("forceSymmetric", signature(x = "denseMatrix", uplo="missing"), function(x, uplo) { uplo <- if(is(x, "triangularMatrix")) x@uplo else "U" .Call(dense_to_symmetric, x, uplo, FALSE) }) setMethod("forceSymmetric", signature(x="sparseMatrix"), function(x, uplo) { x <- as(x, "CsparseMatrix") callGeneric() }) forceCspSymmetric <- function(x, uplo, isTri = is(x, "triangularMatrix"), symDimnames = NA) { if(isTri && x@diag == "U") x <- .Call(Csparse_diagU2N, x) if(missing(uplo)) uplo <- if(isTri) x@uplo else "U" .Call(Csparse_general_to_symmetric, x, uplo, symDimnames) } .gC2sym <- function(x, uplo, symDimnames = NA) .Call(Csparse_general_to_symmetric, x, uplo, symDimnames) setMethod("forceSymmetric", signature(x="CsparseMatrix"), function(x, uplo) forceCspSymmetric(x, uplo)) setMethod("symmpart", signature(x = "symmetricMatrix"), function(x) x) setMethod("skewpart", signature(x = "symmetricMatrix"), function(x) .setZero(x)) if(FALSE) symmetricDimnames <- function(x) { r <- x@Dimnames if(is.null(r[[1L]]) && !is.null(r[[2L]])) r[[1L]] <- r[[2L]] else if(is.null(r[[2L]]) && !is.null(r[[1L]])) r[[2L]] <- r[[1L]] r } symmetricDimnames <- function(x) .Call(R_symmetric_Dimnames, x) setMethod("dimnames", signature(x = "symmetricMatrix"), symmetricDimnames) packM <- function(x, Mtype, kind, unpack=FALSE) { cd <- getClassDef(cx <- class(x)) if(extends(cd, "sparseMatrix")) stop(sprintf("(un)packing only applies to dense matrices, class(x)='%s'", cx)) if(!missing(kind) && kind == "symmetric") { as(x, if(unpack) { if(extends(cd, "dppMatrix")) "dpoMatrix" else paste0(.M.kindC(cd), "syMatrix") } else { if(extends(cd, "dpoMatrix")) "dppMatrix" else paste0(.M.kindC(cd), "spMatrix") }) } else as(x, paste0(.M.kindC(cd), Mtype)) } setMethod("unpack", "symmetricMatrix", function(x, ...) packM(x, kind="symmetric", unpack=TRUE)) setMethod("pack", "symmetricMatrix", function(x, ...) packM(x, kind="symmetric")) setMethod("unpack", "triangularMatrix", function(x, ...) packM(x, "trMatrix", unpack=TRUE)) setMethod("pack", "triangularMatrix", function(x, ...) packM(x, "tpMatrix")) pckErr <- function(x, ...) stop(sprintf("(un)packing only applies to dense matrices, class(x)='%s'", class(x))) setMethod("unpack", "sparseMatrix", pckErr) setMethod("pack", "sparseMatrix", pckErr) rm(pckErr) setMethod("pack", signature(x = "matrix"), function(x, symmetric=NA, upperTri = NA, ...) { if(is.na(symmetric)) symmetric <- isSymmetric.matrix(x) if(symmetric) { pack(.Call(dense_to_symmetric, x, "U", TRUE), ...) } else { if(isTr <- isTriMat(x, upper=upperTri)) { uplo <- attr(isTr, "kind") pack(new(paste0(.M.kind(x),"tpMatrix"), x = x[indTri(nrow(x), upper=(uplo == "U"), diag=TRUE)], Dim = dim(x), Dimnames = .M.DN(x), uplo = uplo), ...) } else stop("'x' is not symmetric nor triangular") } }) setMethod("unpack", "dspMatrix", function(x, ...) dsp2dsy(x), valueClass = "dsyMatrix") setMethod("unpack", "dtpMatrix", function(x, ...) dtp2dtr(x), valueClass = "dtrMatrix") if(FALSE) local({ allCl <- getClasses("package:Matrix") clss <- allCl[sapply(allCl, extends, class2 = "Matrix")] virt <- sapply(clss, isVirtualClass) for(cl in clss[!virt]) { cld <- getClassDef(cl) if(extends(cld, "symmetricMatrix")) cat("\tsymmetric:\t", cl,"\n") else if(extends(cld, "triangularMatrix")) cat("\ttriangular:\t", cl,"\n") else if(extends(cld, "diagonalMatrix")) cat("\tdiagonal:\t", cl,"\n") else { cat("do ",cl,"\n") } } })
bind.mcmc <- function(mcmc.list1,mcmc.list2,start,n.new.iter){ nchains <- length(mcmc.list1) samples <- list() for (i in 1:nchains){ d <- rbind(mcmc.list1[[i]],mcmc.list2[[i]]) samples[[i]] <- mcmc(data=d,start=start,end=(end(mcmc.list1[[i]])+n.new.iter),thin=thin(mcmc.list1[i])) } return(as.mcmc.list(samples)) }
if(interactive()){ library(shiny) library(shinymaterial) ui <- material_page( title = "Basic Page", primary_theme_color = "blue", secondary_theme_color = "green", tags$h1("Page Content"), material_file_input(input_id = "example_file_input", label = "ok") ) server <- function(input, output, session) { observeEvent(input$example_file_input, { inFile <- input$example_file_input if (is.null(inFile)) { return(NULL) } x <- read.csv(inFile$datapath) message(head(x)) }) } shinyApp(ui = ui, server = server) }
count_multigrams <- function(ns, ds = rep(0, length(ns)), seq, u, pos = FALSE, scale = FALSE, threshold = 0) { if(length(ns) != length(ds)) stop("'ns' vector must have equal length to 'ds' list.") n_loops <- length(ns) do.call(cbind, lapply(1L:n_loops, function(current_loop) { count_ngrams(seq, ns[current_loop], u, ds[[current_loop]], pos, scale, threshold) })) }
verificaTipoColuna <- function(coluna){ if(typeof(coluna) == "character") { return ("as.character()"); } return ("as.numeric()"); }
estimate.autocorr.m <- function(dat, ac.cutoff = 0.95){ autocorr.m <- data.frame(autocorr.time = rep(NA, length(unique(dat$chain))), row.names = unique(dat$chain)) for(i in 1:nrow(autocorr.m)){ thischain <- rownames(autocorr.m)[i] thisdata <- dat[dat$chain == thischain,] this.ac.result <- optim(par = c(1, 1), function(data, par){sum((par[1] * (1 - exp(-(data$sampling.interval/par[2]))) - data$topo.distance)^2)}, data = thisdata) if(any(thisdata$topo.distance/this.ac.result$par[1] > ac.cutoff)){ autocorr.m[i,1] <- thisdata$sampling.interval[min(which(thisdata$topo.distance/this.ac.result$par[1] > ac.cutoff))] } else { autocorr.m[i,1] <- -1 } } autocorr.m$chains = rownames(autocorr.m) rownames(autocorr.m) = NULL return(autocorr.m) }
plot.cardiMetacdw <- function(x, y, type = "lattice", scale = TRUE, col.poly = "black", ...) { if (is.null(y)) stop("original data must be provided as second argument") tt <- x dat <- y if (type == "lattice") { if (length(tt$weibullfits[[1]]$p) == 4) { fweibull <- fweibull4 } else { fweibull <- fweibull6 } xyplot(y ~ x|as.factor(sample), data=dat, ..., panel=function(x, y, subscripts, groups, ...) { i <- panel.number() mres <- tt$weibullfits[[i]] smdx <- tt$metares[i, c("tBegin", "tMid", "tEnd")] smdy <- fweibull(smdx, mres$p) panel.xyplot(x, y) xx <- seq(min(x), max(x), length=100) yy <- fweibull(xx, mres$p) panel.lines(xx, mres$ymax * yy, col="darkgreen", lwd=2) panel.points(smdx, smdy * mres$ymax, col="tomato", pch=16) } ) } else { if (type == "polygon") { par(las=1, font=2, font.lab=2, font.axis=2, mai=c(1.5,1,1,0.5)) erg <- tt$metares count <- nrow(erg) if (!(length(col.poly) %in% c(1, count))) stop("length of col.poly does not match number of samples") polygoncols <- if(length(col.poly == 1)){rep(col.poly, count)} else {col.poly} yrange <- 1:count xrange <- floor(seq(min(dat$x), max(dat$x), length=12)) ymax <- max(erg$yMid) ys <- if(scale == TRUE){erg$yMid / ymax} else {rep(1,count)} plot(c(min(xrange),max(xrange)), c(min(yrange), max(yrange) + 1), type="n", yaxt="n", ylab="", xlab="Julian Day of Year", ...) axis(2, at=yrange, labels=levels(erg$sample)) abline(h=yrange, lty=3, col=grey(0.7)) abline(v=xrange, lty=3, col=gray(0.7)) for (i in 1:count) { x <- c(erg$tBegin[i], erg$tMid[i], erg$tEnd[i]) y <- c(i, i + ys[i], i) polygon(x, y, border = NA, col = polygoncols[i]) } } else {stop("plot type unknown")} } }
JDEoptim <- function(lower, upper, fn, constr = NULL, meq = 0, eps = 1e-5, NP = 10*d, Fl = 0.1, Fu = 1, tau_F = 0.1, tau_CR = 0.1, tau_pF = 0.1, jitter_factor = 0.001, tol = 1e-15, maxiter = 200*d, fnscale = 1, compare_to = c("median", "max"), add_to_init_pop = NULL, trace = FALSE, triter = 1, details = FALSE, ...) { handle.bounds <- function(x, u) { bad <- x > upper x[bad] <- 0.5*(upper[bad] + u[bad]) bad <- x < lower x[bad] <- 0.5*(lower[bad] + u[bad]) x } performReproduction <- function() { ignore <- runif(d) > CRtrial if (all(ignore)) ignore[sample(d, 1)] <- FALSE trial <- if (runif(1) <= pFtrial) X.base + Ftrial*(X.r1 - X.r2) else X.base + 0.5*(Ftrial + 1)*(X.r1 + X.r2 - 2*X.base) trial[ignore] <- X.i[ignore] trial } which.best <- if (!is.null(constr)) function(x) { ind <- TAVpop <= mu if (all(ind)) which.min(x) else if (any(ind)) which(ind)[which.min(x[ind])] else which.min(TAVpop) } else which.min compare_to <- match.arg(compare_to) d <- length(lower) if (length(upper) != d) stop("'lower' must have same length as 'upper'") stopifnot(is.numeric(lower), is.numeric(upper), is.finite(lower), is.finite(upper), lower <= upper, length(fnscale) == 1, is.finite(fnscale), fnscale > 0, is.function(fn)) if (!is.null(constr)) { stopifnot(is.function(constr)) stopifnot(length(meq) == 1, meq == as.integer(meq), meq >= 0, is.numeric(eps), is.finite(eps), eps > 0) if (length(eps) == 1) eps <- rep.int(eps, meq) else if (length(eps) != meq) stop("eps must be either of length meq, or length 1") } stopifnot(length(NP) == 1, NP == as.integer(NP), length(Fl) == 1, is.numeric(Fl), length(Fu) == 1, is.numeric(Fu), Fl <= Fu) stopifnot(length(tau_F) == 1, is.numeric(tau_F), 0 <= tau_F, tau_F <= 1, length(tau_CR) == 1, is.numeric(tau_CR), 0 <= tau_CR, tau_CR <= 1, length(tau_pF) == 1, is.numeric(tau_pF), 0 <= tau_pF, tau_pF <= 1) if (!is.null(jitter_factor)) stopifnot(length(jitter_factor) == 1, is.numeric(jitter_factor)) stopifnot(length(tol) == 1, is.numeric(tol), length(maxiter) == 1, maxiter == as.integer(maxiter), length(triter) == 1, triter == as.integer(triter)) if (!is.null(add_to_init_pop)) stopifnot(NROW(add_to_init_pop) == d, is.numeric(add_to_init_pop), add_to_init_pop >= lower, add_to_init_pop <= upper) child <- if (is.null(constr)) { expression({ ftrial <- fn1(trial) if (ftrial <= fpop[i]) { pop[, i] <- trial fpop[i] <- ftrial F[, i] <- Ftrial CR[i] <- CRtrial pF[i] <- pFtrial } }) } else if (meq > 0) { expression({ htrial <- constr1(trial) TAVtrial <- sum( pmax(htrial, 0) ) if (TAVtrial > mu) { if (TAVtrial <= TAVpop[i]) { pop[, i] <- trial hpop[, i] <- htrial F[, i] <- Ftrial CR[i] <- CRtrial pF[i] <- pFtrial TAVpop[i] <- TAVtrial } } else if (TAVpop[i] > mu) { pop[, i] <- trial fpop[i] <- fn1(trial) hpop[, i] <- htrial F[, i] <- Ftrial CR[i] <- CRtrial pF[i] <- pFtrial TAVpop[i] <- TAVtrial } else { ftrial <- fn1(trial) if (ftrial <= fpop[i]) { pop[, i] <- trial fpop[i] <- ftrial hpop[, i] <- htrial F[, i] <- Ftrial CR[i] <- CRtrial pF[i] <- pFtrial TAVpop[i] <- TAVtrial FF <- sum(TAVpop <= mu)/NP mu <- mu*(1 - FF/NP) } } }) } else { expression({ htrial <- constr1(trial) TAVtrial <- sum( pmax(htrial, 0) ) if (TAVtrial > mu) { if (TAVtrial <= TAVpop[i]) { pop[, i] <- trial hpop[, i] <- htrial F[, i] <- Ftrial CR[i] <- CRtrial pF[i] <- pFtrial TAVpop[i] <- TAVtrial } } else if (TAVpop[i] > mu) { pop[, i] <- trial fpop[i] <- fn1(trial) hpop[, i] <- htrial F[, i] <- Ftrial CR[i] <- CRtrial pF[i] <- pFtrial TAVpop[i] <- TAVtrial FF <- sum(TAVpop <= mu)/NP mu <- mu*(1 - FF/NP) } else { ftrial <- fn1(trial) if (ftrial <= fpop[i]) { pop[, i] <- trial fpop[i] <- ftrial hpop[, i] <- htrial F[, i] <- Ftrial CR[i] <- CRtrial pF[i] <- pFtrial TAVpop[i] <- TAVtrial FF <- sum(TAVpop <= mu)/NP mu <- mu*(1 - FF/NP) } } }) } fn1 <- function(par) fn(par, ...) if (!is.null(constr)) constr1 <- if (meq > 0) { eqI <- 1:meq function(par) { h <- constr(par, ...) h[eqI] <- abs(h[eqI]) - eps h } } else function(par) constr(par, ...) use.jitter <- !is.null(jitter_factor) conv <- expression( ( do.call(compare_to, list(fpop)) - fpop[x.best.ind] )/fnscale ) pop <- matrix(runif(NP*d, lower, upper), nrow = d) if (!is.null(add_to_init_pop)) { pop <- unname(cbind(pop, add_to_init_pop)) NP <- ncol(pop) } stopifnot(NP >= 4) F <- if (use.jitter) (1 + jitter_factor*runif(d, -0.5, 0.5)) %o% runif(NP, Fl, Fu) else matrix(runif(NP, Fl, Fu), nrow = 1) CR <- runif(NP) pF <- runif(NP) fpop <- apply(pop, 2, fn1) if (!is.null(constr)) { hpop <- apply(pop, 2, constr1) if ( any(is.na(hpop)) ) stop("value of meq is invalid") if (is.vector(hpop)) dim(hpop) <- c(1, length(hpop)) TAVpop <- apply( hpop, 2, function(x) sum(pmax(x, 0)) ) mu <- median(TAVpop) } popIndex <- 1:NP x.best.ind <- which.best(fpop) converge <- eval(conv) rule <- if (!is.null(constr)) expression(converge >= tol || any(hpop[, x.best.ind] > 0)) else expression(converge >= tol) convergence <- 0 iteration <- 0 while (eval(rule)) { if (iteration >= maxiter) { warning("maximum number of iterations reached without convergence") convergence <- 1 break } iteration <- iteration + 1 for (i in popIndex) { i <- ((iteration + i) %% NP) + 1 Ftrial <- if (runif(1) <= tau_F) { if (use.jitter) runif(1, Fl, Fu) * (1 + jitter_factor*runif(d, -0.5, 0.5)) else runif(1, Fl, Fu) } else F[, i] CRtrial <- if (runif(1) <= tau_CR) runif(1) else CR[i] pFtrial <- if (runif(1) <= tau_pF) runif(1) else pF[i] X.i <- pop[, i] r <- sample(popIndex[-i], 3) X.base <- pop[, r[1L]] X.r1 <- pop[, r[2L]] X.r2 <- pop[, r[3L]] trial <- handle.bounds(performReproduction(), X.base) eval(child) x.best.ind <- which.best(fpop) } converge <- eval(conv) if (trace && (iteration %% triter == 0)) cat(iteration, ":", "<", converge, ">", "(", fpop[x.best.ind], ")", pop[, x.best.ind], if (!is.null(constr)) paste("{", which(hpop[, x.best.ind] > 0), "}"), fill = TRUE) } res <- list(par = pop[, x.best.ind], value = fpop[x.best.ind], iter = iteration, convergence = convergence) if (details) { res$poppar <- pop res$popcost <- fpop } res } doExtras <- function() { interactive() || nzchar(Sys.getenv("R_DEoptimR_check_extra")) || identical("true", unname(Sys.getenv("R_PKG_CHECKING_doExtras"))) }
expected <- eval(parse(text="c(\"Subject\", \"predict.fixed\", \"predict.Subject\")")); test(id=0, code={ argv <- eval(parse(text="list(c(\"Subject\", \"predict.fixed\", \"predict.Subject\"), TRUE)")); .Internal(make.names(argv[[1]], argv[[2]])); }, o=expected);
library("RUnit") library(mcr) options(warn=1) testSuite <- defineTestSuite(name="MCReg", dirs=".", testFileRegexp="runit.*\\.R$", rngKind="default", rngNormalKind="default") testData <- runTestSuite(testSuite, verbose=0L) printTextProtocol(testData, showDetails=FALSE) printHTMLProtocol(testData,file="testProtocol.html")
knitr::opts_chunk$set(echo = TRUE) opt <- options() options(continue=" ", width=70, prompt=" ") on.exit(options(opt)) library(DOVE, quietly=TRUE) data(doveData) head(doveData) summary(doveData) result1 <- readRDS(file = "doveResult.rds") result1$covariates head(result1$vaccine$efficacy) tail(result1$vaccine$efficacy) result1$vaccine$period_efficacy knitr::include_graphics( path=c("dove1a.pdf","dove1b.pdf"), auto_pdf = getOption("knitr.graphics.auto_pdf", FALSE), dpi = NULL, error = getOption("knitr.graphics.error", TRUE) ) result2 <- dove2(formula = Surv(event.time, event.status) ~ priority + sex + vaccine(entry.time, vaccine.status, vaccine.time), data = doveData, changePts = 4*7, timePts = c(4, 16, 28, 40)*7) result2$call result2$changePts result2$covariates head(result2$vaccine$VE_a) tail(result2$vaccine$VE_a) head(result2$vaccine$VE_h) tail(result2$vaccine$VE_h) result2$vaccine$VE_period knitr::include_graphics( path=c("dove2a.pdf","dove2b.pdf"), auto_pdf = getOption("knitr.graphics.auto_pdf", FALSE), dpi = NULL, error = getOption("knitr.graphics.error", TRUE) ) result3 <- dove2(formula = Surv(event.time, event.status) ~ priority + sex + vaccine(entry.time, vaccine.status, vaccine.time), data = doveData, constantVE = TRUE) result3$changePts result3$covariates result3$vaccine$VE plot(x = result3)
test <- data.frame( time = strptime("2016-03-12 16:32:56", format = "%Y-%m-%d %X") + 60 * 1:100, x = cos(1:100) ) p <- ggplot(test, aes(time, x)) + geom_point() test_that("datetimes are displayed in tooltip properly", { l <- expect_doppelganger_built(p, "tooltip-datetime") txt <- strsplit(l$data[[1]]$text, br()) expect_identical( paste0("time: ", test$time), sapply(txt, "[[", 1) ) }) test <- data.frame( time = strptime("2016-03-12", format = "%Y-%m-%d") + 1:100, x = sin(1:100) ) p <- ggplot(test, aes(time, x)) + geom_point() test_that("dates are displayed in tooltip properly", { l <- expect_doppelganger_built(p, "tooltip-date") txt <- strsplit(l$data[[1]]$text, br()) expect_identical( paste0("time: ", test$time), sapply(txt, "[[", 1) ) }) test_that("tooltip argument respects ordering", { p <- ggplot(mtcars, aes(x = mpg, fill = factor(cyl))) + geom_density() p <- ggplotly(p, tooltip = c("density", "x")) info <- plotly_build(p)$x txt <- strsplit(info$data[[1]]$text, br()) expect_true(all(grepl("^density", sapply(txt, "[[", 1)))) expect_true(all(grepl("^mpg", sapply(txt, "[[", 2)))) }) test_that("can hide x values in tooltip", { gg2 <- ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(cyl))) + geom_violin() p <- ggplotly(gg2, tooltip = "y") l <- plotly_build(p)$x expect_equivalent(sum(grepl("cyl", l$data[[1]]$text)), 0) }) cars <- ggplot(mtcars, aes(mpg, factor(cyl))) p <- cars + stat_bin2d(aes(fill = ..density..), binwidth = c(3,1)) test_that("geom_tile() displays correct info in tooltip with discrete y", { L <- expect_doppelganger_built(p, "heatmap-discrete-tooltip") expect_equivalent(length(L$data), 2) expect_equivalent(L$data[[1]]$type, "heatmap") txt <- c(L$data[[1]]$text) txt <- txt[!is.na(txt)] expect_true(all(grepl("factor\\(cyl\\): [4,6,8]", txt))) }) p <- ggplot(txhousing, aes(x = date, y = median, group = city)) + geom_line(alpha = 0.3) test_that("group domain is included in hovertext", { L <- expect_doppelganger_built(p, "group-lines-hovertext") expect_equivalent(length(L$data), 1) txt <- L$data[[1]]$text txt <- txt[!is.na(txt)] pattern <- paste(unique(txhousing$city), collapse = "|") expect_true(all(grepl(pattern, txt))) }) test_that("tooltip elements are not crossed", { mydata <- data.frame(id = paste0("Sample", rep(1:2, times = 4)), x = rep(1:4, each = 2), y = rep(c(1, 10), times = 4), stringsAsFactors = FALSE) gplt <- ggplot(mydata) + geom_line(aes(x=x, y = y, group = id)) pltly <- plotly::ggplotly(gplt) y_equal_ten <- grepl("y: 10", pltly$x$data[[1]]$text) sample_2 <- grepl("id: Sample2", pltly$x$data[[1]]$text) expect_equivalent(y_equal_ten, sample_2) }) labelDF <- data.frame( label = paste0(("label"), c(1:10)), x = runif(10, 1, 10), y = runif(10, 1, 10) ) edgeDF <- data.frame( x = runif(10, 1, 10), y = runif(10, 1, 10), xend = runif(10, 1, 10), yend = runif(10, 1, 10) ) myPlot <- ggplot(data = labelDF, aes(x = x, y = y)) + geom_segment(data = edgeDF, aes(x = x, y = y, xend = xend, yend = yend), colour = "pink") + geom_text(data = labelDF, aes(x = x, y = y, label = label), size = 10) test_that("Hoverinfo is only displayed if no tooltip variables are present", { L <- expect_doppelganger_built(p, "hovertext-display") L <- plotly_build(ggplotly(myPlot, tooltip = "label"))[["x"]] expect_equivalent(length(L$data), 2) expect_equivalent(sum(nchar(L$data[[1]]$text)), 0) expect_true(all(grepl("^label", L$data[[2]]$text))) })
lsmi_cv <- function(net, n.seeds, n.wave, seeds = NULL, B = 100, prob = 0.95, cl = 1, param = c("mu"), method = c("percentile", "basic"), proxyRep = 19, proxySize = 30) { method <- match.arg(method) param <- match.arg(param) param <- ifelse(param == "mu", 2, 1) clStop <- FALSE if (!is.list(cl)) { if (is.null(cl)) { cores <- parallel::detectCores() } else { cores <- cl } if (cores > 1) { cl <- parallel::makeCluster(cores) clStop <- TRUE } } patch <- lsmi_union(net, n.seeds, n.wave, seeds) subpatch <- subsubpatch <- patch$lsmi_big ss <- patch$sequence_seeds ns <- length(ss) if (proxySize < 0.7*length(ss[[1]])) { proxyReplace <- FALSE used <- ss[[1]] } else { proxyReplace <- TRUE used <- unique(na.omit(unlist(patch$lsmi_big))) } used <- net$degree[used] CIs <- estimate <- as.list(rep(NA, ns * n.wave)) counter <- 1 for (i in 1:ns) { if (i > 1) { subpatch <- subsubpatch <- subpatch[is.element(ss[[i - 1]], ss[[i]])] } for (j in 1:(n.wave)) { if (j > 1) { subsubpatch <- lapply(subsubpatch, function(x) x[1:(n.wave - j + 1)]) } dd <- lsmi_dd(subsubpatch, net) bdd <- boot_dd(dd, B, cl = cl) CIs[[counter]] <- boot_ci(bdd, prob, method)[[param]] estimate[[counter]] <- dd[[param]] counter <- counter + 1 } } if (param == 2) { proxies <- sapply(1:proxyRep, function(x) mean(sample(used, proxySize, replace = proxyReplace)) ) } proxiCoverage <- sapply(CIs, function(x) mean(x[1] <= proxies & proxies <= x[2])) SWcombinations <- cbind(rep(1:ns, each = n.wave), rep(n.wave:1, ns)) best_comb_index <- which.min(abs(proxiCoverage - prob))[1] SeedWave <- SWcombinations[best_comb_index,] seeds <- ss[[SeedWave[1]]] best_combination <- SeedWave best_combination[1] <- length(seeds) names(best_combination) <- c("n.seed", "n.wave") if(clStop) { parallel::stopCluster(cl) } list(bci = CIs[[best_comb_index]], estimate = estimate[[best_comb_index]], best_combination = best_combination, seeds = seeds) }
library(knitr) opts_chunk$set(cache = FALSE, tidy = FALSE, fig.align = "center") library(biogas) options(width=75) library(biogas) data("vol") dim(vol) head(vol) summary(vol) data("comp") dim(comp) head(comp) summary(comp) data("setup") setup args(cumBg) cum.prod <- cumBg(vol, comp = comp, time.name = "days", temp = 35, pres = 1, extrap = TRUE) head(cum.prod) dim(cum.prod) library(ggplot2) qplot(x = days, y = cvCH4, data = cum.prod, xlab = "Time (d)", ylab = "Cumulative methane production (mL)", color = id, geom = "line") data("s3voll") data("s3compl") data("s3volw") data("s3compw") data("s3lcombo") s3voll s3compl s3volw s3compw s3lcombo cpl <- cumBg(s3lcombo, comp = s3compl, temp = 25, pres = 1, id.name = 'id', time.name = 'time.d', dat.name = 'vol.ml', comp.name = 'xCH4', extrap = TRUE) cpw <- cumBg(s3volw, comp = s3compw, temp = 25, pres = 1, time.name = 'time.d', data.struct = 'wide', dat.name = 'D', comp.name = 'D', extrap = TRUE) cpc <- cumBg(s3lcombo, temp = 25, pres = 1, id.name = 'id', time.name = 'time.d', data.struct = 'longcombo', dat.name = 'vol.ml', comp.name = 'xCH4', extrap = TRUE) head(cpl) head(cpw) head(cpc) args(summBg) summBg(cum.prod, setup = setup, time.name = "days", descrip.name = "descrip", when = 30) BMP <- summBg(cum.prod, setup = setup, time.name = "days", inoc.name = "inoc", inoc.m.name = "minoc", norm.name = "mvs.sub", when = "1p3d") BMP predBg("C6H10O5") BMP predBg("C6H10O5", fs = 0.1) predBg(COD = c(A = 1.439, B = 1.561, cellu = 1.184)) BMP$mean/predBg(COD = c(A = 1.439, B = 1.561, cellu = 1.184))
test_that("'nest_join_zoomed_dm()'-method for `zoomed_dm` works", { skip("FIXME") skip_if_remote_src() expect_equivalent_tbl( zoomed_dm_2() %>% nest_join_zoomed_dm() %>% pull_tbl(), tf_3() %>% nest_join(tf_2(), name = "tf_2", by = c("f" = "e", "f1" = "e1")) %>% mutate(tf_2 = as_list_of(tf_2)) %>% nest_join(tf_4(), name = "tf_4", by = c("f" = "j")) %>% mutate(tf_4 = as_list_of(tf_4)) ) expect_equivalent_tbl( zoomed_dm_2() %>% nest_join_zoomed_dm(tf_4, tf_2) %>% pull_tbl(), tf_3() %>% nest_join(tf_4(), name = "tf_4", by = c("f" = "j")) %>% mutate(tf_4 = as_list_of(tf_4)) %>% nest_join(tf_2(), name = "tf_2", by = c("f" = "e", "f1" = "e1")) %>% mutate(tf_2 = as_list_of(tf_2)) ) expect_message( expect_equivalent_dm( dm_rm_pk(dm_for_filter(), tf_3, TRUE) %>% dm_zoom_to(tf_3) %>% nest_join_zoomed_dm(), dm_rm_pk(dm_for_filter(), tf_3, TRUE) %>% dm_zoom_to(tf_3) ), "didn't have a primary key" ) expect_dm_error( zoomed_dm_2() %>% select(g) %>% nest_join_zoomed_dm(), "pk_not_tracked" ) }) test_that("'nest_join_zoomed_dm()' fails for DB-'dm'", { expect_dm_error( dm_zoom_to(dm_for_filter_sqlite(), tf_3) %>% nest_join_zoomed_dm(), "only_for_local_src" ) })
TOTVar <- function(data, starttime.vec, endtime.vec, divBy = NA, tot.var) { for (i in seq(length(starttime.vec))) { if (is.na(divBy)) { data$TOT <- data[[endtime.vec[i]]] - data[[starttime.vec[i]]] } else{ data$TOT <- (data[[endtime.vec[i]]] - data[[starttime.vec[i]]]) / divBy } names(data)[length(data)] <- tot.var } return(data) }
NULL swf <- function(config = list()) { svc <- .swf$operations svc <- set_config(svc, config) return(svc) } .swf <- list() .swf$operations <- list() .swf$metadata <- list( service_name = "swf", endpoints = list("*" = list(endpoint = "swf.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "swf.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "swf.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "swf.{region}.sc2s.sgov.gov", global = FALSE)), service_id = "SWF", api_version = "2012-01-25", signing_name = "swf", json_version = "1.0", target_prefix = "SimpleWorkflowService" ) .swf$service <- function(config = list()) { handlers <- new_handlers("jsonrpc", "v4") new_service(.swf$metadata, handlers, config) }
auc_roc <- function(preds, actuals, returnDT=FALSE){ Pred <- NULL Actual <- NULL CumulativeFPR <- NULL CountFalse <- NULL CumulativeTPR <- NULL CountTrue <- NULL AdditionalArea <- NULL CumulativeArea <- NULL if(length(unique(preds)) == 1L) return(0.5) if(is(actuals, "factor")){ if(is.ordered(actuals) & length(levels(actuals)) == 2) actuals <- as.numeric(actuals) - 1 else stop("actuals is type factor, but is unordered. Make it an ordered factor.") } dt <- data.table(Pred=preds, Actual=actuals*1L) setorder(dt, -Pred) dt <- dt[ , { CountTrue = sum(Actual) list(CountFalse=.N - CountTrue, CountTrue=CountTrue) }, by=Pred] dt[, CumulativeFPR := cumsum(CountFalse)/sum(CountFalse)] dt[, CumulativeTPR := cumsum(CountTrue)/sum(CountTrue)] dt[, AdditionalArea := c(head(CumulativeFPR, 1) * head(CumulativeTPR, 1)/2, (tail(CumulativeFPR, -1) - head(CumulativeFPR, -1)) * (head(CumulativeTPR, -1) + (tail(CumulativeTPR, -1) - head(CumulativeTPR, -1))/2))] dt[, CumulativeArea := cumsum(AdditionalArea)] if(returnDT) return(dt[]) else return(tail(dt$CumulativeArea, 1)) }
pValueFun <- function(ndx, coeffMissingAllowed = 0.75) { notMissing <- apply(!is.na(geData[, ndx]), 1, sum) notMissing <- notMissing > floor((length(ndx)-1)^coeffMissingAllowed) aClassify <- classify(geData[notMissing, ndx])$clusters ans <- 1 if(min(table(aClassify)) > floor(0.1 * nrow(geData))) ans <- 1 - pchisq(survdiff(stData[notMissing] ~ aClassify)$chisq, df = 1) return(ans) }
nstr <- function(string, times) { if(!is.atomic(string)) stop("argument string must be an atomic vector") if(!is.numeric(times)) stop("len must be a numeric vector") if(length(string) == 0) return(NULL) if(length(times) == 0) return(character(0)) return(.Call("do_nstr", as.character(string), as.integer(times))) }
library("matrixStats") source("utils/validateIndicesFramework.R") x <- runif(6, min = -6, max = 6) for (l in 1:2) { for (d in 1:2) { for (idxs in index_cases) { validateIndicesTestVector(x, idxs, ftest = diff2, fsure = base::diff, lag = l, differences = d) } } }
NULL realized_count <- function( portfolio_quantity, portfolio_price, transaction_quantity, transaction_price, transaction_type, allow_short = TRUE, realized_only = FALSE ) { qty_diff <- portfolio_quantity + transaction_quantity prz_diff <- transaction_price - portfolio_price if (realized_only) { if (allow_short) { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } else if (prz_diff < 0) { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_count" = 1, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } else { res <- c("RG_count" = 1, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_count" = 0, "RL_count" = 1, "PG_count" = 0, "PL_count" = 0) } else { res <- c("RG_count" = 0, "RL_count" = 1, "PG_count" = 0, "PL_count" = 0) } } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "S") { if (prz_diff > 0) { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } else if (prz_diff < 0) { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "B") { if (prz_diff > 0) { if (qty_diff < 0) { res <- c("RG_count" = 0, "RL_count" = 1, "PG_count" = 0, "PL_count" = 0) } else { res <- c("RG_count" = 0, "RL_count" = 1, "PG_count" = 0, "PL_count" = 0) } } else if (prz_diff < 0) { if (qty_diff < 0) { res <- c("RG_count" = 1, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } else { res <- c("RG_count" = 1, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } else if (prz_diff < 0) { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_count" = 1, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } else { res <- c("RG_count" = 1, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_count" = 0, "RL_count" = 1, "PG_count" = 0, "PL_count" = 0) } else { res <- c("RG_count" = 0, "RL_count" = 1, "PG_count" = 0, "PL_count" = 0) } } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } } else { if (allow_short) { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 1, "PL_count" = 0) } else if (prz_diff < 0) { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 1) } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_count" = 1, "RL_count" = 0, "PG_count" = 1, "PL_count" = 0) } else { res <- c("RG_count" = 1, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_count" = 0, "RL_count" = 1, "PG_count" = 0, "PL_count" = 1) } else { res <- c("RG_count" = 0, "RL_count" = 1, "PG_count" = 0, "PL_count" = 0) } } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "S") { if (prz_diff > 0) { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 1) } else if (prz_diff < 0) { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 1, "PL_count" = 0) } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "B") { if (prz_diff > 0) { if (qty_diff < 0) { res <- c("RG_count" = 0, "RL_count" = 1, "PG_count" = 0, "PL_count" = 1) } else { res <- c("RG_count" = 0, "RL_count" = 1, "PG_count" = 0, "PL_count" = 0) } } else if (prz_diff < 0) { if (qty_diff < 0) { res <- c("RG_count" = 1, "RL_count" = 0, "PG_count" = 1, "PL_count" = 0) } else { res <- c("RG_count" = 1, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 1, "PL_count" = 0) } else if (prz_diff < 0) { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 1) } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_count" = 1, "RL_count" = 0, "PG_count" = 1, "PL_count" = 0) } else { res <- c("RG_count" = 1, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_count" = 0, "RL_count" = 1, "PG_count" = 0, "PL_count" = 1) } else { res <- c("RG_count" = 0, "RL_count" = 1, "PG_count" = 0, "PL_count" = 0) } } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } else { res <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) } } } return(res) } realized_total <- function( portfolio_quantity, portfolio_price, transaction_quantity, transaction_price, transaction_type, allow_short = TRUE, realized_only = FALSE ) { qty_diff <- portfolio_quantity + transaction_quantity prz_diff <- transaction_price - portfolio_price if (realized_only) { if (allow_short) { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } else if (prz_diff < 0) { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_total" = abs(transaction_quantity), "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } else { res <- c("RG_total" = abs(transaction_quantity) + qty_diff, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_total" = 0, "RL_total" = abs(transaction_quantity), "PG_total" = 0, "PL_total" = 0) } else { res <- c("RG_total" = 0, "RL_total" = abs(transaction_quantity) + qty_diff, "PG_total" = 0, "PL_total" = 0) } } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "S") { if (prz_diff > 0) { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } else if (prz_diff < 0) { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "B") { if (prz_diff > 0) { if (qty_diff < 0) { res <- c("RG_total" = 0, "RL_total" = transaction_quantity, "PG_total" = 0, "PL_total" = 0) } else { res <- c("RG_total" = 0, "RL_total" = transaction_quantity - qty_diff, "PG_total" = 0, "PL_total" = 0) } } else if (prz_diff < 0) { if (qty_diff < 0) { res <- c("RG_total" = transaction_quantity, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } else { res <- c("RG_total" = transaction_quantity - qty_diff, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } else if (prz_diff < 0) { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_total" = abs(transaction_quantity), "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } else { res <- c("RG_total" = abs(transaction_quantity) + qty_diff, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_total" = 0, "RL_total" = abs(transaction_quantity), "PG_total" = 0, "PL_total" = 0) } else { res <- c("RG_total" = 0, "RL_total" = abs(transaction_quantity) + qty_diff, "PG_total" = 0, "PL_total" = 0) } } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } } else { if (allow_short) { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = portfolio_quantity, "PL_total" = 0) } else if (prz_diff < 0) { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = portfolio_quantity) } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_total" = abs(transaction_quantity), "RL_total" = 0, "PG_total" = qty_diff, "PL_total" = 0) } else { res <- c("RG_total" = abs(transaction_quantity) + qty_diff, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_total" = 0, "RL_total" = abs(transaction_quantity), "PG_total" = 0, "PL_total" = qty_diff) } else { res <- c("RG_total" = 0, "RL_total" = abs(transaction_quantity) + qty_diff, "PG_total" = 0, "PL_total" = 0) } } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "S") { if (prz_diff > 0) { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = abs(portfolio_quantity)) } else if (prz_diff < 0) { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = abs(portfolio_quantity), "PL_total" = 0) } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "B") { if (prz_diff > 0) { if (qty_diff < 0) { res <- c("RG_total" = 0, "RL_total" = transaction_quantity, "PG_total" = 0, "PL_total" = abs(qty_diff)) } else { res <- c("RG_total" = 0, "RL_total" = transaction_quantity - qty_diff, "PG_total" = 0, "PL_total" = 0) } } else if (prz_diff < 0) { if (qty_diff < 0) { res <- c("RG_total" = transaction_quantity, "RL_total" = 0, "PG_total" = abs(qty_diff), "PL_total" = 0) } else { res <- c("RG_total" = transaction_quantity - qty_diff, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = portfolio_quantity, "PL_total" = 0) } else if (prz_diff < 0) { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = portfolio_quantity) } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_total" = abs(transaction_quantity), "RL_total" = 0, "PG_total" = qty_diff, "PL_total" = 0) } else { res <- c("RG_total" = abs(transaction_quantity) + qty_diff, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_total" = 0, "RL_total" = abs(transaction_quantity), "PG_total" = 0, "PL_total" = qty_diff) } else { res <- c("RG_total" = 0, "RL_total" = abs(transaction_quantity) + qty_diff, "PG_total" = 0, "PL_total" = 0) } } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } else { res <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) } } } return(res) } realized_value <- function( portfolio_quantity, portfolio_price, transaction_quantity, transaction_price, transaction_type, allow_short = TRUE, realized_only = FALSE ) { qty_diff <- portfolio_quantity + transaction_quantity prz_diff <- transaction_price - portfolio_price Er <- prz_diff / portfolio_price if (realized_only) { if (allow_short) { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } else if (prz_diff < 0) { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_value" = Er, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } else { res <- c("RG_value" = Er, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_value" = 0, "RL_value" = Er, "PG_value" = 0, "PL_value" = 0) } else { res <- c("RG_value" = 0, "RL_value" = Er, "PG_value" = 0, "PL_value" = 0) } } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "S") { if (prz_diff > 0) { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } else if (prz_diff < 0) { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "B") { if (prz_diff > 0) { if (qty_diff < 0) { res <- c("RG_value" = 0, "RL_value" = -Er, "PG_value" = 0, "PL_value" = 0) } else { res <- c("RG_value" = 0, "RL_value" = -Er, "PG_value" = 0, "PL_value" = 0) } } else if (prz_diff < 0) { if (qty_diff < 0) { res <- c("RG_value" = -Er, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } else { res <- c("RG_value" = -Er, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } else if (prz_diff < 0) { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_value" = Er, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } else { res <- c("RG_value" = Er, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_value" = 0, "RL_value" = Er, "PG_value" = 0, "PL_value" = 0) } else { res <- c("RG_value" = 0, "RL_value" = Er, "PG_value" = 0, "PL_value" = 0) } } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } } else { if (allow_short) { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = Er, "PL_value" = 0) } else if (prz_diff < 0) { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = Er) } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_value" = Er, "RL_value" = 0, "PG_value" = Er, "PL_value" = 0) } else { res <- c("RG_value" = Er, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_value" = 0, "RL_value" = Er, "PG_value" = 0, "PL_value" = Er) } else { res <- c("RG_value" = 0, "RL_value" = Er, "PG_value" = 0, "PL_value" = 0) } } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "S") { if (prz_diff > 0) { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = -Er) } else if (prz_diff < 0) { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = -Er, "PL_value" = 0) } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "B") { if (prz_diff > 0) { if (qty_diff < 0) { res <- c("RG_value" = 0, "RL_value" = -Er, "PG_value" = 0, "PL_value" = -Er) } else { res <- c("RG_value" = 0, "RL_value" = -Er, "PG_value" = 0, "PL_value" = 0) } } else if (prz_diff < 0) { if (qty_diff < 0) { res <- c("RG_value" = -Er, "RL_value" = 0, "PG_value" = -Er, "PL_value" = 0) } else { res <- c("RG_value" = -Er, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = Er, "PL_value" = 0) } else if (prz_diff < 0) { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = Er) } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_value" = Er, "RL_value" = 0, "PG_value" = Er, "PL_value" = 0) } else { res <- c("RG_value" = Er, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_value" = 0, "RL_value" = Er, "PG_value" = 0, "PL_value" = Er) } else { res <- c("RG_value" = 0, "RL_value" = Er, "PG_value" = 0, "PL_value" = 0) } } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } else { res <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) } } } return(res) } realized_duration <- function( portfolio_quantity, portfolio_price, transaction_quantity, transaction_price, transaction_type, previous_transaction_datetime, previous_datetime, transaction_datetime, allow_short = TRUE, realized_only = FALSE ) { qty_diff <- portfolio_quantity + transaction_quantity prz_diff <- transaction_price - portfolio_price dtt_diff <- difftime_financial(previous_datetime, transaction_datetime) dtt_diff0 <- difftime_financial(previous_transaction_datetime, transaction_datetime) if (realized_only) { if (allow_short) { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } else if (prz_diff < 0) { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_duration" = dtt_diff0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } else { res <- c("RG_duration" = dtt_diff0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_duration" = 0, "RL_duration" = dtt_diff0, "PG_duration" = 0, "PL_duration" = 0) } else { res <- c("RG_duration" = 0, "RL_duration" = dtt_diff0, "PG_duration" = 0, "PL_duration" = 0) } } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "S") { if (prz_diff > 0) { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } else if (prz_diff < 0) { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "B") { if (prz_diff > 0) { if (qty_diff < 0) { res <- c("RG_duration" = 0, "RL_duration" = dtt_diff0, "PG_duration" = 0, "PL_duration" = 0) } else { res <- c("RG_duration" = 0, "RL_duration" = dtt_diff0, "PG_duration" = 0, "PL_duration" = 0) } } else if (prz_diff < 0) { if (qty_diff < 0) { res <- c("RG_duration" = dtt_diff0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } else { res <- c("RG_duration" = dtt_diff0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } else if (prz_diff < 0) { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_duration" = dtt_diff0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } else { res <- c("RG_duration" = dtt_diff0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_duration" = 0, "RL_duration" = dtt_diff0, "PG_duration" = 0, "PL_duration" = 0) } else { res <- c("RG_duration" = 0, "RL_duration" = dtt_diff0, "PG_duration" = 0, "PL_duration" = 0) } } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } } else { if (allow_short) { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = dtt_diff, "PL_duration" = 0) } else if (prz_diff < 0) { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = dtt_diff) } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_duration" = dtt_diff0, "RL_duration" = 0, "PG_duration" = dtt_diff, "PL_duration" = 0) } else { res <- c("RG_duration" = dtt_diff0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_duration" = 0, "RL_duration" = dtt_diff0, "PG_duration" = 0, "PL_duration" = dtt_diff) } else { res <- c("RG_duration" = 0, "RL_duration" = dtt_diff0, "PG_duration" = 0, "PL_duration" = 0) } } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "S") { if (prz_diff > 0) { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = dtt_diff) } else if (prz_diff < 0) { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = dtt_diff, "PL_duration" = 0) } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else if (portfolio_quantity < 0 && transaction_type == "B") { if (prz_diff > 0) { if (qty_diff < 0) { res <- c("RG_duration" = 0, "RL_duration" = dtt_diff0, "PG_duration" = 0, "PL_duration" = dtt_diff) } else { res <- c("RG_duration" = 0, "RL_duration" = dtt_diff0, "PG_duration" = 0, "PL_duration" = 0) } } else if (prz_diff < 0) { if (qty_diff < 0) { res <- c("RG_duration" = dtt_diff0, "RL_duration" = 0, "PG_duration" = dtt_diff, "PL_duration" = 0) } else { res <- c("RG_duration" = dtt_diff0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else { if (portfolio_quantity > 0 && transaction_type == "B") { if (prz_diff > 0) { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = dtt_diff, "PL_duration" = 0) } else if (prz_diff < 0) { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = dtt_diff) } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else if (portfolio_quantity > 0 && transaction_type == "S") { if (prz_diff > 0) { if (qty_diff > 0) { res <- c("RG_duration" = dtt_diff0, "RL_duration" = 0, "PG_duration" = dtt_diff, "PL_duration" = 0) } else { res <- c("RG_duration" = dtt_diff0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else if (prz_diff < 0) { if (qty_diff > 0) { res <- c("RG_duration" = 0, "RL_duration" = dtt_diff0, "PG_duration" = 0, "PL_duration" = dtt_diff) } else { res <- c("RG_duration" = 0, "RL_duration" = dtt_diff0, "PG_duration" = 0, "PL_duration" = 0) } } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } else { res <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) } } } return(res) } realized_compute <- function( portfolio_quantity, portfolio_price, transaction_quantity, transaction_price, transaction_type, previous_transaction_datetime, previous_datetime, transaction_datetime, transaction_asset, allow_short = TRUE, realized_only = FALSE, method = "all" ) { if (method == "count") { rgl_count <- realized_count( portfolio_quantity, portfolio_price, transaction_quantity, transaction_price, transaction_type, allow_short, realized_only ) res_df <- as.data.frame(c("asset" = transaction_asset, as.list(rgl_count))) } else if (method == "total") { rgl_total <- realized_total( portfolio_quantity, portfolio_price, transaction_quantity, transaction_price, transaction_type, allow_short, realized_only ) res_df <- as.data.frame(c("asset" = transaction_asset, as.list(rgl_total))) } else if (method == "value") { rgl_value <- realized_value( portfolio_quantity, portfolio_price, transaction_quantity, transaction_price, transaction_type, allow_short, realized_only ) res_df <- as.data.frame(c("asset" = transaction_asset, as.list(rgl_value))) } else if (method == "duration") { rgl_duration <- realized_duration( portfolio_quantity, portfolio_price, transaction_quantity, transaction_price, transaction_type, previous_transaction_datetime, previous_datetime, transaction_datetime, allow_short, realized_only ) res_df <- as.data.frame(c("asset" = transaction_asset, as.list(rgl_duration))) } else { rgl_count <- realized_count( portfolio_quantity, portfolio_price, transaction_quantity, transaction_price, transaction_type, allow_short, realized_only ) rgl_total <- realized_total( portfolio_quantity, portfolio_price, transaction_quantity, transaction_price, transaction_type, allow_short, realized_only ) rgl_value <- realized_value( portfolio_quantity, portfolio_price, transaction_quantity, transaction_price, transaction_type, allow_short, realized_only ) rgl_duration <- realized_duration( portfolio_quantity, portfolio_price, transaction_quantity, transaction_price, transaction_type, previous_transaction_datetime, previous_datetime, transaction_datetime, allow_short, realized_only ) res_df <- as.data.frame( c("asset" = transaction_asset, as.list(rgl_count), as.list(rgl_total), as.list(rgl_value), as.list(rgl_duration) ) ) } return(res_df) } realized_empty <- function(transaction_asset, method = "all") { if (method == "count") { rgl_count <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) res_df <- as.data.frame(c("asset" = transaction_asset, as.list(rgl_count))) } else if (method == "total") { rgl_total <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) res_df <- as.data.frame(c("asset" = transaction_asset, as.list(rgl_total))) } else if (method == "value") { rgl_value <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) res_df <- as.data.frame(c("asset" = transaction_asset, as.list(rgl_value))) } else if (method == "duration") { rgl_duration <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) res_df <- as.data.frame(c("asset" = transaction_asset, as.list(rgl_duration))) } else { rgl_count <- c("RG_count" = 0, "RL_count" = 0, "PG_count" = 0, "PL_count" = 0) rgl_total <- c("RG_total" = 0, "RL_total" = 0, "PG_total" = 0, "PL_total" = 0) rgl_value <- c("RG_value" = 0, "RL_value" = 0, "PG_value" = 0, "PL_value" = 0) rgl_duration <- c("RG_duration" = 0, "RL_duration" = 0, "PG_duration" = 0, "PL_duration" = 0) res_df <- as.data.frame( c("asset" = transaction_asset, as.list(rgl_count), as.list(rgl_total), as.list(rgl_value), as.list(rgl_duration) ) ) } return(res_df) }
MCp.RInSp = function(dataset, pop.diet = "sum", replicates = 999){ if (!inherits(dataset, "RInSp")) stop("The input must be an object of class RInSp") if (dataset$data.type %in% c("integer", "double") == FALSE) stop("Input data type must be 'integer' or 'double'.") if (pop.diet %in% c("sum", "average") == FALSE) stop("Wrong population diet option.") replicates <- as.integer(replicates) if (replicates <=0) stop("Wrong value for replicates.") if (dataset$data.type == "integer") type.mc = 1 else type.mc= 2 if (pop.diet == "sum") { diet <- apply(dataset$resources, 2, sum) / sum(dataset$resources)} else { diet <- apply(dataset$proportion, 2, mean)} ris <- .Call("MCprocedure", dataset$resources, as.vector(type.mc), as.vector(diet), as.vector(replicates), PACKAGE="RInSp") ris <- array(c(as.vector(dataset$resources), as.vector(ris)), c(dataset$num.individuals, dataset$num.prey, (replicates +1))) return(ris)}
context("Building a knn model") expect_error(knn_model(ts(1:5), lags = 0:3, k = 5)) expect_error(knn_model(ts(1:5), lags = 3:5, k = 1)) expect_error(knn_model(ts(1:5), lags = 2:4, k = 2))
multi_dsciat <- function(sciat1, sciat2, graph = c("density", "violin", "point"), x_values = TRUE, gcolors = c("dark", "greens", "blues", "pinks"), label_sc1 = "SC-IAT1", label_sc2 = "SC-IAT2", label_y = "SC-IAT scores", dens_mean = TRUE){ graph <- match.arg(graph) gcolors <- match.arg(gcolors) if(is.na(class(sciat1)[2]) | is.na(class(sciat2)[2])) { stop("Objects must be of class dsciat") } if (class(sciat1)[2] != "dsciat" | class(sciat2)[2] != "dsciat") { stop("Objects must be of class dsciat") } d_small1 <- sciat1[ , c("participant", "d_sciat")] d_small1$sciat <- label_sc1 d_small2 <- sciat2[ , c("participant", "d_sciat")] d_small2$sciat <- label_sc2 sciat_all <- rbind(d_small1, d_small2) sc_mean <- aggregate(sciat_all$d_sciat, by = list(sciat_all$sciat), FUN = mean) sc_mean <- aggregate(sciat_all$d_sciat, by = list(sciat_all$sciat), FUN = mean) colnames(sc_mean) <- c("sciat", "msc") sciat_all <- merge(sciat_all, sc_mean, by = "sciat") data <- sciat_all if (graph == "density") { d_graph <- ggplot(data, aes(x = .data$d_sciat, color = .data$sciat)) + geom_density(size = 1.1) + theme_minimal() + theme(axis.title.y = element_blank()) + xlab(label_y) if (dens_mean == TRUE) { d_graph <- d_graph + geom_vline(data=data, aes(xintercept = .data$msc, color = .data$sciat), linetype = "dashed", size = 0.9) } else { d_graph <- d_graph } } else if (graph == "violin") { d_graph <- ggplot(data, aes(y = .data$d_sciat, x = .data$sciat, color = .data$sciat)) + geom_violin(trim = FALSE) + stat_summary(fun.data = mean_sdl, geom = "pointrange", color = "black") + theme_minimal() + ylab(label_y) } else if (graph == "point") { d_graph <- ggplot(data, aes(x = .data$participant, y = .data$d_sciat, group = .data$sciat)) + geom_point(aes(shape = .data$sciat, color = .data$sciat)) + theme_minimal() + theme(axis.text.x = element_text(size = 5)) + scale_shape_discrete(name = "SC-IAT type") + ylab(label_y) + xlab("Participant") if (x_values == TRUE){ d_graph <- d_graph } else { d_graph <- d_graph + theme(axis.text.x = element_blank()) } } if (gcolors == "greens"){ d_graph <- d_graph + scale_color_manual(values = c("palegreen", "palegreen4"), name = "SC-IAT type") } else if (gcolors == "blues"){ d_graph <- d_graph + scale_color_manual(values = c("royalblue1", "royalblue4"), name = "SC-IAT type") } else if (gcolors == "pinks") { d_graph <- d_graph + scale_color_manual(values = c("rosybrown1", "plum1"), name = "SC-IAT type") } else { d_graph <- d_graph + scale_color_manual(values = c("gray74", "gray8"), name = "SC-IAT type") } return(d_graph) }
context("pxweb_data_comments") test_that(desc="test data comment structure",{ skip_on_cran() url <- "http://api.scb.se/OV0104/v1/doris/sv/ssd/BE/BE0101/BE0101A/BefolkningNy" json_query <- file.path(system.file(package = "pxweb"), "extdata", "examples", "json_query_example.json") expect_silent(px_data1 <- pxweb_get(url = url, query = json_query)) expect_silent(pxdcs <- pxweb_data_comments(x = px_data1)) expect_output(print(pxdcs), regexp = "pxweb_data_comments\\[\\[2\\]\\]") expect_equal(length(pxdcs$pxweb_data_comments), 2) expect_silent(pxdc_df <- as.data.frame(pxdcs, stringsAsFactors = TRUE)) expect_equal(dim(pxdc_df), c(2, 4)) expect_equal(unname(unlist(lapply(pxdc_df, class))), c("integer", "integer", "factor", "factor")) expect_silent(pxdc_df <- as.data.frame(pxdcs, stringsAsFactors = FALSE)) expect_equal(dim(pxdc_df), c(2, 4)) expect_equal(unname(unlist(lapply(pxdc_df, class))), c("integer", "integer", "character", "character")) url <- "http://api.scb.se/OV0104/v1/doris/sv/ssd/BE/BE0101/BE0101A/BefolkningNy" json_query <- file.path(system.file(package = "pxweb"), "extdata", "examples", "json_query_variables_example.json") expect_silent(px_data2 <- suppressWarnings(pxweb_get(url = url, query = json_query))) expect_silent(pxdcs <- pxweb_data_comments(x = px_data2)) expect_output(print(pxdcs), regexp = "NO PXWEB DATA COMMENTS") expect_equal(length(pxdcs$pxweb_data_comments), 0) expect_silent(pxdc_df <- as.data.frame(pxdcs, stringsAsFactors = FALSE)) expect_equal(dim(pxdc_df), c(0, 4)) expect_equal(colnames(pxdc_df), colnames(as.data.frame(pxweb_data_comments(x = px_data1)))) expect_equal(unname(unlist(lapply(pxdc_df, class))), c("integer", "integer", "character", "character")) })
library("graphsim") library("igraph") context("Make Distance Matrix") test_that("Generate distance relation matrix from adjacency matrix", { graph_test1_edges <- rbind(c("A", "B"), c("B", "C"), c("B", "D")) graph_test1 <- graph.edgelist(graph_test1_edges, directed = TRUE) adjacency_matrix1 <- make_adjmatrix_graph(graph_test1) distance_matrix1 <- make_distance_adjmat(adjacency_matrix1) expect_equal(isSymmetric(distance_matrix1), TRUE) expect_true(all(diag(distance_matrix1) == rep(1, nrow(adjacency_matrix1)))) expect_equal(nrow(distance_matrix1), length(V(graph_test1))) expect_equal(ncol(distance_matrix1), length(V(graph_test1))) expect_equal(sum(distance_matrix1), 8.5) expect_true(all(adjacency_matrix1 == cbind(c(0, 1, 0, 0), c(1, 0, 1, 1), c(0, 1, 0, 0), c(0, 1, 0, 0)))) expect_true(all(distance_matrix1 == 1/cbind(c(1, 2, 4, 4), c(2, 1, 2, 2), c(4, 2, 1, 4), c(4, 2, 4, 1)))) expect_true(all(distance_matrix1 %in% c(0, 1/2^c(0:100)))) }) test_that("Generate distance relation matrix from commonlink matrix", { graph_test1_edges <- rbind(c("A", "B"), c("B", "C"), c("B", "D")) graph_test1 <- graph.edgelist(graph_test1_edges, directed = TRUE) adjacency_matrix1 <- make_adjmatrix_graph(graph_test1) common_link_matrix1 <- make_commonlink_adjmat(adjacency_matrix1) distance_matrix1 <- make_distance_adjmat(common_link_matrix1) expect_equal(isSymmetric(distance_matrix1), TRUE) expect_true(all(diag(distance_matrix1) == rep(1, nrow(adjacency_matrix1)))) expect_equal(nrow(distance_matrix1), length(V(graph_test1))) expect_equal(ncol(distance_matrix1), length(V(graph_test1))) expect_equal(sum(distance_matrix1), length(V(graph_test1))) expect_true(all(adjacency_matrix1 == cbind(c(0, 1, 0, 0), c(1, 0, 1, 1), c(0, 1, 0, 0), c(0, 1, 0, 0)))) expect_true(all(common_link_matrix1 == cbind(c(1, 0, 1, 1), c(0, 3, 0, 0), c(1, 0, 1, 1), c(1, 0, 1, 1)))) expect_true(all(distance_matrix1 == diag(4))) expect_true(all(distance_matrix1 %in% c(0, 1/2^c(0:100)))) }) test_that("Generate distance relation matrix matrix from graph structure", { graph_test1_edges <- rbind(c("A", "B"), c("B", "C"), c("B", "D")) graph_test1 <- graph.edgelist(graph_test1_edges, directed = TRUE) adjacency_matrix1 <- make_adjmatrix_graph(graph_test1) common_link_matrix1 <- make_commonlink_graph(graph_test1) distance_matrix1 <- make_distance_graph(graph_test1) expect_equal(isSymmetric(distance_matrix1), TRUE) expect_true(all(diag(distance_matrix1) == rep(1, nrow(adjacency_matrix1)))) expect_equal(nrow(distance_matrix1), length(V(graph_test1))) expect_equal(ncol(distance_matrix1), length(V(graph_test1))) expect_equal(sum(distance_matrix1), 8.5) expect_true(all(adjacency_matrix1 == cbind(c(0, 1, 0, 0), c(1, 0, 1, 1), c(0, 1, 0, 0), c(0, 1, 0, 0)))) expect_true(all(distance_matrix1 == 1/cbind(c(1, 2, 4, 4), c(2, 1, 2, 2), c(4, 2, 1, 4), c(4, 2, 4, 1)))) expect_true(all(distance_matrix1 %in% c(0, 1/2^c(0:100)))) })
summary.likert.gap <- function(object, ...) { return(list( Satisfaction=summary.likert(object, ...), Importance=summary.likert(object$importance, ...) )) }
setClass("QueryResults", slots = c(librdf_query_results = "_p_librdf_query_results")) setMethod("initialize", signature = "QueryResults", definition = function(.Object, results) { .Object@librdf_query_results <- results return(.Object) }) setGeneric("freeQueryResults", function(.Object) { standardGeneric("freeQueryResults") }) setMethod("freeQueryResults", signature("QueryResults"), function(.Object) { if (!is.null(.Object@librdf_query_results) && librdf_query_results_finished(.Object@librdf_query_results) == 0) { num_nodes <- librdf_query_results_get_bindings_count(.Object@librdf_query_results) for (i in 1:num_nodes-1) { binding_name <- librdf_query_results_get_binding_name(.Object@librdf_query_results, i) val = librdf_query_results_get_binding_value(.Object@librdf_query_results, i) if (!is.null.externalptr(val@ref)) { librdf_free_node(val) } } } librdf_free_query_results(.Object@librdf_query_results) })
NAME <- "ses" source(file.path('_helper', 'init.R')) all.equal(ses(letters[1:10], letters[1:10]), character()) all.equal(ses(letters[1:10], LETTERS[1:10]), "1,10c1,10") all.equal(ses(letters[1:5], LETTERS[1:10]), "1,5c1,10") all.equal(ses(letters[1:10], LETTERS[1:5]), "1,10c1,5") all.equal(ses(letters[2:10], letters[1:7]), c("0a1", "7,9d7")) all.equal( ses(letters[c(1:5, 1:5, 1:5)], c("e", "d", "a", "b", "c")), c("1,4d0", "6,8d1", "10d2", "14,15d5") ) all.equal( ses(c("e", "d", "a", "b", "c"), letters[c(1:5, 1:5, 1:5)]), c("0a1,4", "1a6,8", "2a10", "5a14,15") ) all.equal(ses("a", c("a", "b")), "1a2") all.equal(ses(c("a", "b"), "a"), "2d1") all.equal(ses("c", c("b", "c")), "0a1") all.equal(ses(c("b", "c"), "c"), "1d0") all.equal(ses("a", character()), "1d0") all.equal(ses(character(), "a"), "0a1") all.equal(ses(character(), character()), character()) set.seed(2) w1 <- sample( c( "carrot", "cat", "cake", "eat", "rabbit", "holes", "the", "a", "pasta", "boom", "noon", "sky", "hat", "blah", "paris", "dog", "snake" ), 25, replace=TRUE ) w4 <- w3 <- w2 <- w1 w2[sample(seq_along(w1), 5)] <- LETTERS[1:5] w3 <- w1[8:15] w4 <- c(w1[1:5], toupper(w1[1:5]), w1[6:15], toupper(w1[1:5])) all.equal(ses(w1, w4), c("5a6,10", "15,21d19", "23,25c21,25")) string <- do.call(paste0, expand.grid(LETTERS, LETTERS, LETTERS)) all.equal( ses(string, c("hello", string[-c(5, 500, 1000)], "goodbye")), c("0a1", "5d5", "500d499", "1000d998", "17576a17575") ) all.equal( ses(c(string[200:500], "hello", string[-(1:400)][-c(5, 500, 1000)]), string), c("0a1,199", "207,306d405", "800a900", "1299a1400") ) ses(letters[1:10], LETTERS[1:10], max.diffs=5) all.equal( ses(letters[1:10], LETTERS[1:10], max.diffs=5, warn=FALSE), "1,10c1,10" ) all.equal( ses( letters[1:10], c(letters[1], LETTERS[2:5], letters[6:10]), max.diffs=5, warn=FALSE ), "2,5c2,5" ) all.equal( ses( letters[1:10], c(letters[1], LETTERS[2:5], letters[6:8], LETTERS[9], letters[10]), max.diffs=5, warn=FALSE ), c("2,5c2,5", "9c9") ) all.equal(ses(letters[1:4], letters[1:3]), "4d3") all.equal(ses(letters[1:3], letters[1:4]), "3a4") ses(1, 2:9, max.diffs = 8) a <- c(39.6, 40.1, 35, 42, 34.5, 41.4, 39, 40.6, 36.5, 37.6, 35.7, 41.3, 37.6, 41.1, 36.4, 41.6, 35.5, 41.1, 35.9, 41.8, 33.5, 39.7, 39.6, 45.8, 35.5, 42.8, 40.9, 37.2, 36.2, 42.1, 34.6, 42.9, 36.7, 35.1, 37.3, 41.3, 36.3, 36.9, 38.3, 38.9, 35.7, 41.1, 34, 39.6, 36.2, 40.8, 38.1, 40.3, 33.1, 43.2, 49.1, 48.4, 42.6, 44.4, 44, 48.7, 42.7, 49.6, 45.3, 49.6, 50.5, 43.6, 45.5, 50.5, 44.9, 45.2, 46.6, 48.5, 45.1, 50.1, 46.5, 45, 43.8, 45.5, 43.2, 50.4, 45.3, 46.2, 45.7, 54.3, 45.8, 49.8, 46.2, 49.5, 43.5, 50.7, 47.7, 46.4, 48.2, 46.5, 46.4, 48.6, 47.5, 51.1, 45.2, 45.2, 50.5, 49.5, 46.4, 52.8, 40.9, 54.2, 42.5, 51, 49.7, 47.5, 47.6, 52, 46.9, 53.5, 49, 46.2, 50.9, 45.5) b <- c(39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.1, 42, 37.8, 37.8, 41.1, 38.6, 34.6, 36.6, 38.7, 42.5, 34.4, 46, 37.8, 37.7, 35.9, 38.2, 38.8, 35.3, 40.6, 40.5, 37.9, 40.5, 39.5, 37.2, 39.5, 40.9, 36.4, 39.2, 38.8, 42.2, 37.6, 39.8, 36.5, 40.8, 36, 44.1, 37, 39.6, 41.1, 37.5, 36, 42.3, 46.1, 50, 48.7, 50, 47.6, 46.5, 45.4, 46.7, 43.3, 46.8, 40.9, 49, 45.5, 48.4, 45.8, 49.3, 42, 49.2, 46.2, 48.7, 50.2, 45.1, 46.5, 46.3, 42.9, 46.1, 44.5, 47.8, 48.2, 50, 47.3, 42.8, 45.1, 59.6, 49.6, 50.5, 50.5, 50.1, 50.4, 46.2, 54.3, 49.8, 49.5, 50.7, 46.4, 48.2, 48.6, 45.2, 52.5, 50, 50.8, 52.1, 52.2, 49.5, 50.8, 46.9, 51.1, 55.9, 49.1, 49.8, 51.5, 55.1, 48.8, 50.4, 46.5, 50, 51.3, 45.4, 52.7, 45.2, 46.1, 51.3, 46, 51.3, 46.6, 51.7, 47, 52, 45.9, 50.5, 50.3, 58, 46.4, 49.2, 42.4, 48.5, 43.2, 50.6, 46.7, 52) ses(a[-c(15:38, 50:90)], b[-c(40:85, 100:125)], max.diffs=80) ses(a[-(18:38)], b[-(50:80)], max.diffs=115) a <- c('a', 'b', 'c', 'A', 'X', 'Y', 'Z', 'W') b <- c('X', 'C', 'A', 'U', 1, 2, 3) ses(a, b, max.diffs=13) ses(letters[1:2], LETTERS[1:2], max.diffs = 4) ses(c("G", "C", "T", "C", "A", "C", "G", "C"), c("T", "G"), max.diffs=2) ses(c('A','A','A','A','A'), c('B','A','B','A','B'), max.diffs=0) ses(c('A','A','A','A','A'), c('B','A','B','A','B'), max.diffs=1) ses(c('A','A','A','A','A'), c('B','A','B','A','B'), max.diffs=2) ses_dat( a=c("T", "A", "A", "C", "C", "A"), b=c("A", "G", "A", "A"), max.diffs = 0 ) try(ses('a', 'b', max.diffs='hello')) try(ses('a', 'b', warn='hello')) a <- structure(1, class='diffobj_ogewlhgiadfl2') try(ses(a, 1)) try(ses(1, a)) if( R.Version()$major >= 3 && R.Version()$minor >= "3.1" || R.Version()$major >= 4) { rdsf1 <- function(x) readRDS(file.path("_helper", "objs", "diffStr", sprintf("%s.rds", x))) all.equal( as.character( diffStr(mdl1, mdl2, extra=list(strict.width="wrap"), line.limit=30) ), rdsf1(500) ) } A3 <- c("a b c", "d e f A B C D", "g h i", "f") B3 <- c("a b c", "xd e f E Q L S", "g h i", "q") diffChr(A3, B3, max.diffs=2) a <- b <- do.call(paste0, expand.grid(LETTERS, LETTERS)) set.seed(2) b <- b[-sample(length(b), 100)] a <- a[-sample(length(b), 100)] dat <- ses_dat(a, b) all.equal(dat[['val']][dat[['op']] != 'Delete'], b) all.equal(dat[['val']][dat[['op']] != 'Insert'], a) all.equal(a[dat[['id.a']][!is.na(dat[['id.a']])]], a) dat2 <- ses_dat(a, b, extra=FALSE) all.equal(dat[1:2], dat2) all.equal(length(dat2), 2L) try(ses_dat(a, b, extra=NA)) x <- c("fa\xE7ile", "fa\ue7ile") Encoding(x) <- c("latin1", "UTF-8") y <- rev(x) all.equal(diffobj::ses(x, y), character())
get_data <- function(path = NULL, query = NULL, token) { if (grepl("management", paste(path, collapse = "/"))) { limit <- 1000L items <- "items" } else { limit <- 10000L items <- "rows" } if (is.null(query$start.index)) query$start.index <- 1L total <- ifelse(!is.null(query$max.results) && query$max.results > limit, query$max.results, NA) if (is.null(query$max.results) || query$max.results > limit) { query$max.results <- limit pagination <- getOption("rga.pagination", TRUE) } else pagination <- FALSE if (grepl("data/realtime", paste(path, collapse = "/"))) pagination <- FALSE res <- api_request(get_url(path, query), token) if (res$totalResults == 0L || is.null(res[[items]]) || length(res[[items]]) == 0L) return(NULL) if (isTRUE(pagination) && query$max.results < res$totalResults) { message(sprintf("API response contains more then %d items. Batch processing mode enabled.", query$max.results)) if (is.na(total) || total >= res$totalResults) total <- res$totalResults sidx <- seq.int(query$start.index, total, query$max.results) midx <- diff(c(sidx, total + 1L)) pages <- vector(mode = "list", length = length(sidx)) pb <- txtProgressBar(min = 0, max = length(sidx), initial = 1, style = 3) for (i in 2L:length(sidx)) { query$start.index <- sidx[i] query$max.results <- midx[i] pages[[i]] <- api_request(get_url(path, query), token)[[items]] setTxtProgressBar(pb, i) } pages[[1L]] <- res[[items]] if (is.matrix(pages[[1L]])) pages <- rbind.fill.matrix(pages) if (is.data.frame(pages[[1L]])) pages <- rbind.fill(pages) else if (is.list(pages[[1L]])) pages <- unlist(pages, recursive = FALSE, use.names = FALSE) res[[items]] <- pages close(pb) } res[[items]] <- build_df(res) if (nrow(res[[items]]) < res$totalResults) warning(sprintf("Only %d observations out of %d were obtained. Set max.results = NULL (default value) to get all results.", nrow(res[[items]]), res$totalResults), call. = FALSE) return(res) }
extractLMS <- function(fit, data, sex="M", grid="classic", decimals = c(4,4,4), flatAge = NULL) { check.names(df=data, needed=c("age","t.age")) if (!is.gamlss(fit)) stop("fit not a gamlss object.") tm <- data$t.age[which.min(data$age)] grd <- ageGrid(grid) grid.age <- grd$year minage <- min(data$age, na.rm=TRUE) maxage <- max(data$age, na.rm=TRUE) outside <- grid.age < minage | grid.age > maxage grid.age <- grid.age[!outside] t.grid.age <- approx(x=data$age, y=data$t.age, xout=grid.age, ties=mean)$y if (length(t.grid.age)==0) stop("No overlap between age grid and data.") newdata <- data.frame(t.age=t.grid.age) lms <- predictAll(fit, newdata=newdata, data=data) lms$mu <- round(lms$mu, decimals[2]) lms$sigma <- round(lms$sigma/lms$mu, decimals[3]) if (length(lms)>2) lms$nu <- round(lms$nu, decimals[1]) else lms$nu <- 1 lms <- as.data.frame(lms) result <- data.frame(sex=sex, x=grd$year, L=NA, M=NA, S=NA) result[!outside, "L"] <- lms$nu result[!outside, "M"] <- lms$mu result[!outside, "S"] <- lms$sigma if (!is.null(flatAge)) { if (!(flatAge %in% result$x)) stop("FlatAge value (', FlatAge,') not found in age grid") flatLMS <- result[flatAge==result$x, c("L","M","S")] result[!outside & flatAge<result$x, c("L","M","S")] <- flatLMS } return(result) } ageGrid <- function(grid="compact"){ formats <- c("compact", "classic", "extensive", "0-104w", "0-24m", "0-21y", "0-21yd", "0-21yc") fmi <- pmatch(grid, formats) if (is.na(fmi)) stop("Grid format ",grid," unknown.") grid <- switch(fmi, compact = c((0:14)/365.25, (3:13)*7/365.25, seq(3,11.5,0.5)/12, (12:23)/12, seq(2, 21, 0.5) ), classic = { grid.weeks <- c(0,1,2,3,4,5,6,7,8,9,10,12,14,16,18,20,22,24,26, 28,32,36,40,44,48,52,56,60,64) c(grid.weeks*7/365.25,seq(1.5,21,0.5)) }, extensive = (0:(365.25*21+1))/365.25, week = (0:104)*7/365.25, month = (0:24)/12, year = 0:21, dyear = seq(0, 21, 0.1), cyear = seq(0, 21, 0.01) ) year <- round(grid, 4) month <- round(grid*12, 4) week <- round(grid*365.25/7, 4) day <- round(grid*365.25, 4) return(list(format = formats[fmi], year = year, month = month, week = week, day = day)) }
fit_multi = function(time_col, intensity_col, data, strata_cols , starting_par = list(y0 = 0.01, r = 0.03, K = 0.8), maxiter=500, nlin = FALSE, estimate_K = FALSE){ if (missing(data)) { stop(gettextf("Missing 'data' argument")) } if (missing(intensity_col)) { stop(gettextf("Missing 'intensity_col' argument")) } if (missing(time_col)) { stop(gettextf("Missing 'time_col' argument")) } box = data.frame() pred_box = data.frame() strata_col = strata_cols if(is.null(strata_col)){ data_uni=data %>% dplyr::mutate(strata = "") strata_col= "strata" }else{ data_uni = data %>% tidyr::unite(strata, strata_col, sep = "---") } STRATA = data_uni[["strata"]] strata = as.character(unique(STRATA)) for(i in 1:length(strata)){ rowi = data_uni[["strata"]]==strata[i] datai = data_uni[rowi,] if(nlin == T & estimate_K == T ){ model = fit_nlin2(time = datai[[time_col]], y = datai[[intensity_col]], starting_par = starting_par, maxiter=maxiter) } if(nlin == T & estimate_K == F ){ model = fit_nlin(time = datai[[time_col]], y = datai[[intensity_col]], starting_par = starting_par[1:2], maxiter = maxiter)} if(nlin == F & estimate_K == F){ model = fit_lin(time = datai[[time_col]], y = datai[[intensity_col]]) } if(nlin == F & estimate_K == T){ model = fit_lin(time = datai[[time_col]], y = datai[[intensity_col]]) gettextf("'K' is not estimated when nlin = F. To estimate K, use nlin = T and estimate_K = T ") } lil_pred_box= model$data %>% dplyr::mutate(strata = strata[i]) pred_box = pred_box %>% dplyr::bind_rows(lil_pred_box) lil_box = model$stats_all %>% dplyr::mutate(strata = strata[i]) box = box %>% dplyr::bind_rows(lil_box) } colnames = colnames(lil_box)[colnames(lil_box)!="strata"] colnames_prbox = colnames(lil_pred_box)[colnames(lil_pred_box)!="strata"] box2 = box %>% dplyr::select("strata",colnames) %>% tidyr::separate(strata,into = strata_col, sep = "---") pred_box2 = pred_box %>% dplyr::select("strata",colnames_prbox) %>% tidyr::separate(strata,into = strata_col, sep = "---") if(nlin == F & estimate_K == T){ message("'K' is not estimated when nlin = F. To estimate K, use nlin = T and estimate_K = T ") } a = list(Parameters = box2, Data = pred_box2) return(a) }
search_msig <- function(keywords, collection='',organism='',contributor='', email){ message('Loading HTML') keywords <- key(keywords) url <- constuct(keywords,collection,organism,contributor) if (missing(email)) email = get('email',envir = .GlobalEnv) h <- httr::GET(URLencode(url),httr::authenticate(email, "password")) x <- httr::content(h) if (!grepl('var myDataSource =',x)){ message(' === your search returned no results=== ') }else{ message('Clear javascript') f <- x |> do::Replace0('\r') |> do::Replace0('.*var myData =[\\[ ]{0,}') |> do::Replace0(c('[; ]{0,}\\][; ]{0,}var myDataSource =.*')) |> do::Replace0(c("<span class='highlight' style='padding-left: 0px; padding-right: 0px;'>",'</span>')) |> do::Replace('name:','"name":') |> do::Replace('nameRaw:','"nameRaw":') |> do::Replace('numGenes:','"numGenes":') |> do::Replace('description:','"description":') |> do::Replace('collections:','"collections":') |> do::Replace('organism:','"organism":') |> do::Replace('contributor:','"contributor":') |> do::Replace(' {0,}}','}') |> do::Replace(' {0,}, {1,}',', ') |> do::Replace('\\}, \\{','}}, {{') |> strsplit('\\}, \\{') |> unlist() |> lapply(function(i) as.data.frame(jsonlite::fromJSON(i))) |> do.call(what = plyr::rbind.fill) message('gene sets: ',nrow(f),'\n') message('add description_full') f[,2] <- tolower(f[,2]) colnames(f)[2] <- 'standard_name' if ('NewMsigDB' %in% ls(envir = .GlobalEnv)) msigdb <- get('NewMsigDB',envir = .GlobalEnv) f <- dplyr::inner_join(f,msigdb[,c('standard_name','description_full')],'standard_name') f[,1] <- sprintf('http://www.gsea-msigdb.org/gsea/msigdb/geneset_page.jsp%s', do::Replace0(f[,1],'.*\\|msigdb/geneset_page.jsp')) |> do::Replace('&','&amp;') colnames(f)[1]='link' f <- f[,c(colnames(f)[-1],colnames(f)[1])] f <- f[,c("standard_name", "numGenes", "description",'description_full',"collections", "organism", "contributor", "link")] hightlitht <- strsplit(keywords,' AND | OR | ')[[1]] hightlitht <- hightlitht[nchar(hightlitht)>0] attr(f,'search_msig') <- hightlitht f } } constuct <- function(keywords,collection,organism,contributor){ if (length(keywords) != 1) stop('keywords must be one') keywords <- paste0('keywords=',keywords) collection <- paste0(paste0('&collection=',collection),collapse = '') organism <- paste0(paste0('&organism=',organism),collapse = '') contributor <- paste0(paste0('&contributor=',contributor),collapse = '') q <- paste0(keywords,collection,organism,contributor) sprintf('http://www.gsea-msigdb.org/gsea/msigdb/search.jsp?%s', q) } key <- function(keywords){ if (missing(keywords)) stop('keywords can not be missing') do::Replace(keywords,pattern = c(' {1,}and {1,}: AND ', ' {1,}or {1,}: OR ', ' {1,}& {1,}: AND ', ' {1,}\\| {1,}: OR ')) }
set_reactive_grob <- function(loon.grob, index, ...) { obj <- character(0) class(obj) <- names(loon.grob$children) UseMethod("set_reactive_grob", obj) } set_reactive_grob.l_plot <- function(loon.grob, index, ...) { args <- list(...) pointsTreeName <- args$pointsTreeName if(pointsTreeName != "points: missing glyphs" & length(index) != 0) { newGrob <- grid::getGrob(loon.grob, pointsTreeName) lapply(index, function(i) { if(grepl(newGrob$children[[i]]$name, pattern = "primitive_glyph")) { newGrob$children[[i]] <<- do.call(pointsGrob, getGrobArgs(newGrob$children[[i]])) } else if(grepl(newGrob$children[[i]]$name, pattern = "pointrange_glyph")) { newGrob$children[[i]] <<- gTree( children = gList( do.call(pointsGrob, getGrobArgs(grid::getGrob(newGrob$children[[i]], "point"))), do.call(grid::linesGrob, getGrobArgs(grid::getGrob(newGrob$children[[i]], "range"))) ), name = newGrob$children[[i]]$name ) } else if(grepl(newGrob$children[[i]]$name, pattern = "text_glyph")) { newGrob$children[[i]] <<- do.call(grid::textGrob, getGrobArgs(newGrob$children[[i]])) } else if(grepl(newGrob$children[[i]]$name, pattern = "serialaxes_glyph")) { gTree_names <- newGrob$children[[i]]$childrenOrder newGrob$children[[i]] <<- if("polyline" %in% gTree_names) { grid::setGrob( gTree = newGrob$children[[i]], gPath = "polyline", newGrob = do.call(grid::linesGrob, getGrobArgs(grid::getGrob(newGrob$children[[i]], "polyline"))) ) } else if("polyline: showArea" %in% gTree_names) { grid::setGrob( gTree = newGrob$children[[i]], gPath = "polyline: showArea", newGrob = do.call(grid::polygonGrob, getGrobArgs(grid::getGrob(newGrob$children[[i]], "polyline: showArea"))) ) } else stop("serialaxes name does not match") if("boundary" %in% gTree_names) { newGrob$children[[i]] <<- grid::setGrob( gTree = newGrob$children[[i]], gPath = "boundary", newGrob = do.call(grid::polylineGrob, getGrobArgs(grid::getGrob(newGrob$children[[i]], "boundary"))) ) } if("axes" %in% gTree_names) { newGrob$children[[i]] <<- grid::setGrob( gTree = newGrob$children[[i]], gPath = "axes", newGrob = do.call(grid::polylineGrob, getGrobArgs(grid::getGrob(newGrob$children[[i]], "axes"))) ) } } else if(grepl(newGrob$children[[i]]$name, pattern = "polygon_glyph")) { newGrob$children[[i]] <<- if(grepl(newGrob$children[[i]]$name, pattern = "showArea")) { do.call(grid::polygonGrob, getGrobArgs(newGrob$children[[i]])) } else { do.call(grid::polylineGrob, getGrobArgs(newGrob$children[[i]])) } } else if(grepl(newGrob$children[[i]]$name, pattern = "image_glyph")) { raster_args <- getGrobArgs(grid::getGrob(newGrob$children[[i]], "image")) names(raster_args) <- c("image", names(raster_args)[-1]) newGrob$children[[i]] <<- gTree( children = gList( do.call(grid::rectGrob, getGrobArgs(grid::getGrob(newGrob$children[[i]], "image_border"))), do.call(rasterGrob, raster_args) ), name = newGrob$children[[i]]$name ) } else stop("not inplemented") } ) grid::setGrob( gTree = loon.grob, gPath = pointsTreeName, newGrob = newGrob ) } else loon.grob } set_reactive_grob.l_graph <- function(loon.grob, index, ...) { if(length(index) > 0) { args <- list(...) swap <- args$swap edgesTree <- args$graph_edges if(swap) { edgesTree <- gTree( children = do.call( gList, lapply(1:length(edgesTree$children), function(i){ grobi <- edgesTree$children[[i]] if(!is.null(grobi$x) & !is.null(grobi$y)) { grid::editGrob(grobi, x = grobi$y, y = grobi$x ) } else grobi } ) ), name = "graph edges" ) } loon.grob <- grid::setGrob( gTree = loon.grob, gPath = "graph edges", newGrob = edgesTree ) nodesGrob <- grid::getGrob(loon.grob, "graph nodes") lapply(index, function(i) { nodesGrob$children[[i]] <<- do.call(pointsGrob, getGrobArgs(nodesGrob$children[[i]])) } ) loon.grob <- grid::setGrob( gTree = loon.grob, gPath = "graph nodes", newGrob = nodesGrob ) labelsGrob <- grid::getGrob(loon.grob, "graph labels") lapply(index, function(i) { labelsGrob$children[[i]] <<- do.call(grid::textGrob, getGrobArgs(labelsGrob$children[[i]])) } ) grid::setGrob( gTree = loon.grob, gPath = "graph labels", newGrob = labelsGrob ) } else loon.grob } set_reactive_grob.l_serialaxes <- function(loon.grob, index, ...) { if(length(index) > 0) { args <- list(...) axesGpath <- args$axesGpath showArea <- args$showArea axesGrob <- grid::getGrob(loon.grob, axesGpath) lapply(index, function(i) { axesGrob$children[[i]] <<- if(showArea) { do.call(grid::polygonGrob, getGrobArgs(axesGrob$children[[i]])) } else { do.call(grid::linesGrob, getGrobArgs(axesGrob$children[[i]])) } } ) grid::setGrob( gTree = loon.grob, gPath = axesGpath, newGrob = axesGrob ) } else loon.grob }
library(fpp3) download.file("http://robjhyndman.com/data/tourism.xlsx", tourism_file <- tempfile()) my_tourism <- readxl::read_excel(tourism_file) %>% mutate(Quarter = yearquarter(Quarter)) %>% as_tsibble( index = Quarter, key = c(Region, State, Purpose) ) my_tourism %>% as_tibble() %>% group_by(Region, Purpose) %>% summarise(Trips = mean(Trips)) %>% ungroup() %>% filter(Trips == max(Trips)) state_tourism <- my_tourism %>% group_by(State) %>% summarise(Trips = sum(Trips)) %>% ungroup() aus_production %>% autoplot(Bricks) pelt %>% autoplot(Lynx) gafa_stock %>% autoplot(Close) vic_elec %>% autoplot(Demand) + labs(y = "Demand (MW)", title = "Half-hourly electricity demand", subtitle = "Victoria, Australia") snowy <- tourism %>% filter(Region == "Snowy Mountains") %>% select(-State, -Region) snowy %>% autoplot(Trips) snowy %>% gg_season(Trips) snowy %>% gg_subseries(Trips) library(sugrrants) (tsibble::pedestrian %>% filter(year(Date) == 2016, Sensor == "Southern Cross Station") %>% frame_calendar(x = Time, y = Count, date = Date) %>% ggplot(aes(x = .Time, y = .Count, group = Date)) + geom_line()) %>% prettify() aus_production %>% gg_lag(Bricks) aus_production %>% ACF(Bricks) %>% autoplot() pelt %>% gg_lag(Lynx) pelt %>% ACF(Lynx) %>% autoplot() amzn_stock <- gafa_stock %>% filter(Symbol == "AMZN") %>% mutate(trading_day = row_number()) %>% update_tsibble(index=trading_day, regular=TRUE) amzn_stock %>% gg_lag(Close) amzn_stock %>% ACF(Close) %>% autoplot() vic_elec %>% gg_lag(Demand, period = 1, lags = c(1, 2, 24, 48, 336, 17532)) vic_elec %>% ACF(Demand, lag_max = 336) %>% autoplot() dgoog <- gafa_stock %>% filter(Symbol == "GOOG", year(Date) >= 2018) %>% mutate(trading_day = row_number()) %>% update_tsibble(index=trading_day, regular=TRUE) %>% mutate(diff = difference(Close)) dgoog %>% autoplot(diff) dgoog %>% ACF(diff) %>% autoplot() global_economy %>% autoplot(GDP/Population, alpha = 0.3) + guides(colour = FALSE) avg_gdp_pc <- global_economy %>% as_tibble() %>% group_by(Country) %>% summarise( gdp_pc = mean(GDP/Population, na.rm = TRUE), last = last((GDP/Population)[!is.na(GDP/Population)]) ) top_n(avg_gdp_pc, 5, gdp_pc) max_gdp_pc <- global_economy %>% semi_join( avg_gdp_pc %>% filter(gdp_pc == max(gdp_pc, na.rm = TRUE)), by = "Country" ) library(ggrepel) global_economy %>% ggplot(aes(x = Year, y = GDP / Population, group = Country)) + geom_line(alpha = 0.3) + geom_line(colour = "red", data = max_gdp_pc) + geom_label_repel( aes(label = Country, x = 2020, y = last), data = top_n(avg_gdp_pc, 5, last), ) holidays <- tourism %>% filter(Purpose == "Holiday") %>% group_by(State) %>% summarise(Trips = sum(Trips)) holidays %>% model(stl = STL(Trips ~ season(window = 13) + trend(window = 21))) %>% components() %>% autoplot() global_economy %>% filter(Code == "USA") %>% autoplot(box_cox(GDP, 0.3)) aus_livestock %>% filter( State == "Victoria", Animal == "Bulls, bullocks and steers" ) %>% autoplot(log(Count)) vic_elec %>% autoplot(log(Demand)) aus_production %>% autoplot(box_cox(Gas, 0.1)) canadian_gas %>% autoplot() canadian_gas %>% model(STL(Volume ~ season(window=7) + trend(window=11))) %>% components() %>% autoplot() canadian_gas %>% model(STL(Volume ~ season(window=7) + trend(window=11))) %>% components() %>% gg_season(season_year) canadian_gas %>% model(STL(Volume ~ season(window=7) + trend(window=11))) %>% components() %>% select(Month, season_adjust) %>% autoplot(season_adjust) library(GGally) tourism %>% features(Trips, feat_stl) %>% select(-Region, -State, -Purpose) %>% mutate( seasonal_peak_year = factor(seasonal_peak_year), seasonal_trough_year = factor(seasonal_trough_year), ) %>% ggpairs() tourism %>% group_by(State) %>% summarise(Trips = sum(Trips)) %>% features(Trips, feat_stl) %>% select(State, seasonal_peak_year) PBS_no_zeros <- PBS %>% group_by_key() %>% filter(!all(Cost == 0)) %>% ungroup() library(broom) PBS_feat <- PBS_no_zeros %>% features(Cost, feature_set(pkgs = "feasts")) PBS_prcomp <- PBS_feat %>% select(-Concession, -Type, -ATC1, -ATC2) %>% prcomp(scale = TRUE) %>% augment(PBS_feat) PBS_prcomp %>% ggplot(aes(x = .fittedPC1, y = .fittedPC2)) + geom_point() outliers <- PBS_prcomp %>% filter(.fittedPC1 == max(.fittedPC1)) outliers PBS %>% semi_join(outliers, by = c("Concession", "Type", "ATC1", "ATC2")) %>% autoplot(Cost) + facet_grid(vars(Concession, Type, ATC1, ATC2)) + ggtitle("Outlying time series in PC space") hh_budget %>% autoplot(Wealth) hh_budget %>% model(drift = RW(Wealth ~ drift())) %>% forecast(h = "5 years") %>% autoplot(hh_budget) aus_takeaway <- aus_retail %>% filter(Industry == "Cafes, restaurants and takeaway food services") %>% summarise(Turnover = sum(Turnover)) aus_takeaway %>% autoplot(Turnover) aus_takeaway %>% model(snaive = SNAIVE(log(Turnover) ~ drift())) %>% forecast(h = "3 years") %>% autoplot(aus_takeaway) beer_model <- aus_production %>% model(snaive = SNAIVE(Beer)) beer_model %>% forecast(h = "3 years") %>% autoplot(aus_production) beer_model %>% gg_tsresiduals() augment(beer_model) %>% features(.resid, ljung_box, lag = 8, dof = 0) hh_budget_train <- hh_budget %>% filter(Year <= max(Year) - 4) hh_budget_forecast <- hh_budget_train %>% model( mean = MEAN(Wealth), naive = NAIVE(Wealth), drift = RW(Wealth ~ drift()) ) %>% forecast(h = "4 years") hh_budget_forecast %>% autoplot(hh_budget, level=NULL) hh_budget_forecast %>% accuracy(hh_budget) %>% group_by(.model) %>% summarise_if(is.numeric, mean) aus_takeaway_train <- aus_takeaway %>% filter(year(Month) <= max(year(Month)) - 4) aus_takeaway_forecast <- aus_takeaway_train %>% model( mean = MEAN(Turnover), naive = NAIVE(Turnover), drift = RW(Turnover ~ drift()), snaive = SNAIVE(Turnover) ) %>% forecast(h = "4 years") aus_takeaway_forecast %>% accuracy(aus_takeaway) global_economy %>% filter(Country == "China") %>% autoplot(box_cox(GDP, 0.2)) global_economy %>% filter(Country == "China") %>% features(GDP, guerrero) fit <- global_economy %>% filter(Country == "China") %>% model( ets = ETS(GDP), ets_damped = ETS(GDP ~ trend("Ad")), ets_bc = ETS(box_cox(GDP, 0.2)), ets_log = ETS(log(GDP)) ) fit report(fit) fit %>% select(ets) %>% report() glance(fit) tidy(fit) coef(fit) fit %>% forecast(h = "20 years") %>% autoplot(global_economy, level = NULL) gas <- aus_production %>% select(Gas) %>% filter(Quarter <= yearquarter("2006 Q4")) autoplot(gas) fit <- gas %>% model( auto = ETS(Gas), damped = ETS(Gas ~ trend("Ad")), log = ETS(log(Gas)), snaive = SNAIVE(Gas) ) fit fc <- fit %>% forecast(h = "4 years") fc %>% autoplot(aus_production, level=NULL) fc %>% autoplot( filter(aus_production, Quarter > yearquarter("2000 Q4")), level=NULL) fc %>% accuracy(aus_production) us_gdp <- global_economy %>% filter(Code == "USA") autoplot(us_gdp, log(GDP)) us_gdp_model <- us_gdp %>% model( arima_notransform = ARIMA(GDP), arima = ARIMA(log(GDP)), arima1= ARIMA(log(GDP) ~ pdq(d=1)), ) us_gdp_model glance(us_gdp_model) us_gdp_model %>% forecast(h = "10 years") %>% autoplot(us_gdp, level=NULL) us_gdp_model %>% select(Country,arima_notransform) %>% forecast(h = "10 years") %>% autoplot(us_gdp) tourism_models <- tourism %>% filter(Purpose=="Holiday") %>% model(arima = ARIMA(Trips)) tourism_fc <- forecast(tourism_models) tourism_fc tourism_fc %>% filter(Region == "Snowy Mountains") %>% autoplot(tourism) tourism_fc %>% filter(Region == "Melbourne") %>% autoplot(tourism) vic_elec_daily <- vic_elec %>% filter(year(Time) == 2014) %>% index_by(Date = date(Time)) %>% summarise( Demand = sum(Demand)/1e3, Temperature = max(Temperature), Holiday = any(Holiday)) %>% mutate( Day_Type = case_when( Holiday ~ "Holiday", wday(Date) %in% 2:6 ~ "Weekday", TRUE ~ "Weekend") ) elec_model <- vic_elec_daily %>% model(fit = ARIMA(Demand ~ Temperature + I(pmax(Temperature-22,0)) + (Day_Type=="Weekday"))) report(elec_model) elec_model %>% gg_tsresiduals() augment(elec_model) %>% features(.resid, ljung_box, dof = 9, lag = 14) vic_next_day <- new_data(vic_elec_daily, 1) %>% mutate(Temperature = 26, Day_Type = "Holiday") forecast(elec_model, vic_next_day) vic_elec_future <- new_data(vic_elec_daily, 14) %>% mutate( Temperature = 26, Holiday = c(TRUE, rep(FALSE, 13)), Day_Type = case_when( Holiday ~ "Holiday", wday(Date) %in% 2:6 ~ "Weekday", TRUE ~ "Weekend" ) ) forecast(elec_model, vic_elec_future) %>% autoplot(vic_elec_daily) + ylab("Electricity demand (GW)") vic_elec_daily <- vic_elec %>% index_by(Date = date(Time)) %>% summarise( Demand = sum(Demand)/1e3, Temperature = max(Temperature), Holiday = any(Holiday)) %>% mutate( Day_Type = case_when( Holiday ~ "Holiday", wday(Date) %in% 2:6 ~ "Weekday", TRUE ~ "Weekend") ) elec_model <- vic_elec_daily %>% model(fit = ARIMA(Demand ~ fourier("year", K = 10) + PDQ(0,0,0) + Temperature + lag(Temperature) + I(pmax(Temperature-20,0)) + (Day_Type=="Weekday"))) report(elec_model) augment(elec_model) %>% gg_tsdisplay(.resid, plot_type = "histogram") augment(elec_model) %>% features(.resid, ljung_box, dof = 9, lag = 14) vic_next_day <- new_data(vic_elec_daily, 1) %>% mutate(Temperature = 26, Day_Type = "Holiday") forecast(elec_model, vic_next_day) vic_elec_future <- new_data(vic_elec_daily, 14) %>% mutate( Temperature = 26, Holiday = c(TRUE, rep(FALSE, 13)), Day_Type = case_when( Holiday ~ "Holiday", wday(Date) %in% 2:6 ~ "Weekday", TRUE ~ "Weekend" ) ) forecast(elec_model, vic_elec_future) %>% autoplot(filter(vic_elec_daily, year(Date) > 2013)) + ylab("Electricity demand (GW)") PBS_aggregated <- PBS %>% aggregate_key( Concession * Type * ATC1, Cost = sum(Cost) / 1e6 ) fit <- PBS_aggregated %>% filter(Month <= yearmonth("2005 Jun")) %>% model( ets = ETS(Cost), arima = ARIMA(Cost), snaive = SNAIVE(Cost) ) fc <- fit %>% reconcile( ets_adj = min_trace(ets), arima_adj = min_trace(arima), snaive_adj = min_trace(snaive) ) %>% forecast(h = "3 years") accuracy(fc, PBS_aggregated) %>% group_by(.model) %>% summarise(MASE = mean(MASE)) %>% arrange(MASE)
atom2mass <- function(...) UseMethod("atom2mass") atom2mass.default <- function(x, mass.custom=NULL, elety.custom=NULL, grpby=NULL, rescue=TRUE, ...){ if(!is.null(mass.custom)) { if(!all(c("symb","mass") %in% names(mass.custom))) stop("'mass.custom' must contains 'symb' and 'mass' components") inds <- unlist(lapply(mass.custom, is.factor)) mass.custom[inds] <- lapply(mass.custom[inds], as.character) } elements <- rbind(mass.custom[,c("symb","mass")], elements[,c("symb","mass")]) symb <- atom2ele.default(x, elety.custom, rescue, ...) M <- elements[match(symb, elements[,"symb"]), "mass"] if(any(is.na(M))) stop(paste("\n\tatom2mass: mass of element '", symb[is.na(M)], "' unknown", sep="")) if(!is.null(grpby)) { if(length(grpby) != length(M)) warning("'grpby' as been recycled") M <- unlist(lapply(split(M, grpby), sum)) } return(M) } atom2mass.pdb <- function(pdb, inds=NULL, mass.custom=NULL, elety.custom=NULL, grpby=NULL, rescue=TRUE, ...){ if(!is.null(inds)) pdb <- trim.pdb(pdb, inds) atom.names <- pdb$atom[,"elety"] M <- atom2mass.default(atom.names, mass.custom, elety.custom, grpby, rescue, ...) return(M) }
dglg = function(x, location, scale, shape) { if(missingArg(x)) return("The real value x is missing!") if(missingArg(location)) location <- 0 if(missingArg(scale)) scale <- 1 if(missingArg(shape)) shape <- 1 base_dglg <- function(x, location, scale, shape){ y <- (x - location)/scale out <- (1/shape)*y -(1/shape^2)*exp(shape*y) out <- exp(out) out <- c_l(shape)*out/scale return(out) } v_dglg <- Vectorize(base_dglg,vectorize.args = c("x","location")) return(v_dglg(x, location, scale, shape)) }
fit_diagram <- function(combinations, type = c("euler", "venn"), input = c("disjoint", "union"), shape = c("circle", "ellipse"), control = list(), ...) { input <- match.arg(input) shape <- match.arg(shape) type <- match.arg(type) n_restarts <- 10L small <- sqrt(.Machine$double.eps) if (!is.numeric(combinations)) stop("`combinations` must be numeric") if (any(combinations < 0)) stop("values in `combinations` cannot be negative") if (is.null(attr(combinations, "names")) || any(names(combinations) == "")) stop("every element in `combinations` needs to be named") if (any(duplicated(names(combinations)))) stop("names of elements in `combinations` cannot be duplicated") combo_names <- strsplit(names(combinations), split = "&", fixed = TRUE) setnames <- unique(unlist(combo_names, use.names = FALSE)) n <- length(setnames) id <- bit_indexr(n) N <- NROW(id) areas <- double(N) for (i in 1L:N) { s <- setnames[id[i, ]] for (j in seq_along(combo_names)) { if (setequal(s, combo_names[[j]])) { areas[i] <- combinations[j] } } } if (input == "disjoint") { areas_disjoint <- areas areas[] <- 0 for (i in rev(seq_along(areas))) { prev_areas <- rowSums(id[, id[i, ], drop = FALSE]) == sum(id[i, ]) areas[i] <- sum(areas_disjoint[prev_areas]) } } else if (input == "union") { areas_disjoint <- double(length(areas)) for (i in rev(seq_along(areas))) { prev_areas <- rowSums(id[, id[i, ], drop = FALSE]) == sum(id[i, ]) areas_disjoint[i] <- areas[i] - sum(areas_disjoint[prev_areas]) } if (any(areas_disjoint < 0)) stop("Check your set configuration. Some disjoint areas are negative.") } orig <- rep.int(0, N) fit <- rep.int(0, N) names(orig) <- names(fit) <- apply(id, 1L, function(x) paste0(setnames[x], collapse = "&")) if (type == "venn") { fpar <- venn_spec[[n]] rownames(fpar) <- setnames orig[] <- areas_disjoint out <- structure(list(ellipses = fpar, original.values = orig, fitted.values = rep(1, length(orig))), class = c("venn", "euler", "list")) return(out) } fpar <- as.data.frame(matrix( NA, ncol = 5L, nrow = n, dimnames = list(setnames, c("h", "k", "a", "b", "phi")) ), stringsAsFactors = TRUE) empty_sets <- areas[seq_len(n)] < sqrt(.Machine$double.eps) empty_subsets <- rowSums(id[, empty_sets, drop = FALSE]) > 0 id <- id[!empty_subsets, !empty_sets, drop = FALSE] N <- NROW(id) n <- sum(!empty_sets) areas <- areas[!empty_subsets] areas_disjoint <- areas_disjoint[!empty_subsets] control <- utils::modifyList( list(extraopt = (n == 3) && (match.arg(shape) == "ellipse"), extraopt_threshold = 0.001, extraopt_control = list()), control) if (n > 1L) { if (all(areas == 0)) { fpar[] <- 0 } else { id_sums <- rowSums(id) ones <- id_sums == 1L twos <- id_sums == 2L two <- choose_two(1:n) r <- sqrt(areas[ones]/pi) subset <- disjoint <- matrix(FALSE, ncol = n, nrow = n) distances <- area_mat <- matrix(0, ncol = n, nrow = n) lwrtri <- lower.tri(subset) tmp <- matrix(areas[ones][two], ncol = 2L) subset[lwrtri] <- areas[twos] == tmp[, 1L] | areas[twos] == tmp[, 2L] disjoint[lwrtri] <- areas[twos] == 0 distances[lwrtri] <- mapply(separate_two_discs, r1 = r[two[, 1L]], r2 = r[two[, 2L]], overlap = areas[twos], USE.NAMES = FALSE) loss <- Inf initial_layouts <- vector("list", n_restarts) bnd <- sqrt(sum(r^2*pi)) i <- 1L while (loss > small && i <= n_restarts) { initial_layouts[[i]] <- stats::nlm( f = optim_init, p = stats::runif(n*2, 0, bnd), d = distances, disjoint = disjoint, subset = subset, iterlim = 1000L, check.analyticals = FALSE ) loss <- initial_layouts[[i]]$minimum i <- i + 1L } best_init <- which.min(lapply(initial_layouts[1L:(i - 1L)], "[[", "minimum")) initial_layout <- initial_layouts[[best_init]] circle <- match.arg(shape) == "circle" if (circle) { pars <- as.vector(matrix(c(initial_layout$estimate, r), 3L, byrow = TRUE)) lwr <- rep.int(0, 3L) upr <- rep.int(bnd, 3L) } else { pars <- as.vector(rbind(matrix(initial_layout$estimate, 2L, byrow = TRUE), r, r, 0, deparse.level = 0L)) lwr <- c(rep.int(0, 4L), -2*pi) upr <- c(rep.int(bnd, 4L), 2*pi) } orig[!empty_subsets] <- areas_disjoint nlm_solution <- stats::nlm(f = optim_final_loss, p = pars, areas = areas_disjoint, circle = circle, iterlim = 1e6)$estimate tpar <- as.data.frame(matrix( data = nlm_solution, ncol = if (circle) 3L else 5L, dimnames = list(setnames[!empty_sets], if (circle) c("h", "k", "r") else c("h", "k", "a", "b", "phi")), byrow = TRUE ), stringsAsFactors = TRUE) if (circle) tpar <- cbind(tpar, tpar[, 3L], 0) nlm_fit <- as.vector(intersect_ellipses(nlm_solution, circle)) nlm_pars <- compress_layout(normalize_pars(tpar), id, nlm_fit) nlm_diagError <- diagError(nlm_fit, orig[!empty_subsets]) if (!circle && control$extraopt && nlm_diagError > control$extraopt_threshold) { newpars <- matrix( data = as.vector(t(nlm_pars)), ncol = 5L, dimnames = list(setnames, c("h", "k", "a", "b", "phi")), byrow = TRUE ) constraints <- get_constraints(compress_layout(newpars, id, nlm_fit)) last_ditch_effort <- GenSA::GenSA( par = as.vector(newpars), fn = optim_final_loss, lower = constraints$lwr, upper = constraints$upr, circle = circle, areas = areas_disjoint, control = utils::modifyList( list(threshold.stop = sqrt(.Machine$double.eps), max.call = 1e7, trace.mat = FALSE), control$extraopt_control ) )$par last_ditch_fit <- as.vector(intersect_ellipses(last_ditch_effort, circle)) last_ditch_diagError <- diagError(last_ditch_fit, orig) if (last_ditch_diagError < nlm_diagError) { final_par <- last_ditch_effort fit[!empty_subsets] <- last_ditch_fit } else { final_par <- nlm_solution fit[!empty_subsets] <- nlm_fit } } else { final_par <- nlm_solution fit[!empty_subsets] <- nlm_fit } regionError <- regionError(fit, orig) diagError <- diagError(regionError = regionError) stress <- stress(orig, fit) temp <- matrix(data = final_par, ncol = if (circle) 3L else 5L, byrow = TRUE) if (circle) temp <- cbind(temp, temp[, 3L], 0) temp <- normalize_pars(temp) temp <- compress_layout(temp, id, fit[!empty_subsets]) fpar[!empty_sets, ] <- center_layout(temp) } } else { if (length(areas) == 0) { fpar[] <- 0 } else { fpar[!empty_sets, ] <- c(0, 0, sqrt(areas/pi), sqrt(areas/pi), 0) orig[!empty_subsets] <- fit[!empty_subsets] <- areas } regionError <- diagError <- stress <- 0 } structure(list(ellipses = fpar, original.values = orig, fitted.values = fit, residuals = orig - fit, regionError = regionError, diagError = diagError, stress = stress), class = c("euler", "list")) }
expected <- eval(parse(text="c(\"% This file is part of the 'foreign' package for R\", \"% It is distributed under the GPL version 2 or later\", \"\", \"\\\\name{S3 read functions}\", \"\\\\alias{data.restore}\", \"\\\\alias{read.S}\", \"\\\\title{Read an S3 Binary or data.dump File}\", \"\\\\description{\", \" Reads binary data files or \\\\code{data.dump} files that were produced\", \" in S version 3.\", \"}\", \"\\\\usage{\", \" data.restore(file, print = FALSE, verbose = FALSE, env = .GlobalEnv)\", \" read.S(file)\", \"}\", \"\\\\arguments{\", \" \\\\item{file}{the filename of the S-PLUS \\\\code{data.dump} or binary\", \" file.}\", \" \\\\item{print}{whether to print the name of each object as read from the\", \" file.}\", \" \\\\item{verbose}{whether to print the name of every subitem within each\", \" object.}\", \" \\\\item{env}{environment within which to create the restored object(s).}\", \"}\", \"\\\\value{\", \" For \\\\code{read.S}, an R version of the S3 object.\", \"\", \" For \\\\code{data.restore}, the name of the file.\", \"}\", \"\\\\details{\", \" \\\\code{read.S} can read the binary files produced in some older\", \" versions of S-PLUS on either Windows (versions 3.x, 4.x, 2000) or Unix\", \" (version 3.x with 4 byte integers). It automatically detects whether\", \" the file was produced on a big- or little-endian machine and adapts\", \" itself accordingly.\", \"\", \" \\\\code{data.restore} can read a similar range of files produced by\", \" \\\\code{data.dump} and for newer versions of S-PLUS, those from\", \" \\\\code{data.dump(....., oldStyle=TRUE)}.\", \"\", \" Not all S3 objects can be handled in the current version. The most\", \" frequently encountered exceptions are functions and expressions; you\", \" will also have trouble with objects that contain model formulas. In\", \" particular, comments will be lost from function bodies, and the\", \" argument lists of functions will often be changed.\", \"}\", \"\\\\author{\", \" Duncan Murdoch\", \"}\", \"\\\\examples{\", \"\\\\dontrun{read.S(file.path(\\\"_Data\\\", \\\"myobj\\\"))\", \"data.restore(\\\"dumpdata\\\", print = TRUE)\", \"}}\", \"\\\\keyword{data}\", \"\\\\keyword{file}\")")); test(id=0, code={ argv <- eval(parse(text="list(c(\"% This file is part of the 'foreign' package for R\", \"% It is distributed under the GPL version 2 or later\", \"\", \"\\\\name{S3 read functions}\", \"\\\\alias{data.restore}\", \"\\\\alias{read.S}\", \"\\\\title{Read an S3 Binary or data.dump File}\", \"\\\\description{\", \" Reads binary data files or \\\\code{data.dump} files that were produced\", \" in S version 3.\", \"}\", \"\\\\usage{\", \" data.restore(file, print = FALSE, verbose = FALSE, env = .GlobalEnv)\", \" read.S(file)\", \"}\", \"\\\\arguments{\", \" \\\\item{file}{the filename of the S-PLUS \\\\code{data.dump} or binary\", \" file.}\", \" \\\\item{print}{whether to print the name of each object as read from the\", \" file.}\", \" \\\\item{verbose}{whether to print the name of every subitem within each\", \" object.}\", \" \\\\item{env}{environment within which to create the restored object(s).}\", \"}\", \"\\\\value{\", \" For \\\\code{read.S}, an R version of the S3 object.\", \"\", \" For \\\\code{data.restore}, the name of the file.\", \"}\", \"\\\\details{\", \" \\\\code{read.S} can read the binary files produced in some older\", \" versions of S-PLUS on either Windows (versions 3.x, 4.x, 2000) or Unix\", \" (version 3.x with 4 byte integers). It automatically detects whether\", \" the file was produced on a big- or little-endian machine and adapts\", \" itself accordingly.\", \"\", \" \\\\code{data.restore} can read a similar range of files produced by\", \" \\\\code{data.dump} and for newer versions of S-PLUS, those from\", \" \\\\code{data.dump(....., oldStyle=TRUE)}.\", \"\", \" Not all S3 objects can be handled in the current version. The most\", \" frequently encountered exceptions are functions and expressions; you\", \" will also have trouble with objects that contain model formulas. In\", \" particular, comments will be lost from function bodies, and the\", \" argument lists of functions will often be changed.\", \"}\", \"\\\\author{\", \" Duncan Murdoch\", \"}\", \"\\\\examples{\", \"\\\\dontrun{read.S(file.path(\\\"_Data\\\", \\\"myobj\\\"))\", \"data.restore(\\\"dumpdata\\\", print = TRUE)\", \"}}\", \"\\\\keyword{data}\", \"\\\\keyword{file}\"), \"\", \"ASCII\", NA_character_, TRUE, FALSE)")); .Internal(iconv(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]], argv[[6]])); }, o=expected);
test_that("can round-trip Rd", { rd <- tools::parse_Rd(test_path("escapes.Rd")) field <- find_field(rd, "description") lines <- strsplit(field, "\n")[[1]] expect_equal( lines, c( "% Comment", "\\code{\\\\}" ) ) }) test_that("\\links are transformed", { out <- roc_proc_text(rd_roclet(), " wrapper <- function(algo) {}" )[[1]] verify_output( test_path("test-rd-inherit-link.txt"), { "\\link{} should include [digest]" out$get_section("param") } ) }) test_that("warns on unknown inherit type", { expect_warning( parse_text(" NULL "), "Unknown inherit type: blah" ) }) test_that("no options gives default values", { block <- parse_text(" NULL ")[[1]] expect_equal( block_get_tag_value(block, "inherit")$fields, c( "params", "return", "title", "description", "details", "seealso", "sections", "references", "examples", "author", "source" ) ) }) test_that("some options overrides defaults", { block <- parse_text(" NULL ")[[1]] expect_equal(block_get_tag_value(block, "inherit")$fields, "return") }) test_that("can inherit return values from roxygen topic", { out <- roc_proc_text(rd_roclet(), " a <- function(x) {} b <- function(y) {} ")[[2]] expect_equal(out$get_value("value"), "ABC") }) test_that("takes value from first with return", { out <- roc_proc_text(rd_roclet(), " a1 <- function(x) {} a2 <- function() {} b <- function(x) {} c <- function(y) {} ")[[3]] expect_equal(out$get_value("value"), "B") }) test_that("can inherit return value from external function", { out <- roc_proc_text(rd_roclet(), " a1 <- function(x) {} ")[[1]] expect_match(out$get_value("value"), "before the mean is computed.$") expect_match(out$get_value("value"), "^If \\\\code") }) test_that("can inherit return values from roxygen topic", { out <- roc_proc_text(rd_roclet(), " a <- function(x) {} b <- function(y) {} ")[[2]] expect_equal(out$get_value("seealso"), "ABC") }) test_that("can inherit description from roxygen topic", { out <- roc_proc_text(rd_roclet(), " a <- function(x) {} b <- function(y) {} ")[[2]] expect_equal(out$get_value("description"), "B") }) test_that("inherits description if omitted", { out <- roc_proc_text(rd_roclet(), " a <- function(x) {} b <- function(y) {} ")[[2]] expect_equal(out$get_value("description"), "B") }) test_that("can inherit details from roxygen topic", { out <- roc_proc_text(rd_roclet(), " a <- function(x) {} b <- function(y) {} ")[[2]] expect_equal(out$get_value("description"), "E") expect_equal(out$get_value("details"), "C") }) test_that("inherits missing sections", { out <- roc_proc_text(rd_roclet(), " a <- function(x) {} b <- function(y) {} ")[[2]] section <- out$get_value("section") expect_equal(section$title, c("A", "B")) expect_equal(section$content, c("2", "1")) }) test_that("can inherit single section", { out <- roc_proc_text(rd_roclet(), " a <- function(x) {} b <- function(y) {} ")[[2]] section <- out$get_value("section") expect_equal(section$title, "B") expect_equal(section$content, "1") }) test_that("multiple @inheritParam tags gathers all params", { out <- roc_proc_text(rd_roclet(), " a <- function(x) {} b <- function(y) {} c <- function(x, y) {} ") params <- out[["c.Rd"]]$get_value("param") expect_equal(length(params), 2) expect_equal(params[["x"]], "X") expect_equal(params[["y"]], "Y") }) test_that("multiple @inheritParam tags gathers all params", { out <- roc_proc_text(rd_roclet(), " a <- function(x) {} b <- function(.y) {} c <- function(.x, y) {} ") params <- out[["c.Rd"]]$get_value("param") expect_equal(length(params), 2) expect_equal(params[[".x"]], "X") expect_equal(params[["y"]], "Y") }) test_that("@inheritParams can inherit from inherited params", { out <- roc_proc_text(rd_roclet(), " c <- function(x) {} b <- function(x) {} a <- function(x) {} ") expect_equal(out[["c.Rd"]]$get_value("param"), c(x = "X")) }) test_that("multiple @inheritParam inherits from existing topics", { out <- roc_proc_text(rd_roclet(), " mymean <- function(x, trim) {}")[[1]] params <- out$get_value("param") expect_equal(length(params), 2) expect_equal(sort(names(params)), c("trim", "x")) }) test_that("@inheritParam can cope with multivariable argument definitions", { out <- roc_proc_text(rd_roclet(), " mymerge <- function(x, y) {}")[[1]] params <- out$get_value("param") expect_equal(length(params), 2) expect_equal(sort(names(params)), c("x", "y")) }) test_that("@inheritParam understands compound docs", { out <- roc_proc_text(rd_roclet(), " x <- function(x, y) {} y <- function(x, y) {}")[[2]] params <- out$get_value("param") expect_equal(params, c(x = "x", y = "y")) }) test_that("warned if no params need documentation", { code <- " x <- function(x, y) {} " expect_warning(roc_proc_text(rd_roclet(), code), "no parameters to inherit") }) test_that("argument order, also for incomplete documentation", { out <- roc_proc_text(rd_roclet(), " a <- function(x, y) {} b <- function(x, y) {} c <- function(x, y) {} d <- function(x, y, z) {} e <- function(x, y, z) {} ") expect_equal(out[["a.Rd"]]$get_value("param"), c(x="X", y="Y")) expect_equal(out[["b.Rd"]]$get_value("param"), c(y="Y")) expect_equal(out[["c.Rd"]]$get_value("param"), c(x="X")) expect_equal(out[["d.Rd"]]$get_value("param"), c(y="Y", z="Z")) expect_equal(out[["e.Rd"]]$get_value("param"), c(x="X", y="Y")) }) test_that("argument order with @inheritParam", { out <- roc_proc_text(rd_roclet(), " a <- function(x, y) {} b1 <- function(x, y) {} b2 <- function(x, y) {} c1 <- function(x, y) {} c2<- function(x, y) {} ") expect_equal(out[["b1.Rd"]]$get_value("param"), c(x = "X", y = "B")) expect_equal(out[["b2.Rd"]]$get_value("param"), c(x = "X", y = "B")) expect_equal(out[["c1.Rd"]]$get_value("param"), c(x = "C", y = "Y")) expect_equal(out[["c2.Rd"]]$get_value("param"), c(x = "C", y = "Y")) }) test_that("inherit params ... named \\dots", { out <- roc_proc_text(rd_roclet(), " foo <- function(x, ...) {} bar <- function(x=1, ...) {} ")[[2]] expect_equal( out$get_value("param"), c(x = "x", "\\dots" = "bar") ) }) test_that("can inherit all from single function", { out <- roc_proc_text(rd_roclet(), " foo <- function(x, y) {} bar <- function(...) {} ")[[2]] verify_output( test_path("test-rd-inherit-dots.txt"), out$get_section("param") ) }) test_that("does not produce multiple ... args", { out <- roc_proc_text(rd_roclet(), " foo <- function(x, ...) {} bar <- function(x, ...) {} baz <- function(y, z) {} ")[[1]] verify_output( test_path("test-rd-inherit-dots-inherit.txt"), out$get_section("param") ) }) test_that("can inherit dots from several functions", { out <- roc_proc_text(rd_roclet(), " foo <- function(x, y) {} bar <- function(z) {} foobar <- function(...) {} ")[[3]] verify_output( test_path("test-rd-inherit-dots-multi.txt"), out$get_section("param") ) }) test_that("inheritDotParams does not add already-documented params", { out <- roc_proc_text(rd_roclet(), " wrapper <- function(x = 'some_value', y = 'some other value', ...) { original(x = x, y = y, ...) } original <- function(x, y, z, ...) {} ")[[1]] params <- out$get_value("param") dot_param <- params[["..."]] expect_named(params, c("x", "y", "...")) expect_false(grepl("item{x}{x description}", dot_param, fixed = TRUE)) expect_false(grepl("item{y}{y description}", dot_param, fixed = TRUE)) expect_match(dot_param, "item{\\code{z}}{z description}", fixed = TRUE) }) test_that("can inherit all from single function", { out <- roc_proc_text(rd_roclet(), " foo <- function(x, y) {} bar <- function(x, y) {} ")[[2]] expect_named(out$get_value("param"), c("x", "y")) expect_equal(out$get_value("title"), "Foo") expect_equal(out$get_value("description"), "Description") expect_equal(out$get_value("details"), "Details") expect_equal(out$get_value("examples"), rd("x <- 1")) expect_equal(out$get_value("author"), "Hadley") expect_equal(out$get_value("source"), "my mind") }) test_that("useful warnings if can't find topics", { expect_warning(get_rd("base2::attach"), "Can't find package") expect_warning(get_rd("base::function_not_found"), "Can't find help topic") expect_warning(get_rd("function", RoxyTopics$new()), "Can't find help topic") }) test_that("can find section in existing docs", { out <- find_sections(get_rd("base::attach")) expect_equal(out$title, "Good practice") }) test_that("find_params parses input", { params <- find_params("utils::`?`", NULL) expect_equal(names(params), c("topic", "type")) })
stat_density <- function(mapping = NULL, data = NULL, geom = "area", position = "stack", ..., bw = "nrd0", adjust = 1, kernel = "gaussian", trim = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) { layer( data = data, mapping = mapping, stat = StatDensity, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( bw = bw, adjust = adjust, kernel = kernel, trim = trim, na.rm = na.rm, ... ) ) } StatDensity <- gganimintproto("StatDensity", Stat, required_aes = "x", default_aes = aes(y = ..density.., fill = NA), compute_group = function(data, scales, bw = "nrd0", adjust = 1, kernel = "gaussian", trim = FALSE, na.rm = FALSE) { if (trim) { range <- range(data$x, na.rm = TRUE) } else { range <- scales$x$dimension() } compute_density(data$x, data$weight, from = range[1], to = range[2], bw = bw, adjust = adjust, kernel = kernel) } ) compute_density <- function(x, w, from, to, bw = "nrd0", adjust = 1, kernel = "gaussian") { n <- length(x) if (is.null(w)) { w <- rep(1 / n, n) } if (n < 3) { return(data.frame( x = x, density = w / sum(w), scaled = w / max(w), count = 1, n = n )) } dens <- stats::density(x, weights = w, bw = bw, adjust = adjust, kernel = kernel, from = from, to = to) data.frame( x = dens$x, density = dens$y, scaled = dens$y / max(dens$y, na.rm = TRUE), count = dens$y * n, n = n ) }
summaryBundles <- function (x, file = NULL, latex = FALSE, byties) { if (isTRUE(attr(x, "class")[1] == "Rel.Bundles") == FALSE) stop("Data must be a \"Rel.Bundles\" class.") sep <- dhc(attr(x, "class")[2], ": ")[2] ifelse(isTRUE(sep == " -- ") == TRUE, sep2 <- ", ", sep2 <- " -- ") ifelse(missing(byties) == FALSE && isTRUE(byties == TRUE) == TRUE, byties <- TRUE, byties <- FALSE) if (latex) { if (isTRUE(is.null(file)) == TRUE) stop("No connection provided.") } else { if (isTRUE(is.null(file)) == FALSE) file = NULL } ulx <- unlist(x) if (isTRUE(length(ulx) != 0) == TRUE) { lb <- vector() for (i in seq_len(length(ulx))) { lb <- append(lb, strsplit(ulx[i], sep)[[1]]) } rm(i) lb <- levels(factor(lb)) } asym <- list() k <- 1L if (length(unlist(x[[k]])) > 0) { q <- 1L for (i in seq_len(length(x[[k]]))) { for (j in seq_len(length(x[[k]][[i]]))) { if (isTRUE(length(x[[k]][[i]]) != 0) == TRUE) { if (latex) { if (isTRUE(is.null(attr(x[[k]], "names")) == FALSE)) { asym[[q]] <- noquote(paste("\\stackrel{\\rightarrow}{\\sf ", attr(x[[k]][i], "names"), "} (", x[[k]][[i]][j], ")", sep = "")) } else { asym[[q]] <- noquote(paste("\\stackrel{\\rightarrow}{", "R", "} (", x[[k]][[i]][j], ")", sep = "")) } } else if (isTRUE(byties == TRUE) == TRUE) { asym[[q]] <- x[[k]][[i]][j] } else { if (isTRUE(is.null(attr(x[[k]], "names")) == FALSE)) { asym[[q]] <- noquote(paste("->", "{", attr(x[[k]][i], "names"), "} (", x[[k]][[i]][j], ")", sep = "")) } else { asym[[q]] <- noquote(paste("->", "{", "R", "} (", x[[k]][[i]][j], ")", sep = "")) } } q <- q + 1L } } rm(j) } rm(i) } recp <- list() k <- 2L if (length(unlist(x[[k]])) > 0) { q <- 1L if (isTRUE(is.list(x[[k]])) == TRUE) { for (i in seq_len(length(x[[k]]))) { if (isTRUE(length(x[[k]][[i]]) != 0) == TRUE) { tmp <- trnf(x[[k]][[i]], tolist = FALSE, lb2lb = TRUE, lbs = lb, ord = length(lb), sep = sep) tmp[lower.tri(tmp)] <- NA tmp[is.na(tmp)] <- 0 if (isTRUE(sum(tmp) == 0) == FALSE) { tmp <- trnf(tmp, tolist = TRUE, lb2lb = TRUE, lbs = lb, sep = sep) for (j in seq_len(length(tmp))) { if (latex) { if (isTRUE(is.null(attr(x[[k]], "names")) == FALSE)) { recp[[q]] <- noquote(paste("\\stackrel{\\leftrightarrow}{\\sf ", attr(x[[k]][i], "names"), "} (", tmp[j], ")", sep = "")) } else { recp[[q]] <- noquote(paste("\\stackrel{\\leftrightarrow}{", "R", "} (", tmp[j], ")", sep = "")) } } else if (isTRUE(byties == TRUE) == TRUE) { recp[[q]] <- (paste0(c(tmp[j], swp(tmp[j], sep = sep)), collapse = sep2)) } else { if (isTRUE(is.null(attr(x[[k]], "names")) == FALSE)) { recp[[q]] <- noquote(paste("<->", "{", attr(x[[k]][i], "names"), "} (", tmp[j], ")", sep = "")) } else { recp[[q]] <- noquote(paste("<->", "{", "R", "} (", tmp[j], ")", sep = "")) } } q <- q + 1L } rm(j) } } } rm(i) } else if (isTRUE(is.list(x[[k]])) == FALSE) { tmp <- men(x[[k]], sep = sep) for (j in seq_len(length(tmp))) { if (latex) { recp[[q]] <- noquote(paste("\\stackrel{\\leftrightarrow}{", "R", "} (", tmp[j], ")", sep = "")) } else if (isTRUE(byties == TRUE) == TRUE) { recp[[q]] <- (paste0(c(tmp[j], swp(tmp[j], sep = sep)), collapse = sep2)) } else { recp[[q]] <- noquote(paste("<->", "{", "R", "} (", tmp[j], ")", sep = "")) } q <- q + 1L } rm(j) } } tent <- list() k <- 3L if (length(unlist(x[[k]])) > 0) { q <- 1L tmp <- vector() for (l in seq_len(length(levels(factor(unlist(x[[k]])))))) { for (i in seq_len(length(x[[k]]))) { if (isTRUE(levels(factor(unlist(x[[k]])))[l] %in% x[[k]][[i]]) == TRUE) { if (latex) { tmp <- append(tmp, paste("\\stackrel{\\rightarrow}{\\sf ", attr(x[[k]][i], "names"), "}", sep = "")) } else { ifelse(isTRUE(byties == TRUE) == TRUE, tmp <- append(tmp, levels(factor(unlist(x[[k]])))[l]), tmp <- append(tmp, paste("->", "{", attr(x[[k]][i], "names"), "}", sep = ""))) } } } rm(i) if (isTRUE(byties == TRUE) == FALSE) { tmp <- append(tmp, paste(" (", levels(factor(unlist(x[[k]])))[l], ")", sep = "")) tent[[q]] <- noquote(paste(tmp, collapse = " ")) } else if (isTRUE(byties == TRUE) == TRUE) { tent[[q]] <- (paste0(tmp, collapse = sep2)) } q <- q + 1L tmp <- vector() } rm(l) } txch <- list() k <- 4L if (length(unlist(x[[k]])) > 0) { q <- 1L temp <- men(levels(factor(unlist(x[[k]]))), sep = sep) tmp <- vector() for (l in seq_len(length(temp))) { for (i in seq_len(length(x[[k]]))) { if (isTRUE(length(x[[k]][[i]]) != 0) == TRUE) { if (isTRUE(temp[l] %in% x[[k]][[i]]) == TRUE) { if (latex) { tmp <- append(tmp, paste("\\stackrel{\\rightarrow}{\\sf ", attr(x[[k]][i], "names"), "}", sep = "")) } else { ifelse(isTRUE(byties == TRUE) == TRUE, tmp <- append(tmp, temp[l]), tmp <- append(tmp, paste("->", "{", attr(x[[k]][i], "names"), "}", sep = ""))) } } if (isTRUE(swp(temp[l], sep = sep) %in% x[[k]][[i]]) == TRUE) { if (latex) { tmp <- append(tmp, paste("\\stackrel{\\leftarrow}{\\sf ", attr(x[[k]][i], "names"), "}", sep = "")) } else { ifelse(isTRUE(byties == TRUE) == TRUE, tmp <- append(tmp, swp(temp[l], sep = sep)), tmp <- append(tmp, paste("<-", "{", attr(x[[k]][i], "names"), "}", sep = ""))) } } } } rm(i) if (isTRUE(byties == TRUE) == FALSE) { tmp <- append(tmp, paste("(", temp[l], ")", sep = "")) txch[[q]] <- noquote(paste(tmp, collapse = " ")) } else if (isTRUE(byties == TRUE) == TRUE) { txch[[q]] <- (paste0(tmp, collapse = sep2)) } q <- q + 1L tmp <- vector() } rm(l) } mixd <- list() k <- 5L if (length(unlist(x[[k]])) > 0) { q <- 1L temp <- men(levels(factor(unlist(x[[k]]))), sep = sep) tmp <- vector() for (l in seq_len(length(temp))) { for (i in seq_len(length(x[[k]]))) { if (isTRUE(length(x[[k]][[i]]) != 0) == TRUE) { if (isTRUE(temp[l] %in% x[[k]][[i]]) == TRUE && isTRUE(swp(temp[l], sep = sep) %in% x[[k]][[i]]) == TRUE) { if (latex) { tmp <- append(tmp, paste("\\stackrel{\\leftrightarrow}{\\sf ", attr(x[[k]][i], "names"), "}", sep = "")) } else { ifelse(isTRUE(byties == TRUE) == TRUE, tmp <- append(tmp, c(temp[l], swp(temp[l], sep = sep))), tmp <- append(tmp, paste("<->", "{", attr(x[[k]][i], "names"), "}", sep = ""))) } } else { if (isTRUE(temp[l] %in% x[[k]][[i]]) == TRUE) { if (latex) { tmp <- append(tmp, paste("\\stackrel{\\rightarrow}{\\sf ", attr(x[[k]][i], "names"), "}", sep = "")) } else { ifelse(isTRUE(byties == TRUE) == TRUE, tmp <- append(tmp, temp[l]), tmp <- append(tmp, paste("->", "{", attr(x[[k]][i], "names"), "}", sep = ""))) } } if (isTRUE(swp(temp[l], sep = sep) %in% x[[k]][[i]]) == TRUE) { if (latex) { tmp <- append(tmp, paste("\\stackrel{\\leftarrow}{\\sf ", attr(x[[k]][i], "names"), "}", sep = "")) } else { ifelse(isTRUE(byties == TRUE) == TRUE, tmp <- append(tmp, swp(temp[l], sep = sep)), tmp <- append(tmp, paste("<-", "{", attr(x[[k]][i], "names"), "}", sep = ""))) } } } } } rm(i) if (isTRUE(byties == TRUE) == FALSE) { tmp <- append(tmp, paste(" (", temp[l], ")", sep = "")) mixd[[q]] <- noquote(paste(tmp, collapse = " ")) } else if (isTRUE(byties == TRUE) == TRUE) { mixd[[q]] <- (paste0(tmp, collapse = sep2)) } q <- q + 1L tmp <- vector() } rm(l) } full <- list() k <- 6L if (length(unlist(x[[k]])) > 0) { q <- 1L temp <- men(levels(factor(unlist(x[[k]]))), sep = sep) tmp <- vector() for (l in seq_len(length(temp))) { for (i in seq_len(length(x[[k]]))) { if (isTRUE(length(x[[k]][[i]]) != 0) == TRUE) { if (isTRUE(temp[l] %in% x[[k]][[i]]) == TRUE) { if (latex) { tmp <- append(tmp, paste("\\stackrel{", "\\leftrightarrow}{\\sf ", attr(x[[k]][i], "names"), "}", sep = "")) } else { ifelse(isTRUE(byties == TRUE) == TRUE, tmp <- append(tmp, c(temp[l], swp(temp[l], sep = sep))), tmp <- append(tmp, paste("<->", "{", attr(x[[k]][i], "names"), "}", sep = ""))) } } } } rm(i) if (isTRUE(byties == TRUE) == FALSE) { tmp <- append(tmp, paste(" (", temp[l], ")", sep = "")) full[[q]] <- noquote(paste(tmp, collapse = " ")) } else if (isTRUE(byties == TRUE) == TRUE) { full[[q]] <- (paste0(tmp, collapse = sep2)) } q <- q + 1L tmp <- vector() } rm(l) } if (isTRUE(length(x) == 7L) == TRUE) { loop <- list() k <- 7L if (length(unlist(x[[k]])) > 0) { q <- 1L for (i in seq_len(length(x[[k]]))) { for (j in seq_len(length(x[[k]][[i]]))) { if (isTRUE(length(x[[k]][[i]]) != 0) == TRUE) { if (latex) { if (isTRUE(is.null(attr(x[[k]], "names")) == FALSE)) { loop[[q]] <- noquote(paste("\\stackrel{\\curvearrowright}{\\sf ", attr(x[[k]][i], "names"), "} (", x[[k]][[i]][j], ")", sep = "")) } else { loop[[q]] <- noquote(paste("\\stackrel{\\curvearrowright}{", "R", "} (", x[[k]][[i]][j], ")", sep = "")) } } else if (isTRUE(byties == TRUE) == TRUE) { loop[[q]] <- x[[k]][[i]][j] } else { if (isTRUE(is.null(attr(x[[k]], "names")) == FALSE)) { loop[[q]] <- noquote(paste("o", "{", attr(x[[k]][i], "names"), "} (", x[[k]][[i]][j], ")", sep = "")) } else { loop[[q]] <- noquote(paste("o", "{", "R", "} (", x[[k]][[i]][j], ")", sep = "")) } } q <- q + 1L } } rm(j) } rm(i) } } ifelse(isTRUE(length(x) == 7L) == TRUE, bndl <- list(Asym = asym, Recp = recp, Tent = tent, Txch = txch, Mixd = mixd, Full = full, Loop = loop), bndl <- list(Asym = asym, Recp = recp, Tent = tent, Txch = txch, Mixd = mixd, Full = full)) Bundles <- unlist(bndl) if (latex) { cat(paste("%% Produced by \"multiplex\"", paste("\"", utils::packageDescription("multiplex")["Version"]$Version, "\"", sep = ""), collapse = " \\\\\n"), file = file, sep = "\n", append = TRUE) cat(paste("\\documentclass{article}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat(paste("\\usepackage[landscape,a4paper]{geometry}", collapse = "\n"), file = file, sep = "\n", append = TRUE) if (isTRUE(length(bndl) == 7L) == TRUE) { cat(paste("\\usepackage{amssymb}", collapse = "\n"), file = file, sep = "\n", append = TRUE) } cat(paste("\\begin{document}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat(paste("\\pagestyle{empty}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat("", file = file, sep = "\n", append = TRUE) cat(paste("\\setlength{\\tabcolsep}{5pt}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat(paste("\\begin{tabular}[t]{lllllll}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat("", file = file, sep = "\n", append = TRUE) cat(paste("\\begin{tabular}[t]{l}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat(paste("\\normalsize{\\bf Asymmetric}:", length(bndl[[1]]), sep = " "), file = file, append = TRUE) cat("\\\\", file = file, sep = "\n", append = TRUE) cat(paste("$", bndl[[1]], "$", sep = "", collapse = " \\\\\n"), file = file, append = TRUE) cat(" \\\\", file = file, sep = "\n", append = TRUE) cat(paste("\\end{tabular}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat("&", file = file, sep = "\n", append = TRUE) cat(paste("\\begin{tabular}[t]{l}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat(paste("\\normalsize{\\bf Reciprocal}:", length(bndl[[2]]), sep = " "), file = file, append = TRUE) cat("\\\\", file = file, sep = "\n", append = TRUE) cat(paste("$", bndl[[2]], "$", sep = "", collapse = " \\\\\n"), file = file, append = TRUE) cat(" \\\\", file = file, sep = "\n", append = TRUE) cat(paste("\\end{tabular}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat("&", file = file, sep = "\n", append = TRUE) cat(paste("\\begin{tabular}[t]{l}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat(paste("\\normalsize{\\bf Tie Entrainment}:", length(bndl[[3]]), sep = " "), file = file, append = TRUE) cat("\\\\", file = file, sep = "\n", append = TRUE) cat(paste("$", bndl[[3]], "$", sep = "", collapse = " \\\\\n"), file = file, append = TRUE) cat(" \\\\", file = file, sep = "\n", append = TRUE) cat(paste("\\end{tabular}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat("&", file = file, sep = "\n", append = TRUE) cat(paste("\\begin{tabular}[t]{l}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat(paste("\\normalsize{\\bf Tie Exchange}:", length(bndl[[4]]), sep = " "), file = file, append = TRUE) cat("\\\\", file = file, sep = "\n", append = TRUE) cat(paste("$", bndl[[4]], "$", sep = "", collapse = " \\\\\n"), file = file, append = TRUE) cat(" \\\\", file = file, sep = "\n", append = TRUE) cat(paste("\\end{tabular}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat("&", file = file, sep = "\n", append = TRUE) cat(paste("\\begin{tabular}[t]{l}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat(paste("\\normalsize{\\bf Mixed}:", length(bndl[[5]]), sep = " "), file = file, append = TRUE) cat("\\\\", file = file, sep = "\n", append = TRUE) cat(paste("$", bndl[[5]], "$", sep = "", collapse = " \\\\\n"), file = file, append = TRUE) cat(" \\\\", file = file, sep = "\n", append = TRUE) cat(paste("\\end{tabular}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat("&", file = file, sep = "\n", append = TRUE) cat(paste("\\begin{tabular}[t]{l}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat(paste("\\normalsize{\\bf Full}:", length(bndl[[6]]), sep = " "), file = file, append = TRUE) cat("\\\\", file = file, sep = "\n", append = TRUE) cat(paste("$", bndl[[6]], "$", sep = "", collapse = " \\\\\n"), file = file, append = TRUE) cat(" \\\\", file = file, sep = "\n", append = TRUE) cat(paste("\\end{tabular}", collapse = "\n"), file = file, sep = "\n", append = TRUE) if (isTRUE(length(bndl) == 7) == TRUE) { cat("&", file = file, sep = "\n", append = TRUE) cat(paste("\\begin{tabular}[t]{l}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat(paste("\\normalsize{\\bf Loops}:", length(bndl[[7]]), sep = " "), file = file, append = TRUE) cat("\\\\", file = file, sep = "\n", append = TRUE) cat(paste("$", bndl[[7]], "$", sep = "", collapse = " \\\\\n"), file = file, append = TRUE) cat(" \\\\", file = file, sep = "\n", append = TRUE) cat(paste("\\end{tabular}", collapse = "\n"), file = file, sep = "\n", append = TRUE) } cat("", file = file, sep = "\n", append = TRUE) cat(paste("\\end{tabular}", collapse = "\n"), file = file, sep = "\n", append = TRUE) cat("", file = file, sep = "\n", append = TRUE) cat(paste("\\end{document}", collapse = "\n"), file = file, sep = "\n", append = TRUE) } else { if (isTRUE(byties == TRUE) == TRUE && isTRUE(length(ulx) != 0) == TRUE) { dfbndl <- as.data.frame(Bundles) ltbndl <- list() length(ltbndl) <- nrow(dfbndl) for (i in seq_len(nrow(dfbndl))) { ltbndl[[i]] <- dhc(as.vector(dfbndl[i, ]), sep = sep2) } rm(i) attr(ltbndl, "names") <- attr(Bundles, "names") return(ltbndl) } else { return(as.data.frame(Bundles)) } } }
pSeqStop <- function(p) { m <- length(p) int <- seq(1, m, 1) pFDR <- cumsum(-log(1-p[int])) / int pFWER <- rev(exp(cumsum(rev(log(p[int])) / rev(int)))) * (m / int) out <- cbind.data.frame(pFWER, pFDR, p) colnames(out) <- c("StrongStop", "ForwardStop", "UnAdjusted") out }
context("estCdf & estQdf") tol <- 1e-4 xx <- seq(-5, 5, length.out = 1e5) test_that("estCdf works.", { approxCdf <- estCdf(dnorm(xx)) trueCdf<- pnorm(xx) expect_equal( object = approxCdf, expected = trueCdf, tolerance = tol ) }) test_that("estQdf works", { d <- dnorm(xx) p <- seq(0, 1, length.out = 21) cEst <- estCdf(d) approxQdf <- estQdf(p = p, x = xx, cdf = cEst) trueQdf <- qnorm(p) expect_equal( object = approxQdf[-c(1, length(approxQdf))], expected = trueQdf[-c(1, length(trueQdf))], tolerance = tol ) }) test_that("Normalize works", { d <- dnorm(xx) d0 <- normalize(d, xx) expect_equal( object = DstarM:::simpson(xx, d), expected = 0.9999994, label = "simpson integrates to approximately 1.", tolerance = tol ) expect_equal( object = DstarM:::simpson(xx, d0), expected = 1, label = "After normalization integrates to 1.", tolerance = tol ) d1 <- normalize(d, xx, props = .5) expect_equal( object = DstarM:::simpson(xx, d1), expected = .5, label = "After normalization integrates to 0.5.", tolerance = tol ) })
a <- matrix(c(-3, 2,1, 1), byrow = TRUE, ncol = 2) b <- matrix(c(0, 1), nrow = 2) c <- matrix(c(1, -1), ncol=2) q <- t(c)%*%c r <- 3 res <- care(a,b,q,r) X <- rbind( c(0.5895174, 1.821575), c(1.8215747, 8.818840)) L <- rbind(-3.502629, -1.436984) G <- cbind(0.6071916, 2.939613) context("CARE: (A, B, Q, R) test") test_that("Alebraic Ricatti Equation Function matches expectation", { expect_equal(res$X, X, tolerance = 1e-05) expect_equal(res$L, L, tolerance = 1e-05) expect_equal(res$G, G, tolerance = 1e-05) }) X2 <- rbind( c(0.2949113, 0.5198625), c(0.5198625, 3.0197648)) L2 <- rbind(-3.605551, -1.414214) G2 <- cbind(0.5198625, 3.019765) res2 <- care(a,b,q) context("CARE: (A, B, Q) test") test_that("Alebraic Ricatti Equation Function matches expectation", { expect_equal(res2$X, X2, tolerance = 1e-05) expect_equal(res2$L, L2, tolerance = 1e-05) expect_equal(res2$G, G2, tolerance = 1e-05) })
test_that("data structure", { skip_if_not(winch_available()) out <- winch_trace_back() expect_s3_class(out, "data.frame") expect_identical(names(out), c("func", "ip", "pathname")) })
knitr::opts_chunk$set( collapse = TRUE, comment = " warning = FALSE, message = FALSE, fig.width = 7, fig.height = 7 ) library(MazamaSpatialPlots) head(example_US_stateObesity) stateMap( data = example_US_stateObesity, parameter = 'obesityRate', palette = 'BuPu', breaks = seq(20, 38, 3), stateBorderColor = 'white', title = "Obesity Rate in U.S. States" ) head(example_US_countyCovid) countyMap( data = example_US_countyCovid, parameter = "cases", breaks = c(0,100,200,500,1000,2000,5000,10000,20000,50000,1e6), countyBorderColor = "white", title = "COVID19 Cases in U.S. States" )
SL.mean <- function (Y, X, newX, family, obsWeights, id, ...) { meanY <- weighted.mean(Y, w = obsWeights) pred <- rep.int(meanY, times = nrow(newX)) fit <- list(object = meanY) out <- list(pred = pred, fit = fit) class(out$fit) <- c("SL.mean") return(out) } predict.SL.mean <- function (object, newdata, family, X = NULL, Y = NULL, ...) { pred <- rep.int(object$object, times = nrow(newdata)) return(pred) }
expected <- eval(parse(text="0L")); test(id=0, code={ argv <- eval(parse(text="list(\"fanny.object.\", \"fanny.object\", 0L, FALSE)")); .Internal(pmatch(argv[[1]], argv[[2]], argv[[3]], argv[[4]])); }, o=expected);
library(qtl2pleio) context("calc_covs testing") phe <- matrix(runif(200), ncol = 2) sex <- matrix(rbinom(100, size = 1, prob = 1 / 2), ncol = 1) calc_covs(phe, kinship = diag(100)) -> cc1 calc_covs(phe, kinship = diag(100), covariates = sex) -> cc2 phe3 <- matrix(runif(300), ncol = 3) phe5 <- matrix(runif(500), ncol = 5) test_that("calc_covs returns different answers when covariates are used vs. not used", { expect_false(identical(cc1$Vg, cc2$Vg)) expect_false(identical(cc1$Ve, cc2$Ve)) }) test_that("calc_covs, when kinship is identity, has output that sums to give same result as cov()", { expect_equal(round(cc1$Vg + cc1$Ve, 4), round(cov(phe), 4), ) }) test_that("calc_covs accommodates d-variate phenotype for d more than 2 & Vg = Ve when kinship is identity", { expect_equal(calc_covs(phe3, diag(100))$Vg, calc_covs(phe3, diag(100))$Ve) expect_equal(calc_covs(phe5, diag(100))$Vg, calc_covs(phe5, diag(100))$Ve) expect_equal(calc_covs(phe5, diag(100), covariates = sex)$Vg, calc_covs(phe5, diag(100), covariates = sex)$Ve) }) test_that("calc_covs outputs are full rank matrices", { expect_equal(qr(calc_covs(phe3, diag(100))$Vg)$rank, 3) expect_equal(qr(calc_covs(phe3, diag(100))$Ve)$rank, 3) expect_equal(qr(calc_covs(phe5, diag(100))$Ve)$rank, 5) expect_equal(qr(calc_covs(phe5, diag(100))$Vg)$rank, 5) expect_equal(qr(calc_covs(phe3, diag(100), covariates = sex)$Vg)$rank, 3) expect_equal(qr(calc_covs(phe3, diag(100), covariates = sex)$Ve)$rank, 3) expect_equal(qr(calc_covs(phe5, diag(100), covariates = sex)$Ve)$rank, 5) expect_equal(qr(calc_covs(phe5, diag(100), covariates = sex)$Vg)$rank, 5) }) test_that("calc_covs outputs are symmetric", { expect_true(isSymmetric(calc_covs(phe3, diag(100))$Vg, tol = 0.001)) expect_true(isSymmetric(calc_covs(phe3, diag(100))$Ve, tol = 0.001)) expect_true(isSymmetric(calc_covs(phe5, diag(100))$Vg, tol = 0.001)) expect_true(isSymmetric(calc_covs(phe5, diag(100))$Ve, tol = 0.001)) expect_true(isSymmetric(calc_covs(phe3, diag(100), covariates = sex)$Vg, tol = 0.001)) expect_true(isSymmetric(calc_covs(phe3, diag(100), covariates = sex)$Ve, tol = 0.001)) expect_true(isSymmetric(calc_covs(phe5, diag(100), covariates = sex)$Vg, tol = 0.001)) expect_true(isSymmetric(calc_covs(phe5, diag(100), covariates = sex)$Ve, tol = 0.001)) })
tucker_4wayna <- function(data,nfac,naid=which(is.na(data)),maxit=500, ctol=1e-4,Afixed=NULL,Bfixed=NULL,Cfixed=NULL, Dfixed=NULL,Bstart=NULL,Cstart=NULL,Dstart=NULL){ xcx.nona <- sumsq(data, na.rm = TRUE) data[naid] <- rnorm(length(naid)) xcx <- sum(data^2) xdims <- dim(data) Xa <- matrix(data,xdims[1],xdims[2]*xdims[3]*xdims[4]) if(is.null(Bfixed)){Xb <- matrix(aperm(data,perm=c(2,1,3,4)),xdims[2],xdims[1]*xdims[3]*xdims[4])} if(is.null(Cfixed)){Xc <- matrix(aperm(data,perm=c(3,1,2,4)),xdims[3],xdims[1]*xdims[2]*xdims[4])} if(is.null(Dfixed)){Xd <- matrix(aperm(data,perm=c(4,1,2,3)),xdims[4],xdims[1]*xdims[2]*xdims[3])} if(is.null(Afixed)){ Aold <- svd(matrix(rnorm(xdims[1]*nfac[1]),xdims[1],nfac[1]),nu=nfac[1],nv=0)$u } else {Aold <- Anew <- Afixed} if(is.null(Bfixed)){ if(is.null(Bstart)){ Bold <- svd(matrix(rnorm(xdims[2]*nfac[2]),xdims[2],nfac[2]),nu=nfac[2],nv=0)$u } else {Bold <- Bstart} } else {Bold <- Bnew <- Bfixed} if(is.null(Cfixed)){ if(is.null(Cstart)){ Cold <- svd(matrix(rnorm(xdims[3]*nfac[3]),xdims[3],nfac[3]),nu=nfac[3],nv=0)$u } else {Cold <- Cstart} } else {Cold <- Cnew <- Cfixed} if(is.null(Dfixed)){ if(is.null(Dstart)){ Dold <- svd(matrix(rnorm(xdims[4]*nfac[4]),xdims[4],nfac[4]),nu=nfac[4],nv=0)$u } else {Dold <- Dstart} } else {Dold <- Dnew <- Dfixed} vtol <- sseold <- xcx + ctol iter <- 0 cflag <- NA while(vtol>ctol && iter<maxit) { if(is.null(Afixed)){ Anew <- svd(Xa%*%kronecker(Dold,kronecker(Cold,Bold)),nu=nfac[1],nv=0)$u } if(is.null(Bfixed)){ Bnew <- svd(Xb%*%kronecker(Dold,kronecker(Cold,Anew)),nu=nfac[2],nv=0)$u } if(is.null(Cfixed)){ Cnew <- svd(Xc%*%kronecker(Dold,kronecker(Bnew,Anew)),nu=nfac[3],nv=0)$u } if(is.null(Dfixed)){ Dnew <- svd(Xd%*%kronecker(Cnew,kronecker(Bnew,Anew)),nu=nfac[4],nv=0)$u } DkCkB <- kronecker(Dnew,kronecker(Cnew,Bnew)) Ga <- crossprod(Anew,Xa%*%DkCkB) ssenew <- xcx - sum(rowSums(Ga^2)) vtol <- (sseold - ssenew) / xcx Aold <- Anew Bold <- Bnew Cold <- Cnew Dold <- Dnew sseold <- ssenew iter <- iter + 1 Xhat <- tcrossprod(Anew %*% Ga, DkCkB) data[naid] <- Xhat[naid] xcx <- sum(data^2) Xa <- matrix(data,xdims[1],xdims[2]*xdims[3]*xdims[4]) if(is.null(Bfixed)){Xb <- matrix(aperm(data,perm=c(2,1,3,4)),xdims[2],xdims[1]*xdims[3]*xdims[4])} if(is.null(Cfixed)){Xc <- matrix(aperm(data,perm=c(3,1,2,4)),xdims[3],xdims[1]*xdims[2]*xdims[4])} if(is.null(Dfixed)){Xd <- matrix(aperm(data,perm=c(4,1,2,3)),xdims[4],xdims[1]*xdims[2]*xdims[3])} } ssenew <- sum((Xa-Xhat)^2) Adf <- xdims[1]*nfac[1] - nfac[1]*(nfac[1]+1)/2 Bdf <- xdims[2]*nfac[2] - nfac[2]*(nfac[2]+1)/2 Cdf <- xdims[3]*nfac[3] - nfac[3]*(nfac[3]+1)/2 Ddf <- xdims[4]*nfac[4] - nfac[4]*(nfac[4]+1)/2 edf <- c(Adf,Bdf,Cdf,Ddf,prod(nfac)) pxdim <- prod(xdims) GCV <- (ssenew/pxdim) / (1 - sum(edf)/pxdim)^2 Rsq <- 1 - ssenew / xcx.nona if(is.na(cflag)){ if(vtol<=ctol){cflag <- 0} else {cflag <- 1} } names(edf) <- c("A","B","C","D","G") tuck <- list(A=Anew,B=Bnew,C=Cnew,D=Dnew,G=array(Ga,dim=nfac), SSE=ssenew,Rsq=Rsq,GCV=GCV,edf=edf,iter=iter,cflag=cflag) return(tuck) }
context("Errors") library(fairness) data("compas") compas$Two_yr_Recidivism_01 <- ifelse(compas$Two_yr_Recidivism == 'yes', 1, 0) test_that("errors in acc_parity", { expect_error(acc_parity(data = compas, outcome = "Two_yr_Recidivism_01", group = "ethnicity", probs = NULL, preds = NULL, cutoff = 0.5, base = "Caucasian"))}) test_that("errors in dem_parity", { expect_error(dem_parity(data = compas, outcome = "Two_yr_Recidivism_01", group = "ethnicity", probs = NULL, preds = NULL, cutoff = 0.5, base = "Caucasian"))}) test_that("errors in equal_odds", { expect_error(equal_odds(data = compas, outcome = "Two_yr_Recidivism_01", group = "ethnicity", probs = NULL, preds = NULL, cutoff = 0.5, base = "Caucasian"))}) test_that("errors in fnr_parity", { expect_error(fnr_parity(data = compas, outcome = "Two_yr_Recidivism_01", group = "ethnicity", probs = NULL, preds = NULL, cutoff = 0.5, base = "Caucasian"))}) test_that("errors in fpr_parity", { expect_error(fpr_parity(data = compas, outcome = "Two_yr_Recidivism_01", group = "ethnicity", probs = NULL, preds = NULL, cutoff = 0.5, base = "Caucasian"))}) test_that("errors in mcc_parity", { expect_error(mcc_parity(data = compas, outcome = "Two_yr_Recidivism_01", group = "ethnicity", probs = NULL, preds = NULL, cutoff = 0.5, base = "Caucasian"))}) test_that("errors in npv_parity", { expect_error(npv_parity(data = compas, outcome = "Two_yr_Recidivism_01", group = "ethnicity", probs = NULL, preds = NULL, cutoff = 0.5, base = "Caucasian"))}) test_that("errors in pred_rate_parity", { expect_error(pred_rate_parity(data = compas, outcome = "Two_yr_Recidivism_01", group = "ethnicity", probs = NULL, preds = NULL, cutoff = 0.5, base = "Caucasian"))}) test_that("errors in prop_parity", { expect_error(prop_parity(data = compas, outcome = "Two_yr_Recidivism_01", group = "ethnicity", probs = NULL, preds = NULL, cutoff = 0.5, base = "Caucasian"))}) test_that("errors in spec_parity", { expect_error(spec_parity(data = compas, outcome = "Two_yr_Recidivism_01", group = "ethnicity", probs = NULL, preds = NULL, cutoff = 0.5, base = "Caucasian"))}) test_that("errors in acc_parity, no outcome", { expect_error(acc_parity(data = compas, group = "ethnicity", probs = NULL, preds = "predicted", cutoff = 0.5, base = "Caucasian"))}) test_that("errors in acc_parity, no outcome", { expect_error(acc_parity(data = compas, group = "ethnicity", probs = NULL, preds = "predicted", cutoff = 0.5, base = "Caucasian"))}) test_that("errors in equal_odds, no outcome", { expect_error(equal_odds(data = compas, group = "ethnicity", probs = NULL, preds = "predicted", cutoff = 0.5, base = "Caucasian"))}) test_that("errors in fnr_parity, no outcome", { expect_error(fnr_parity(data = compas, group = "ethnicity", probs = NULL, preds = "predicted", cutoff = 0.5, base = "Caucasian"))}) test_that("errors in fpr_parity, no outcome", { expect_error(fpr_parity(data = compas, group = "ethnicity", probs = NULL, preds = "predicted", cutoff = 0.5, base = "Caucasian"))}) test_that("errors in mcc_parity, no outcome", { expect_error(mcc_parity(data = compas, group = "ethnicity", probs = NULL, preds = "predicted", cutoff = 0.5, base = "Caucasian"))}) test_that("errors in npv_parity, no outcome", { expect_error(npv_parity(data = compas, group = "ethnicity", probs = NULL, preds = "predicted", cutoff = 0.5, base = "Caucasian"))}) test_that("errors in pred_rate_parity, no outcome", { expect_error(pred_rate_parity(data = compas, group = "ethnicity", probs = NULL, preds = "predicted", cutoff = 0.5, base = "Caucasian"))}) test_that("errors in spec_parity, no outcome", { expect_error(spec_parity(data = compas, group = "ethnicity", probs = NULL, preds = "predicted", cutoff = 0.5, base = "Caucasian"))})
context("Parsing Zonation input files") options <- get_options() test_that("Parsing a bat file works", { bat.file <- options$bat.file faulty.bat.file <- file.path(dirname(bat.file), "wrong.bat") if (.Platform$OS.type == "unix") { correct.sequence <- c("zig4", "-r", "01/01.dat", "01/01.spp", "01/01_out/01.txt", "0.0", "0", "1.0", "0", "--grid-output-formats=compressed-tif", "--image-output-formats=png") } else { correct.sequence <- c("call", "zig4.exe", "-r", "01/01.dat", "01/01.spp", "01/01_out/01.txt", "0.0", "0", "1.0", "0", "--grid-output-formats=compressed-tif", "--image-output-formats=png") } expect_identical(parse_bat(bat.file), paste(correct.sequence, collapse = " ")) if (.Platform$OS.type == "unix") { correct.sequence[1] <- "zig4" expect_identical(parse_bat(bat.file, exe = "zig4"), paste(correct.sequence, collapse = " ")) } else { correct.sequence[2] <- "zig4.exe" expect_identical(parse_bat(bat.file, exe = "zig4.exe"), paste(correct.sequence, collapse = " ")) } }) test_that("Parsing an ini file (dat) works", { dat.file <- options$dat.file faulty.dat.file <- file.path(dirname(dat.file), "wrong.bat") suppressWarnings(expect_error(read_dat(faulty.dat.file), "(dat-file).+(not found!)", info = "Error raised should name the dat file")) bat.file <- options$bat.file suppressWarnings(expect_error(read_dat(bat.file), "(dat-file).+(doesn't seem to have any section headers.).+", info = "Error raised should name the dat file")) correct.data <- list() correct.data[["Settings"]] <- list() correct.data[["Settings"]][["removal rule"]] <- "1" correct.data[["Settings"]][["warp factor"]] <- "100" correct.data[["Settings"]][["edge removal"]] <- "1" correct.data[["Settings"]][["annotate name"]] <- "0" correct.data[["Settings"]][["use groups"]] <- "1" correct.data[["Settings"]][["groups file"]] <- "01/01_groups.txt" expect_equal(read_dat(dat.file), correct.data, info = "Data parsed from dat file is not correct") }) test_that("Parsing a valid groups file works", { groups.file <- options$groups.file groups.data <- read_groups(groups.file) expect_true(is.data.frame(groups.data), "Groups data read in not a data frame") correct.data <- data.frame(output.group = c(1, 2, 2, 1, 2, 1, 1), condition.group = -1, retention.group = -1, retention.mode = 1, local.edge.correct.group = -1) expect_true(all(names(groups.data) == names(correct.data)), paste("Groups data names no what expected:", paste(names(groups.data), collapse = " "))) expect_true(all(groups.data == correct.data), "Groups data does not correspond to expectations") }) test_that("Parsing an invalid groups file works", { groups.file <- system.file("extdata/tutorial/basic", "invalid_groups.txt", package = "zonator") expect_error(groups.data <- read_groups(groups.file), info = "Invalid groups file should throw an error") }) test_that("Parsing an unpopulated spp file works", { spp.file <- system.file("extdata", "template.spp", package = "zonator") suppressWarnings(spp.data <- read_spp(spp.file)) expect_true(is.data.frame(spp.data), "Spp data read in not a data frame") expect_true(all(dim(spp.file) == c(0, 0)), "Spp data should have dim c(0,0)") }) test_that("Parsing a populated spp file works", { spp.file <- options$spp.file correct.data <- data.frame(weight = 1, alpha = c(1.0, 0.5, 0.25, 0.75, 0.50, 1.50, 1.0), bqp = 1, bqp_p = 1, cellrem = 1, filepath = paste0("../data/species", 1:7, ".tif"), stringsAsFactors = FALSE) spp.data <- read_spp(spp.file) expect_true(is.data.frame(spp.data), "Spp data read in not a data frame") expect_true(all(names(spp.data) == names(correct.data)), paste("Spp data names no what expected:", paste(names(spp.data), collapse = " "))) expect_true(all(spp.data == correct.data), "Spp data does not correspond to expectations") })
suppressPackageStartupMessages(library(vegdata)) tmp <- tempdir() options(tv_home = tmp) dir.create(file.path(tmp, 'Species')) dir.create(file.path(tmp, 'Popup')) dir.create(file.path(tmp, 'Data')) file.copy(from = file.path(path.package("vegdata"), 'tvdata', 'Popup'), to = tmp, recursive = TRUE) file.copy(from = file.path(path.package("vegdata"), 'tvdata', 'Species'), to = tmp, recursive = TRUE) file.copy(from = file.path(path.package("vegdata"), 'tvdata', 'Data'), to = tmp, recursive = TRUE) library(eHOF) library(vegdata) db <- 'elbaue' site <- tv.site(db) veg <- tv.veg(db, taxval = FALSE, spcnames = 'Numbers') obs <- tv.obs(db) taxa <- tax('all') names(veg) <- sub('.0', '', names(veg), fixed=TRUE) for(i in 1:ncol(veg)) names(veg)[i] <- as.character(taxa$LETTERCODE[match(as.numeric(names(veg)[i]), taxa$TaxonUsageID)]) veg.sqrt <- tv.veg(db, cover.transform='sqrt', tax=FALSE, spcnames='Numbers') names(veg.sqrt) <- sub('.0', '', names(veg.sqrt), fixed=TRUE) names(veg.sqrt) <- taxa$LETTERCODE[match(names(veg.sqrt), taxa$TaxonUsageID)] veg.pa <- tv.veg(db, cover.transform='pa', tax=FALSE, spcnames='Numbers') names(veg.pa) <- sub('.0', '', names(veg.pa), fixed=TRUE) names(veg.pa) <- taxa$LETTERCODE[match(names(veg.pa), taxa$TaxonUsageID)] data(acre) sel <- c('ELYMREP', 'VEROPES', 'CONSREG', 'DESUSOP', 'VEROARV', 'ARTE mo <- HOF(acre[match(sel, names(acre))], acre.env$PH_KCL, M=1, bootstrap=NULL) par(mar=c(4,4,1,1)+.1) autolayout(7) par(mar=c(4,4,1,1)+.1) for(i in 1:7) plot(mo[[i]], model = eHOF.modelnames[i], marginal ='n') mods <- HOF(veg, site$MGL, M=100, family = poisson, bootstrap = NULL) mods mods.sq <- HOF(veg.sqrt, site$MGL, M=10, family= poisson, freq.limit=10, bootstrap=NULL) plot(mods.sq) mods.pa <- HOF(veg.pa, site$MGL, M=1, bootstrap=NULL) plot(mods.pa) lRP <- taxa$LETTERCODE[taxa$TaxonName == 'Ranunculus repens'] plot(mods.pa[[lRP]], para=TRUE, onlybest=FALSE) mod.sqrt <- HOF(veg.sqrt[[lRP]], site$MGL, M=10, family=poisson, bootstrap = 10) plot(mod.sqrt, marginal='point', para=TRUE, onlybest=FALSE, newdata=seq(min(mod.sqrt$range), max(mod.sqrt$range), length.out=10000) ) Para(mod.sqrt)
library(tidymodels) library(nycflights13) library(doMC) library(rlang) library(xgboost) library(vctrs) library(embed) library(rstanarm) num_resamples <- 5 num_grid <- 10 num_cores <- 3 preproc <- "expensive preprocessing" par_method <- "everything" set.seed(123) flight_data <- flights %>% mutate( arr_delay = ifelse(arr_delay >= 30, "late", "on_time"), arr_delay = factor(arr_delay), date = as.Date(time_hour) ) %>% inner_join(weather, by = c("origin", "time_hour")) %>% select(dep_time, flight, origin, dest, air_time, distance, carrier, date, arr_delay, time_hour) %>% na.omit() %>% mutate_if(is.character, as.factor) %>% sample_n(4000) flights_rec <- recipe(arr_delay ~ ., data = flight_data) %>% update_role(flight, time_hour, new_role = "ID") %>% step_date(date, features = c("dow", "month")) %>% step_holiday(date, holidays = timeDate::listHolidays("US")) %>% step_rm(date) %>% step_mutate(flight = as.factor(flight)) %>% step_lencode_bayes(flight, outcome = vars(arr_delay)) %>% step_dummy(all_nominal_predictors()) %>% step_zv(all_predictors()) xgboost_spec <- boost_tree(trees = tune(), min_n = tune(), tree_depth = tune(), learn_rate = tune(), loss_reduction = tune(), sample_size = tune()) %>% set_mode("classification") %>% set_engine("xgboost") if (preproc != "no preprocessing") { xgboost_workflow <- workflow() %>% add_recipe(flights_rec) %>% add_model(xgboost_spec) set.seed(33) bt <- bootstraps(flight_data, times = num_resamples) } else { xgboost_workflow <- workflow() %>% add_variables(arr_delay, predictors = c(everything())) %>% add_model(xgboost_spec) set.seed(33) bt <- bootstraps(preproc_data, times = num_resamples) } set.seed(22) xgboost_grid <- xgboost_workflow %>% parameters() %>% update(trees = trees(c(100, 2000))) %>% grid_max_entropy(size = num_grid) if (num_cores > 1) { registerDoMC(cores=num_cores) } roc_res <- metric_set(roc_auc) ctrl <- control_grid(parallel_over = par_method) grid_time <- system.time({ set.seed(99) xgboost_workflow %>% tune_grid(bt, grid = xgboost_grid, metrics = roc_res, control = ctrl) }) times <- tibble::tibble( elapsed = grid_time[3], num_resamples = num_resamples, num_grid = num_grid, num_cores = num_cores, preproc = preproc, par_method = par_method ) save(times, file = paste0("xgb_", num_cores, format(Sys.time(), "_%Y_%m_%d_%H_%M_%S.RData"))) sessioninfo::session_info() if (!interactive()) { q("no") }
context("columns") source('helpers.R') test_that("Columns identical across old and new sources", { skip_on_cran() g1 <- fast_scraper(game_ids[1]) g2 <- fast_scraper(game_ids[2]) expect_identical(names(g1), names(g2)) })
context("stat-alluvium") test_that("`stat_alluvium` weights computed variables but drops weight", { data <- expand.grid(alluvium = letters[1:3], x = 1:2) data$stratum <- LETTERS[c(1, 1, 2, 1, 2, 2)] data$y <- c(1, 1, 1, 1, 1, 2) data$weight <- c(.5, 1, 1, .5, 1, 1) comp <- StatAlluvium$compute_panel(data) comp <- comp[with(comp, order(x, alluvium)), ] expect_equivalent(comp$n, c(0.5, 1, 1, 0.5, 1, 1)) expect_equivalent(comp$count, c(0.5, 1, 1, 0.5, 1, 2)) expect_equivalent(comp$prop, c(c(1, 2, 2) / 5, c(1, 2, 4) / 7)) expect_equal(comp$lode, factor(rep(letters[1:3], times = 2))) expect_null(comp$weight) data$stratum <- LETTERS[c(1, 1, 2)] comp <- StatAlluvium$compute_panel(data, cement.alluvia = TRUE) comp <- comp[with(comp, order(x, alluvium)), ] expect_equivalent(comp$n, c(1.5, 1, 1.5, 1)) expect_equivalent(comp$count, c(1.5, 1, 1.5, 2)) expect_equivalent(comp$prop, c(c(3, 2) / 5, c(3, 4) / 7)) expect_equal(comp$lode, rep(factor(letters[1:3])[c(1, 3)], times = 2)) expect_null(comp$weight) }) test_that("`stat_alluvium` orders alluvia without regard to negative values", { data <- expand.grid(alluvium = letters[1:2], x = 1:2) data$stratum <- LETTERS[1] data$y <- c(-1, -1) comp <- StatAlluvium$compute_panel(data) expect_identical(comp[with(comp, order(x, alluvium)), ]$y, c(-0.5, -1.5, -0.5, -1.5)) comp <- StatAlluvium$compute_panel(data, absolute = FALSE) expect_identical(comp[with(comp, order(x, alluvium)), ]$y, c(-0.5, -1.5, -0.5, -1.5)) }) test_that("`stat_alluvium` orders alluvia correctly according to `aes.bind`", { data <- expand.grid(alluvium = letters[1:4], x = 1:2) data$stratum <- LETTERS[1:2][c(1, 1, 2, 2, 2, 2, 2, 1)] data$y <- 1 data$fill <- c("red", "blue", "blue", "blue") comp <- StatAlluvium$compute_panel(data) expect_identical(comp[with(comp, order(x, alluvium)), ]$y, c(3.5, 2.5, 0.5, 1.5, 2.5, 1.5, 0.5, 3.5)) comp <- StatAlluvium$compute_panel(data, aes.bind = "flows") expect_identical(comp[with(comp, order(x, alluvium)), ]$y, c(2.5, 3.5, 0.5, 1.5, 1.5, 2.5, 0.5, 3.5)) comp <- StatAlluvium$compute_panel(data, aes.bind = "alluvia") expect_identical(comp[with(comp, order(x, alluvium)), ]$y, c(2.5, 3.5, 0.5, 1.5, 0.5, 2.5, 1.5, 3.5)) }) test_that("`stat_flow` handles exceptional data with out errors", { data(Refugees, package = "alluvial") refugees_sub <- subset(Refugees, year %in% c(2003, 2005, 2010, 2013)) gg <- ggplot(refugees_sub, aes(x = year, y = refugees, alluvium = country)) + geom_alluvium(aes(fill = country)) expect_silent(ggplot_build(gg)) })
knitr::opts_chunk$set( collapse = TRUE, comment = " ) backup_option <- options() base_wd <- getwd() options(rgl.useNULL=TRUE) library(spNetwork) library(rgeos) library(sp) library(maptools) library(rgl) library(FNN) wkt_lines <- c( "LINESTRING (0 0, 1 0)", "LINESTRING (1 0, 2 0)", "LINESTRING (2 0, 3 0)", "LINESTRING (0 1, 1 1)", "LINESTRING (1 1, 2 1)", "LINESTRING (2 1, 3 1)", "LINESTRING (0 2, 1 2)", "LINESTRING (1 2, 2 2)", "LINESTRING (2 2, 3 2)", "LINESTRING (0 3, 1 3)", "LINESTRING (1 3, 2 3)", "LINESTRING (2 3, 3 3)", "LINESTRING (0 0, 0 1)", "LINESTRING (0 1, 0 2)", "LINESTRING (0 2, 0 3)", "LINESTRING (1 0, 1 1)", "LINESTRING (1 1, 1 2)", "LINESTRING (1 2, 1 3)", "LINESTRING (2 0, 2 1)", "LINESTRING (2 1, 2 2)", "LINESTRING (2 2, 2 3)", "LINESTRING (3 0, 3 1)", "LINESTRING (3 1, 3 2)", "LINESTRING (3 2, 3 3)" ) linesdf <- data.frame(wkt = wkt_lines, id = paste("l",1:length(wkt_lines),sep="")) geoms <- do.call(rbind,lapply(1:nrow(linesdf),function(i){ txt <- as.character(linesdf[i,]$wkt) geom <- rgeos::readWKT(txt,id=i) return(geom) })) all_lines <- sp::SpatialLinesDataFrame(geoms, linesdf,match.ID = F) event <- data.frame(x=c(1), y=c(1.5)) sp::coordinates(event) <- cbind(event$x,event$y) par(mar=c(0.1,0.1,0.1,0.1)) sp::plot(all_lines) sp::plot(event,add=T,col="red",pch = 19) d3_plot_situation <- function(lines, events, pt_samples, densities, scales){ open3d(scale=scales) densities < round(densities,7) XY1 <- coordinates(pt_samples) XY2 <- coordinates(events) idx <- knnx.index(XY1, query = XY2, k = 1) events$dens <- densities[idx] events$x <- XY2[,1] events$y <- XY2[,2] eidx <- do.call(c,lapply(1:nrow(events), function(i){c(i,i)})) vert_lines <- events@data[eidx,] vert_lines$dens <- ifelse(1:nrow(vert_lines)%%2 == 0, vert_lines$dens,0) line_coords <- do.call(rbind,unlist(coordinates(lines), recursive = FALSE)) sample_coords <- coordinates(pt_samples) segments3d(x=line_coords[,1], y=line_coords[,2], z=rep(0, nrow(line_coords))) segments3d(x=vert_lines$x, y=vert_lines$y, z=vert_lines$dens, col = "red") coords_events <- coordinates(events) points3d( x = coords_events[,1], y = coords_events[,2], z = rep(0,nrow(event)), col = "red", size = 5 ) points3d( x = sample_coords[,1], y = sample_coords[,2], z = densities, col = "blue" ) axes3d() title3d(xlab="X",ylab="Y",zlab="Z") } knitr::knit_hooks$set(webgl = hook_webgl) samples_pts <- lines_points_along(all_lines,0.01) simple_kernel <- nkde(all_lines, event, w = 1, samples = samples_pts, kernel_name = "quartic", bw = 2, method = "simple", div = "bw", digits = 3, tol = 0.001, grid_shape = c(1,1), check = FALSE, verbose = FALSE) d3_plot_situation(all_lines, event, samples_pts, simple_kernel, scales = c(1,1,3)) discontinuous_kernel <- nkde(all_lines, event, w = 1, samples = samples_pts, kernel_name = "quartic", bw = 2, method = "discontinuous", div = "bw", digits = 3, tol = 0.001, grid_shape = c(1,1), check = FALSE, verbose = FALSE) d3_plot_situation(all_lines, event, samples_pts, discontinuous_kernel, scales = c(1,1,3)) continuous_kernel <- nkde(all_lines, event, w = 1, samples = samples_pts, kernel_name = "quartic", bw = 2, method = "continuous", div = "bw", digits = 3, tol = 0.001, grid_shape = c(1,1), check = FALSE, verbose = FALSE) d3_plot_situation(all_lines, event, samples_pts, continuous_kernel, scales = c(1,1,3)) events <- data.frame(x=c(1,2), y=c(1.5,1.5)) sp::coordinates(events) <- cbind(events$x,events$y) continuous_kernel <- nkde(all_lines, events, w = 1, samples = samples_pts, kernel_name = "quartic", bw = 1.3, method = "continuous", div = "bw", digits = 3, tol = 0.001, grid_shape = c(1,1), check = FALSE, verbose = FALSE) d3_plot_situation(all_lines, events, samples_pts, continuous_kernel, scales = c(1,1,3)) continuous_kernel <- nkde(all_lines, events, w = 1, samples = samples_pts, kernel_name = "quartic", bw = 1.6, method = "continuous", div = "bw", digits = 3, tol = 0.001, grid_shape = c(1,1), check = FALSE, verbose = FALSE) d3_plot_situation(all_lines, events, samples_pts, continuous_kernel, scales = c(1,1,3)) options(backup_option) setwd(base_wd) oldpar <- par(mfrow = c(1,2)) par(oldpar)
test_that("cusum_control_median works", { test_vec <- c(1,1,2,11,3,5,7,2,4,3,5) x <- c(1,1,2,11,3,5,7,2,4,3,5) target <- c(3,3,3,3,3,3,3,3,3,3,3) variance <- c(-2, -2, -1, 8,0,2,4,-1,1,0,2) std_dev <- c(2.8368794, 2.8368794, 2.8368794, 2.8368794, 2.8368794, 2.8368794, 2.8368794, 2.8368794, 2.8368794, 2.8368794, 2.8368794) cusum <- c(-2, -4, -5, 3, 3, 5, 9, 8, 9, 9, 11) cplus <- c(0, 0, 0, 6.58156028, 5.16312057, 5.74468085, 8.32624113, 5.90780142, 5.48936170, 4.07092199, 4.652482) cneg <- c(-0.58156028, -1.16312057, -0.74468085, 0, 0, 0, 0, 0, 0, 0,0) cum_nplus <- c(0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8) cum_nneg <- c(1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0) ucl <- rep(11.34752,11) ucl <- round(ucl,3) lcl <- rep(-11.34752,11) lcl <- round(lcl,3) centre <- 0 obs <- 1:11 output <- data.frame(x, target, variance,std_dev, cusum, cplus, cneg, cum_nplus,cum_nneg,ucl,lcl,centre,obs) res <- cusum_control_median(test_vec) res$ucl <- round(res$ucl,3) res$lcl <- round(res$lcl,3) expect_equal(output, res) }) test_that("non numeric vector fails", { test_vec3 <- as.character(c(1,1,2,11,3,5,7,2,4,3,5)) expect_error(cusum_control_median(test_vec3, target = 5)) }) test_that("na elements fail", { test_vec3 <- c(0.175, NA, 0.15, 0.207, 0.136, NA, 0.166) expect_error(cusum_control_median(test_vec3, target = 0.16)) }) test_that("high k generates warning",{ test_vec <- c(1,1,2,11,3,5,7,2,4,3,5) expect_warning(cusum_control_median(test_vec,k = 2)) }) test_that("high h generates warning",{ test_vec <- c(1,1,2,11,3,5,7,2,4,3,5) expect_warning(cusum_control_median(test_vec, h = 6)) }) test_that("k = NULL generates message", { test_vec <- c(1,1,2,11,3,5,7,2,4,3,5) expect_message(cusum_control_median(test_vec, target = 4, k = NULL, h = 5), "k was not supplied so using 0.5 as a default") }) test_that("h = NULL generates message", { test_vec <- c(1,1,2,11,3,5,7,2,4,3,5) expect_message(cusum_control_median(test_vec, target = 4, k = 1, h = NULL), "h was not supplied so using 4 as a default") }) test_that("target value propagates", { test_vec <- c(1,1,2,11,3,5,7,2,4,3,5) target1 <- rep(6,11) res <- cusum_control_median(test_vec,target = 6) expect_equal(target1,res$target) })
regpolca_penalty_fun <- function(x, regular_grouped, I, partable, combis_classes_list, regular_lam, eps, penalty_used, Ni, combis_categ_list, fuse_categories, K) { pen <- 0 if (regular_grouped=="none"){ for (ii in 1L:I){ x_ii <- x[ partable$itemnr==ii ] a1 <- regpolca_penalty_fun_value_nongrouped(x_ii=x_ii, combis_ii=combis_classes_list[[ii]], regular_lam=regular_lam[1], eps=eps, penalty_used=penalty_used) pen <- pen + Ni[ii]*sum(a1) } for (ii in 1L:I){ if (fuse_categories[ii]){ x_ii <- x[ partable$itemnr==ii ] a1 <- regpolca_penalty_fun_value_nongrouped(x_ii=x_ii, combis_ii=combis_categ_list[[ii]], regular_lam=regular_lam[2], eps=eps, penalty_used=penalty_used) pen <- pen + Ni[ii]*sum(a1) } } } else { for (ii in 1L:I){ x_ii <- x[ partable$itemnr==ii ] combis_ii <- combis_categ_list[[ii]] nc <- nrow(combis_ii) a1 <- 0 if (regular_grouped=="class"){ K1 <- max(combis_ii$cat_pair) for (kk in 1:K1){ cii_kk <- combis_ii[ seq(kk,nc,by=nc/K), ] a2 <- regpolca_penalty_fun_value_grouped(x_ii=x_ii, combis_ii=cii_kk, regular_lam=regular_lam[1], eps=eps, penalty_used=penalty_used) a1 <- a1 + a2 } } if (regular_grouped=="categ"){ for (kk in 1:K){ cii_kk <- combis_ii[ combis_ii$class==kk, ] a2 <- regpolca_penalty_fun_value_grouped(x_ii=x_ii, combis_ii=cii_kk, regular_lam=regular_lam[1], eps=eps, penalty_used=penalty_used) a1 <- a1 + a2 } } pen <- pen + Ni[ii]*sum(a1) } } return(pen) }
is_keyed_by_columns <- function(d, keys) { if(length(keys)<1) { return(nrow(d)<=1) } dt <- as.data.table(d) dt <- dt[ , j = list(RQDATATABLE_TMP = 1), by = keys ] return(nrow(dt)==nrow(d)) } ex_data_table_step.relop_project <- function(optree, ..., tables = list(), source_usage = NULL, source_limit = NULL, env = parent.frame()) { force(env) wrapr::stop_if_dot_args(substitute(list(...)), "rqdatatable::ex_data_table_step.relop_project") n <- length(optree$parsed) if(is.null(source_usage)) { source_usage <- columns_used(optree) } x <- ex_data_table_step(optree$source[[1]], tables = tables, source_usage = source_usage, source_limit = source_limit, env = env) byi <- "" if(length(optree$groupby)>0) { pterms <- paste0("\"", optree$groupby, "\"") byi <- paste0(" , by = c(", paste(pterms, collapse = ", "), ")") } tmpnam <- ".rquery_ex_project_tmp" tmpenv <- patch_global_child_env(env) assign(tmpnam, x, envir = tmpenv) cols_to_remove <- character(0) rqdatatable_temp_one_col <- NULL if(n>0) { prepped <- prepare_prased_assignments_for_data_table(optree$parsed) enames <- prepped$enames eexprs <- prepped$eexprs if(prepped$need_one_col) { x[ , rqdatatable_temp_one_col := 1.0] } cols_to_remove <- "rqdatatable_temp_one_col" } else { enames <- "RQDATATABLE_FAKE_COL" eexprs <- "1" cols_to_remove <- enames need_one_col <- FALSE } src <- paste0(tmpnam, "[ ", " , j = list(", paste(paste(enames, "=", eexprs), collapse = ", "), ") ", byi, " ]") expr <- parse(text = src) res <- eval(expr, envir = tmpenv, enclos = tmpenv) cols_to_remove <- intersect(cols_to_remove, colnames(res)) if(length(cols_to_remove)>0) { res[, (cols_to_remove) := NULL] } if(!is_keyed_by_columns(res, optree$groupby)) { stop("project: result was not keyed by groubpy columns, likely unaggregated columns in calculation") } res }
library(sand) data(hc) head(hc) ID.stack <- c(hc$ID1,hc$ID2) Status.stack <- c(as.character(hc$S1), as.character(hc$S2)) my.t <- table(ID.stack,Status.stack) v.status <- character(nrow(my.t)) for(i in (1:length(v.status))){ v.status[i] <- names(which(my.t[i,]!=0)) } table(v.status) status.t <- table(hc$S1,hc$S2) status.t <- status.t + t(status.t) diag(status.t) <- round(diag(status.t)/2) status.t tmp.es <- paste(hc$S1,"-",hc$S2,sep="") e.status <- character(dim(hc)[[1]]) e.status[tmp.es=="ADM-ADM"] <- "ADM-ADM" e.status[tmp.es=="MED-MED"] <- "MED-MED" e.status[tmp.es=="NUR-NUR"] <- "NUR-NUR" e.status[tmp.es=="PAT-PAT"] <- "PAT-PAT" e.status[(tmp.es=="ADM-MED") | (tmp.es=="MED-ADM")] <- "ADM-MED" e.status[(tmp.es=="ADM-NUR") | (tmp.es=="NUR-ADM")] <- "ADM-NUR" e.status[(tmp.es=="ADM-PAT") | (tmp.es=="PAT-ADM")] <- "ADM-PAT" e.status[(tmp.es=="MED-NUR") | (tmp.es=="NUR-MED")] <- "MED-NUR" e.status[(tmp.es=="MED-PAT") | (tmp.es=="PAT-MED")] <- "MED-PAT" e.status[(tmp.es=="NUR-PAT") | (tmp.es=="PAT-NUR")] <- "NUR-PAT" my.hc <- data.frame(Time = hc$Time/(60*60), ID1 = hc$ID1, ID2 = hc$ID2, Status = e.status) library(lattice) histogram(~Time|Status, data=my.hc, xlab="Hours", layout=c(5,2)) vids <- sort(unique(c(hc$ID1, hc$ID2))) g.week <- graph_from_data_frame(hc[, c("ID1", "ID2", "Time")], vertices=data.frame(vids), directed=FALSE) E(g.week)$Time <- E(g.week)$Time / (60 * 60) summary(g.week) status <- unique(rbind(data.frame(id=hc$ID1, status=hc$S1), data.frame(id=hc$ID2, status=hc$S2))) V(g.week)$Status <- as.character(status[order(status[,1]),2]) E(g.week)$weight <- 1 g.week.wgtd <- simplify(g.week) summary(g.week.wgtd) is_simple(g.week.wgtd) summary(E(g.week.wgtd)$weight) g.week.96 <- subgraph.edges(g.week, E(g.week)[Time <= 96]) g.sl12 <- lapply(1:8, function(i) { g <- subgraph.edges(g.week, E(g.week)[Time > 12*(i-1) & Time <= 12*i], delete.vertices=FALSE) simplify(g) }) sapply(g.sl12,vcount) sapply(g.sl12,ecount) library(networkDynamic) hc.spls <- cbind((hc$Time-20)/(60*60), hc$Time/(60*60), hc$ID1,hc$ID2) hc.dn <- networkDynamic(edge.spells=hc.spls) is.active(hc.dn,onset=0,terminus=1,e=c(1)) is.active(hc.dn,onset=1,terminus=2,e=c(1)) get.edge.activity(hc.dn,e=c(1)) get.edge.activity(hc.dn,e=c(10)) g.sl12.dN <- get.networks(hc.dn,start=0,end=96, time.increment=12) hc.dn.df <- as.data.frame(hc.dn) names(hc.dn.df) summary(hc.dn.df$duration) detach(package:networkDynamic) set.seed(42) l = layout_with_fr(g.week.wgtd) v.cols <- character(75) v.cols[V(g.week.wgtd)$Status=="ADM"] <- "yellow" v.cols[V(g.week.wgtd)$Status=="MED"] <- "blue" v.cols[V(g.week.wgtd)$Status=="NUR"] <- "green" v.cols[V(g.week.wgtd)$Status=="PAT"] <- "black" plot(g.week.wgtd, layout=l, vertex.size=3, edge.width=2*(E(g.week.wgtd)$weight)/100, vertex.color=v.cols,vertex.label=NA,) opar <- par() par(mfrow=c(2,4), mar=c(0.5, 0.5, 0.5, 0.5), oma=c(0.5, 1.0, 0.5, 0)) for(i in (1:8)) { plot(g.sl12[[i]], layout=l, vertex.size=5, edge.width=2*(E(g.week.wgtd)$weight)/1000, vertex.color=v.cols,vertex.label=NA) title(paste(12*(i-1),"to",12*i,"hrs")) } par(opar) tmp.es <- paste(v.status[hc.dn.df$tail],"-", v.status[hc.dn.df$head],sep="") mycols <- numeric(nrow(hc.dn.df)) mycols[tmp.es=="ADM-ADM"] <- 1 mycols[tmp.es=="MED-MED"] <- 2 mycols[tmp.es=="NUR-NUR"] <- 3 mycols[tmp.es=="PAT-PAT"] <- 4 mycols[(tmp.es=="ADM-MED") | (tmp.es=="MED-ADM")] <- 5 mycols[(tmp.es=="ADM-NUR") | (tmp.es=="NUR-ADM")] <- 6 mycols[(tmp.es=="ADM-PAT") | (tmp.es=="PAT-ADM")] <- 7 mycols[(tmp.es=="MED-NUR") | (tmp.es=="NUR-MED")] <- 8 mycols[(tmp.es=="MED-PAT") | (tmp.es=="PAT-MED")] <- 9 mycols[(tmp.es=="NUR-PAT") | (tmp.es=="PAT-NUR")] <- 10 my.palette <- rainbow(10) ne <- max(hc.dn.df$edge.id) max.t <- max(hc.dn.df$terminus) plot(c(0,max.t),c(0,ne),ann=F,type='n') segments(hc.dn.df$onset,hc.dn.df$edge.id, hc.dn.df$terminus,hc.dn.df$edge.id, col=my.palette[mycols]) title(xlab="Time (hours)", ylab="Interacting Pair (Ordered by First Interaction)") clip(0,max.t,0,ne) abline(v=c(11,35,59,83),lty="dashed",lw=2, col="lightgray") status.pairs <- c("ADM-ADM","MED-MED","NUR-NUR", "PAT-PAT", "ADM-MED","ADM-NUR","ADM-PAT", "MED-NUR", "MED-PAT","NUR-PAT") legend(7,1140,status.pairs, text.col=my.palette[(1:10)],cex=0.7) all.deg <- sapply(g.sl12,degree) sl.lab<- sapply(1:8, function(i) paste(12*(i-1), "-", 12*i, "hrs", sep="")) deg.df <- data.frame(Degree=as.vector(all.deg), Slice = rep(sl.lab,each=75), Status = rep(V(g.week)$Status, times=8)) library(ggplot2) p = qplot(factor(Degree), data=deg.df, geom="bar",fill=Status) p+facet_grid(Slice~.) + xlab("Degree") + ylab("Count") top.deg <- lapply(1:8,function(i) { all.deg[,i][rank(all.deg[,i])>=70] }) table(unlist(lapply(1:8,function(i) as.numeric(names(top.deg[[i]]))))) V(g.week)$Status[c(7,15)] all.str <- sapply(g.sl12,strength) all.r <- all.str/all.deg round(all.r[c(7,15),],digits=2) summary(c(all.r)) sp.len <- lapply(1:8, function(i) { spl <- distances(g.sl12[[i]],v=c(7,15), to=V(g.sl12[[i]]), weights=NA) spl[spl==Inf] <- NA spl }) ave.spl <- sapply(1:8,function(i) apply(sp.len[[i]],1,mean,na.rm=T)) round(ave.spl,digits=2) sapply(g.sl12,diameter) round(sapply(g.sl12,mean_distance),digits=2)
jacobian_Ising_group <- function(omega,tau,beta,squares,means,responses,nobs,exp_v1,exp_v2,exp_H,...){ thresholds <- as.vector(tau) graph <- as.matrix(omega) beta <- as.numeric(beta) v1 <- as.vector(means * nobs) v2 <- as.matrix(squares) H <- ( - sum(thresholds * v1) - sum((graph * v2)[lower.tri(v2,diag=FALSE)]) ) threshGrad <- ( 2 * beta * exp_v1 - 2 * beta * v1 / nobs ) graphGrad <- ( 2 * beta * exp_v2 - 2 * beta * v2 / nobs )[lower.tri(v2,diag=FALSE)] betaGrad <- ( 2*(H/nobs - exp_H) ) grad <- Matrix(c(threshGrad, graphGrad, betaGrad),nrow = 1) return(grad) } jacobian_Ising <- function(prep){ g_per_group <- lapply(prep$groupModels,do.call,what=jacobian_Ising_group) for (i in 1:length(prep$groupModels)){ g_per_group[[i]] <- (prep$nPerGroup[i] / prep$nTotal) * g_per_group[[i]] } Reduce("cbind",g_per_group) }
glamlasso <-function(X, Y, Z = NULL, family = "gaussian", penalty = "lasso", intercept = FALSE, weights = NULL, betainit = NULL, alphainit = NULL, nlambda = 100, lambdaminratio = 0.0001, lambda = NULL, penaltyfactor = NULL, penaltyfactoralpha = NULL, reltolinner = 1e-07, reltolouter = 1e-04, maxiter = 15000, steps = 1, maxiterinner = 3000, maxiterouter = 25, btinnermax = 100, btoutermax = 100, iwls = "exact", nu = 1) { dimglam <- length(X) if (dimglam < 2 || dimglam > 3){ stop(paste("the dimension of the GLAM must be 2 or 3!")) }else if(dimglam == 2){X[[3]] <- matrix(1, 1, 1)} X1 <- X[[1]] X2 <- X[[2]] X3 <- X[[3]] dimX <- rbind(dim(X1), dim(X2), dim(X3)) n1 <- dimX[1, 1] n2 <- dimX[2, 1] n3 <- dimX[3, 1] p1 <- dimX[1, 2] p2 <- dimX[2, 2] p3 <- dimX[3, 2] n <- prod(dimX[,1]) p <- prod(dimX[,2]) if(is.null(Z) == TRUE & intercept == FALSE){ nonten <- 0 q <- 1 Z <- matrix(0, 1, q) }else if(is.null(Z) == TRUE & intercept == TRUE){ nonten <- 1 q <- 1 Z <- matrix(1, n, q) }else if(is.null(Z) == FALSE & intercept == FALSE){ nonten <- 1 q <- dim(Z)[2] }else{ nonten <- 1 Z <- cbind(matrix(1, n, 1), Z) q <- dim(Z)[2] } Y <- matrix(Y, n1, n2 * n3) if(sum(family == c("gaussian", "binomial", "poisson", "gamma")) != 1){ stop(paste("family must be correctly specified")) } if(sum(penalty == c("lasso", "scad")) != 1){stop(paste("penalty must be correctly specified"))} if(penalty == "lasso"){steps <- 1} if(family == "binomial" & is.null(weights)){stop(paste("for binomial model number of trials (weights) must be specified"))} if(is.null(weights)){ weightedgaussian <- 0 weights <- matrix(1, n1, n2 * n3) }else{ if(min(weights) < 0){stop(paste("only positive weights allowed"))} weightedgaussian <- 1 weights <- matrix(weights, n1, n2 * n3) } if(is.null(betainit)){betainit <- matrix(0, p1, p2 * p3)}else{betainit <- matrix(betainit, p1, p2 * p3)} if(is.null(alphainit)){alphainit <- matrix(0, q, 1)} if(is.null(lambda)){ makelamb <- 1 lambda <- rep(NA, nlambda) }else{ if(length(lambda) != nlambda){ nlambda <- length(lambda) } makelamb <- 0 } if(is.null(penaltyfactor)){ penaltyfactor <- matrix(1, p1, p2 * p3) }else if(prod(dim(penaltyfactor)) != p){ stop( paste("number of elements in penaltyfactor (", length(penaltyfactor),") is not equal to the number of coefficients (", p,")", sep = "") ) }else { if(min(penaltyfactor) < 0){stop(paste("penaltyfactor must be positive"))} penaltyfactor <- matrix(penaltyfactor, p1, p2 * p3) } if(is.null(penaltyfactoralpha)){ penaltyfactoralpha <- matrix(1, q, 1) }else if(prod(dim(penaltyfactoralpha)) != q){ stop( paste("number of elements in penaltyfactoralpha (", length(penaltyfactoralpha),") is not equal to the number of coefficients (", q,")", sep = "") ) }else { if(min(penaltyfactoralpha) < 0){stop(paste("penaltyfactoralpha must be positive"))} } if(is.null(iwls)){ iwls <- "exact" }else{ if(sum(iwls == c("exact", "identity", "kron1", "kron2")) != 1){stop(paste("iwls must be correctly specified"))} } if(nu < 0 || nu > 1){stop(paste("nu must be between 0 and 1"))} res <- gdpg(X1, X2, X3, Z, matrix(0, n, q), Y, matrix(0, n3, n1 * n2), matrix(0, n1, n2 * n3), weights, matrix(0, n3, n1 * n2), betainit, matrix(0, 1, 1), matrix(0, 1, 1), alphainit, family, penalty, nonten, iwls, nu, lambda, makelamb, nlambda, lambdaminratio, penaltyfactor, matrix(0, 1, 1), matrix(0, 1, 1), penaltyfactoralpha, reltolinner, reltolouter, 0, maxiter, steps, maxiterinner, maxiterouter, 1, btinnermax, btoutermax, weightedgaussian, 0, 0, n1, n2, n3) if(res$STOPmaxiter == 1){ warning(paste("program exit due to maximum number of iterations (",maxiter,") reached for model no ",res$endmodelno,"")) } if(res$STOPprox == 1){ warning(paste("program exit due to maximum number of backtraking steps in the inner loop reached for model no ",res$endmodelno,"")) } if(res$STOPnewt == 1){ warning(paste("program exit due to max number of backtraking steps in the outer loop reached for model no ",res$endmodelno,"")) } endmodelno <- res$endmodelno + 1 Iter <- res$Iter if(family != "gaussian" || (weightedgaussian == 1 & iwls == "kron")){ maxiterouterreached <- ifelse(Iter[1:endmodelno, maxiterouter] > 0, 1, 0) * (1:endmodelno) maxiterouterreached <- maxiterouterreached[maxiterouterreached > 0] if(length(maxiterouterreached)){ models <- paste("", maxiterouterreached) warning(paste("maximum number of outer iterations (", maxiterouter,") reached for model(s):"), models) } } maxiterinnerpossible <- sum(Iter > 0) maxiterinnerreached <- sum(Iter >= (maxiterinner - 1)) if(maxiterinnerreached > 0){ warning( paste("maximum number of inner iterations (",maxiterinner,") reached ",maxiterinnerreached," time(s) out of ",maxiterinnerpossible," possible") ) } out <- list() class(out) <- "glamlasso" out$alpha <- res$alpha[ , 1:endmodelno] out$coef <- res$Beta[ , 1:endmodelno] out$df <- res$df[1:endmodelno] out$dimcoef <- c(p1, p2, p3)[1:dimglam] out$dimobs <- c(n1, n2, n3)[1:dimglam] out$family <- family out$lambda <- res$lambda[1:endmodelno] out$spec <- paste("", dimglam,"-dimensional ", penalty," penalized ", family," GLAM") Iter <- list() Iter$bt_enter_inner <- res$btenterprox Iter$bt_iter_inner <- res$btiterprox Iter$bt_iter_outer <- res$btiternewt Iter$iter_mat <- res$Iter[1:endmodelno, ] Iter$iter <- sum(Iter$iter_mat, na.rm = TRUE) out$Iter <- Iter return(out) }
bposa<-function(m,n,n.chains,data) { cl<-match.call() cl1<-as.list(cl[-1]) if(cl1$data==deparse(substitute(catdata))){ data<-catdata[c(1:26),c(9:11)] }else{ data<-data } data1=function(d){ data1=matrix(ncol=ncol(d),nrow=nrow(d)) for(i in 1:nrow(d)) { for(j in 1:ncol(d)){ data1[i,j]=ifelse(is.na(d[i,j])==TRUE,1,d[i,j]) } } data1 } tim<-unname(unlist(data[1,c(m:n)])) data<-data1(data) data<-data[,m:n] N <- nrow(data) M <- n-m+1 Y <-data mdata<-list("N","M","Y", "tim") mreg105A<-function(){ for (i in 1:N){for (j in 1:M){Y[i,j]~dpois(mu[i,j]) log(mu[i,j])<-beta[1]+beta[2]*tim[j]+b1[i]+b2[i]*tim[j]}} for(i in 1:2){beta[i]~dnorm(0,.0001)} for (i in 1:N){b1[i]~dnorm(0,tau1)} for (i in 1:N){b2[i]~dnorm(0,tau2)} tau1~dgamma(0.001,.001) tau2~dgamma(0.001,.001) sigma1<-1/tau1 sigma2<-1/tau2 } jagsfit1 <- jags( model.file=mreg105A, data =mdata, n.chains=n.chains,parameters.to.save =c('beta','sigma1') ) jagsfit1 } utils::globalVariables(c("b2","tau1","tau2","catdata","log<-"))
JobProvider <- R6::R6Class( inherit = BaseProvider, 'JobProvider', public = list( locale = NULL, formats = NULL, allowed_locales = function() private$locales, initialize = function(locale = NULL) { if (!is.null(locale)) { super$check_locale(locale) check_locale_(locale, private$locales) self$locale <- locale } else { self$locale <- 'en_US' } self$formats <- parse_eval("job_formats_", self$locale) }, render = function() { super$random_element(self$formats) } ), private = list( locales = c("da_DK", "fa_IR", "fr_CH", "uk_UA", "ru_RU", "pl_PL", "en_US", "fr_FR", "hr_HR", "zh_TW", "fi_FI") ) )
getHDmembers <- function (data, maxrows = 10000, radius = NULL) { data <- as.matrix(data) n <- nrow(data) p <- ncol(data) if (is.null(radius)) radius <- 0.1/(log(n)^(1/p)) if (n <= maxrows) { cl <- partuniq(data) U <- unique(cl) m <- length(U) if (m != n) { members <- rep(list(NULL), m) j <- 0 for (u in U) { j <- j + 1 members[[j]] <- which(cl == u) } } else members <- as.list(1:n) } else { members <- rep(list(NULL), n) exemplars <- 1 members[[1]] <- 1 for (i in 2:n) { KNN <- get.knnx(data = data[exemplars, , drop = F], query = data[i, , drop = F], k = 1) m <- KNN$nn.index[1, 1] d <- KNN$nn.dist[1, 1] if (d < radius) { l <- exemplars[m] members[[l]] <- c(members[[l]], i) next } exemplars <- c(exemplars, i) members[[i]] <- i } } members <- members[!sapply(members, is.null)] exemplars <- sapply(members, function(x) x[[1]]) names(members) <- exemplars members }
pasteC <- function(...,collapse=", ",lastCol=" and ",quoteC=""){ inp <- list(...) chNa0 <- list(.seqCutStr("collapse",2),.seqCutStr("lastCol",2),.seqCutStr("quoteC",2)) chNa <- lapply(chNa0,function(x) stats::na.omit(match(x,names(inp)))[1]) if(any(!is.na(chNa[[1]]))) {collapse <- inp[[chNa[[1]]]]; inp <- inp[-chNa[[1]]]} if(any(!is.na(chNa[[2]]))) {lastCol <- inp[[chNa[[2]]]]; inp <- inp[-chNa[[2]]]} if(any(!is.na(chNa[[3]]))) {quoteC <- inp[[chNa[[3]]]]; inp <- inp[-chNa[[3]]]} .paQ <- function(x,quo) sapply(x,function(y) paste(quo,y,quo,sep="")) if(nchar(quoteC) >0) inp <- lapply(inp,.paQ,quoteC) if(length(unlist(inp)) >1) { out <- if(length(inp) >1) paste(unlist(inp[-length(inp)]),collapse=collapse) else NULL tmp <- inp[[length(inp)]] tmp <- list(tmp[-length(tmp)], tmp[length(tmp)]) out <- paste0(paste(c(out,tmp[[1]]),collapse=collapse),lastCol,tmp[[2]]) } else out <- as.character(unlist(inp)) out } .seqCutStr <- function(txt,startFr=1,reverse=TRUE){ nCh <- nchar(txt) out <- if(startFr > nCh) NULL else sapply(startFr:nCh, function(x) substr(txt,1,x)) if(reverse & length(out) >1) out <- rev(out) out }
rcox <- function(gm=NULL, vcc=NULL, ecc=NULL, type = c('rcon', 'rcor'), method = "ipm", fit=TRUE, data=NULL, S=NULL, n=NULL, Kstart=NULL, control=list(), details=1, trace=0){ type <- match.arg(type) method <- match.arg(method,c("ipm", "scoring", "matching", "ipms", "hybrid1")) modelSpec <- list(gm=gm, vcc=vcc, ecc=ecc) con <- list( vccfit = TRUE, eccfit = TRUE, vcov = "inf", nboot = 100, maxouter = 500, maxinner = 10, logL = FALSE, logLeps = 1e-6, deltaeps = 1e-3, hybrid1switch = 10, short = FALSE ) con[(namc <- names(control))] <- control gmN <- formula2names(gm) vccN <- formula2names(vcc) eccN <- formula2names(ecc) usedVars <- unique(unlist(c(gmN, vccN, eccN))) if (trace>=2) cat("..Building data representation\n") dataRep <- .buildDataRepresentation (data, S, n, usedVars, type, trace) nodes <- dataRep$nodes if (trace>=2) cat("..Building data representation - done\n") if (trace>=2) cat("..Building standard representation\n") stdRep <- .buildStandardRepresentation (gmN, vccN, eccN, dataNames=dataRep$dataNames, trace) vccN <- .addccnames(stdRep$vccN, type="vcc") eccN <- .addccnames(stdRep$eccN, type="ecc") if (trace>=2) cat("..Building internal representation\n") intRep <- .buildInternalRepresentation(vccN=vccN, eccN=eccN, dataNames=dataRep$dataNames, trace) ans <- structure(list(vcc = vccN, ecc = eccN, nodes = nodes, intRep = intRep, dataRep = dataRep, Kstart = Kstart, type = type, method = method, trace = trace, control = con ), class=c(type, "rcox")) if (fit){ ans$fitInfo <- fit(ans, method=method, trace=trace, returnModel=FALSE) } return(ans) } print.rcox <- function(x, ...){ cat(toupper(getSlot(x,"type")), "model: ") if (!is.null(x$fitInfo)){ cat("logL=", x$fitInfo$logL, " dimension=", dimension(x), " method=", x$method, " time=", fitInfo(x,"time"),sep='') } cat("\n") if (!(x$control$short)){ xcc <- getvcc(x) xcc <- getecc(x) xf <- names2formula(xcc) xs <- formula2string(xf) cat("vcc: ",paste(unlist(xs),collapse=", "),"\n") if (length(xcc)){ xf <- names2formula(xcc) xs <- formula2string(xf) cat("ecc: ",paste(unlist(xs),collapse=", "),"\n") } } } .buildDataRepresentation <- function(data=NULL, S=NULL, n=NULL, nodes, type="rcon", trace=2){ if (is.null(data) & is.null(S)){ stop("No data given...\n") } if (!is.null(data)){ dataNames <- names(data) S <- cov(data) n <- nrow(data) } else { dataNames <- colnames(S) } nodes <- dataNames[sort(match(nodes, dataNames))] S <- S[nodes, nodes] ans <- list(S=S, n=n, dataNames=rownames(S), nodes=nodes) return(ans) } .buildStandardRepresentation <- function(gmN, vccN, eccN, dataNames, trace=2){ t0 <- proc.time() idx <- unlistPrim(lapply(gmN, length)) gmNvertices <- lapply(uniquePrim(unlistPrim(gmN)),list) x <- unlist(lapply(gmN[idx>1], names2pairs),recursive=FALSE) gmNedges <- lapply(x, list) eccN <- c(eccN, gmNedges) uuu <- unlistPrim(eccN) uuu <- lapply(uuu, as.list) vccN <- uniquePrim(c(uuu, vccN, gmNvertices)) vccI <- names2indices(vccN, dataNames, matrix=FALSE) eccI <- names2indices(eccN, dataNames, matrix=FALSE) xxxx2 <- lapply(vccI, function(x3) {z<-do.call("rbind",x3); z[,1]<-z[,1]*10000; rowSumsPrim(z)}) ri <- which(remove_redundant(xxxx2, index=TRUE)>0) vccN <- vccN[ri] if (length(eccI)){ xxxx2 <- lapply(eccI, function(x3) {z<-do.call("rbind",x3); z[,1]<-z[,1]*10000; rowSumsPrim(z)}) ri <- which(remove_redundant(xxxx2, index=TRUE)>0) eccN <- eccN[ri] } varNames <- uniquePrim(unlistPrim(c(vccN,eccN))) ans <- list(vccN=vccN, eccN=eccN, varNames=varNames) return(ans) } .redundant.index <- function(xxxx){ if (length(xxxx)==0) return(FALSE) else if (length(xxxx)==1) return(TRUE) xxxx2 <- lapply(xxxx, function(x3) {z<-do.call("rbind",x3); z[,1]<-z[,1]*10000; rowSums(z)}) ind <- rep(TRUE, length(xxxx2)) for (i in 1:length(xxxx2)){ xi <- xxxx2[[i]] for (j in 1:length(xxxx2)){ if (i != j){ xj <- xxxx2[[j]] if (subsetof(xj,xi) && ind[i]) ind[j] <- FALSE } } } ind } .buildInternalRepresentation <- function(vccN, eccN, dataNames, trace=2){ vccI <- names2indices(vccN, dataNames, matrix=TRUE) eccI <- names2indices(eccN, dataNames, matrix=TRUE) eccV <- indices2vectors(eccI) vccV <- indices2vectors(vccI) ans <- list(vccI=vccI, eccI=eccI, vccV=vccV, eccV=eccV) return(invisible(ans)) } summary.rcox <- function(object, type="coef",...){ type <- match.arg(type, c("coef", "K", "KC", "ACA")) m <- object vn <- unlist(lapply(getcc(object),names)) cctype <- c(rep("vcc", length(getSlot(m,"vcc"))), rep("ecc", length(getSlot(m,"ecc")))) ans <- list(type=type, self = object, vcc = getSlot(m, "vcc"), ecc = getSlot(m, "ecc"), logL = fitInfo(m, "logL"), dimension = dimension(m), method = getSlot(m, "method"), time = fitInfo(m, "time"), short = object$control$short ) switch(type, "coef"={ cm <- as.numeric(coef(m)) if (!is.null(fitInfo(m)$J)){ V <- vcov(m) vv <- (diag(V)) X2 <- cm^2 / vv p <- 1 - pchisq(X2, 1) v <- data.frame(cctype=cctype, cc=vn, estimate=cm, stderr=sqrt(vv), X2=X2, p=p) } else { v <- data.frame(cctype=cctype, cc=vn, estimate=cm) } ans$coefficients <- v rownames(v) <- NULL }, "K"={ ans$K <- fitInfo(m, "K") }, "KC"={ KC <- fitInfo(m, "K") dKC <- diag(KC) CorMatrix <- -cov2cor(KC) KC[lower.tri(KC)] <- CorMatrix[lower.tri(CorMatrix)] diag(KC) <- sqrt(dKC) ans$KC <- KC }, "ACA"={ K <- fitInfo(m," K") C <- -cov2cor(K) diag(C) <- 1 ans$A <- sqrt(diag(K)) ans$C <- C } ) class(ans) <- "summary.rcox" ans } print.summary.rcox <- function(x, ...){ print(x$self) switch(x$type, "coef"={ cat("\n") print(x$coefficients) if (!x$short){ cat("\n");print(getvcc(x));print(getecc(x)) } }, "K"={ print(x$K) }, "KC"={ print(x$KC) }, "ACA"={ print(x$A) print(x$C) } ) return(invisible(x)) }
library(leaflet.extras) leaf <- leaflet() %>% addTiles() leaf %>% addPulseMarkers( lng = -118.456554, lat = 34.078039, label = "This is a label", icon = makePulseIcon(heartbeat = 0.5)) cities <- read.csv(textConnection(" City,Lat,Long,Pop Boston,42.3601,-71.0589,645966 Hartford,41.7627,-72.6743,125017 New York City,40.7127,-74.0059,8406000 Philadelphia,39.9500,-75.1667,1553000 Pittsburgh,40.4397,-79.9764,305841 Providence,41.8236,-71.4222,177994")) library(dplyr) cities <- cities %>% mutate(PopCat = ifelse(Pop < 500000, "blue", "red")) leaflet(cities) %>% addTiles() %>% addPulseMarkers(lng = ~Long, lat = ~Lat, label = ~City, icon = makePulseIcon()) icon.pop <- pulseIcons(color = ifelse(cities$Pop < 500000, "blue", "red"), heartbeat = ifelse(cities$Pop < 500000, "0.8", "0.4")) leaflet(cities) %>% addTiles() %>% addPulseMarkers(lng = ~Long, lat = ~Lat, label = ~City, icon = icon.pop) popIcons <- pulseIconList( blue = makePulseIcon(color = "blue"), red = makePulseIcon(color = "red") ) leaflet(cities) %>% addTiles() %>% addPulseMarkers(lng = ~Long, lat = ~Lat, label = ~City, labelOptions = rep(labelOptions(noHide = T), nrow(cities)), icon = ~popIcons[PopCat] )
pwe_error_checks <- function(effect_vals, hist_control_data, rand_control_diff, time_vec, censor_value, alpha) { hist_chk <- class(hist_control_data) rcp_chk <- is.null(rand_control_diff) tv_chk <- is.null(time_vec) for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("historic_sim() requires effect_vals to be numeric.") if (eff_val <= 0) stop("For pwe, historic_sim() requires effect_vals to represent Hazard Ratios which must be positive numbers") } if (hist_chk == "data.frame") { colnamevals <- colnames(hist_control_data) colnamechk <- (colnamevals == c("id", "treatment", "event_time", "status", "indicator")) if (sum(colnamechk) != 5) { stop("historic_sim() requires hist_control_data to have columns: id, treatment, event_time, status, and indicator.") } if (sum(colnamechk) == 5) { if (!is.numeric(hist_control_data$event_time)) { stop("historic_sim() requires hist_control_data$event_time to be positive numeric data.") } if (is.numeric(hist_control_data$event_time)) { if (min(hist_control_data$event_time) <= 0) { stop("historic_sim() requires hist_control_data$event_time to be positive numeric data.") } } if (!is.numeric(hist_control_data$treatment)) { stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.") } if (is.numeric(hist_control_data$treatment)) { trt_levels <- names(table(hist_control_data$treatment)) if (length(trt_levels) > 2 | (trt_levels[1] != "0" & trt_levels[2] != "1")) { stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.") } } if (!is.numeric(hist_control_data$status)) { stop("historic_sim() requires hist_control_data$status to be numeric 0/1 data.") } if (is.numeric(hist_control_data$status)) { trt_levels <- names(table(hist_control_data$status)) if (length(trt_levels) > 2 | (trt_levels[1] != "0" & trt_levels[2] != "1")) { stop("historic_sim() requires hist_control_data$status to be numeric 0/1 data.") } } if (!is.numeric(hist_control_data$indicator)) { stop("historic_sim() requires hist_control_data$indicator to be a vector of 2s.") } if (2*dim(hist_control_data)[1] != sum(hist_control_data$indicator)) { stop("historic_sim() requires hist_control_data$indicator to be a vector of 2s.") } } } if (rcp_chk == FALSE) { for (Rand_cp in rand_control_diff) { if (!is.numeric(Rand_cp)) stop("historic_sim() requires rand_control_diff to be numeric.") if (Rand_cp <= 0) stop("historic_sim() requires rand_control_diff to be Hazard Ratios, so they must be positive.") } } if (tv_chk == TRUE) { stop("historic_sim() requires at least one value in time_vec for a pwe model.") } if (tv_chk == FALSE) { for (tvcp in time_vec) { if (!is.numeric(tvcp)) stop("historic_sim() requires time_vec to be numeric.") if (tvcp <= 0) stop("historic_sim() requires time_vec to be positive.") } } if (!is.null(censor_value) == TRUE) { if (!is.numeric(censor_value)) stop("historic_sim() requires censor_value to be numeric.") if (censor_value <= 0) stop("historic_sim() requires censor_value to be positive.") } if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("historic_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("historic_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } } pwe_error_checks_simple <- function(effect_vals, time_vec, control_parms, censor_value, alpha) { tv_chk <- is.null(time_vec) tv_len <- length(time_vec) rv_chk <- is.null(control_parms) rv_len <- length(control_parms) for (eff_val in effect_vals) { if (!is.numeric(eff_val)) stop("simple_sim() requires effect_vals to be numeric.") if (eff_val <= 0) stop("For pwe, simple_sim() requires effect_sizes to represent Hazard Ratios which must be positive numbers") } if (tv_chk == TRUE) { stop("simple_sim() requires at least one value in time_vec for a pwe model.") } if (tv_chk == FALSE) { for (tvcp in time_vec) { if (!is.numeric(tvcp)) stop("simple_sim() requires time_vec to be numeric.") if (tvcp <= 0) stop("simple_sim() requires time_vec to be positive.") } } if (rv_chk == TRUE) { stop("simple_sim() requires at least two value in control_parms for a pwe model.") } if (rv_chk == FALSE) { if (length(control_parms) < 2) { stop("simple_sim() requires at least two value in control_parms for a pwe model.") } if (rv_len != (tv_len + 1)) { stop("simple_sim() requires control_parms to have one more element than time_vec") } for (rvcp in control_parms) { if (!is.numeric(rvcp)) stop("simple_sim() requires control_parms to be numeric.") if (rvcp <= 0) stop("simple_sim() requires control_parms to be positive.") } } if (!is.null(censor_value) == TRUE) { if (!is.numeric(censor_value)) stop("simple_sim() requires censor_value to be numeric.") if (censor_value <= 0) stop("simple_sim() requires censor_value to be positive.") } if (!is.null(alpha) == TRUE) { if (!is.numeric(alpha)) stop("simple_sim() requires alpha to be numeric.") if (alpha <= 0 | alpha >= 1) stop("simple_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.") } }
prepare_edges <- function(g, k = NULL, distance = 1, create_edge_name = TRUE){ g_list <- igraph::as_data_frame(g, what = "both") edges_df <- g_list$edges if(!is.null(k)){ edges_df <- edges_df %>% dplyr::mutate( k = k) } if(!is.null(distance)){ edges_df <- edges_df %>% dplyr::mutate( distance = distance) } if(create_edge_name){ edges_df <- edges_df %>% dplyr::mutate( edge_name = paste(from, to, sep ="-")) } g2 <- igraph::graph_from_data_frame(edges_df, directed = FALSE, vertices = g_list$vertices) return(g2) }
set.seed(1010093) pValues2 <- rep(NA,1000) for(i in 1:1000){ x <- rnorm(20) if(i <= 500){y <- rnorm(20)}else{ y <- rnorm(20,mean=2*x)} pValues2[i] <- summary(lm(y ~ x))$coeff[2,4] } trueStatus <- rep(c("zero","not zero"),each=500)
load(system.file("extdata", "study_data.RData", package = "dataquieR")) sd1 <- study_data load(system.file("extdata", "meta_data.RData", package = "dataquieR")) md1 <- meta_data code_labels <- read.csv2(system.file("extdata", "Missing-Codes-2020.csv", package = "dataquieR"), stringsAsFactors = FALSE, na.strings = c()) item_miss <- com_item_missingness(study_data = sd1, meta_data = md1, label_col = 'LABEL', show_causes = TRUE, cause_label_df = code_labels, include_sysmiss = TRUE, threshold_value = 80 ) View(item_miss$ReportSummaryTable) View(md0) View(mdmd1) View(md1) View(item_miss$ReportSummaryTable) x <- (item_miss$ReportSummaryTable) rownames(x) rownames(x) <- x$Variables x$Variables <- NULL x x <- x / X$N x <- x / x$N x x$N <- NULL x <- x * 100 View(x) melt(x) x$Variable <- rownames(x) x melt(x, measure.vars = setdiff(colnames(x, c("Variable")))) melt(x) ggballoonplot(melt(x)) apm <- pro_applicability_matrix(study_data, meta_data) print(item_miss$ReportSummaryTable, dt = TRUE) print(apm$ReportSummaryTable, dt = TRUE) item_missc <- com_item_missingness(study_data = sd1, resp_vars = c("CENTER_0"), meta_data = md1, label_col = 'LABEL', show_causes = TRUE, cause_label_df = code_labels, include_sysmiss = TRUE, threshold_value = 80 ) item_misss <- com_item_missingness(study_data = sd1, resp_vars = c("SEX_0"), meta_data = md1, label_col = 'LABEL', show_causes = TRUE, cause_label_df = code_labels, include_sysmiss = TRUE, threshold_value = 80 ) item_missa <- com_item_missingness(study_data = sd1, resp_vars = c("AGE_0"), meta_data = md1, label_col = 'LABEL', show_causes = TRUE, cause_label_df = code_labels, include_sysmiss = TRUE, threshold_value = 80 ) item_missb <- com_item_missingness(study_data = sd1, resp_vars = c("SBP_0"), meta_data = md1, label_col = 'LABEL', show_causes = TRUE, cause_label_df = code_labels, include_sysmiss = TRUE, threshold_value = 80 ) item_miss_combined <- rbind(item_missa$ReportSummaryTable, item_missb$ReportSummaryTable, item_missc$ReportSummaryTable, item_misss$ReportSummaryTable) item_miss_combined print(item_miss_combined, dt = TRUE) print(item_missa$ReportSummaryTable, dt = TRUE) print(item_missb$ReportSummaryTable, dt = TRUE) print(item_missc$ReportSummaryTable, dt = TRUE) print(item_misss$ReportSummaryTable, dt = TRUE)
library(testit) assert( 'parse_params() parses chunk options to a list', identical(parse_params('a-s-d,b=TRUE,c=def'), alist(label = 'a-s-d', b = TRUE, c = def)), has_error(parse_params('a,b')), has_error(parse_params('a,b,c=qwer')), identical(parse_params('a,opt=c(1,3,5)'), alist(label = 'a', opt = c(1, 3, 5))), identical(parse_params('label="xx",opt=zz'), alist(label = 'xx', opt = zz)), identical(parse_params('label=foo'), alist(label = 'foo')), identical(parse_params('a,b=2,c="qwer",asdf="efg"'), alist(label = 'a', b = 2, c = 'qwer', asdf = 'efg')), identical(parse_params('2a'), alist(label = '2a')), identical(parse_params('abc-function,fig.path="foo/bar-"'), alist(label = 'abc-function', fig.path = "foo/bar-")) ) opts_knit$set(out.format = 'markdown') assert( 'parse_params() parses the language engine from ```{lang}', identical( parse_block(NULL, '', 'r, foo, a=1,')$params, alist(label = 'foo', a = 1) ), identical( parse_block(NULL, '', 'Rcpp, foo, a=1,')$params, alist(label = 'foo', a = 1, engine = 'Rcpp') ) ) res = split_file( c('abc', '```{r foo}', '1+1', '```{r bar}', '2+2', '```', 'def'), patterns = all_patterns$md ) assert( 'split_file() treats ``` as part of code chunk instead of beginning of text chunk', knit_code$get('foo') == '1+1', knit_code$get('bar') == '2+2', identical(res[[4]][['input']], 'def') ) opts_knit$restore() knit_code$restore(); knit_concord$restore() res = parse_inline(c('aaa \\Sexpr{x}', 'bbb \\Sexpr{NA} and \\Sexpr{1+2}', 'another expression \\Sexpr{rnorm(10)}'), all_patterns$rnw) assert( 'parse_inline() parses inline text', identical(res$code, c('x', 'NA', '1+2', 'rnorm(10)')), identical(nchar(res$input), 81L), identical(parse_inline('\\Sexpr{}', all_patterns$rnw)$code, character(0)), identical(parse_inline('<!--rinline "<a>" -->', all_patterns$html)$code, ' "<a>" ') ) res = parse_inline('inline expressions `r pi+1`, +r cos(0)+ in AsciiDoc', all_patterns$asciidoc) assert( 'both `r expression` and +r expression+ work for AsciiDoc', identical(res$code, c('pi+1', 'cos(0)')) ) knit_code$restore() read_chunk(lines = c('1+1')) assert( 'read_chunk() does not discard code without chunk headers', identical(knit_code$get(), list('unnamed-chunk-1' = '1+1')) ) knit_code$restore() read_chunk(lines = c(' assert( 'read_chunk() can identify chunk labels', identical(knit_code$get(), list(foo = '1+1')) ) knit_code$restore() knit_code$restore(list( a = '1+1', b = '2-2', c = c('if (T)', ' <<a>>'), d = c('function() {', ' <<c>>', '}') )) pc = function(x) parse_chunk(x, all_patterns$rnw$ref.chunk) assert( 'parse_chunk() preserves indentation', identical(pc(c('3*3', '<<a>>', ' <<b>>', 'if (T)', ' <<a>>')), c("3*3", "1+1", " 2-2", "if (T)", " 1+1" )), identical(pc('<<d>>'), c('function() {', ' if (T)', ' 1+1', '}')) ) knit_code$restore()
TableStyle <- R6::R6Class("TableStyle", public = list( initialize = function(parentTable, styleName=NULL, declarations= NULL) { if(parentTable$argumentCheckMode > 0) { checkArgument(parentTable$argumentCheckMode, FALSE, "TableStyle", "initialize", parentTable, missing(parentTable), allowMissing=FALSE, allowNull=FALSE, allowedClasses="BasicTable") checkArgument(parentTable$argumentCheckMode, FALSE, "TableStyle", "initialize", styleName, missing(styleName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") checkArgument(parentTable$argumentCheckMode, FALSE, "TableStyle", "initialize", declarations, missing(declarations), allowMissing=TRUE, allowNull=TRUE, allowedClasses="list", allowedListElementClasses=c("character", "integer", "numeric")) } private$p_parentTable <- parentTable if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyle$new", "Creating new Table Style...", list()) private$p_declarations <- list() private$p_name <- styleName if(!is.null(declarations)) { if(length(declarations)>0) { nms <- names(declarations) for(i in 1:length(declarations)) { nme <- nms[i] val <- declarations[[i]] if(is.null(nme)) next if(is.null(val)) next private$p_declarations[[tolower(trimws(nme))]] <- as.character(val) } } } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyle$new", "Created new Table Style") }, setPropertyValue = function(property=NULL, value=NULL) { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyle", "setPropertyValue", property, missing(property), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyle", "setPropertyValue", value, missing(value), allowMissing=FALSE, allowNull=FALSE, allowedClasses=c("character", "integer", "numeric")) } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyle$setPropertyValue", "Setting property value...", list(property=property, value=value)) private$p_declarations[[tolower(trimws(property))]] <- value if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyle$setPropertyValue", "Set property value.") return(invisible()) }, setPropertyValues = function(declarations=NULL) { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyle", "setPropertyValues", declarations, missing(declarations), allowMissing=FALSE, allowNull=FALSE, allowedClasses="list", allowedListElementClasses=c("character", "integer", "numeric")) } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyle$setPropertyValues", "Setting property values...") nms <- names(declarations) if(length(nms)==0) return(invisible()) for(i in 1:length(nms)) { property <- nms[i] if(is.null(property)) stop("TableStyle$setPropertyValues(): NULL style property encountered.") value <- declarations[[i]] private$p_declarations[[tolower(trimws(property))]] <- value } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyle$setPropertyValues", "Set property values.") return(invisible()) }, getPropertyValue = function(property=NULL) { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyle", "getPropertyValue", property, missing(property), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyle$getPropertyValue", "Getting property value...", list(property=property)) val <- private$p_declarations[[tolower(trimws(property))]] if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyle$getPropertyValue", "Got property value.") return(invisible(val)) }, asCSSRule = function(selector=NULL) { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyle", "asCSSRule", selector, missing(selector), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyle$asCSSRule", "Getting CSS rule...") cssRule <- NULL if(!is.null(selector)) cssRule <- paste0(selector, " {") if(length(private$p_declarations)>0) { nms <- names(private$p_declarations) for(i in 1:length(private$p_declarations)) { if(length(nms[i])==0) stop("TableStyle$asCSSRule(): Encountered a style declaration without a name.", call. = FALSE) if(startsWith(tolower(nms[i]), "xl-")) next cssRule <- paste0(cssRule, nms[i], ": ", private$p_declarations[[i]], "; ") } } if(!is.null(selector)) cssRule <- paste0(cssRule, "}") if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyle$asCSSRule", "Got CSS rule.") return(invisible(cssRule)) }, asNamedCSSStyle = function(styleNamePrefix=NULL) { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyle", "asNamedCSSStyle", styleNamePrefix, missing(styleNamePrefix), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyle$asCSSRule", "Getting named CSS rule...") if(is.null(styleNamePrefix)) { selector <- paste0(".", private$p_name) } else { selector <- paste0(".", styleNamePrefix, private$p_name) } cssRule <- self$asCSSRule(selector=selector) if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyle$asNamedCSSStyle", "Got named CSS rule.") return(invisible(cssRule)) }, getCopy = function(newStyleName=NULL) { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyle", "getCopy", newStyleName, missing(newStyleName), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } copy <- TableStyle$new(parentTable=private$p_parentTable, styleName=newStyleName, declarations=private$p_declarations) return(invisible(copy)) }, asList = function() { lst <- list( name = private$p_name, declarations = private$p_declarations ) return(invisible(lst)) }, asJSON = function() { if (!requireNamespace("jsonlite", quietly = TRUE)) { stop("The jsonlite package is needed to convert to JSON. Please install the jsonlite package.", call. = FALSE) } jsonliteversion <- utils::packageDescription("jsonlite")$Version if(numeric_version(jsonliteversion) < numeric_version("1.1")) { stop("Version 1.1 or above of the jsonlite package is needed to convert to JSON. Please install an updated version of the jsonlite package.", call. = FALSE) } return(jsonlite::toJSON(self$asList())) } ), active = list( name = function(value) { return(invisible(private$p_name)) }, declarations = function(value) { return(invisible(private$p_declarations)) } ), private = list( p_parentTable = NULL, p_name = NULL, p_declarations = NULL ) )
lnorms <- function(n, mean = 2, var = 1) { nmeans <- log(mean) - 0.5 * log(var / mean^2 + 1) nvars <- log(var / mean^2 + 1) normals <- rnorm(n) * sqrt(nvars) + nmeans lns <- exp(normals) lns }
context("ncbi_children") test_that("ncbi_children returns correct class and result", { skip_on_cran() vcr::use_cassette("ncbi_children", { tt <- ncbi_children(id = '4751') tt2 <- ncbi_children(id = '4751', out_type = 'uid') }) expect_is(tt, "list") expect_is(tt[[1]], "data.frame") expect_equal(ncol(tt[[1]]), 3) expect_is(tt2, "list") expect_is(tt2[[1]], "character") expect_error(ncbi_children(name = 'Ilex', id = '4751')) expect_equal(ncbi_children(name = NA)[[1]], NA) expect_equal( unname(sapply(ncbi_children('dragon', db='ncbi')[[1]], class)), c('character', 'character', 'character') ) }) test_that("ncbi_children does remove some ambiguous taxa", { skip_on_cran() vcr::use_cassette("ncbi_children_ambiguous", { subsp <- ncbi_children(id = '28901') sp <- ncbi_children(id = '2508041') }) expect_is(subsp, "list") expect_is(subsp[[1]], "data.frame") expect_is(sp, "list") expect_is(sp[[1]], "data.frame") }) test_that("ncbi_children accepts numeric and character class ids", { skip_on_cran() vcr::use_cassette("ncbi_children_id_class_check", { tt <- ncbi_children(id = 4751) tt2 <- ncbi_children(id = '4751') }) expect_identical(tt, tt2) })
NULL xray <- function(config = list()) { svc <- .xray$operations svc <- set_config(svc, config) return(svc) } .xray <- list() .xray$operations <- list() .xray$metadata <- list( service_name = "xray", endpoints = list("*" = list(endpoint = "xray.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "xray.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "xray.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "xray.{region}.sc2s.sgov.gov", global = FALSE)), service_id = "XRay", api_version = "2016-04-12", signing_name = "xray", json_version = "", target_prefix = "" ) .xray$service <- function(config = list()) { handlers <- new_handlers("restjson", "v4") new_service(.xray$metadata, handlers, config) }
mendelianCheck = function(x, remove = FALSE, verbose = !remove) { if (is.singleton(x) || !hasMarkers(x)) return(if(remove) x else numeric(0)) nucs = subnucs(x) chromX = which(isXmarker(x)) chromAUT = .mysetdiff(seq_markers(x), chromX) errorlist = vector(length = pedsize(x), mode = "list") names(errorlist) = labels(x) nuc_errors = numeric() if (length(chromAUT) > 0) { allelematr = do.call(cbind, x$MARKERS[chromAUT]) for (sub in nucs) { fa = allelematr[sub$father, ] mo = allelematr[sub$mother, ] offs = sub$children labs = attr(sub, 'labels') for (of in offs) { triopass = trioCheckFast(fa, mo, allelematr[of, ]) if (all(triopass)) next new_errs = chromAUT[!triopass] errorlist[[of]] = c(errorlist[[of]], new_errs) if (verbose) message(sprintf("Individual `%s` incompatible with parents at markers: %s", labs[of], toString(new_errs))) } if (length(offs) == 1) next sibpass = sibshipCheck(allelematr[offs, ]) if(all(sibpass)) next new_errs = chromAUT[!sibpass] nuc_errors = c(nuc_errors, new_errs) if (verbose) message(sprintf("Sibship with parents `%s` and `%s` have too many alleles at markers: %s", labs[sub$father], labs[sub$mother], toString(new_errs))) } } if (length(chromX) > 0) { sex = x$SEX allelematr = do.call(cbind, x$MARKERS[chromX]) even = 2 * seq_along(chromX) odd = even - 1 maleXhet = allelematr[sex == 1, odd, drop = FALSE] != allelematr[sex == 1, even, drop = FALSE] if(any(maleXhet)) { maleXhet_errors = which(maleXhet, arr.ind = TRUE) error_males_int = which(sex == 1)[maleXhet_errors[, 1]] error_markers = maleXhet_errors[, 2] for(i in unique.default(error_males_int)) { new_errs = chromX[error_markers[error_males_int == i]] errorlist[[i]] = c(errorlist[[i]], new_errs) if (verbose) message(sprintf("Male `%s` is heterozygous at markers: %s", labels(x)[i], toString(new_errs))) } } for (sub in nucs) { fa = allelematr[sub$father, ] mo = allelematr[sub$mother, ] offs = sub$children labs = attr(sub, 'labels') for (of in offs) { ofdat = allelematr[of, ] if (sex[of] == 1) { maleXpass = maleXCheck(mo, ofdat) if (all(maleXpass)) next new_errs = chromX[!maleXpass] errorlist[[of]] = c(errorlist[[of]], new_errs) if (verbose) message(sprintf("Male `%s` incompatible with mother at markers: %s", labs[of], toString(new_errs))) } else { triopass = trioCheckFast(fa, mo, ofdat) if (all(triopass)) next new_errs = chromX[!triopass] errorlist[[of]] = c(errorlist[[of]], new_errs) if (verbose) message(sprintf("Female `%s` incompatible with parents at markers: %s", labs[of], toString(new_errs))) } } next if (length(offs) <= 2) next sibpass = sibshipCheck(allelematr[offs, ]) if(all(sibpass)) next new_errs = chromX[!sibpass] nuc_errors = c(nuc_errors, new_errs) if (verbose) message(sprintf("Sibship with parents `%s` and `%s` have too many alleles at markers: %s", labs[sub$father], labs[sub$mother], toString(new_errs))) } } err_index = sort.int(unique.default(c(unlist(errorlist), nuc_errors))) if (remove) return(removeMarkers(x, err_index)) else return(err_index) } trioCheckFast = function(fa, mo, of) { even = 2 * seq_len(length(fa)/2) odd = even - 1 fa_odd = fa[odd] fa_even = fa[even] mo_odd = mo[odd] mo_even = mo[even] of_odd = of[odd] of_even = of[even] fa0 = (fa_odd == 0 | fa_even == 0) mo0 = (mo_odd == 0 | mo_even == 0) of_odd0 = (of_odd == 0) of_even0 = (of_even == 0) ff1 = (fa0 | of_odd0 | of_odd == fa_odd | of_odd == fa_even) ff2 = (fa0 | of_even0 | of_even == fa_odd | of_even == fa_even) mm1 = (mo0 | of_odd0 | of_odd == mo_odd | of_odd == mo_even) mm2 = (mo0 | of_even0 | of_even == mo_odd | of_even == mo_even) (ff1 & mm2) | (ff2 & mm1) } maleXHomoz = function(of) { even = 2 * seq_len(length(of)/2) odd = even - 1 of[odd] == of[even] } maleXCheck = function(mo, of) { even = 2 * seq_len(length(of)/2) odd = even - 1 mo_odd = mo[odd] mo_even = mo[even] of = of[odd] mo0 = (mo_odd == 0 | mo_even == 0) of == 0 | mo0 | of == mo_odd | of == mo_even } sibshipCheck = function(offs) { even = 2 * seq_len(ncol(offs)/2) unlist(lapply(even, function(i) { genos = offs[, (i - 1):i] homoz_alleles = genos[genos[,1] == genos[,2], 1] n_homoz = length(.mysetdiff(homoz_alleles, 0)) n_alleles = length(.mysetdiff(genos, 0)) n_alleles <= (4 - n_homoz) })) }
df <- data_frame(x = 1:3, y = 3:1) p <- ggplot(df, aes(x, y)) + geom_point() p_col <- ggplot(df, aes(x, y, colour = factor(x))) + geom_point() test_that("setting parameters makes one row df", { b <- p + geom_hline(yintercept = 1.5) expect_equal(layer_data(b, 2)$yintercept, 1.5) b <- p + geom_vline(xintercept = 1.5) expect_equal(layer_data(b, 2)$xintercept, 1.5) b <- p + geom_abline() expect_equal(layer_data(b, 2)$intercept, 0) expect_equal(layer_data(b, 2)$slope, 1) b <- p + geom_abline(slope = 0, intercept = 1) expect_equal(layer_data(b, 2)$intercept, 1) expect_equal(layer_data(b, 2)$slope, 0) }) test_that("setting aesthetics generates one row for each input row", { b <- p + geom_hline(aes(yintercept = 1.5)) expect_equal(layer_data(b, 2)$yintercept, rep(1.5, 3)) b <- p + geom_vline(aes(xintercept = 1.5)) expect_equal(layer_data(b, 2)$xintercept, rep(1.5, 3)) b <- p + geom_abline(aes(slope = 0, intercept = 1)) expect_equal(layer_data(b, 2)$intercept, rep(1, 3)) expect_equal(layer_data(b, 2)$slope, rep(0, 3)) })
expected <- eval(parse(text="structure(list(), .Names = character(0))")); test(id=0, code={ argv <- eval(parse(text="list(NULL)")); .Internal(options(argv[[1]])); }, o=expected);
test_that("`str_can_be_numeric()` works", { expect_true(str_can_be_numeric("3")) expect_true(str_can_be_numeric("5 ")) expect_equal(str_can_be_numeric(c("1a", "abc")), rep(FALSE, 2)) expect_equal(str_can_be_numeric(character()), logical()) expect_equal(str_can_be_numeric(numeric()), logical()) })
.estimate2 <- function(object, epsilon, n.cluster, name.param, name.endogenous, name.meanparam, name.varparam, index.Omega, adjust.Omega, adjust.n, tol, n.iter, trace){ Omega <- object$conditionalMoment$Omega dmu <- object$conditionalMoment$dmu dOmega <- object$conditionalMoment$dOmega name.hybridparam <- intersect(name.meanparam, name.varparam) n.param <- length(name.param) n.meanparam <- length(name.meanparam) n.varparam <- length(name.varparam) n.hybridparam <- length(name.hybridparam) n.endogenous <- length(name.endogenous) grid.meanparam <- .combination(name.meanparam, name.meanparam) n.grid.meanparam <- NROW(grid.meanparam) grid.varparam <- .combination(name.varparam, name.varparam) n.grid.varparam <- NROW(grid.varparam) name2num <- setNames(1:n.param,name.param) if(!all(name2num[grid.meanparam[,1]]-name2num[grid.meanparam[,2]]>=0)){ stop("Incorrect allocation of the computation of the information matrix (mean parameter) \n") } name2num <- setNames(1:n.param,name.param) if(!all(name2num[grid.varparam[,1]]-name2num[grid.varparam[,2]]>=0)){ stop("Incorrect allocation of the computation of the information matrix (variance parameter) \n") } leverage <- matrix(NA, nrow = n.cluster, ncol = n.endogenous, dimnames = list(NULL, name.endogenous)) ls.dmu <- vector(mode = "list", length = n.cluster) for(iC in 1:n.cluster){ if(is.null(index.Omega)){ leverage[iC,] <- 0 ls.dmu[[iC]] <- matrix(0, nrow = n.param, ncol = n.endogenous, dimnames = list(name.param, name.endogenous)) ls.dmu[[iC]][name.meanparam,] <- do.call(rbind, lapply(dmu[name.meanparam],function(x){x[iC,]})) }else{ leverage[iC,index.Omega[[iC]]] <- 0 ls.dmu[[iC]] <- matrix(0, nrow = n.param, ncol = length(index.Omega[[iC]]), dimnames = list(name.param, name.endogenous[index.Omega[[iC]]])) ls.dmu[[iC]][name.meanparam,] <- do.call(rbind, lapply(dmu[name.meanparam],function(x){x[iC,index.Omega[[iC]]]})) } } if(any(eigen(Omega)$value<=0)){ stop("the residual variance-covariance matrix is not positive definite \n") } if(is.null(index.Omega)){ n.corrected <- rep(n.cluster, n.endogenous) }else{ n.corrected <- NULL } ls.Psi <- vector(mode = "list", length = n.cluster) Omega.adj <- Omega if(!adjust.n){ epsilon.adj <- epsilon } if(trace>0){ cat("* Reconstruct estimated information matrix ") } iInfo <- .information2(dmu = dmu, dOmega = dOmega, Omega = Omega, n.corrected = n.corrected, leverage = leverage, index.Omega = index.Omega, n.cluster = n.cluster, grid.meanparam = grid.meanparam, n.grid.meanparam = n.grid.meanparam, grid.varparam = grid.varparam, n.grid.varparam = n.grid.varparam, name.param = name.param, n.param = n.param) iVcov.param <- try(chol2inv(chol(iInfo)), silent = TRUE) if(inherits(iVcov.param, "try-error")){ iVcov.param <- solve(iInfo) } if(trace>0){ cat("- done \n") } if(adjust.Omega || adjust.n){ if(trace>0){ cat("* iterative small sample correction: ") } iIter <- 0 iTol <- Inf Omega_save <- Omega iOmega.adj <- Omega.adj }else{ iIter <- Inf iTol <- -Inf } while(iIter < n.iter & iTol > tol){ if(trace>0){ cat("*") } Psi <- matrix(0, nrow = n.endogenous, ncol = n.endogenous, dimnames = list(name.endogenous, name.endogenous)) M.countCluster <- matrix(0, nrow = n.endogenous, ncol = n.endogenous, dimnames = list(name.endogenous, name.endogenous)) for(iC in 1:n.cluster){ ls.Psi[[iC]] <- t(ls.dmu[[iC]]) %*% iVcov.param %*% ls.dmu[[iC]] if(is.null(index.Omega)){ Psi <- Psi + ls.Psi[[iC]] M.countCluster <- M.countCluster + 1 }else{ Psi[index.Omega[[iC]],index.Omega[[iC]]] <- Psi[index.Omega[[iC]],index.Omega[[iC]]] + ls.Psi[[iC]] M.countCluster[index.Omega[[iC]],index.Omega[[iC]]] <- M.countCluster[index.Omega[[iC]],index.Omega[[iC]]] + 1 } } for(iPsi in 1:length(Psi)){ if(M.countCluster[iPsi]>0){ Psi[iPsi] <- Psi[iPsi]/M.countCluster[iPsi] } } if(adjust.n){ epsilon.adj <- .adjustResiduals(Omega = Omega.adj, Psi = Psi, epsilon = epsilon, index.Omega = index.Omega, name.endogenous = name.endogenous, n.endogenous = n.endogenous, n.cluster = n.cluster) leverage <- .adjustLeverage(Omega = Omega.adj, epsilon = epsilon.adj, ls.dmu = ls.dmu, dOmega = dOmega, vcov.param = iVcov.param, index.Omega = index.Omega, name.endogenous = name.endogenous, n.endogenous = n.endogenous, name.varparam = name.varparam, n.varparam = n.varparam, n.cluster = n.cluster) n.corrected <- rep(n.cluster, n.endogenous) - colSums(leverage, na.rm = TRUE) } if(adjust.Omega){ Omega.adj <- Omega + Psi object$conditionalMoment <- .adjustMoment(object, Omega = Omega.adj) dOmega <- object$conditionalMoment$dOmega } iInfo <- .information2(dmu = dmu, dOmega = dOmega, Omega = Omega.adj, n.corrected = n.corrected, leverage = leverage, index.Omega = index.Omega, n.cluster = n.cluster, grid.meanparam = grid.meanparam, n.grid.meanparam = n.grid.meanparam, grid.varparam = grid.varparam, n.grid.varparam = n.grid.varparam, name.param = name.param, n.param = n.param) iVcov.param <- try(chol2inv(chol(iInfo)), silent = TRUE) if(inherits(iVcov.param, "try-error")){ iVcov.param <- solve(iInfo) } iIter <- iIter + 1 iTol <- norm(Omega.adj-Omega_save, type = "F") Omega_save <- Omega.adj } if(!is.infinite(iIter)){ if(iTol > tol){ warning("small sample correction did not reach convergence after ",iIter," iterations \n") if(trace>0){ cat(" - incomplete \n") } }else{ if(trace>0){ cat(" - done \n") } } } vcov.param <- try(chol2inv(chol(iInfo)), silent = TRUE) if("try-error" %in% class(vcov.param)){ errorMessage <- vcov.param vcov.param <- solve(iInfo) attr(vcov.param, "warning") <- errorMessage } dimnames(vcov.param) <- dimnames(iInfo) object$conditionalMoment$Omega <- Omega.adj object$dVcov <- list(param = object$conditionalMoment$param, score = NULL, vcov.param = vcov.param, dVcov.param = NULL, Omega = Omega.adj, residuals = epsilon.adj, leverage = leverage, n.corrected = rep(n.cluster, n.endogenous) - colSums(leverage, na.rm = TRUE), opt = list(objective = iTol, iterations = iIter, convergence = (iTol <= tol), grid.meanparam = grid.meanparam, grid.varparam = grid.varparam)) return(object) } .adjustResiduals <- function(Omega, Psi, epsilon, index.Omega, name.endogenous, n.endogenous, n.cluster){ if(is.null(index.Omega)){ Omega.chol <- matrixPower(Omega, symmetric = TRUE, power = 1/2) H <- Omega %*% Omega - Omega.chol %*% Psi %*% Omega.chol HM1 <- tryCatch(matrixPower(H, symmetric = TRUE, power = -1/2), warning = function(w){w}) if(inherits(HM1,"warning")){ stop("Cannot compute the adjusted residuals \n", "Estimated bias too large compared to the estimated variance-covariance matrix \n", "Consider setting argument \'adjust.n\' to FALSE when calling sCorrect \n") } epsilon.adj <- epsilon %*% Omega.chol %*% HM1 %*% Omega.chol }else{ epsilon.adj <- matrix(NA, nrow = n.cluster, ncol = n.endogenous, dimnames = list(NULL, name.endogenous)) for(iC in 1:n.cluster){ iIndex <- index.Omega[[iC]] iOmega <- Omega[iIndex,iIndex,drop=FALSE] iOmega.chol <- matrixPower(iOmega, symmetric = TRUE, power = 1/2) iH <- iOmega %*% iOmega - iOmega.chol %*% Psi[iIndex,iIndex,drop=FALSE] %*% iOmega.chol iHM1 <- tryCatch(matrixPower(iH, symmetric = TRUE, power = -1/2), warning = function(w){w}) if(inherits(iHM1,"warning")){ stop("Cannot compute the adjusted residuals \n", "Estimated bias too large compared to the estimated variance-covariance matrix \n", "Consider setting argument \'adjust.n\' to FALSE when calling sCorrect \n") } epsilon.adj[iC,iIndex] <- epsilon[iC,iIndex] %*% iOmega.chol %*% iHM1 %*% iOmega.chol } } dimnames(epsilon.adj) <- list(NULL,name.endogenous) return(epsilon.adj) } .adjustLeverage <- function(Omega, epsilon, ls.dmu, dOmega, vcov.param, index.Omega, name.endogenous, n.endogenous, name.varparam, n.varparam, n.cluster){ leverage <- matrix(NA, nrow = n.cluster, ncol = n.endogenous, dimnames = list(NULL, name.endogenous)) if(is.null(index.Omega)){ iIndex <- 1:n.endogenous iOmegaM1 <- chol2inv(chol(Omega)) iOmegaM1.dOmega.OmegaM1 <- lapply(dOmega, function(x){iOmegaM1 %*% x %*% iOmegaM1}) } for(iC in 1:n.cluster){ if(!is.null(index.Omega)){ iIndex <- index.Omega[[iC]] iOmegaM1 <- chol2inv(chol(Omega[iIndex,iIndex,drop=FALSE])) iOmegaM1.dOmega.OmegaM1 <- lapply(dOmega, function(x){iOmegaM1 %*% x[iIndex,iIndex] %*% iOmegaM1}) } scoreY <- ls.dmu[[iC]] %*% iOmegaM1 for(iP in 1:n.varparam){ scoreY[name.varparam[iP],] <- scoreY[name.varparam[iP],] + 2 * epsilon[iC,iIndex] %*% iOmegaM1.dOmega.OmegaM1[[name.varparam[iP]]] } leverage[iC,iIndex] <- colSums(vcov.param %*% ls.dmu[[iC]] * scoreY) } return(leverage) } `.adjustMoment` <- function(object, ...) UseMethod(".adjustMoment") .adjustMoment.lm <- function(object, Omega){ object$conditionalMoment$param["sigma2"] <- as.double(Omega) return(object$conditionalMoment) } .adjustMoment.gls <- function(object, Omega, ...){ class.cor <- object$conditionalMoment$skeleton$class.cor class.var <- object$conditionalMoment$skeleton$class.var name.corcoef <- object$conditionalMoment$skeleton$name.corcoef name.otherVar <- object$conditionalMoment$skeleton$name.otherVar name.varcoef <- object$conditionalMoment$skeleton$name.varcoef ref.group <- object$conditionalMoment$skeleton$ref.group M.corcoef <- object$conditionalMoment$skeleton$M.corcoef name.endogenous <- object$conditionalMoment$skeleton$name.endogenous n.endogenous <- object$conditionalMoment$skeleton$n.endogenous if(identical(class.var, "NULL")){ object$conditionalMoment$param["sigma2"] <- mean(diag(Omega)) }else{ index.Sigma2 <- which(ref.group %in% name.otherVar == FALSE) object$conditionalMoment$param["sigma2"] <- mean(diag(Omega)[index.Sigma2]) vec.k <- tapply(diag(Omega)/Omega[index.Sigma2,index.Sigma2], ref.group, mean) object$conditionalMoment$param[name.otherVar] <- vec.k[name.otherVar] } if(identical(class.cor, "NULL")){ }else if("corCompSymm" %in% class.cor){ object$conditionalMoment$param[name.corcoef] <- mean(stats::cov2cor(Omega)[lower.tri(Omega)]) }else if("corSymm" %in% class.cor){ vec.cor <- tapply(stats::cov2cor(Omega)[lower.tri(Omega)], M.corcoef[lower.tri(Omega)], mean) object$conditionalMoment$param[name.corcoef] <- vec.cor[name.corcoef] } object$conditionalMoment$Omega <- .getVarCov2(object, param = object$conditionalMoment$param, attr.param = attributes(object$conditionalMoment$param), name.endogenous = name.endogenous, n.endogenous = n.endogenous, ref.group = ref.group) object$conditionalMoment$dOmega <- skeletonDtheta(object, class.cor = class.cor, class.var = class.var, sigma2.base0 = object$conditionalMoment$skeleton$sigma2.base0, Msigma2.base0 = object$conditionalMoment$skeleton$Msigma2.base0, M.corcoef = M.corcoef, ref.group = ref.group, index.lower.tri = object$conditionalMoment$skeleton$index.lower.tri, indexArr.lower.tri = object$conditionalMoment$skeleton$indexArr.lower.tri, name.endogenous = name.endogenous, n.endogenous = n.endogenous, cluster = object$conditionalMoment$skeleton$cluster, n.cluster = object$conditionalMoment$skeleton$n.cluster, var.coef = object$conditionalMoment$param[name.varcoef], name.varcoef = name.varcoef, name.otherVar = name.otherVar, n.varcoef = object$conditionalMoment$skeleton$n.varcoef, cor.coef = object$conditionalMoment$param[name.corcoef], name.corcoef = name.corcoef, n.corcoef = object$conditionalMoment$skeleton$n.corcoef, update.mean = FALSE, update.variance = TRUE, ...)$dOmega return(object$conditionalMoment) } .adjustMoment.lme <- function(object, Omega){ name.rancoef <- attr(object$conditionalMoment$param,"ran.coef") if(!identical(object$conditionalMoment$skeleton$class.cor,"NULL")){ stop("Does not know how to identify the correlation coefficients when corStruct is not NULL \n") } object$conditionalMoment$param[name.rancoef] <- mean(Omega[lower.tri(Omega)]) save <- object$conditionalMoment$dOmega$ranCoef1 conditionalMoment <- .adjustMoment.gls(object, Omega = Omega - object$conditionalMoment$param["ranCoef1"], name.rancoef = name.rancoef) conditionalMoment$dOmega$ranCoef1 <- save return(conditionalMoment) } .adjustMoment.lvmfit <- function(object, Omega){ n.endogenous <- NROW(Omega) df.param <- object$conditionalMoment$df.param index.matrix <- object$conditionalMoment$adjustMoment$index.matrix index.Psi <- object$conditionalMoment$adjustMoment$index.Psi A <- object$conditionalMoment$adjustMoment$A name.var <- object$conditionalMoment$adjustMoment$name.var n.rhs <- object$conditionalMoment$adjustMoment$n.rhs index.LambdaB <- object$conditionalMoment$adjustMoment$index.LambdaB name.endogenous <- object$conditionalMoment$adjustMoment$name.endogenous name.latent <- object$conditionalMoment$adjustMoment$name.latent skeleton <- object$conditionalMoment$skeleton param <- object$conditionalMoment$param Lambda <- object$conditionalMoment$value$Lambda iIB <- object$conditionalMoment$value$iIB iIB.Lambda <- object$conditionalMoment$value$iIB.Lambda dLambda <- object$conditionalMoment$dMoment.init$dLambda dB <- object$conditionalMoment$dMoment.init$dB eq.rhs <- Omega[index.matrix$index] if(NROW(index.Psi)>0){ n.index.Psi <- NROW(index.Psi) n.latent <- NROW(skeleton$Psi) Z <- iIB %*% Lambda for(iIndex in 1:n.rhs){ iRow <- index.matrix[iIndex,"row"] iCol <- index.matrix[iIndex,"col"] for(iPsi in 1:n.index.Psi){ iRowPsi <- index.Psi[iPsi,"row"] iColPsi <- index.Psi[iPsi,"col"] A[iIndex,skeleton$Psi[iRowPsi,iColPsi]] <- A[iIndex,skeleton$Psi[iRowPsi,iColPsi]] + Z[iRowPsi,iRow]*Z[iColPsi,iCol] } } } if(lava.options()$method.estimate2=="svd"){ asvd <- svd(A) iSolution <- try((asvd$v %*% diag(1/asvd$d) %*% t(asvd$u) %*% eq.rhs)[,1], silent = TRUE) }else if(lava.options()$method.estimate2=="ols"){ iSolution <- try(OLS_cpp(A, eq.rhs)[,1], silent = TRUE) }else{ stop("unknown OLS methods \n") } if(inherits(iSolution, "try-error")){ if(abs(det(t(A) %*% A)) < 1e-10){ stop("Singular matrix: cannot update the estimates \n") }else{ stop(iSolution) } } object$conditionalMoment$param[name.var] <- setNames(iSolution, name.var) object$conditionalMoment$skeleton$toUpdate <- object$conditionalMoment$adjustMoment$toUpdate object$conditionalMoment$value <- skeleton.lvmfit(object, param = param, data = NULL, name.endogenous = name.endogenous, name.latent = name.latent) object$conditionalMoment$Omega <- Omega if(length(index.LambdaB)>0){ object$conditionalMoment$dMoment.init$toUpdate[] <- FALSE object$conditionalMoment$dMoment.init$toUpdate[index.LambdaB] <- TRUE object$conditionalMoment$dOmega <- skeletonDtheta.lvmfit(object, name.endogenous = name.endogenous, name.latent = name.latent)$dOmega } return(object$conditionalMoment) }
library("shiny") library("billboarder") library("magrittr") ui <- fluidPage( tags$h1("Update billboard chart"), billboarderOutput(outputId = "mybb1"), actionButton(inputId = "update", label = "Update data !") ) server <- function(input, output, session) { data_r <- reactive({ input$update data.frame(x = letters[1:10], y = round(runif(n = 10, min = 10, max = 100))) }) output$mybb1 <- renderBillboarder({ billboarder() %>% bb_barchart(data = isolate(data_r())) %>% bb_axis(y = list(max = 100, padding = 0, tick = list(outer = FALSE))) }) observeEvent(input$update, { billboarderProxy("mybb1") %>% bb_barchart(data = data_r()) }, ignoreInit = TRUE) } shinyApp(ui = ui, server = server)
compare <- function(x, y, ...) { UseMethod("compare", x) } comparison <- function(equal = TRUE, message = "Equal") { stopifnot(is.logical(equal), length(equal) == 1) stopifnot(is.character(message)) structure( list( equal = equal, message = paste(message, collapse = "\n") ), class = "comparison" ) } difference <- function(..., fmt = "%s") { comparison(FALSE, sprintf(fmt, ...)) } no_difference <- function() { comparison() } print.comparison <- function(x, ...) { if (x$equal) { cat("Equal\n") return() } cat(x$message) } compare.default <- function(x, y, ..., max_diffs = 9) { same <- all.equal(x, y, ...) if (length(same) > max_diffs) { same <- c(same[1:max_diffs], "...") } comparison(identical(same, TRUE), as.character(same)) } print_out <- function(x, ...) { lines <- capture_output_lines(x, ..., print = TRUE) paste0(lines, collapse = "\n") } same_length <- function(x, y) length(x) == length(y) diff_length <- function(x, y) difference(fmt = "Lengths differ: %i is not %i", length(x), length(y)) same_type <- function(x, y) identical(typeof(x), typeof(y)) diff_type <- function(x, y) difference(fmt = "Types not compatible: %s is not %s", typeof(x), typeof(y)) same_class <- function(x, y) { if (!is.object(x) && !is.object(y)) { return(TRUE) } identical(class(x), class(y)) } diff_class <- function(x, y) { difference(fmt = "Classes differ: %s is not %s", format_class(class(x)), format_class(class(y))) } same_attr <- function(x, y) { is.null(attr.all.equal(x, y)) } diff_attr <- function(x, y) { out <- attr.all.equal(x, y) difference(out) } vector_equal <- function(x, y) { (is.na(x) & is.na(y)) | (!is.na(x) & !is.na(y) & x == y) } vector_equal_tol <- function(x, y, tolerance = .Machine$double.eps ^ 0.5) { (is.na(x) & is.na(y)) | (!is.na(x) & !is.na(y)) & (x == y | abs(x - y) < tolerance) } compare.character <- function(x, y, check.attributes = TRUE, ..., max_diffs = 5, max_lines = 5, width = cli::console_width()) { if (identical(x, y)) { return(no_difference()) } if (!same_type(x, y)) { return(diff_type(x, y)) } if (!same_class(x, y)) { return(diff_class(x, y)) } if (!same_length(x, y)) { return(diff_length(x, y)) } if (check.attributes && !same_attr(x, y)) { return(diff_attr(x, y)) } diff <- !vector_equal(x, y) if (!any(diff)) { no_difference() } else { mismatches <- mismatch_character(x, y, diff) difference(format( mismatches, max_diffs = max_diffs, max_lines = max_lines, width = width )) } } mismatch_character <- function(x, y, diff = !vector_equal(x, y)) { structure( list( i = which(diff), x = x[diff], y = y[diff], n = length(diff), n_diff = sum(diff) ), class = "mismatch_character" ) } format.mismatch_character <- function(x, ..., max_diffs = 5, max_lines = 5, width = cli::console_width()) { width <- width - 6 n_show <- seq_len(min(x$n_diff, max_diffs)) encode <- function(x) encodeString(x, quote = '"') show_x <- str_trunc(encode(x$x[n_show]), width * max_lines) show_y <- str_trunc(encode(x$y[n_show]), width * max_lines) show_i <- x$i[n_show] sidebyside <- Map(function(x, y, pos) { x <- paste0("x[", pos, "]: ", str_chunk(x, width)) y <- paste0("y[", pos, "]: ", str_chunk(y, width)) paste(c(x, y), collapse = "\n") }, show_x, show_y, show_i) summary <- paste0(x$n_diff, "/", x$n, " mismatches") paste0(summary, "\n", paste0(sidebyside, collapse = "\n\n")) } print.mismatch_character <- function(x, ...) { cat(format(x, ...), "\n", sep = "") } str_trunc <- function(x, length) { too_long <- nchar(x) > length x[too_long] <- paste0(substr(x[too_long], 1, length - 3), "...") x } str_chunk <- function(x, length) { lines <- ceiling(nchar(x) / length) start <- (seq_len(lines) - 1) * length + 1 substring(x, start, start + length - 1) } compare.numeric <- function(x, y, tolerance = testthat_tolerance(), check.attributes = TRUE, ..., max_diffs = 9) { all_equal <- all.equal( x, y, tolerance = tolerance, check.attributes = check.attributes, ... ) if (isTRUE(all_equal)) { return(no_difference()) } if (!typeof(y) %in% c("integer", "double")) { return(diff_type(x, y)) } if (!same_class(x, y)) { return(diff_class(x, y)) } if (!same_length(x, y)) { return(diff_length(x, y)) } if (check.attributes && !same_attr(x, y)) { return(diff_attr(x, y)) } diff <- !vector_equal_tol(x, y, tolerance = tolerance) if (!any(diff)) { no_difference() } else { mismatches <- mismatch_numeric(x, y, diff) difference(format(mismatches, max_diffs = max_diffs)) } } testthat_tolerance <- function() { if (identical(capabilities("long.double"), FALSE)) { skip("Long doubles not available and `tolerance` not supplied") } .Machine$double.eps ^ 0.5 } mismatch_numeric <- function(x, y, diff = !vector_equal(x, y)) { structure( list( i = which(diff), x = x[diff], y = y[diff], n = length(diff), n_diff = sum(diff), mu_diff = mean(abs(x[diff] - y[diff]), na.rm = TRUE) ), class = "mismatch_numeric" ) } format.mismatch_numeric <- function(x, ..., max_diffs = 9, digits = 3) { summary <- paste0(x$n_diff, "/", x$n, " mismatches") if (x$n_diff > 1) { mu <- format(x$mu_diff, digits = digits, trim = TRUE) summary <- paste0(summary, " (average diff: ", mu, ")") } n_show <- seq_len(min(x$n_diff, max_diffs)) diffs <- paste0( format(paste0("[", x$i[n_show], "]")), " ", format(x$x[n_show], digits = digits), " - ", format(x$y[n_show], digits = digits), " == ", format(x$x[n_show] - x$y[n_show], digits = digits) ) if (x$n_diff > length(n_show)) { diffs <- c(diffs, "...") } paste0(summary, "\n", paste(diffs, collapse = "\n")) } print.mismatch_numeric <- function(x, ...) { cat(format(x, ...), "\n", sep = "") } compare.POSIXt <- function(x, y, tolerance = 0.001, ..., max_diffs = 9) { if (!inherits(y, "POSIXt")) { return(diff_class(x, y)) } if (!same_length(x, y)) { return(diff_length(x, y)) } x <- standardise_tzone(as.POSIXct(x)) y <- standardise_tzone(as.POSIXct(y)) if (!same_attr(x, y)) { return(diff_attr(x, y)) } diff <- !vector_equal_tol(x, y, tolerance = tolerance) if (!any(diff)) { no_difference() } else { mismatches <- mismatch_numeric(x, y, diff) difference(format(mismatches, max_diffs = max_diffs)) } } standardise_tzone <- function(x) { if (is.null(attr(x, "tzone")) || identical(attr(x, "tzone"), Sys.timezone())) { attr(x, "tzone") <- "" } x }
sortSets <- function(sets, order.by = "cardinality", limit = NULL) { setAttr <- function(order.by.attr) { if (order.by.attr == "cardinality") { sapply(sets, function(x) { if (length(x$elems) == 0) { x$cardinality * -1 } else { length(x$elems) * -1 } }) } else if (order.by.attr == "degree") { sapply(sets, function(x) { length(x$setNames) }) } else { sapply(sets, function(x) { x$name }) } } if (length(order.by) == 1 && order.by[1] == "cardinality") { order.by <- c("cardinality", "name") } else if (length(order.by) == 1 && order.by[1] == "degree") { order.by <- c("degree", "name") } if (length(sets) > 1) { values <- lapply(order.by, setAttr) o <- do.call(order, values) r <- sets[o] } else { r <- sets } if (is.null(limit) || length(r) <= limit) { r } else { r[1:limit] } } colorLookup <- function(colors = NULL) { if (is.null(colors)) { function(c) { NULL } } else { colorNames <- names(colors) function(c) { if (c %in% colorNames) { colors[[c]] } else { NULL } } } } generateCombinationsImpl <- function(sets, c_type, min, max, empty, order.by, limit, colors = NULL, symbol = "&", store.elems = TRUE) { combinations <- list() distinct <- (c_type == "distinctIntersection") cc <- colorLookup(colors) mergeUnion <- function(a, b) { abSets <- union(a$setNames, b$setNames) abName <- paste(abSets, collapse = symbol) abElems <- c() if (a$cardinality == 0) { abElems <- b$elems } else if (b$cardinality == 0) { abElems <- a$elems } else { abElems <- union(a$elems, b$elems) } asCombination(abName, abElems, "union", abSets, color = cc(abName)) } mergeIntersect <- function(a, b) { abSets <- union(a$setNames, b$setNames) abName <- paste(abSets, collapse = symbol) abElems <- c() if (a$cardinality > 0 && b$cardinality > 0) { abElems <- intersect(a$elems, b$elems) } asCombination(abName, abElems, "intersect", abSets, color = cc(abName)) } calc <- ifelse(c_type == "union", mergeUnion, mergeIntersect) pushCombination <- function(s) { if (s$degree < min || (!is.null(max) && s$degree > max) || (s$cardinality == 0 && !empty)) { return() } if (!store.elems) { s <<- asCombination(s$name, c(), "distinctIntersection", s$setNames, cardinality = s$cardinality, color = s$color) } if (!distinct) { combinations <<- c(combinations, list(s)) return() } otherSets <- Filter(function(ss) { !(ss$name %in% s$setNames) }, sets) dElems <- Filter(function(e) { for (o in otherSets) { if (e %in% o$elems) { return(FALSE) } } TRUE }, s$elems) if (s$cardinality == length(dElems)) { combinations <<- c(combinations, list(s)) return() } sDistinct <- asCombination(s$name, if (store.elems) { dElems } else { c() }, "distinctIntersection", s$setNames, cardinality = length(dElems), color = s$color) if (sDistinct$cardinality > 0 || empty) { combinations <<- c(combinations, list(sDistinct)) } } generateLevel <- function(arr, degree) { if (!is.null(max) && degree > max) { return() } l <- length(arr) for (i in 1:l) { a <- arr[[i]] sub <- list() if (i < l) { for (j in (i + 1):l) { b <- arr[[j]] ab <- calc(a, b) pushCombination(ab) if (c_type == "union" || ab$cardinality > 0 || empty) { sub[[length(sub) + 1]] <- ab } } } if (length(sub) > 1) { generateLevel(sub, degree + 1) } } } degree1 <- lapply(seq_along(sets), function(i) { s <- sets[[i]] sC <- asCombination(s$name, s$elems, c_type, c(s$name), s$cardinality, s$color) pushCombination(sC) sC }) generateLevel(degree1, 2) names(combinations) <- NULL sortSets(combinations, order.by, limit) } extractCombinationsImpl <- function(df, sets, empty, order.by, limit = NULL, colors = NULL, symbol = "&", store.elems = TRUE) { allSetNames <- sapply(seq_along(sets), function(i) sets[[i]]$name) if (is.list(allSetNames)) { allSetNames <- unlist(allSetNames) } cc <- colorLookup(colors) elems <- rownames(df) dfSets <- df[, allSetNames] cName <- apply(dfSets, 1, function(r) { nn <- allSetNames[as.logical(r)] if (length(nn) == 1) { nn } else { paste(nn, collapse = symbol) } }) dd <- aggregate(elems, list(c_name = cName), function(r) { r }) setNames <- strsplit(dd$c_name, symbol, fixed = TRUE) setColors <- cc(dd$c_name) combinations <- lapply(seq_len(nrow(dd)), function(i) { elems <- as.character(dd[i, "x"][[1]]) structure( list( name = dd[i, "c_name"], color = setColors[i], type = "distinctIntersection", elems = if (store.elems) elems else c(), setNames = setNames[i][[1]], cardinality = length(elems) ), class = "upsetjs_combination" ) }) names(combinations) <- NULL sortSets(combinations, order.by, limit) }
make.soapgrid<-function(bnd,n.grid){ if(length(n.grid)==2){ m<-n.grid[1] n<-n.grid[2] }else{ m<-n<-n.grid } xmin<-min(bnd$x,na.rm=TRUE) ymin<-min(bnd$y,na.rm=TRUE) xmax<-max(bnd$x,na.rm=TRUE) ymax<-max(bnd$y,na.rm=TRUE) ng<-expand.grid(x=seq(xmin,xmax,length=m), y=seq(ymin,ymax,length=n)) x <- ng$x; y <- ng$y onoff<-inSide(as.list(bnd),x,y) ng<-ng[onoff,] return(ng) }
coef.trial <- function(object,...){ par <- coef(object$mr) row.names(par) <- paste("mr :",row.names(coef(object$mr))) if(!is.null(coef(object$ds)$exponent)){ rn <- row.names(par) par <- rbind(par,coef(object$ds)$exponent) row.names(par) <- c(rn, paste("ds expon:", row.names(coef(object$ds)$exponent))) } rn <- row.names(par) ds.scale <- coef(object$ds)$scale if(!is.null(ds.scale)){ par <- rbind(par,coef(object$ds)$scale) row.names(par) <- c(rn,paste("ds scale:", row.names(coef(object$ds)$scale))) } if(!is.null(coef(object$ds)$adjustment)){ rn <- row.names(par) par <- rbind(par,coef(object$ds)$adjustment) row.names(par) <- c(rn, paste("ds adjust:", row.names(coef(object$ds)$adjustment))) } return(par) }
map.eda7 <- function (xx, yy, zz, sfact = 1, logz = FALSE, xlab = "Easting", ylab = "Northing", zlab = deparse(substitute(zz)), main = "", ifgrey = FALSE, symcolr = NULL, tol = 0.04, iflgnd = FALSE, title = deparse(substitute(zz)), cex.lgnd = 0.8, ...) { frame() old.par <- par(); on.exit(par(old.par)) par(pty = "m") temp.x <- remove.na(cbind(xx, yy, zz)) x <- temp.x$x[1:temp.x$n, 1] y <- temp.x$x[1:temp.x$n, 2] z <- temp.x$x[1:temp.x$n, 3] nz <- temp.x$n if (main == "") if (zlab == "") banner <- "" else { if (logz) banner <- paste("EDA Tukey Boxplot Based Map for Log10", zlab) else banner <- paste("EDA Tukey Boxplot Based Map for", zlab) } else banner <- main eqscplot(x, y, type = "n", xlab = xlab, ylab = ylab, main = banner, tol = tol, ...) if (logz) z <- log10(z) q <- quantile(z, probs = c(0.25, 0.75)) zcut <- numeric(6) hw <- q[2] - q[1] zcut[1] <- q[1] - 3 * hw zcut[2] <- q[1] - 1.5 * hw zcut[3] <- q[1] zcut[4] <- q[2] zcut[5] <- q[2] + 1.5 * hw zcut[6] <- q[2] + 3 * hw zzz <- cutter(z, zcut) npch <- c(1, 1, 1, 3, 0, 0, 0) size <- c(2, 1.5, 1, 0.5, 1, 1.5, 2) * sfact if (ifgrey) { symcolr <- grey(c(0, 0.15, 0.3, 0.4, 0.3, 0.15, 0)) } else { palette(rainbow(36)) if (length(symcolr) != 7) symcolr <- c(25, 22, 20, 13, 6, 4, 1) } for (i in 1:nz) { points(x[i], y[i], pch = npch[zzz[i]], cex = size[zzz[i]], col = symcolr[zzz[i]]) } cat("\n\tCut Levels\t No. of Symbols Symbol - size - Colour\n\tLog =", logz, "\t\t\t\tsfact =", format(sfact, nsmall = 2), "\n\n") stype <- character(7) stype[1:3] <- "Circle " stype[4] <- "Cross " stype[5:7] <- "Square " for (i in 1:6) { if (logz) zcut[i] <- 10^zcut[i] ni <- length(zzz[zzz == i]) cat("\t\t\t ", ni, "\t ", stype[i], format(size[i], nsmall = 2), " ", symcolr[i], "\n\t", round(zcut[i], 2), "\n") } cat("\t\t\t ", length(zzz[zzz == 7]), "\t ", stype[7], format(size[7], nsmall = 2), " ", symcolr[7], "\n") if (iflgnd) { lgnd.line <- numeric(7) zcut <- signif(zcut, 3) lgnd.line[1] <- paste(">", zcut[6]) lgnd.line[2] <- paste(zcut[5], "-", zcut[6]) lgnd.line[3] <- paste(zcut[4], "-", zcut[5]) lgnd.line[4] <- paste(zcut[3], "-", zcut[4]) lgnd.line[5] <- paste(zcut[2], "-", zcut[3]) lgnd.line[6] <- paste(zcut[1], "-", zcut[2]) lgnd.line[7] <- paste("<", zcut[1]) legend(locator(1), pch = npch[7:1], col = symcolr[7:1], pt.cex = size[7:1], lgnd.line[1:7], cex = cex.lgnd, title = title, ...) } palette("default") invisible() }
climate.anom.dendro.season<-function(climate.data,year1,year2,year.start,is.anomaly) { colnames(climate.data)[1] <- "YEAR" x<-climate.data aver.month.year1.year2<-function(x,year1,year2){ xx<-subset(x=x,subset=("YEAR">=year1)) xxx<-subset(x=xx,subset=("YEAR"<=year2)) colMeans(xxx) } year<-as.vector(climate.data$YEAR,"character") if (is.anomaly == "TRUE"){ xxx<-climate.data[2:13] }else{ aver.month<-aver.month.year1.year2(climate.data,year1,year2) month<-dimnames(x)[[2]][2:13] xxx<-matrix("na",dim(x)[1],dim(x)[2]-1) rownames(xxx)<-year colnames(xxx)<-month for( j in 1:12){ xxx[,month[j]]<-apply(x,1,function(y){y[month[j]]-aver.month[month[j]]}) } } Jan.Aug.dendro<-rbind(xxx[2:length(year),1:8],NA) rownames(Jan.Aug.dendro)<-year[1:(length(year))] Sep.Dec.dendro<-xxx[,9:12] dendro.anom<-cbind(Jan.Aug.dendro,Sep.Dec.dendro) JJA<-matrix("na",length(year),1) rownames(JJA)<-year for( k in 1:length(year)){ JJA[k]<-if(is.na(dendro.anom[year[k],"Jun"])==FALSE & is.na(dendro.anom[year[k],"Jul"])==FALSE & is.na(dendro.anom[year[k],"Aug"])==FALSE){ mean(as.numeric(c(dendro.anom[year[k],"Jun"], dendro.anom[year[k],"Jul"], dendro.anom[year[k],"Aug"])))}else{"NA"} } MAM<-matrix("na",length(year),1) rownames(MAM)<-year for( k in 1:length(year)){ MAM[k]<-if(is.na(dendro.anom[year[k],"Mar"])==FALSE & is.na(dendro.anom[year[k],"Apr"])==FALSE & is.na(dendro.anom[year[k],"May"])==FALSE){ mean(as.numeric(c(dendro.anom[year[k],"Mar"], dendro.anom[year[k],"Apr"], dendro.anom[year[k],"May"])))}else{"NA"} } DJF<-matrix("na",length(year),1) rownames(DJF)<-year for( k in 1:length(year)){ DJF[k]<-if(is.na(dendro.anom[year[k],"Dec"])==FALSE & is.na(dendro.anom[year[k],"Jan"])==FALSE & is.na(dendro.anom[year[k],"Feb"])==FALSE){ mean(as.numeric(c(dendro.anom[year[k],"Dec"], dendro.anom[year[k],"Jan"], dendro.anom[year[k],"Feb"])))}else{"NA"} } SON<-matrix("na",length(year),1) rownames(SON)<-year for( k in 1:length(year)){ SON[k]<-if(is.na(dendro.anom[year[k],"Sep"])==FALSE & is.na(dendro.anom[year[k],"Oct"])==FALSE & is.na(dendro.anom[year[k],"Nov"])==FALSE){ mean(as.numeric(c(dendro.anom[year[k],"Sep"], dendro.anom[year[k],"Oct"], dendro.anom[year[k],"Nov"])))}else{"NA"} } JJA_1<-matrix(c("NA",JJA[1:(length(JJA)-1)])) rownames(JJA_1)<-year[1:(length(year))] MAM_1<-matrix(c("NA",MAM[1:(length(MAM)-1)])) rownames(MAM_1)<-year[1:(length(year))] DJF_1<-matrix(c("NA",DJF[1:(length(DJF)-1)])) rownames(DJF_1)<-year[1:(length(year))] SON_1<-matrix(c("NA",SON[1:(length(SON)-1)])) rownames(SON_1)<-year[1:(length(year))] JJA_2<-matrix(c("NA",JJA_1[1:(length(JJA_1)-1)])) rownames(JJA_2)<-year[1:(length(year))] MAM_2<-matrix(c("NA",MAM_1[1:(length(MAM_1)-1)])) rownames(MAM_2)<-year[1:(length(year))] DJF_2<-matrix(c("NA",DJF_1[1:(length(DJF_1)-1)])) rownames(DJF_2)<-year[1:(length(year))] SON_2<-matrix(c("NA",SON_1[1:(length(SON_1)-1)])) rownames(SON_2)<-year[1:(length(year))] climate.season<-cbind(SON_2,DJF_2,MAM_2,JJA_2,SON_1,DJF_1,MAM_1,JJA_1,SON,DJF,MAM,JJA) col.names.season<-list("SON_2","DJF_2","MAM_2","JJA_2","SON_1","DJF_1","MAM_1", "JJA_1","SON","DJF","MAM","JJA") colnames(climate.season)<-(col.names.season) climate.season<- ts ( climate.season , start=year.start ) climate.season }
getMinimumSpanningTree <- function(nodes, arcs, algorithm, start.node = 1, show.data = TRUE, show.graph = TRUE, check.graph = FALSE) { if (check.graph) { validGraph <- checkGraph(nodes, arcs, start.node, directed = FALSE) if (validGraph == FALSE) { stop("Invalid graph") } } arcs <- removeLoops(arcs) arcs <- removeMultiArcs(arcs, directed = FALSE) tini <- proc.time() if (algorithm == "Prim") { mst <- msTreePrim(nodes, arcs, start.node) } else if (algorithm == "Kruskal") { mst <- msTreeKruskal(nodes, arcs) } else if (algorithm == "Boruvka") { mst <- msTreeBoruvka(nodes, arcs) } else { stop("Unknown algorithm") } running.time <- proc.time() - tini if (show.data) { dfTree <- mst$tree.arcs weight <- sum(dfTree[, 3]) df <- as.data.frame(dfTree) colnames(df) <- c(" ept1 ", " ept2 ", " weight ") showdf <- capture.output(print(df, row.names=FALSE)) pastedf <- paste(showdf, "\n", sep="") cat("\n") cat(" Minimum Cost Spanning Tree \n") cat(" Algorithm:", algorithm, "\n") cat(" Stages: ", mst$stages, "| Time: ", running.time[3], "\n") cat(" ------------------------------\n") cat(" ", pastedf) cat(" ------------------------------\n") cat(" Total =", weight, "\n") cat("\n") } if (show.graph) { repGraph(nodes, arcs, tree = mst$tree.arcs, plot.title = "Minimum Cost Spanning Tree") } output <- list("tree.nodes" = mst$tree.nodes, "tree.arcs" = mst$tree.arcs, "weight" = sum(mst$tree.arcs[, 3]), "stages" = mst$stages, "stages.arcs" = mst$stages.arcs, "time" = running.time) invisible(output) }
timestamp <- Sys.time() library(caret) library(plyr) library(recipes) library(dplyr) model <- "AdaBag" set.seed(2) training <- twoClassSim(50, linearVars = 2) testing <- twoClassSim(500, linearVars = 2) trainX <- training[, -ncol(training)] trainY <- training$Class rec_cls <- recipe(Class ~ ., data = training) %>% step_center(all_predictors()) %>% step_scale(all_predictors()) seeds <- vector(mode = "list", length = nrow(training) + 1) seeds <- lapply(seeds, function(x) 1:20) grid <- expand.grid(mfinal = (1:3)*3, maxdepth = c(1, 3)) cctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all", classProbs = TRUE, summaryFunction = twoClassSummary, seeds = seeds) cctrl2 <- trainControl(method = "LOOCV", classProbs = TRUE, summaryFunction = twoClassSummary, seeds = seeds) cctrl3 <- trainControl(method = "none", classProbs = TRUE, summaryFunction = twoClassSummary, seeds = seeds) cctrlR <- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random") set.seed(849) test_class_cv_model <- train(trainX, trainY, method = "AdaBag", trControl = cctrl1, tuneGrid = grid, metric = "ROC", preProc = c("center", "scale")) set.seed(849) test_class_cv_form <- train(Class ~ ., data = training, method = "AdaBag", tuneGrid = grid, trControl = cctrl1, metric = "ROC", preProc = c("center", "scale")) test_class_pred <- predict(test_class_cv_model, testing[, -ncol(testing)]) test_class_prob <- predict(test_class_cv_model, testing[, -ncol(testing)], type = "prob") test_class_pred_form <- predict(test_class_cv_form, testing[, -ncol(testing)]) test_class_prob_form <- predict(test_class_cv_form, testing[, -ncol(testing)], type = "prob") set.seed(849) test_class_rand <- train(trainX, trainY, method = "AdaBag", trControl = cctrlR, tuneLength = 4, preProc = c("center", "scale")) set.seed(849) test_class_loo_model <- train(trainX, trainY, method = "AdaBag", trControl = cctrl2, tuneGrid = grid, metric = "ROC", preProc = c("center", "scale")) set.seed(849) test_class_none_model <- train(trainX, trainY, method = "AdaBag", trControl = cctrl3, tuneLength = 1, metric = "ROC", preProc = c("center", "scale")) test_class_none_pred <- predict(test_class_none_model, testing[, -ncol(testing)]) test_class_none_prob <- predict(test_class_none_model, testing[, -ncol(testing)], type = "prob") set.seed(849) test_class_rec <- train(x = rec_cls, data = training, method = "AdaBag", trControl = cctrl1, tuneGrid = grid, metric = "ROC") if( !isTRUE( all.equal(test_class_cv_model$results, test_class_rec$results)) ) stop("CV weights not giving the same results") test_class_imp_rec <- varImp(test_class_rec) test_class_pred_rec <- predict(test_class_rec, testing[, -ncol(testing)]) test_class_prob_rec <- predict(test_class_rec, testing[, -ncol(testing)], type = "prob") test_levels <- levels(test_class_cv_model) if(!all(levels(trainY) %in% test_levels)) cat("wrong levels") sInfo <- sessionInfo() timestamp_end <- Sys.time() tests <- grep("test_", ls(), fixed = TRUE, value = TRUE) save(list = c(tests, "sInfo", "timestamp", "timestamp_end"), file = file.path(getwd(), paste(model, ".RData", sep = ""))) if(!interactive()) q("no")
mpcollapse <- function(mallele, nloci) { tmp <- data.frame(m2 = (m <- floor(mallele/2):0), m1 = mallele - 2 * m) tmp[tmp$m1 <= nloci & tmp$m2 <= nloci, ] }