code
stringlengths
1
13.8M
test_that("Calibrating a unit matrix against a unit vector, with attributes", { N <- 10 X <- diag(N) d <- rep(1, N) totals <- rep(1, N) for (method in eval(formals(dss)$method)) { g <- dss(X, d, totals, method = method, attributes = TRUE) expect_equal(as.numeric(g), totals, info = method) expect_true(attr(g, "success")) expect_equal(length(g), N) expect_type(g, "double") expect_type(attr(g, "iterations"), "integer") expect_lt(attr(g, "iterations"), 3) expect_equal(attr(g, "method"), method) if (method == "logit") { expect_equal(attr(g, "bounds"), c(0, 10)) } else { expect_null(attr(g, "bounds")) } } }) test_that("Test non-convergence, with attributes", { X <- matrix(rep(1, 4), nrow = 2) d <- rep(1, 2) totals <- 1:2 for (method in eval(formals(dss)$method)) { expect_warning( g <- dss(X, d, totals, method = method, attributes = TRUE), NA ) expect_false(attr(g, "success")) expect_equal(length(g), 2) expect_type(g, "double") expect_type(attr(g, "iterations"), "integer") } })
context("test-get_poverty_lines") test_that("test GBA", { skip_if_offline() canasta <- get_poverty_lines() expect_equal(canasta$CBA[1], 1514.53) expect_equal(canasta$ICE[1], 2.42) expect_equal(canasta$CBT[1], 3663.66) }) test_that("test regiones", { skip_if_offline() canasta <- get_poverty_lines(regional = TRUE) expect_equal(canasta$CBA[1], 1224.64) expect_equal(unique(canasta$region), c( "Cuyo" , "GBA", "Noreste", "Noroeste", "Pampeana", "Patagonia")) })
current.xts_chob <- function() invisible(get(".xts_chob",.plotxtsEnv)) chart.lines <- function(x, type="l", lty=1, lwd=2, lend=1, col=NULL, up.col=NULL, dn.col=NULL, legend.loc=NULL, ...){ xx <- current.xts_chob() switch(type, h={ if (!is.null(up.col) && !is.null(dn.col)){ colors <- ifelse(x[,1] < 0, dn.col, up.col) } else { colors <- if (is.null(col)) 1 else col } if (length(colors) < nrow(x[,1])) colors <- colors[1] xcoords <- xx$get_xcoords(x[,1]) lines(xcoords,x[,1],lwd=2,col=colors,lend=lend,lty=1,type="h",...) }, p=, l=, b=, c=, o=, s=, S=, n={ if(is.null(col)) col <- xx$Env$theme$col if(length(lty) < NCOL(x)) lty <- rep(lty, length.out = NCOL(x)) if(length(lwd) < NCOL(x)) lwd <- rep(lwd, length.out = NCOL(x)) if(length(col) < NCOL(x)) col <- rep(col, length.out = NCOL(x)) for(i in NCOL(x):1) { xcoords <- xx$get_xcoords(x[,i]) lines(xcoords, x[,i], type=type, lend=lend, col=col[i], lty=lty[i], lwd=lwd[i], ...) } }, { warning(paste(type, "not recognized. Type must be one of 'p', 'l', 'b, 'c', 'o', 'h', 's', 'S', 'n'. plot.xts supports the same types as plot.default, see ?plot for valid arguments for type")) } ) if(!is.null(legend.loc)){ lc <- legend.coords(legend.loc, xx$Env$xlim, range(x, na.rm=TRUE)) legend(x=lc$x, y=lc$y, legend=colnames(x), xjust=lc$xjust, yjust=lc$yjust, fill=col[1:NCOL(x)], bty="n") } } add.par.from.dots <- function(call., ...) { stopifnot(is.call(call.)) parnames <- c("xlog","ylog","adj","ann","ask","bg","bty","cex","cex.axis", "cex.lab","cex.main","cex.sub","cin","col","col.axis","col.lab", "col.main","col.sub","cra","crt","csi","cxy","din","err", "family", "fg","fig","fin","font","font.axis","font.lab", "font.main","font.sub","lab","las","lend","lheight","ljoin", "lmitre","lty","lwd","mai","mar","mex","mfcol","mfg","mfrow", "mgp","mkh","new","oma","omd","omi","page","pch","pin","plt", "ps","pty","smo","srt","tck","tcl","usr","xaxp","xaxs","xaxt", "xpd","yaxp","yaxs","yaxt","ylbias") dots <- list(...) argnames <- names(dots) pm <- match(argnames, parnames, nomatch = 0L) call.list <- as.list(call.) as.call(c(call.list, dots[pm > 0L])) } chart.lines.expression <- function(...) { mc <- match.call() mc[[1]] <- quote(chart.lines) as.expression(mc) } isNullOrFalse <- function(x) { is.null(x) || identical(x, FALSE) } plot.xts <- function(x, y=NULL, ..., subset="", panels=NULL, multi.panel=FALSE, col=1:8, up.col=NULL, dn.col=NULL, bg=" type="l", lty=1, lwd=2, lend=1, main=deparse(substitute(x)), observation.based=FALSE, ylim=NULL, yaxis.same=TRUE, yaxis.left=TRUE, yaxis.right=TRUE, major.ticks="auto", minor.ticks=NULL, grid.ticks.on="auto", grid.ticks.lwd=1, grid.ticks.lty=1, grid.col="darkgray", labels.col=" format.labels=TRUE, grid2=" legend.loc=NULL, extend.xaxis=FALSE){ if(is.numeric(multi.panel)){ multi.panel <- min(NCOL(x), multi.panel) idx <- seq.int(1L, NCOL(x), 1L) chunks <- split(idx, ceiling(seq_along(idx)/multi.panel)) if(length(lty) < ncol(x)) lty <- rep(lty, length.out = ncol(x)) if(length(lwd) < ncol(x)) lwd <- rep(lwd, length.out = ncol(x)) if(length(col) < ncol(x)) col <- rep(col, length.out = ncol(x)) if(!is.null(panels) && nchar(panels) > 0){ multi.panel <- FALSE } else { multi.panel <- TRUE panels <- NULL if(yaxis.same) ylim <- range(x[subset], na.rm=TRUE) } for(i in 1:length(chunks)){ tmp <- chunks[[i]] p <- plot.xts(x=x[,tmp], y=y, ...=..., subset=subset, panels=panels, multi.panel=multi.panel, col=col[tmp], up.col=up.col, dn.col=dn.col, bg=bg, type=type, lty=lty[tmp], lwd=lwd[tmp], lend=lend, main=main, observation.based=observation.based, ylim=ylim, yaxis.same=yaxis.same, yaxis.left=yaxis.left, yaxis.right=yaxis.right, major.ticks=major.ticks, minor.ticks=minor.ticks, grid.ticks.on=grid.ticks.on, grid.ticks.lwd=grid.ticks.lwd, grid.ticks.lty=grid.ticks.lty, grid.col=grid.col, labels.col=labels.col, format.labels=format.labels, grid2=grid2, legend.loc=legend.loc, extend.xaxis=extend.xaxis) if(i < length(chunks)) print(p) } return(p) } cs <- new.replot_xts() if(is.null(major.ticks)) { xs <- x[subset] mt <- c(years=nyears(xs), months=nmonths(xs), days=ndays(xs)) major.ticks <- names(mt)[rev(which(mt < 30))[1]] } plot.call <- match.call(expand.dots=TRUE) if(isTRUE(multi.panel)){ if(NCOL(x) == 1) cs$set_asp(3) else cs$set_asp(NCOL(x)) } else { cs$set_asp(3) } cs$Env$cex <- if (hasArg("cex")) eval.parent(plot.call$cex) else 0.6 cs$Env$mar <- if (hasArg("mar")) eval.parent(plot.call$mar) else c(3,2,0,2) cs$Env$theme$up.col <- up.col cs$Env$theme$dn.col <- dn.col if(hasArg("colorset")) col <- eval.parent(plot.call$colorset) if(length(col) < ncol(x)) col <- rep(col, length.out = ncol(x)) cs$Env$theme$col <- col cs$Env$theme$rylab <- yaxis.right cs$Env$theme$lylab <- yaxis.left cs$Env$theme$bg <- bg cs$Env$theme$grid <- grid.col cs$Env$theme$grid2 <- grid2 cs$Env$theme$labels <- labels.col cs$Env$theme$srt <- if (hasArg("srt")) eval.parent(plot.call$srt) else 0 cs$Env$theme$las <- if (hasArg("las")) eval.parent(plot.call$las) else 0 cs$Env$theme$cex.axis <- if (hasArg("cex.axis")) eval.parent(plot.call$cex.axis) else 0.9 cs$Env$format.labels <- format.labels cs$Env$major.ticks <- if (isTRUE(major.ticks)) "auto" else major.ticks cs$Env$minor.ticks <- if (isTRUE(minor.ticks)) "auto" else minor.ticks cs$Env$grid.ticks.on <- if (isTRUE(grid.ticks.on)) "auto" else grid.ticks.on cs$Env$grid.ticks.lwd <- grid.ticks.lwd cs$Env$grid.ticks.lty <- grid.ticks.lty cs$Env$type <- type if(length(lty) < ncol(x)) lty <- rep(lty, length.out = ncol(x)) if(length(lwd) < ncol(x)) lwd <- rep(lwd, length.out = ncol(x)) cs$Env$lty <- lty cs$Env$lwd <- lwd cs$Env$lend <- lend cs$Env$legend.loc <- legend.loc cs$Env$extend.xaxis <- extend.xaxis cs$Env$call_list <- list() cs$Env$call_list[[1]] <- plot.call cs$Env$observation.based <- observation.based if(is.character(x)) stop("'x' must be a time-series object") cs$Env$xdata <- x cs$Env$xsubset <- subset cs$Env$column_names <- colnames(x) cs$Env$nobs <- NROW(cs$Env$xdata) cs$Env$main <- main cs$Env$ylab <- if (hasArg("ylab")) eval.parent(plot.call$ylab) else "" if(is.null(ylim)){ if(isTRUE(multi.panel)){ if(yaxis.same){ yrange <- range(cs$Env$xdata[subset], na.rm=TRUE) } else { yrange <- range(cs$Env$xdata[,1][subset], na.rm=TRUE) } } else { yrange <- range(cs$Env$xdata[subset], na.rm=TRUE) } if(yrange[1L] == yrange[2L]) { if(yrange[1L] == 0) { yrange <- yrange + c(-1, 1) } else { yrange <- c(0.8, 1.2) * yrange[1L] } } cs$set_ylim(list(structure(yrange, fixed=FALSE))) cs$Env$constant_ylim <- range(cs$Env$xdata[subset], na.rm=TRUE) } else { cs$set_ylim(list(structure(ylim, fixed=TRUE))) cs$Env$constant_ylim <- ylim } cs$set_frame(1,FALSE) if(!isNullOrFalse(grid.ticks.on)) { cs$add(expression(xcoords <- get_xcoords(), x_index <- get_xcoords(at_posix = TRUE), atbt <- axTicksByTime(.xts(,x_index)[xsubset], ticks.on=grid.ticks.on), segments(xcoords[atbt], get_ylim()[[2]][1], xcoords[atbt], get_ylim()[[2]][2], col=theme$grid, lwd=grid.ticks.lwd, lty=grid.ticks.lty)), clip=FALSE, expr=TRUE) } cs$add_frame(0,ylim=c(0,1),asp=0.5) cs$set_frame(1) cs$add(expression(if(NROW(xdata[xsubset])<400) {axis(1,at=get_xcoords(),labels=FALSE,col=theme$grid2,col.axis=theme$grid2,tcl=0.3)}),expr=TRUE) if(!isNullOrFalse(major.ticks)) { cs$add(expression(xcoords <- get_xcoords(), x_index <- get_xcoords(at_posix = TRUE), axt <- axTicksByTime(.xts(,x_index)[xsubset], ticks.on=major.ticks, format.labels=format.labels), axis(1, at=xcoords[axt], labels=names(axt), las=theme$las, lwd.ticks=1.5, mgp=c(3,1.5,0), tcl=-0.4, cex.axis=theme$cex.axis, col=theme$labels, col.axis=theme$labels)), expr=TRUE) } if(!isNullOrFalse(minor.ticks)) { cs$add(expression(xcoords <- get_xcoords(), x_index <- get_xcoords(at_posix = TRUE), axt <- axTicksByTime(.xts(,x_index)[xsubset], ticks.on=minor.ticks, format.labels=format.labels), axis(1, at=xcoords[axt], labels=FALSE, las=theme$las, lwd.ticks=0.75, mgp=c(3,1.5,0), tcl=-0.4, cex.axis=theme$cex.axis, col=theme$labels, col.axis=theme$labels)), expr=TRUE) } text.exp <- c(expression(text(xlim[1],0.5,main,font=2,col=theme$labels,offset=0,cex=1.1,pos=4)), expression(text(xlim[2],0.5, paste(start(xdata[xsubset]),end(xdata[xsubset]),sep=" / "), col=theme$labels,adj=c(0,0),pos=2))) cs$add(text.exp, env=cs$Env, expr=TRUE) cs$set_frame(2) exp <- expression(segments(xlim[1], y_grid_lines(get_ylim()[[2]]), xlim[2], y_grid_lines(get_ylim()[[2]]), col=theme$grid, lwd=grid.ticks.lwd, lty=grid.ticks.lty)) if(yaxis.left){ exp <- c(exp, expression(text(xlim[1], y_grid_lines(get_ylim()[[2]]), noquote(format(y_grid_lines(get_ylim()[[2]]), justify="right")), col=theme$labels, srt=theme$srt, offset=1, pos=2, cex=theme$cex.axis, xpd=TRUE))) } if(yaxis.right){ exp <- c(exp, expression(text(xlim[2], y_grid_lines(get_ylim()[[2]]), noquote(format(y_grid_lines(get_ylim()[[2]]), justify="right")), col=theme$labels, srt=theme$srt, offset=1, pos=4, cex=theme$cex.axis, xpd=TRUE))) } exp <- c(exp, expression(title(ylab = ylab[1], mgp = c(1, 1, 0)))) cs$add(exp, env=cs$Env, expr=TRUE) cs$set_frame(2) if(isTRUE(multi.panel)){ lenv <- cs$new_environment() lenv$xdata <- cs$Env$xdata[subset,1] lenv$label <- colnames(cs$Env$xdata[,1]) lenv$type <- cs$Env$type if(yaxis.same){ lenv$ylim <- cs$Env$constant_ylim } else { lenv$ylim <- range(cs$Env$xdata[subset,1], na.rm=TRUE) } exp <- quote(chart.lines(xdata, type=type, lty=lty, lwd=lwd, lend=lend, col=theme$col, up.col=theme$up.col, dn.col=theme$dn.col, legend.loc=legend.loc)) exp <- as.expression(add.par.from.dots(exp, ...)) cs$add(exp, env=lenv, expr=TRUE) text.exp <- expression(text(x=get_xcoords()[2], y=ylim[2]*0.9, labels=label, col=theme$labels, adj=c(0,0),cex=1,offset=0,pos=4)) cs$add(text.exp,env=lenv,expr=TRUE) if(NCOL(cs$Env$xdata) > 1){ for(i in 2:NCOL(cs$Env$xdata)){ lenv <- cs$new_environment() lenv$xdata <- cs$Env$xdata[subset,i] lenv$label <- cs$Env$column_names[i] if(yaxis.same){ lenv$ylim <- cs$Env$constant_ylim } else { yrange <- range(cs$Env$xdata[subset,i], na.rm=TRUE) if(all(yrange == 0)) yrange <- yrange + c(-1,1) lenv$ylim <- yrange } lenv$type <- cs$Env$type lenv$lty <- cs$Env$lty[i] lenv$lwd <- cs$Env$lwd[i] lenv$col <- cs$Env$theme$col[i] cs$add_frame(ylim=c(0,1),asp=0.25) cs$next_frame() text.exp <- expression(text(x=xlim[1], y=0.5, labels="", adj=c(0,0),cex=0.9,offset=0,pos=4)) cs$add(text.exp, env=lenv, expr=TRUE) cs$add_frame(ylim=lenv$ylim, asp=NCOL(cs$Env$xdata), fixed=TRUE) cs$next_frame() exp <- quote(chart.lines(xdata[xsubset], type=type, lty=lty, lwd=lwd, lend=lend, col=col, up.col=theme$up.col, dn.col=theme$dn.col, legend.loc=legend.loc)) exp <- as.expression(add.par.from.dots(exp, ...)) exp <- c(exp, expression(segments(xlim[1], y_grid_lines(ylim), xlim[2], y_grid_lines(ylim), col=theme$grid, lwd=grid.ticks.lwd, lty=grid.ticks.lty)), expression(x_grid_lines(xdata[xsubset], grid.ticks.on, ylim))) if(yaxis.left){ exp <- c(exp, expression(text(xlim[1], y_grid_lines(ylim), noquote(format(y_grid_lines(ylim),justify="right")), col=theme$labels, srt=theme$srt, offset=1, pos=2, cex=theme$cex.axis, xpd=TRUE))) } if(yaxis.right){ exp <- c(exp, expression(text(xlim[2], y_grid_lines(ylim), noquote(format(y_grid_lines(ylim),justify="right")), col=theme$labels, srt=theme$srt, offset=1, pos=4, cex=theme$cex.axis, xpd=TRUE))) } cs$add(exp,env=lenv,expr=TRUE,no.update=TRUE) text.exp <- expression(text(x=get_xcoords()[2], y=ylim[2]*0.9, labels=label, col=theme$labels, adj=c(0,0),cex=1,offset=0,pos=4)) cs$add(text.exp,env=lenv,expr=TRUE) } } } else { if(type == "h" && NCOL(x) > 1) warning("only the univariate series will be plotted") exp <- quote(chart.lines(xdata[xsubset], type=type, lty=lty, lwd=lwd, lend=lend, col=theme$col, up.col=theme$up.col, dn.col=theme$dn.col, legend.loc=legend.loc)) exp <- as.expression(add.par.from.dots(exp, ...)) cs$add(exp, expr=TRUE) assign(".xts_chob", cs, .plotxtsEnv) } if(!is.null(panels) && nchar(panels) > 0) { panels <- parse(text=panels, srcfile=NULL) for( p in 1:length(panels)) { if(length(panels[p][[1]][-1]) > 0) { cs <- eval(panels[p]) } else { cs <- eval(panels[p]) } } } assign(".xts_chob", cs, .plotxtsEnv) cs } addPanel <- function(FUN, main="", on=NA, type="l", col=NULL, lty=1, lwd=1, pch=1, ...){ chob <- current.xts_chob() xdata <- chob$Env$xdata fun <- match.fun(FUN) .formals <- formals(fun) if("..." %in% names(.formals)) { x <- try(do.call(fun, c(list(xdata), list(...)), quote=TRUE), silent=TRUE) } else { .formals <- modify.args(formals=.formals, arglist=list(...)) .formals[[1]] <- quote(xdata) x <- try(do.call(fun, .formals), silent=TRUE) } if(inherits(x, "try-error")) { message(paste("FUN function failed with message", x)) return(NULL) } addSeriesCall <- quote(addSeries(x = x, main = main, on = on, type = type, col = col, lty = lty, lwd = lwd, pch = pch)) addSeriesCall <- add.par.from.dots(addSeriesCall, ...) eval(addSeriesCall) } addSeries <- function(x, main="", on=NA, type="l", col=NULL, lty=1, lwd=1, pch=1, ...){ plot_object <- current.xts_chob() lenv <- plot_object$new_environment() lenv$main <- main lenv$plot_lines <- function(x, ta, on, type, col, lty, lwd, pch, ...){ xdata <- x$Env$xdata xsubset <- x$Env$xsubset xDataSubset <- xdata[xsubset] if(all(is.na(on))){ x$Env$x_grid_lines(xDataSubset, x$Env$grid.ticks.on, par("usr")[3:4]) } if(xsubset == "") { subset.range <- xsubset } else { fmt <- "%Y-%m-%d %H:%M:%OS6" subset.range <- paste(format(start(xDataSubset), fmt), format(end(xDataSubset), fmt), sep = "/") } xds <- .xts(, .index(xDataSubset), tzone=tzone(xdata)) ta.y <- merge(ta, xds)[subset.range] if (!isTRUE(x$Env$extend.xaxis)) { xi <- .index(ta.y) xc <- .index(xds) xsubset <- which(xi >= xc[1] & xi <= xc[length(xc)]) ta.y <- ta.y[xsubset] } chart.lines(ta.y, type=type, col=col, lty=lty, lwd=lwd, pch=pch, ...) } expargs <- substitute(alist(ta=x, on=on, type=type, col=col, lty=lty, lwd=lwd, pch=pch, ...)) expargs <- lapply(expargs[-1L], eval, parent.frame()) exp <- as.call(c(quote(plot_lines), x = quote(current.xts_chob()), expargs)) plot_object$add_call(match.call()) xdata <- plot_object$Env$xdata xsubset <- plot_object$Env$xsubset no.update <- FALSE lenv$xdata <- merge(x,xdata,retside=c(TRUE,FALSE)) if(hasArg("ylim")) { ylim <- eval.parent(substitute(alist(...))$ylim) } else { ylim <- range(lenv$xdata[xsubset], na.rm=TRUE) if(all(ylim == 0)) ylim <- c(-1, 1) } lenv$ylim <- ylim if(is.na(on[1])){ plot_object$add_frame(ylim=c(0,1),asp=0.25) plot_object$next_frame() text.exp <- expression(text(x=xlim[1], y=0.3, labels=main, col=1,adj=c(0,0),cex=0.9,offset=0,pos=4)) plot_object$add(text.exp, env=lenv, expr=TRUE) plot_object$add_frame(ylim=ylim,asp=1,fixed=TRUE) plot_object$next_frame() exp <- c(exp, expression(segments(xlim[1], y_grid_lines(ylim), xlim[2], y_grid_lines(ylim), col=theme$grid, lwd=grid.ticks.lwd, lty=grid.ticks.lty))) if(plot_object$Env$theme$lylab){ exp <- c(exp, expression(text(xlim[1]-xstep*2/3-max(strwidth(y_grid_lines(ylim))), y_grid_lines(ylim), noquote(format(y_grid_lines(ylim),justify="right")), col=theme$labels, srt=theme$srt, offset=0, pos=4, cex=theme$cex.axis, xpd=TRUE))) } if(plot_object$Env$theme$rylab){ exp <- c(exp, expression(text(xlim[2]+xstep*2/3, y_grid_lines(ylim), noquote(format(y_grid_lines(ylim),justify="right")), col=theme$labels, srt=theme$srt, offset=0, pos=4, cex=theme$cex.axis, xpd=TRUE))) } plot_object$add(exp,env=lenv,expr=TRUE,no.update=TRUE) } else { for(i in 1:length(on)) { plot_object$set_frame(2*on[i]) plot_object$add(exp,env=lenv,expr=TRUE,no.update=no.update) } } plot_object } lines.xts <- function(x, ..., main="", on=0, col=NULL, type="l", lty=1, lwd=1, pch=1){ if(!is.na(on[1])) if(on[1] == 0) on[1] <- current_panel() addSeries(x, ...=..., main=main, on=on, type=type, col=col, lty=lty, lwd=lwd, pch=pch) } points.xts <- function(x, ..., main="", on=0, col=NULL, pch=1){ if(!is.na(on[1])) if(on[1] == 0) on[1] <- current_panel() addSeries(x, ...=..., main=main, on=on, type="p", col=col, pch=pch) } addEventLines <- function(events, main="", on=0, lty=1, lwd=1, col=1, ...){ events <- try.xts(events) if(!is.na(on[1])) if(on[1] == 0) on[1] <- current_panel() if(nrow(events) > 1){ if(length(lty) == 1) lty <- rep(lty, nrow(events)) if(length(lwd) == 1) lwd <- rep(lwd, nrow(events)) if(length(col) == 1) col <- rep(col, nrow(events)) } plot_object <- current.xts_chob() lenv <- plot_object$new_environment() lenv$main <- main lenv$plot_event_lines <- function(x, events, on, lty, lwd, col, ...){ xdata <- x$Env$xdata xsubset <- x$Env$xsubset if(all(is.na(on))){ x$Env$x_grid_lines(xdata[xsubset], x$Env$grid.ticks.on, par("usr")[3:4]) } ypos <- x$Env$ylim[[2*on]][2]*0.995 subset.range <- paste(format(start(xdata[xsubset]), "%Y%m%d %H:%M:%OS6"), format(end(xdata[xsubset]), "%Y%m%d %H:%M:%OS6"), sep = "/") ta.adj <- merge(n=.xts(1:NROW(xdata[xsubset]), .index(xdata[xsubset]), tzone=tzone(xdata)), .xts(rep(1, NROW(events)), .index(events)))[subset.range] ta.y <- ta.adj[,-1] event.ind <- which(!is.na(ta.y)) abline(v=x$get_xcoords()[event.ind], col=col, lty=lty, lwd=lwd) text(x=x$get_xcoords()[event.ind], y=ypos, labels=as.character(events[,1]), col=x$Env$theme$labels, ...) } expargs <- substitute(alist(events=events, on=on, lty=lty, lwd=lwd, col=col, ...)) expargs <- lapply(expargs[-1L], eval, parent.frame()) exp <- as.call(c(quote(plot_event_lines), x = quote(current.xts_chob()), expargs)) plot_object$add_call(match.call()) if(is.na(on[1])){ xdata <- plot_object$Env$xdata xsubset <- plot_object$Env$xsubset no.update <- FALSE lenv$xdata <- xdata ylim <- range(xdata[xsubset], na.rm=TRUE) lenv$ylim <- ylim plot_object$add_frame(ylim=c(0,1),asp=0.25) plot_object$next_frame() text.exp <- expression(text(x=xlim[1], y=0.3, labels=main, col=1,adj=c(0,0),cex=0.9,offset=0,pos=4)) plot_object$add(text.exp, env=lenv, expr=TRUE) plot_object$add_frame(ylim=ylim,asp=1,fixed=TRUE) plot_object$next_frame() exp <- c(exp, expression(segments(xlim[1], y_grid_lines(ylim), xlim[2], y_grid_lines(ylim), col=theme$grid, lwd=grid.ticks.lwd, lty=grid.ticks.lty))) if(plot_object$Env$theme$lylab){ exp <- c(exp, expression(text(xlim[1]-xstep*2/3-max(strwidth(y_grid_lines(ylim))), y_grid_lines(ylim), noquote(format(y_grid_lines(ylim),justify="right")), col=theme$labels, srt=theme$srt, offset=0, pos=4, cex=theme$cex.axis, xpd=TRUE))) } if(plot_object$Env$theme$rylab){ exp <- c(exp, expression(text(xlim[2]+xstep*2/3, y_grid_lines(ylim), noquote(format(y_grid_lines(ylim),justify="right")), col=theme$labels, srt=theme$srt, offset=0, pos=4, cex=theme$cex.axis, xpd=TRUE))) } plot_object$add(exp,env=lenv,expr=TRUE,no.update=TRUE) } else { for(i in 1:length(on)) { no.update <- FALSE plot_object$set_frame(2*on[i]) plot_object$add(exp,env=lenv,expr=TRUE,no.update=no.update) } } plot_object } addLegend <- function(legend.loc="topright", legend.names=NULL, col=NULL, ncol=1, on=0, ...){ if(!is.na(on[1])) if(on[1] == 0) on[1] <- current_panel() plot_object <- current.xts_chob() lenv <- plot_object$new_environment() lenv$plot_legend <- function(x, legend.loc, legend.names, col, ncol, on, bty, text.col, ...){ if(is.na(on[1])){ yrange <- c(0, 1) } else { yrange <- x$Env$ylim[[2*on]] } if(is.null(ncol)){ ncol <- NCOL(x$Env$xdata) } if(is.null(col)){ col <- x$Env$theme$col[1:NCOL(x$Env$xdata)] } if(is.null(legend.names)){ legend.names <- x$Env$column_names } if(missing(bty)){ bty <- "n" } if(missing(text.col)){ text.col <- x$Env$theme$labels } lc <- legend.coords(legend.loc, x$Env$xlim, yrange) legend(x=lc$x, y=lc$y, legend=legend.names, xjust=lc$xjust, yjust=lc$yjust, ncol=ncol, col=col, bty=bty, text.col=text.col, ...) } plot_object$add_call(match.call()) expargs <- substitute(alist(legend.loc=legend.loc, legend.names=legend.names, col=col, ncol=ncol, on=on, ...)) expargs <- lapply(expargs[-1L], eval, parent.frame()) exp <- as.call(c(quote(plot_legend), x = quote(current.xts_chob()), expargs)) if(is.na(on[1])){ plot_object$add_frame(ylim=c(0,1),asp=0.25) plot_object$next_frame() text.exp <- expression(text(x=xlim[1], y=0.3, labels=main, col=theme$labels,adj=c(0,0),cex=0.9,offset=0,pos=4)) plot_object$add(text.exp, env=lenv, expr=TRUE) plot_object$add_frame(ylim=c(0,1),asp=0.8,fixed=TRUE) plot_object$next_frame() plot_object$add(exp,env=lenv,expr=TRUE,no.update=TRUE) } else { for(i in 1:length(on)) { no.update <- FALSE plot_object$set_frame(2*on[i]) plot_object$add(exp,env=lenv,expr=TRUE,no.update=no.update) } } plot_object } legend.coords <- function(legend.loc, xrange, yrange) { switch(legend.loc, topleft = list(xjust = 0, yjust = 1, x = xrange[1], y = yrange[2]), left = list(xjust = 0, yjust = 0.5, x = xrange[1], y = sum(yrange) / 2), bottomleft = list(xjust = 0, yjust = 0, x = xrange[1], y = yrange[1]), top = list(xjust = 0.5, yjust = 1, x = (xrange[1] + xrange[2]) / 2, y = yrange[2]), center = list(xjust = 0.5, yjust = 0.5, x = (xrange[1] + xrange[2]) / 2, y = sum(yrange) / 2), bottom = list(xjust = 0.5, yjust = 0, x = (xrange[1] + xrange[2]) / 2, y = yrange[1]), topright = list(xjust = 1, yjust = 1, x = xrange[2], y = yrange[2]), right = list(xjust = 1, yjust = 0.5, x = xrange[2], y = sum(yrange) / 2), bottomright = list(xjust = 1, yjust = 0, x = xrange[2], y = yrange[1]) ) } addPolygon <- function(x, y=NULL, main="", on=NA, col=NULL, ...){ x <- try.xts(x) if(!is.null(y)) stop("y is not null") if(ncol(x) > 2) warning("more than 2 columns detected in x, only the first 2 will be used") plot_object <- current.xts_chob() lenv <- plot_object$new_environment() lenv$main <- main lenv$plot_lines <- function(x, ta, on, col, ...){ xdata <- x$Env$xdata xsubset <- x$Env$xsubset if(is.null(col)) col <- x$Env$theme$col if(all(is.na(on))){ x$Env$x_grid_lines(xdata[xsubset], x$Env$grid.ticks.on, par("usr")[3:4]) } subset.range <- paste(start(xdata[xsubset]), end(xdata[xsubset]),sep="/") ta.adj <- merge(n=.xts(1:NROW(xdata[xsubset]), .index(xdata[xsubset]), tzone=tzone(xdata)),ta)[subset.range] ta.y <- na.omit(ta.adj[,-1]) n <- NROW(ta.y) xx <- .index(ta.y)[c(1,1:n,n:1)] yu <- as.vector(coredata(ta.y[,1])) yl <- as.vector(coredata(ta.y[,2])) polygon(x=xx, y=c(yl[1], yu, rev(yl)), border=NA, col=col, ...) } expargs <- substitute(alist(ta=x, col=col, on=on, ...)) expargs <- lapply(expargs[-1L], eval, parent.frame()) exp <- as.call(c(quote(plot_lines), x = quote(current.xts_chob()), expargs)) plot_object$add_call(match.call()) xdata <- plot_object$Env$xdata xsubset <- plot_object$Env$xsubset no.update <- FALSE lenv$xdata <- merge(x,xdata,retside=c(TRUE,FALSE)) if(hasArg("ylim")) { ylim <- eval.parent(substitute(alist(...))$ylim) } else { ylim <- range(lenv$xdata[xsubset], na.rm=TRUE) if(all(ylim == 0)) ylim <- c(-1, 1) } lenv$ylim <- ylim if(is.na(on[1])){ plot_object$add_frame(ylim=c(0,1),asp=0.25) plot_object$next_frame() text.exp <- expression(text(x=xlim[1], y=0.3, labels=main, col=1,adj=c(0,0),cex=0.9,offset=0,pos=4)) plot_object$add(text.exp, env=lenv, expr=TRUE) plot_object$add_frame(ylim=ylim,asp=1,fixed=TRUE) plot_object$next_frame() exp <- c(exp, expression(segments(xlim[1], y_grid_lines(ylim), xlim[2], y_grid_lines(ylim), col=theme$grid, lwd=grid.ticks.lwd, lty=grid.ticks.lty))) if(plot_object$Env$theme$lylab){ exp <- c(exp, expression(text(xlim[1], y_grid_lines(ylim), noquote(format(y_grid_lines(ylim),justify="right")), col=theme$labels, srt=theme$srt, offset=1, pos=2, cex=theme$cex.axis, xpd=TRUE))) } if(plot_object$Env$theme$rylab){ exp <- c(exp, expression(text(xlim[2], y_grid_lines(ylim), noquote(format(y_grid_lines(ylim),justify="right")), col=theme$labels, srt=theme$srt, offset=1, pos=4, cex=theme$cex.axis, xpd=TRUE))) } plot_object$add(exp,env=lenv,expr=TRUE,no.update=TRUE) } else { for(i in 1:length(on)) { plot_object$set_frame(2*on[i]) plot_object$add(exp,env=lenv,expr=TRUE,no.update=no.update) } } plot_object } new.replot_xts <- function(frame=1,asp=1,xlim=c(1,10),ylim=list(structure(c(1,10),fixed=FALSE))) { Env <- new.env() Env$frame <- frame Env$asp <- asp Env$xlim <- xlim Env$ylim <- ylim Env$pad1 <- -0 Env$pad3 <- 0 if(length(asp) != length(ylim)) stop("'ylim' and 'asp' must be the same length") set_frame <- function(frame,clip=TRUE) { Env$frame <<- frame; set_window(clip); } set_asp <- function(asp) { Env$asp <<- asp } set_xlim <- function(xlim) { Env$xlim <<- xlim } set_ylim <- function(ylim) { Env$ylim <<- ylim } set_pad <- function(pad) { Env$pad1 <<- pad[1]; Env$pad3 <<- pad[2] } reset_ylim <- function() { ylim <- get_ylim() ylim <- rep(list(c(Inf,-Inf)),length(ylim)) lapply(Env$actions, function(x) { frame <- attr(x, "frame") if(frame > 0) { lenv <- attr(x,"env") if(is.list(lenv)) lenv <- lenv[[1]] ylim[[frame]][1] <<- min(ylim[[frame]][1],range(na.omit(lenv$xdata[Env$xsubset]))[1],na.rm=TRUE) ylim[[frame]][2] <<- max(ylim[[frame]][2],range(na.omit(lenv$xdata[Env$xsubset]))[2],na.rm=TRUE) } }) set_ylim(ylim) } get_frame <- function(frame) { Env$frame } get_asp <- function(asp) { Env$asp } get_xlim <- function(xlim) { Env$xlim } get_ylim <- function(ylim) { Env$ylim } scale_ranges <- function(frame, asp, ranges) { asp/asp[frame] * abs(diff(ranges[[frame]])) } set_window <- function(clip=TRUE,set=TRUE) { frame <- Env$frame frame <- abs(frame) asp <- Env$asp xlim <- Env$xlim ylim <- lapply(Env$ylim, function(x) structure(x + (diff(x) * c(Env$pad1, Env$pad3)),fixed=attr(x,"fixed"))) sr <- scale_ranges(frame, asp, ylim) if(frame == 1) { win <- list(xlim, c((ylim[[frame]][1] - sum(sr[-1])), ylim[[frame]][2])) } else if(frame == length(ylim)) { win <- list(xlim, c(ylim[[frame]][1], ylim[[frame]][2] + sum(sr[-length(sr)]))) } else { win <- list(xlim, c(ylim[[frame]][1] - sum(sr[-(1:frame)]), ylim[[frame]][2] + sum(sr[-(frame:length(sr))]))) } if(!set) return(win) do.call("plot.window",win) if(clip) clip(par("usr")[1],par("usr")[2],ylim[[frame]][1],ylim[[frame]][2]) } get_actions <- function(frame) { actions <- NULL for(i in 1:length(Env$actions)) { if(abs(attr(Env$actions[[i]],"frame"))==frame) actions <- c(actions, Env$actions[i]) } actions } get_xcoords <- function(xts_object = NULL, at_posix = FALSE) { xcoords <- Env$xycoords$x if (!is.null(xts_object)) { xcoords <- merge(.xts(seq_along(xcoords), xcoords), xts_object, fill = na.locf, join = "right", retside = c(TRUE, FALSE)) if (!isTRUE(Env$extend.xaxis)) { xc <- Env$xycoords$x xi <- .index(xcoords) xsubset <- which(xi >= xc[1] & xi <= xc[length(xc)]) xcoords <- xcoords[xsubset] } if(Env$observation.based && !at_posix) { result <- drop(coredata(xcoords)) } else { result <- .index(xcoords) } } else { if(Env$observation.based && !at_posix) { result <- seq_along(xcoords) } else { result <- xcoords } } return(result) } add_frame <- function(after, ylim=c(0,0), asp=0, fixed=FALSE) { if(missing(after)) after <- max(abs(sapply(Env$actions, function(x) attr(x,"frame")))) for(i in 1:length(Env$actions)) { cframe <- attr(Env$actions[[i]],"frame") if(cframe > 0 && cframe > after) attr(Env$actions[[i]], "frame") <- cframe+1L if(cframe < 0 && cframe < -after) attr(Env$actions[[i]], "frame") <- cframe-1L } Env$ylim <- append(Env$ylim,list(structure(ylim,fixed=fixed)),after) Env$asp <- append(Env$asp,asp,after) } update_frames <- function(headers=TRUE) { from_by <- ifelse(headers,2,1) ylim <- get_ylim() for(y in seq(from_by,length(ylim),by=from_by)) { if(!attr(ylim[[y]],'fixed')) ylim[[y]] <- structure(c(Inf,-Inf),fixed=FALSE) } update_frame <- function(x) { if(!is.null(attr(x,"no.update")) && attr(x, "no.update")) return(NULL) frame <- abs(attr(x, "frame")) fixed <- attr(ylim[[frame]],'fixed') if(frame %% from_by == 0 && !fixed) { lenv <- attr(x,"env") if(is.list(lenv)) lenv <- lenv[[1]] lenv_data <- lenv$xdata if(!is.null(lenv_data)) { dat.range <- range(na.omit(lenv$xdata[Env$xsubset])) min.tmp <- min(ylim[[frame]][1],dat.range,na.rm=TRUE) max.tmp <- max(ylim[[frame]][2],dat.range,na.rm=TRUE) ylim[[frame]] <<- structure(c(min.tmp,max.tmp),fixed=fixed) } } } lapply(Env$actions, update_frame) set_ylim(ylim) x_axis <- Env$xdata[Env$xsubset][,1] update_xaxis <- function(action) { action_frame <- abs(attr(action, "frame")) if (action_frame %% from_by == 0) { lenv <- attr(action, "env") if (is.list(lenv)) { lenv <- lenv[[1]] } lenv_data <- lenv$xdata if (!is.null(lenv_data)) { new_x_axis <- merge(x_axis, .xts(, .index(lenv_data[Env$xsubset]))) if (isTRUE(Env$extend.xaxis)) { x_axis <<- new_x_axis } else { ixc <- .index(new_x_axis) xaxis_rng <- range(.index(x_axis), na.rm = TRUE) x_axis <<- new_x_axis[ixc >= xaxis_rng[1L] & ixc <= xaxis_rng[2L],] } } } } lapply(Env$actions, update_xaxis) x_axis <- unique(.index(x_axis)) Env$xycoords <- xy.coords(x_axis, seq_along(x_axis)) if (Env$observation.based) { Env$xlim <- c(1, length(get_xcoords())) Env$xstep <- 1 } else { Env$xlim <- range(get_xcoords(), na.rm = TRUE) Env$xstep <- diff(get_xcoords()[1:2]) } } remove_frame <- function(frame) { rm.frames <- NULL max.frame <- max(abs(sapply(Env$actions, function(x) attr(x,"frame")))) for(i in 1:length(Env$actions)) { cframe <- attr(Env$actions[[i]],"frame") if(abs(attr(Env$actions[[i]],"frame"))==frame) rm.frames <- c(rm.frames, i) if(cframe > 0 && cframe > frame) { attr(Env$actions[[i]], "frame") <- cframe-1L } if(cframe < 0 && cframe < -frame) { attr(Env$actions[[i]], "frame") <- cframe+1L } } if(frame > max.frame) { Env$frame <- max.frame } else Env$frame <- max.frame-1 Env$ylim <- Env$ylim[-frame] Env$asp <- Env$asp[-frame] if(!is.null(rm.frames)) Env$actions <- Env$actions[-rm.frames] } next_frame <- function() { set_frame(max(abs(sapply(Env$actions,function(x) attr(x,"frame"))))+1L) } Env$actions <- list() add <- replot <- function(x,env=Env,expr=FALSE,clip=TRUE,...) { if(!expr) { x <- match.call()$x } a <- structure(x,frame=Env$frame,clip=clip,env=env,...) Env$actions[[length(Env$actions)+1]] <<- a } subset <- function(x="") { Env$xsubset <<- x set_xlim(range(get_xcoords(), na.rm=TRUE)) ylim <- get_ylim() for(y in seq(2,length(ylim),by=2)) { if(!attr(ylim[[y]],'fixed')) ylim[[y]] <- structure(c(Inf,-Inf),fixed=FALSE) } lapply(Env$actions, function(x) { frame <- abs(attr(x, "frame")) fixed <- attr(ylim[[frame]],'fixed') if(frame %% 2 == 0 && !fixed) { lenv <- attr(x,"env") if(is.list(lenv)) lenv <- lenv[[1]] yrange <- range(lenv$xdata[Env$xsubset], na.rm=TRUE) if(all(yrange == 0)) yrange <- yrange + c(-1,1) min.tmp <- min(ylim[[frame]][1],yrange[1],na.rm=TRUE) max.tmp <- max(ylim[[frame]][2],yrange[2],na.rm=TRUE) ylim[[frame]] <<- structure(c(min.tmp,max.tmp),fixed=fixed) } }) set_ylim(ylim) } add_call <- function(call.) { stopifnot(is.call(call.)) ncalls <- length(Env$call_list) Env$call_list[[ncalls+1]] <- call. } replot_env <- new.env() class(replot_env) <- c("replot_xts","environment") replot_env$Env <- Env replot_env$set_window <- set_window replot_env$add <- add replot_env$replot <- replot replot_env$get_actions <- get_actions replot_env$subset <- subset replot_env$get_xcoords <- get_xcoords replot_env$update_frames <- update_frames replot_env$set_frame <- set_frame replot_env$get_frame <- get_frame replot_env$next_frame <- next_frame replot_env$add_frame <- add_frame replot_env$remove_frame <- remove_frame replot_env$set_asp <- set_asp replot_env$get_asp <- get_asp replot_env$set_xlim <- set_xlim replot_env$get_xlim <- get_xlim replot_env$reset_ylim <- reset_ylim replot_env$set_ylim <- set_ylim replot_env$get_ylim <- get_ylim replot_env$set_pad <- set_pad replot_env$add_call <- add_call replot_env$new_environment <- function() { new.env(TRUE, Env) } replot_env$Env$y_grid_lines <- function(ylim) { p <- pretty(ylim,5) p[p > ylim[1] & p < ylim[2]] } replot_env$Env$x_grid_lines <- function(x, ticks.on, ylim) { if (isNullOrFalse(ticks.on)) { invisible() } else { if (isTRUE(ticks.on)) ticks.on <- "auto" xcoords <- get_xcoords(at_posix = TRUE) atbt <- axTicksByTime(.xts(, xcoords), ticks.on = ticks.on) segments(xcoords[atbt], ylim[1L], xcoords[atbt], ylim[2L], col = Env$theme$grid, lwd = Env$grid.ticks.lwd, lty = Env$grid.ticks.lty) } } return(replot_env) } str.replot_xts <- function(x, ...) { print(str(unclass(x))) } print.replot_xts <- function(x, ...) plot(x,...) plot.replot_xts <- function(x, ...) { obg <- par(bg = x$Env$theme$bg) plot.new() assign(".xts_chob",x,.plotxtsEnv) ocex <- par(cex = if(.Device == "X11") x$Env$cex else x$Env$cex * 1.5) omar <- par(mar = x$Env$mar) oxpd <- par(xpd = FALSE) usr <- par("usr") last.frame <- x$get_frame() x$update_frames() is_underlay_action <- sapply(x$Env$actions, function(a) attr(a, "frame") < 0) plot_action <- function(action) { x$set_frame(attr(action,"frame"),attr(action,"clip")) env <- attr(action,"env") if(is.list(env)) { env <- unlist(lapply(env, function(x) eapply(x, eval)),recursive=FALSE) } eval(action, env) } for(a in x$Env$actions[ is_underlay_action]) { plot_action(a) } for(a in x$Env$actions[!is_underlay_action]) { plot_action(a) } x$set_frame(abs(last.frame),clip=FALSE) do.call("clip", as.list(usr)) par(xpd = oxpd$xpd, cex = ocex$cex, mar = omar$mar, bg = obg$bg) invisible(x$Env$actions) } actions <- function(obj) obj$Env$actions chart_actions <- function() actions(current.xts_chob()) current_panel <- function() { act <- chart_actions() attr(act[[length(act)]], "frame") / 2 }
word_cor <- function(x, word, type = "dtm", method = "kendall", p = NULL, min = NULL){ infolocale <- localestart2() on.exit(localeend2(infolocale)) if (identical(class(x)[1], "DocumentTermMatrix")){ truetype <- 1 all_word <- x$dimnames$Terms } else if (identical(class(x)[1] , "TermDocumentMatrix")){ all_word <- x$dimnames$Terms truetype <- 2 } else if (identical(class(x)[1], "matrix")){ if (!is_character_vector(type, len = 1)) stop ("When x is matrix, type must tell me its type: dtm or tdm.") if (grepl("^d|^D", type)){ truetype <- 3 all_word <- colnames(x) if (is.null(all_word)) stop ("colnames as words should not be NULL.") } else if (grepl("^t|^T", type)){ truetype <- 4 all_word <- rownames(x) if (is.null(all_word)) stop("rownames as words should not be NULL.") } else { stop ("When x is matrix, type must tell me its type: dtm or tdm.") } } else { stop("x must be among DTM, TDM or matrix.") } stopifnot(method %in% c("pearson", "kendall", "spearman")) if (!is.null(p)) stopifnot(is.numeric(p), length(p) == 1) if (!is.null(min)) stopifnot(is.numeric(min), length(min) == 1) word <- as.character2(word) if (length(word) > 200) stop("Argument word allows input of not more than 200 words.") if (any(is.na(word))) stop("Argument word should not have NA.") all_word <- sort(all_word) word <- intersect(word, all_word) word <- sort(unique(word)) if (length(word) < 2) stop("At least 2 words should be left.") pos <- match(word, all_word) if (truetype %in% c(1, 3)){ x <- x[, pos] } else { x <- t(x[pos, ]) } nc <- ncol(x) correlation <- matrix(NA, nrow = nc, ncol = nc) pvalue <- matrix(NA, nrow = nc, ncol = nc) if (truetype %in% c(3, 4)){ for (i in 1: nc){ for (j in 1: nc){ if (i > j){ cc <- stats::cor.test(x = x[, i], y = x[, j], method = method, exact = FALSE) cc1 <- round(cc$estimate, 4) correlation[i, j] <- cc1 correlation[j, i] <- cc1 cc2 <- round(cc$p.value, 4) pvalue[i, j] <- cc2 pvalue[j, i] <- cc2 } } } } else { for (i in 1: nc){ ii <- as.numeric(as.matrix(x[, i])) for (j in 1: nc){ jj <- as.numeric(as.matrix(x[, j])) if (i > j){ cc <- stats::cor.test(x = ii, y = jj, method = method, exact = FALSE) cc1 <- round(cc$estimate, 4) correlation[i, j] <- cc1 correlation[j, i] <- cc1 cc2 <- round(cc$p.value, 4) pvalue[i, j] <- cc2 pvalue[j, i] <- cc2 } } } } rownames(correlation) <- word colnames(correlation) <- word rownames(pvalue) <- word colnames(pvalue) <- word if (!is.null(p) & is.null(min)){ correlation[pvalue >= p] <- NA } if (!is.null(min) & is.null(p)){ correlation[abs(correlation) < min] <- NA } if (!is.null(min) & !is.null(p)){ hidethis1 <- pvalue >= p hidethis2 <- abs(correlation) < min correlation[hidethis1 | hidethis2] <- NA } return(list(corMatrix = correlation, pMatrix = pvalue)) }
"tteign" <- function(covtau,nq,mdc=np-nq) { if (missing(covtau)) messagena("covtau") if (missing(nq)) messagena("nq") np <- ncol(covtau) xlmbda <- single(np) iv <- integer(np) sv <- single(np) f.res <- .Fortran("tteignz", covtau=to.single(covtau), np=to.integer(np), nq=to.integer(nq), mdc=to.integer(mdc), xlmbda=to.single(xlmbda), iv=to.integer(iv), sv=to.single(sv)) list(xlmbda=f.res$xlmbda) }
NULL init_knitr_for_roxygen <- function() { Sys.setenv(CLI_TICK_TIME = "100") options( cli.num_colors = 256L, asciicast_cols = 70 ) proc <- .GlobalEnv$.knitr_asciicast_process if (is.null(proc) || !proc$is_alive()) { asciicast::init_knitr_engine( startup = quote({ options(cli.width = 70) options(cli.progress_show_after = 0) options(cli.progress_clear = FALSE) library(cli) set.seed(1) }), echo = TRUE, echo_input = FALSE, options = list( asciicast_cols = 70, asciicast_end_wait = 3 ) ) } invisible("") } `%||%` <- function(l, r) if (is.null(l)) r else l new_class <- function(class_name, ...) { structure(as.environment(list(...)), class = class_name) } make_space <- function(len) { strrep(" ", len) } strrep <- function(x, times) { x <- as.character(x) if (length(x) == 0L) return(x) r <- .mapply( function(x, times) { if (is.na(x) || is.na(times)) return(NA_character_) if (times <= 0L) return("") paste0(replicate(times, x), collapse = "") }, list(x = x, times = times), MoreArgs = list() ) res <- unlist(r, use.names = FALSE) Encoding(res) <- Encoding(x) res } is_latex_output <- function() { if (!("knitr" %in% loadedNamespaces())) return(FALSE) get("is_latex_output", asNamespace("knitr"))() } is_windows <- function() { .Platform$OS.type == "windows" } apply_style <- function(text, style, bg = FALSE) { if (identical(text, "")) return(text) if (is.function(style)) { style(text) } else if (is.character(style)) { make_ansi_style(style, bg = bg)(text) } else if (is.null(style)) { text } else { stop("Not a colour name or ANSI style function", call. = FALSE) } } vcapply <- function(X, FUN, ..., USE.NAMES = TRUE) { vapply(X, FUN, FUN.VALUE = character(1), ..., USE.NAMES = USE.NAMES) } viapply <- function(X, FUN, ..., USE.NAMES = TRUE) { vapply(X, FUN, FUN.VALUE = integer(1), ..., USE.NAMES = USE.NAMES) } vlapply <- function(X, FUN, ..., USE.NAMES = TRUE) { vapply(X, FUN, FUN.VALUE = logical(1), ..., USE.NAMES = USE.NAMES) } rpad <- function(x, width = NULL) { if (!length(x)) return(x) w <- nchar(x, type = "width") if (is.null(width)) width <- max(w) paste0(x, strrep(" ", pmax(width - w, 0))) } lpad <- function(x, width = NULL) { if (!length(x)) return(x) w <- nchar(x, type = "width") if (is.null(width)) width <- max(w) paste0(strrep(" ", pmax(width - w, 0)), x) } tail_na <- function(x, n = 1) { utils::tail(c(rep(NA, n), x), n) } dedent <- function(x, n = 2) { first_n_char <- strsplit(ansi_substr(x, 1, n), "")[[1]] n_space <- cumsum(first_n_char == " ") d_n_space <- diff(c(0, n_space)) first_not_space <- utils::head(c(which(d_n_space == 0), n + 1), 1) ansi_substr(x, first_not_space, nchar(x)) } new_uuid <- (function() { cnt <- 0 function() { cnt <<- cnt + 1 paste0("cli-", clienv$pid, "-", cnt) } })() na.omit <- function(x) { if (is.atomic(x)) x[!is.na(x)] else x } last <- function(x) { utils::tail(x, 1)[[1]] } str_tail <- function(x) { substr(x, 2, nchar(x)) } push <- function(l, el, name = NULL) { c(l, structure(list(el), names = name)) } try_silently <- function(expr) { suppressWarnings(tryCatch(expr, error = function(x) x)) } random_id <- local({ i <- 0 function() { i <<- i + 1 paste0("FCkNXbE-", i) } }) random_marker <- "ImzV8dciA4cn4POI" str_trim <- function(x) { sub("^\\s+", "", sub("\\s+$", "", x)) } has_asciicast_support <- function() { tryCatch({ asNamespace("asciicast")$is_recording_supported() && asNamespace("asciicast")$is_svg_supported() }, error = function(e) FALSE) } last_character <- function(x) { substr(x, nchar(x), nchar(x)) } first_character <- function(x) { substr(x, 1, 1) } second_character <- function(x) { substr(x, 2, 2) } is_alnum <- function(x, ok = "") { grepl(paste0("^[[:alnum:]/_.", ok, "]*$"), x) } os_type <- function() { .Platform$OS.type } leading_space <- function(x) { sub("^([\\s\u00a0]*).*$", "\\1", x, perl = TRUE) } trailing_space <- function(x) { sub("^.*[^\\s\u00a0]([\\s\u00a0]*)$", "\\1", x, perl = TRUE) }
UnormalizedSC <- function(W, K=5, flagDiagZero=FALSE, verbose = FALSE){ W <- checking.gram.similarityMatrix(W, flagDiagZero=flagDiagZero, verbose = verbose) if(verbose){message("CALCULATION OF THE DEGREE MATRIX")} D <- diag(rowSums(W)) if(verbose){print(D)} if(verbose){message("CALCULATION OF THE LAPLACIAN MATRIX")} L <- D - W if(verbose){print(L)} if(verbose){message("CALCULATION OF THE EIGEN VECTORS AND VALUES")} U <- eigen(L) if(verbose){ message("EIGEN VALUES = ") print(U$values) message("EIGEN VECTOR = ") print(U$vector) } if(verbose){message(paste(K, "EIGEN VECTORS SELECTION"))} V <- U$vectors[ , ((ncol(L)-K+1):ncol(L))] if(verbose){print(V)} if(verbose){message("CUTTING THE CLUSTER WITH KMEANS")} cluster <- kmeans(V, K)$cluster if(verbose){cat("cluster = ", cluster, "\n")} out <- list(cluster = cluster, eigenVect = U$vector, eigenVal = U$values) }
dyplot.CalGR <- function(x, ...) { if (!inherits(x, "CalGR")) { stop("Non convenient data for x argument. Must be of class \"CalGR\"") } dyplot.default(x, ...) }
getSummary.crch <- function(obj, alpha = 0.05, ...) { memisc::setSummaryTemplate("crch" = c( "Log-likelihood" = "($logLik:f "AIC" = "($AIC:f "BIC" = "($BIC:f "N" = "($N:d)" )) cf <- summary(obj)$coefficients cval <- qnorm(1 - alpha/2) for(i in seq_along(cf)) cf[[i]] <- cbind(cf[[i]], cf[[i]][, 1] - cval * cf[[i]][, 2], cf[[i]][, 1] + cval * cf[[i]][, 2]) nam <- unique(unlist(lapply(cf, rownames))) acf <- array(dim = c(length(nam), 6, length(cf)), dimnames = list(nam, c("est", "se", "stat", "p", "lwr", "upr"), names(cf))) for(i in seq_along(cf)) acf[rownames(cf[[i]]), , i] <- cf[[i]] ctr <- c(obj$contrasts$location, obj$contrasts$scale) ctr <- ctr[!duplicated(names(ctr))] xlev <- obj$levels$full return(list( coef = acf, sumstat = c( "N" = nobs(obj), "logLik" = as.vector(logLik(obj)), "AIC" = AIC(obj), "BIC" = BIC(obj) ), contrasts = ctr, xlevels = xlev, call = obj$call )) }
mvmr_egger_rjags <- function(object, prior = "default", betaprior = "", sigmaprior = "", orientate = 1, n.chains = 3, n.burn = 1000, n.iter = 5000, seed = NULL, rho = 0.5, ...) { if (!("mvmr_format" %in% class(object))) { stop('The class of the data object must be "mvmr_format", please resave the object with the output of e.g. object <- mvmr_format(object).') } rjags_check() if (orientate %in% 1:dim(object$beta.exposure)[2]) { orientAte = orientate } else { orientAte = 1 } orient <- sign(object$beta.exposure)[,orientAte] Likelihood <- "for (i in 1:N){ by[i] ~ dnorm(by.hat[i], tau[i]) by.hat[i] <- Pleiotropy + inprod(Estimate[], bx[i,]) tau[i] <- pow(byse[i] * sigma, -2) }" if (prior == "default" & betaprior == "") { Priors <-"Pleiotropy ~ dnorm(0, 1E-3) \n for (j in 1:K) { Estimate[j] ~ dnorm(0,1E-3) } \n sigma ~ dunif(.0001, 10)" egger_model_string <- paste0("model {", Likelihood, "\n\n", Priors, "\n\n}") } else if (prior == "weak" & betaprior == "") { Priors <- "Pleiotropy ~ dnorm(0, 1E-6) \n for (j in 1:K) { Estimate[j] ~ dnorm(0,1E-6) } \n sigma ~ dunif(.0001, 10)" egger_model_string <- paste0("model {", Likelihood, "\n\n", Priors, "\n\n}") } else if (prior == "pseudo" & betaprior == "") { Priors <-"Pleiotropy ~ dnorm(0,1E-3) \n for (j in 1:K) { Estimate[j] ~ dt(0, 1, 1)} \n invpsi ~ dgamma(1E-3, 1E-3)\n sigma <- 1/invpsi" egger_model_string <- paste0("model {", Likelihood, "\n\n", Priors, "\n\n}") } else if (prior == "joint" & betaprior == ""){ vcov_mat<-" beta[1:l] ~ dmnorm.vcov(mu[], prec[ , ])\n Pleiotropy <- beta[1] for (i in 2:K){ Estimate[i] <- beta[i] } for (i in 1:l){ for (j in 1:l){ mu[i] <- 0 var[i] <- 1e4 sd <- sqrt(var) prec[i,j] <- sd[i] * sd[j] * rho prec[j,i] <- sd[j] * sd[i] * rho prec[i,i] <- var[i] } } sigma ~ dunif(.0001, 10) rho <-" Priors<- paste0(vcov_mat,rho) egger_model_string <- paste0("model {", Likelihood,"\n\n",Priors,"\n\n}") } else if (betaprior != "" & sigmaprior != "") { part1 <-"Pleiotropy ~ dnorm(0, 1E-3) \n for (j in 1:K) {Estimate[j] ~ " part2 <- "\n sigma ~ " Priors <- paste0(part1,betaprior,"}",part2,sigmaprior) egger_model_string <- paste0("model {",Likelihood,"\n\n", Priors,"\n\n }") } else if (betaprior != "" & sigmaprior == "") { part1 <-"Pleiotropy ~ dnorm(0, 1E-3) \n for (j in 1:K) {Estimate[j] ~ " part2 <- "\n sigma ~ dunif(.0001,10)" Priors <- paste0(part1,betaprior,"}",part2) egger_model_string <- paste0("model {",Likelihood,"\n\n", Priors,"\n\n }") } else if (betaprior == "" & sigmaprior != "") { part1 <-"Pleiotropy ~ dnorm(0, 1E-3) \n for (j in 1:K) { Estimate[j] ~ dnorm(0, 1E-6)} \n sigma ~" Priors <- paste0(part1,sigmaprior) egger_model_string <- paste0("model {",Likelihood,"\n\n", Priors,"\n\n }") } if (!is.null(seed)) { if (length(seed) != n.chains) { stop('The length of the seed vector must be equal to the number of chains.') } initsopt <- list() for (i in 1:n.chains) { initsopt[[i]] <- list(.RNG.name = "base::Mersenne-Twister", .RNG.seed = seed[i]) } } else { initsopt <- NULL } egger_model <- rjags::jags.model( textConnection(egger_model_string), data = list( N = length(object$beta.outcome), K = ncol(object$beta.exposure), by = orient * object$beta.outcome, bx = orient * object$beta.exposure, byse = object$se.outcome ), n.chains = n.chains, inits = initsopt, quiet = TRUE, ... ) update.jags <- utils::getFromNamespace("update.jags", "rjags") update.jags(egger_model, n.iter = n.burn) egger_samp <- rjags::coda.samples( egger_model, variable.names = c("Pleiotropy", "Estimate", "sigma"), n.iter = n.iter ) g <- egger_samp p <- summary(egger_samp) prior <- prior niter <- n.iter nburn <- n.burn nchain <- n.chains nsnps <- length(object$beta.outcome) mcmciter <- n.iter + n.burn avg.pleio <- p$statistics[ncol(object$beta.exposure) + 1, 1] avg.pleiostd <- p$statistics[ncol(object$beta.exposure) + 1, 2] avg.pleioLI <- p$quantiles[ncol(object$beta.exposure) + 1, 1] avg.pleioM <- p$quantiles[ncol(object$beta.exposure) + 1, 3] avg.pleioUI <- p$quantiles[ncol(object$beta.exposure) + 1, 5] CI_avgpleio <- c(avg.pleioLI, avg.pleioM, avg.pleioUI) sigma <- p$statistics[ncol(object$beta.exposure) + 2, 1] causal.est <- p$statistics[1:ncol(object$beta.exposure), 1] standard.dev <- p$statistics[1:ncol(object$beta.exposure), 2] lower.credible_interval <- p$quantiles[1:ncol(object$beta.exposure), 1] Median_interval <- p$quantiles[1:ncol(object$beta.exposure), 3] Higher.credible_interval <- p$quantiles[1:ncol(object$beta.exposure), 5] credible_interval <- c(lower.credible_interval, Median_interval, Higher.credible_interval) if (sigma < 1) { warning("The mean of the sigma parameter, the residual standard deviation, we recommend refitting the model with sigma constrained to be >= 1.") } out <- list() out$CausalEffect <- causal.est out$StandardError <- standard.dev out$lower.credible_interval <- lower.credible_interval out$Median_interval <- Median_interval out$Higher.credible_interval <- Higher.credible_interval out$CredibleInterval <- credible_interval out$AvgPleio <- avg.pleio out$AvgPleioSD <- avg.pleiostd out$AvgPleioCI <- CI_avgpleio out$sigma <- sigma out$samples <- g out$priormethod <- prior out$betaprior <- betaprior out$sigmaprior <- sigmaprior out$samplesize <- niter out$burnin <- nburn out$chains <- nchain out$MCMC <- mcmciter out$nsnps <- nsnps out$Prior <- Priors out$model <- egger_model_string class(out) <- "mveggerjags" return(out) } print.mveggerjags <- function(x, ...) { estmat<- matrix(ncol = 5, nrow = length(x$CausalEffect)) for (i in 1:3){ estmat[i,] <- c(x$CausalEffect[i],x$StandardError[i],x$lower.credible_interval[i], x$Median_interval[i],x$Higher.credible_interval[i])} pleiomat<- c(x$AvgPleio,x$AvgPleioSD,x$AvgPleioCI) outt <- matrix( rbind(pleiomat,estmat), nrow = 1 + length(x$CausalEffect), ncol = 5, dimnames = list( c("Avg Pleio", paste0("Causal Effect",1:length(x$CausalEffect))), c("Estimate", "SD", "2.5%", "50%", "97.5%") ) ) print(outt) invisible(x) } summary.mveggerjags <- function(object, ...) { out <- object estmat<- matrix(ncol = 5, nrow = length(out$CausalEffect)) for (i in 1:3){ estmat[i,] <- c(out$CausalEffect[i],out$StandardError[i],out$lower.credible_interval[i], out$Median_interval[i],out$Higher.credible_interval[i])} pleiomat<- c(out$AvgPleio,out$AvgPleioSD,out$AvgPleioCI) out1 <- matrix( rbind(pleiomat,estmat), nrow = 1 + length(out$CausalEffect), ncol = 5, dimnames = list( c("Avg Pleio", paste0("Causal Effect",1:length(out$CausalEffect))), c("Estimate", "SD", "2.5%", "50%", "97.5%") ) ) cat("Prior : \n\n", out$Prior, "\n\n") cat("Estimation results:", "\n", "\n") cat(DescTools::StrAlign("MCMC iterations = ", "\\r"), out$MCMC, "\n") cat(DescTools::StrAlign("Burn in = ", "\\r"), out$burnin, "\n") cat(DescTools::StrAlign("Sample size by chain = ", "\\r"), out$samplesize, "\n") cat(DescTools::StrAlign("Number of Chains = ", "\\r"), out$chains, "\n") cat(DescTools::StrAlign("Number of SNPs = ", "\\r"), out$nsnps, "\n", "\n") cat("Inflating Parameter:", out$sigma, "\n\n") print(out1, ...) }
context("Randomized ID") library(rsvd) set.seed(1234) atol_float64 <- 1e-8 m = 50 n = 30 k = 10 testMat <- matrix(runif(m*k), m, k) testMat <- testMat %*% t(testMat) testMat <- testMat[,1:n] id_out <- rid(testMat) testMat.re = id_out$C %*% id_out$Z testthat::test_that("Test 1: Interpolative decomposition (column) k=NULL", { testthat::expect_equal(testMat, testMat.re) }) testMat.re = testMat[,id_out$idx] %*% id_out$Z testthat::test_that("Test 2: Interpolative decomposition (column idx) k=NULL", { testthat::expect_equal(testMat, testMat.re) }) id_out <- rid(testMat, mode='row') testMat.re = id_out$Z %*% id_out$R testthat::test_that("Test 3: Interpolative decomposition (row) k=NULL", { testthat::expect_equal(testMat, testMat.re) }) testMat.re = id_out$Z %*% testMat[id_out$idx,] testthat::test_that("Test 4: Interpolative decomposition (row idx) k=NULL", { testthat::expect_equal(testMat, testMat.re) }) id_out <- rid(testMat, k=k) testMat.re = id_out$C %*% id_out$Z testthat::test_that("Test 5: Interpolative decomposition (column) k=k", { testthat::expect_equal(testMat, testMat.re) }) testMat.re = testMat[,id_out$idx] %*% id_out$Z testthat::test_that("Test 6: Interpolative decomposition (column idx) k=k", { testthat::expect_equal(testMat, testMat.re) }) id_out <- rid(testMat, mode='row', k=k) testMat.re = id_out$Z %*% id_out$R testthat::test_that("Test 7: Interpolative decomposition (row) k=k", { testthat::expect_equal(testMat, testMat.re) }) testMat.re = id_out$Z %*% testMat[id_out$idx,] testthat::test_that("Test 8: Interpolative decomposition (row idx) k=k", { testthat::expect_equal(testMat, testMat.re) }) testMat <- matrix(runif(m*k), m, k) + 1i* matrix(runif(m*k), m, k) testMat <- testMat %*% H(testMat) testMat <- testMat[,1:n] id_out <- rid(testMat, k=k) testMat.re = id_out$C %*% id_out$Z testthat::test_that("Test 9: Interpolative decomposition (column) k=k", { testthat::expect_equal(testMat, testMat.re) }) testMat.re = testMat[,id_out$idx] %*% id_out$Z testthat::test_that("Test 10: Interpolative decomposition (column idx) k=k", { testthat::expect_equal(testMat, testMat.re) }) id_out <- rid(testMat, mode='row', k=k) testMat.re = id_out$Z %*% id_out$R testthat::test_that("Test 11: Interpolative decomposition (row) k=k", { testthat::expect_equal(testMat, testMat.re) }) testMat.re = id_out$Z %*% testMat[id_out$idx,] testthat::test_that("Test 12: Interpolative decomposition (row idx) k=k", { testthat::expect_equal(testMat, testMat.re) })
test_that("'utf8_normalize' can reproduce Fig. 3", { src <- c("\u212b", "\u2126") nfd <- c("\u0041\u030a", "\u03a9") nfc <- c("\u00c5", "\u03a9") expect_equal(utf8_normalize(src), nfc) expect_equal(utf8_normalize(nfd), nfc) }) test_that("'utf8_normalize' can reproduce Fig. 4", { src <- c("\u00c5", "\u00f4") nfd <- c("\u0041\u030a", "\u006f\u0302") nfc <- c("\u00c5", "\u00f4") expect_equal(utf8_normalize(src), nfc) expect_equal(utf8_normalize(nfd), nfc) }) test_that("'utf8_normalize' can reproduce Fig. 5", { src <- c("\u1e69", "\u1e0b\u0323", "\u0071\u0307\u0323") nfd <- c("\u0073\u0323\u0307", "\u0064\u0323\u0307", "\u0071\u0323\u0307") nfc <- c("\u1e69", "\u1e0d\u0307", "\u0071\u0323\u0307") expect_equal(utf8_normalize(src), nfc) expect_equal(utf8_normalize(nfd), nfc) }) test_that("'utf8_normalize' can reproduce Fig. 6", { src <- c("\ufb01", "\u0032\u2075", "\u1e9b\u0323") nfd <- c("\ufb01", "\u0032\u2075", "\u017f\u0323\u0307") nfc <- c("\ufb01", "\u0032\u2075", "\u1e9b\u0323") nfkd <- c("\u0066\u0069", "\u0032\u0035", "\u0073\u0323\u0307") nfkc <- c("\u0066\u0069", "\u0032\u0035", "\u1e69") expect_equal(utf8_normalize(src), nfc) expect_equal(utf8_normalize(nfd), nfc) expect_equal(utf8_normalize(src, map_compat = TRUE), nfkc) expect_equal(utf8_normalize(nfd, map_compat = TRUE), nfkc) expect_equal(utf8_normalize(nfkd), nfkc) }) test_that("'utf8_normalize' can normalize, case fold, and remove ignorables", { src <- c("A", "\u00df", "\u1e9e", "\u1fc3", "\u200b") nfkc_casefold <- c("a", "ss", "ss", "\u03b7\u03b9", "") expect_equal( utf8_normalize(src, map_case = TRUE, remove_ignorable = TRUE), nfkc_casefold ) }) test_that("'utf8_normalize' can map quotes", { src <- c("\"", "'", "\u2018", "\u2019", "\u201c", "\u201d") quotefold <- c("\"", "'", "'", "'", "\u201c", "\u201d") expect_equal(utf8_normalize(src, map_quote = TRUE), quotefold) }) test_that("'utf8_normalize' accepts NULL", { expect_equal(utf8_normalize(NULL), NULL) }) test_that("'utf8_normalize' accepts NA", { expect_equal(utf8_normalize(NA_character_), NA_character_) }) test_that("'utf8_normalize' can handle backslash", { expect_equal(utf8_normalize("\\m"), "\\m") })
library(tidyverse) library(tidymodels) library(SSLR) context("Testing triTraining") source("wine.R") rf <- rand_forest(trees = 100, mode = "classification") %>% set_engine("randomForest") m <- triTraining(learner = rf) test_that( desc = "triTraining model", code = { expect_is(m,"model_sslr") } ) model <- m %>% fit(Wine ~ ., data = wine$train) test_that( desc = "triTraining fit", code = { expect_is(model,"model_sslr_fitted") expect_equal(model$model$mode,"classification") } ) test_that( desc = "triTraining predictions data frame", code = { predictions_frame <- predict(model,wine$test) expect_is(predictions_frame,"data.frame") } ) test_that( desc = "triTraining predictions factor", code = { predictions_factor <- predict(model,wine$test, type = "raw") expect_is(predictions_factor,"factor") expect_equal(length(predictions_factor),nrow(wine$test)) } )
context("Function as_survey design works.") df <- data.frame(id = 1:5, strata = c(2, 2, 3, 3, 3), x = 11:15) test_that("as_survey_design works with both tbl_dfs and data.frames", expect_equal(df %>% as_survey_design(ids = id, strata = strata), df %>% tibble::as_tibble() %>% as_survey_design(ids = id, strata = strata))) test_that("as_survey_design_ works with character", expect_equal(df %>% as_survey_design_(ids = "id", strata = "strata"), df %>% as_survey_design(ids = id, strata = strata))) test_that("as_survey_design_ works with formulas", expect_equal(df %>% as_survey_design_(ids = ~id, strata = ~strata), df %>% as_survey_design(ids = id, strata = strata)))
summary.timeDate <- function(object, ...) { x = object cat( "Object: ", as.character(match.call())[2]) cat("\nStart Record: ", as.character(start(x))) cat("\nEnd Record: ", as.character(end(x))) cat("\nObservations: ", length(as.character(x))) cat("\nFormat: ", x@format) cat("\nFinCenter: ", x@FinCenter) cat("\n") invisible(object) }
plot.propagate <- function(x, logx = FALSE, ...) { object <- x par(mar = c(4, 4, 3, 1)) resSIM <- object$resSIM FILTER <- quantile(resSIM, c(0.001, 0.999), na.rm = TRUE) plotDATA <- resSIM[resSIM > FILTER[1] & resSIM < FILTER[2]] plotDATA <- plotDATA[!is.na(plotDATA)] if (logx) plotDATA <- suppressWarnings(log(plotDATA)) HIST <- hist(plotDATA, col = "dodgerblue3", breaks = 100, main = NULL, cex.main = 1, freq = FALSE, xlab = "Bin", ylab = "Density", ...) DENS <- density(plotDATA) lines(DENS, col = "red3", lwd = 3) title(main = paste("Histogram of Monte Carlo simulation results with density curve (red),\n", (1 - object$alpha) * 100, "% confidence interval (black), median (orange) and mean (green)", sep = ""), cex.main = 1) abline(v = object$sim[c(5, 6)], col = "black", lwd = 3) abline(v = object$sim[3], col = "darkorange", lwd = 3, lty = 1) abline(v = object$sim[1], col = "green3", lwd = 3, lty = 1) }
coef.aidsEst <- function( object, ... ) { result <- list() result$alpha0 <- object$coef$alpha0 result$alpha <- object$coef$alpha result$beta <- object$coef$beta result$gamma <- object$coef$gamma result$delta <- object$coef$delta class( result ) <- "coef.aidsEst" return( result ) }
if(require("suppdata") & require("testthat")){ context("RSBP") test_that("'Proceedings of the royal society Biology' (RSBP) works", { skip_on_cran() expect_true(file.exists(suppdata("10.1098/rspb.2015.0338", vol = 282, issue = 1811, 1))) }) test_that("'Proceedings of the royal society Biology' (RSBP) fails for character SI info", { skip_on_cran() expect_error(suppdata("10.1098/rspb.2015.0338", vol = 282, issue = 1811, "99"), "numeric SI info") }) }
adversarial_debiasing <- function(unprivileged_groups, privileged_groups, scope_name='current', sess=tf$compat$v1$Session(), seed=NULL, adversary_loss_weight=0.1, num_epochs=50, batch_size=128, classifier_num_hidden_units=200, debias=TRUE) { unprivileged_dict <- dict_fn(unprivileged_groups) privileged_dict <- dict_fn(privileged_groups) ad <- in_algo$AdversarialDebiasing(unprivileged_dict, privileged_dict, scope_name=scope_name, sess=sess) return (ad) }
print.summary.lcpm<-function(x,...){ cat("Call:\n") print(x$call) cat("\n") printCoefmat(x$coefficients, P.values = TRUE, has.Pvalue = TRUE) cat("\n") cat("loglikelihood: ",x$loglik) cat("\n") if(x$boundaryissue){cat("WARNING: MLE possibly on a boundary") cat("\n")} cat("Score Test of Proportionality: ") cat("Chisq test statistic ", x$proptest, " with ", x$propdf, " degrees of freedom and p-value ", x$propval) cat("\n") }
library(metaplotr) rm(list = ls()) attach(FergusonBrannick2012) crosshairs(pub_z, dis_z, pub_z_se, dis_z_se) crosshairs(pub_z, dis_z, pub_z_se, dis_z_se, confint = .7) crosshairs(pub_z, dis_z, pub_z_se, dis_z_se, confint = .95) crosshairs(pub_z, dis_z, pub_z_se, dis_z_se, confint = .3) crosshairs(pub_z, dis_z, pub_z_se, dis_z_se, whis_on = FALSE) crosshairs(pub_z, dis_z, pub_z_se, dis_z_se, main_lab = 'Published vs. Dissertation Effect Sizes', x_lab = 'Published Studies', y_lab = 'Dissertations') attach(Sweeney2015) crosshairs(inten_d, beh_d, inten_se, beh_se, main_lab = 'Sweeney (2015) Data', x_lab = 'Intentions', y_lab = 'Behaviors', annotate = TRUE) crosshairs(inten_d, beh_d, inten_se, beh_se, main_lab = 'Sweeney (2015) Data', x_lab = 'Intentions', y_lab = 'Behaviors', annotate = TRUE, bxplts = FALSE) attach(GenderDiff02) crosshairs(men_z, women_z, men_se, women_se, main_lab = 'Ali et al. Psychopathology and Parental Acceptance', x_lab = 'Men', y_lab = 'Women', mdrtr = region, mdrtr_lab = 'Region', mdrtr_lab_pos = c(.1, .5)) attach(McLeod2007) library(metafor) res1 <- rma(yi = z, vi = var, method = 'DL', data = McLeod2007) res2 <- blup(res1) head(res2, 15) x1 <- McLeod2007$z se.x1 <- sqrt(McLeod2007$var) y1 <- res2$pred se.y1 <- res2$se crosshairs(x1, y1, se.x1, se.y1, main_lab = 'Effects of Empirical Bayes Estimation', x_lab = 'Parenting and Depression Correlations', y_lab = 'Shrunken Estimates', annotate = TRUE, whis_on = FALSE)
MultipleChoice <- function(x,y,tvectors=tvectors,breakdown=FALSE){ cos <- vector(length=length(y)) names(cos) <- y for(j in 1:length(y)){value <- costring(x,y[j], tvectors=tvectors, breakdown=breakdown) if(is.na(value)){cos[j] <- -2} if(!is.na(value)){cos[j] <- value} } mc <- names(cos)[which(cos == max(cos))] return(mc) }
verify_length <- function(val) { year <- substr(val, 12, 13) len <- ifelse(year == "20", 15, 13) wrong_len <- which(nchar(val) != len) if (length(wrong_len) > 0) { examples <- paste(utils::head(val[wrong_len], 10), sep = ", ") tip <- "\n\nDid you remove the check digits?" stop(paste0("Wrong lengths: ", examples, "...", tip)) } } carf_calc_dig <- function(id, build = FALSE, verify = TRUE) { val <- gsub("[^0-9]", "", id) val <- substr(val, 1, nchar(val)) if (verify) verify_length(val) calc_dv_one <- function(val) { len <- nchar(val) index <- seq(len + 1, 2) all_values <- as.numeric(unlist(strsplit(val, ""))) weighted_sum <- sum(all_values * index) dv <- 11 - (weighted_sum %% 11) if (dv == 10) dv <- 0 if (dv == 11) dv <- 1 as.character(dv) } dv1 <- purrr::map_chr(val, calc_dv_one) dv2 <- purrr::map_chr(paste0(val, dv1), calc_dv_one) dv <- paste0(dv1, dv2) if (build) { paste0(val, dv) } else { dv } } carf_check_dig <- function(id) { val <- gsub("[^0-9]", "", id) len <- nchar(val) actual_dv <- substr(val, len - 1, len) calc_dv <- carf_calc_dig(substr(val, 1, len - 2), verify = FALSE) actual_dv == calc_dv } carf_build_id <- function(id) { val <- gsub("[^0-9]", "", id) if (all(nchar(val) %in% c(15, 17))) { mask <- "([0-9]{5})([0-9]{6})([0-9]{2}|[0-9]{4})([0-9]{2}$)" pattern <- "\\1.\\2/\\3-\\4" gsub(mask, pattern, val) } else { stop("Length must be 15 or 17.") } }
res <- confmatrix(c(1,1,1,0), c(1,1,0,0)) test_that("Test confMtrix dimention!", { expect_equal(dim(res$table), c(2,2)) }) test_that("Test confMtrix right value?", { expect_true(res$table[4] == 2) }) test_that("Test confMtrix class", { expect_equal(class(res), "confusionMatrix") })
makeRLearner.regr.LiblineaRL2L1SVR = function() { makeRLearnerRegr( cl = "regr.LiblineaRL2L1SVR", package = "LiblineaR", par.set = makeParamSet( makeNumericLearnerParam(id = "cost", default = 1, lower = 0), makeNumericLearnerParam(id = "epsilon", default = 0.1, lower = 0), makeNumericLearnerParam(id = "svr_eps", lower = 0), makeLogicalLearnerParam(id = "bias", default = TRUE), makeIntegerLearnerParam(id = "cross", default = 0L, lower = 0L, tunable = FALSE), makeLogicalLearnerParam(id = "verbose", default = FALSE, tunable = FALSE) ), par.vals = list(svr_eps = 0.1), properties = "numerics", name = "L2-Regularized L1-Loss Support Vector Regression", short.name = "liblinl2l1svr", note = "Parameter `svr_eps` has been set to `0.1` by default.", callees = "LiblineaR" ) } trainLearner.regr.LiblineaRL2L1SVR = function(.learner, .task, .subset, .weights = NULL, ...) { d = getTaskData(.task, .subset, target.extra = TRUE) LiblineaR::LiblineaR(data = d$data, target = d$target, type = 13L, ...) } predictLearner.regr.LiblineaRL2L1SVR = function(.learner, .model, .newdata, ...) { predict(.model$learner.model, newx = .newdata, ...)$predictions }
set_edge_attr_to_display <- function(graph, attr = NULL, edges = NULL, default = "label") { time_function_start <- Sys.time() fcn_name <- get_calling_fcn() if (graph_object_valid(graph) == FALSE) { emit_error( fcn_name = fcn_name, reasons = "The graph object is not valid") } if (graph_contains_edges(graph) == FALSE) { emit_error( fcn_name = fcn_name, reasons = "The graph contains no edges") } attr <- rlang::enquo(attr) %>% rlang::get_expr() %>% as.character() if (attr == "NULL") { attr <- NULL } edf <- graph$edges_df if (is.null(edges)) { edges <- get_edge_ids(graph) } if (!any(edges %in% edf$id)) { emit_error( fcn_name = fcn_name, reasons = "One or more edge ID values in `edges` are not present in the graph") } if (!is.null(attr)) { if (!(attr %in% colnames(edf))) { emit_error( fcn_name = fcn_name, reasons = "The edge attribute given in `attr` is not in the graph's edf") } } if (!("display" %in% colnames(edf))) { edf <- edf %>% dplyr::mutate(display = as.character(default)) } if (!is.null(attr)) { attr_to_display <- dplyr::tibble( id = as.integer(edges), display = as.character(attr)) } else if (is.null(attr)) { attr_to_display <- dplyr::tibble( id = as.integer(edges), display = as.character("is_na")) } edf <- edf %>% dplyr::left_join(attr_to_display, by = "id") x_col <- which(grepl("\\.x$", colnames(edf))) y_col <- which(grepl("\\.y$", colnames(edf))) if (!is.null(attr)) { display_col <- dplyr::coalesce(edf[, y_col], edf[, x_col]) %>% as.data.frame(stringsAsFactors = FALSE) } else if (is.null(attr)) { display_col <- dplyr::coalesce(edf[, y_col], edf[, x_col]) display_col <- dplyr::case_when( display_col == "is_na" ~ as.character(NA), TRUE ~ display_col) %>% as.data.frame(stringsAsFactors = FALSE) } colnames(display_col)[1] <- "display" edf <- edf[-which(grepl("\\.x$", colnames(edf)))] edf <- edf[-which(grepl("\\.y$", colnames(edf)))] edf <- dplyr::bind_cols(edf, display_col) %>% dplyr::select( id, from, to, rel, display, dplyr::everything()) graph$edges_df <- edf graph$graph_log <- add_action_to_log( graph_log = graph$graph_log, version_id = nrow(graph$graph_log) + 1, function_used = fcn_name, time_modified = time_function_start, duration = graph_function_duration(time_function_start), nodes = nrow(graph$nodes_df), edges = nrow(graph$edges_df)) if (graph$graph_info$write_backups) { save_graph_as_rds(graph = graph) } graph }
.InitClassUnion <- function(where) { setClass("ClassUnionRepresentation", "classRepresentation", validity =function(object) { if(isTRUE(object@virtual) && length(object@slots)==0 && is.null(object@prototype)) TRUE else "Class must be an empty virtual class with NULL prototype" }, where = where) setClassUnion("OptionalFunction", c("function", "NULL"), where) setClassUnion("PossibleMethod", c("function", "MethodDefinition"), where) clList <- c("ClassUnionRepresentation", "OptionalFunction", "PossibleMethod") assign(".SealedClasses", c(get(".SealedClasses", where), clList), where) } setClassUnion <- function(name, members = character(), where = topenv(parent.frame())) { if(length(members)>0) { membersDefined <- sapply(members, isClass, where = as.environment(where)) if(!all(membersDefined)) stop(gettextf("the member classes must be defined: not true of %s", paste(.dQ(as(members[!membersDefined], "character")), collapse=", ")), domain = NA) } def <- new("ClassUnionRepresentation", makeClassRepresentation(name, package = getPackageName(where), where = where)) prev <- getClassDef(name, where = where) value <- setClass(name, def, where = where) failed <- character() hasNull <- match("NULL", members, 0) if(hasNull) members <- c("NULL", members[-hasNull]) for(what in members) { if(is(try(setIs(what, name, where = where)), "try-error")) { if(!is.character(what)) what <- getClass(what, TRUE, where)@className failed <- c(failed, what) } } if(length(failed)>0) { if(is.null(prev)) try(removeClass(name, where = where)) else try(setClass(name, prev, where = where)) stop(gettextf("unable to create union class: could not set members %s", paste(.dQ(failed), collapse=", ")), domain = NA) } invisible(value) } isClassUnion <- function(Class) { if(is.character(Class)) Class <- getClass(Class, TRUE) extends(class(Class), "ClassUnionRepresentation") }
NULL expfInit <- function(mCall, LHS, data, ...){ xy <- sortedXyData(mCall[["x"]], LHS, data) if(nrow(xy) < 3){ stop("Too few distinct input values to fit an exponential") } if(any(xy[,"y"] < 0)) stop("negative values in y are not allowed.") fit <- try(stats::lm(log(xy[,"y"]) ~ xy[,"x"], na.action = "na.omit"), silent = TRUE) if(class(fit) == "try-error"){ a <- xy[1,"y"] c <- (xy[nrow(xy),"y"] - xy[1,"y"])/(xy[nrow(xy),"x"] - xy[1,"x"]) }else{ a <- exp(coef(fit)[1]) c <- coef(fit)[2] } value <- c(a, c) names(value) <- mCall[c("a","c")] value } expf <- function(x, a, c){ .value <- a * exp(c * x) .exp1 <- exp(c * x) .exp2 <- a * (.exp1 * x) .actualArgs <- as.list(match.call()[c("a","c")]) if (all(unlist(lapply(.actualArgs, is.name)))) { .grad <- array(0, c(length(.value), 2L), list(NULL, c("a", "c"))) .grad[, "a"] <- .exp1 .grad[, "c"] <- .exp2 dimnames(.grad) <- list(NULL, .actualArgs) attr(.value, "gradient") <- .grad } .value } SSexpf <- selfStart(expf, initial = expfInit, c("a", "c"))
test.distCheck <- function() { NA return() }
get_starred <- function(stoken, id = NULL){ dataRaw <- get_basic(url_segment(id=id, request="starred"), stoken) return(dataRaw) }
search <- function(database, name = NULL) { if (is.null(name)) { name <- prompt_string( "Which do you want to search for?:", allowed = "A-Za-z0-9-_" ) } matches <- search_name(database, name) if (length(matches) == 1) { usethis::ui_done("Found one matching tool") cat("\n") database$Tools[[matches]] } else if (length(matches) > 1) { usethis::ui_done(glue::glue( "Found {usethis::ui_value(length(matches))} possible tools: ", "{usethis::ui_value(matches)}" )) match <- prompt_menu("Which tool would you like to display?", matches) cat("\n") database$Tools[[match]] } else { usethis::ui_done("No matches found!") } } search_name <- function(database, name) { matches <- stringdist::stringsim( tolower(name), tolower(names(database$Tools)), method = "jw", p = 0.1 ) > 0.9 matches_names <- names(database$Tools)[matches] return(matches_names) }
IRT.se <- function (object, ...) { UseMethod("IRT.se") }
NULL generate_regional_trends <- function(indices = NULL, Min_year = NULL, Max_year = NULL, quantiles = c(0.025,0.05,0.25,0.75,0.95,0.975), slope = FALSE, prob_decrease = NULL, prob_increase = NULL) { .Deprecated(new = "generate_trends", msg = paste("generate_regional_trends is deprecated in favour of generate_trends()")) if (is.null(indices)) { stop("No indices supplied to generate_regional_trends()."); return(NULL) } n_all = indices$samples if (is.null(Min_year)) { min_year = indices$y_min Min_year <- indices$startyear minyn <- 1 }else{ min_year <- indices$y_min + (Min_year-indices$startyear) minyn <- 1 + (Min_year-indices$startyear) if(min_year < 0){ min_year = indices$y_min Min_year <- indices$startyear minyn <- 1 } } if (is.null(Max_year)) { max_year = indices$y_max Max_year = indices$startyear+(max_year - indices$y_min) maxyn <- 1+(indices$y_max-indices$y_min) }else{ max_year <- indices$y_min + (Max_year-indices$startyear) maxyn <- 1+(Max_year-indices$startyear) } regions = indices$regions area_weights <- indices$area_weights all_regions = names(n_all) dsum = indices$data_summary trend <- data.frame(Start_year = integer(), End_year = integer(), Region = character(), Region_alt = character(), Region_type = character(), Strata_included = character(), Strata_excluded = character(), Trend = double(), stringsAsFactors = FALSE) for(qq in quantiles){ trend[,paste0("Trend_Q",qq)] <- double() } trend[,"Percent_Change"] <- double() for(qq in quantiles){ trend[,paste0("Percent_Change_Q",qq)] <- double() } for(rr in regions){ regsest = paste0(rr,"_",unique(dsum[which(dsum$Region_type == rr),"Region"])) for(rrs in regsest){ reg = gsub(rrs,pattern = paste0(rr,"_"),replacement = "",fixed = TRUE) w_summary_rows = which(dsum$Region == reg & dsum$Region_type == rr) n = n_all[[rrs]] reg_alt = unique(dsum[w_summary_rows,"Region_alt"]) st_inc = unique(dsum[w_summary_rows,"Strata_included"]) nstr = length(unlist(stringr::str_split(st_inc,pattern = " ; "))) st_exc = unique(dsum[w_summary_rows,"Strata_excluded"]) if(slope){ bsl = function(i){ n = length(wy) sy = sum(i) sx = sum(wy) ssx = sum(wy^2) sxy = sum(i*wy) b = (n*sxy - sx*sy)/(n*ssx - sx^2) return(b) } wy = c(minyn:maxyn) ne = log(n[,wy]) m = t(apply(ne,1,FUN = bsl)) sl.t = as.vector((exp(m)-1)*100) } ch = n[,maxyn]/n[,minyn] tr = 100*((ch^(1/(maxyn-minyn)))-1) trendt <- data.frame(Start_year = (indices$startyear+minyn)-1, End_year = (indices$startyear+maxyn)-1, Region = reg, Region_alt = reg_alt, Region_type = rr, Strata_included = st_inc, Strata_excluded = st_exc, Trend = median(tr), stringsAsFactors = FALSE) for(qq in quantiles){ trendt[,paste0("Trend_Q",qq)] <- stats::quantile(tr,qq,names = FALSE) } trendt[,"Percent_Change"] <- 100*(median(ch)-1) for(qq in quantiles){ trendt[,paste0("Percent_Change_Q",qq)] <- 100*(stats::quantile(ch,qq,names = FALSE)-1) } if(slope){ trendt[,"Slope_Trend"] <- median(sl.t) for(qq in quantiles){ trendt[,paste0("Slope_Trend_Q",qq)] <- stats::quantile(sl.t,qq,names = FALSE) } } if(!is.null(prob_decrease)){ pch = 100*(ch-1) for(pp in prob_decrease){ trendt[,paste0("prob_decrease_",pp,"_percent")] <- length(pch[which(pch < (-1*pp))])/length(pch) } } if(!is.null(prob_increase)){ pch = 100*(ch-1) for(pp in prob_increase){ trendt[,paste0("prob_increase_",pp,"_percent")] <- length(pch[which(pch > (pp))])/length(pch) } } trendt[,"Relative_Abundance"] <- mean(dsum[w_summary_rows,"Index"]) trendt[,"Observed_Relative_Abundance"] <- mean(dsum[w_summary_rows,"obs_mean"]) trendt[,"Number_of_strata"] <- nstr q1 = quantiles[1] q2 = quantiles[length(quantiles)] trendt[,paste0("Width_of_",(q2-q1)*100,"_percent_Credible_Interval")] <- trendt[,paste0("Trend_Q",q2)]-trendt[,paste0("Trend_Q",q1)] if(slope){ trendt[,paste0("Width_of_",(q2-q1)*100,"_percent_Credible_Interval_Slope")] <- trendt[,paste0("Slope_Trend_Q",q2)]-trendt[,paste0("Slope_Trend_Q",q1)] } trendt[,"Number_of_Routes"] <- mean(dsum[w_summary_rows,"nrts_total"]) trendt[,"Mean_Number_of_Routes"] <- mean(dsum[w_summary_rows,"nrts"]) trendt[,"backcast_flag"] <- mean(dsum[w_summary_rows,"backcast_flag"]) trend = rbind(trend,trendt) } } return(trend) }
"checkPackageExamples" <- function (pkg, outDir = file.path(tempdir(), "runPackageExamplesDir"), types = c("examples", "tests", "vignettes")) { if (!(file.exists(outDir) && file.info(outDir)$isdir)) { dir.create(outDir, showWarnings = FALSE, recursive = TRUE) on.exit(unlink(outDir)) } if (compareVersion(paste(R.version$major, R.version$minor, sep = ".") , "2.9.2") >= 0) tools::testInstalledPackage(pkg = pkg, lib.loc = .Library, outDir = outDir, types = types) == 0L else TRUE }
MicrobenchmarkClusteringKernel <- function(benchmarkParameters, numberOfThreads, resultsDirectory, runIdentifier) { resultsFrame <- data.frame(BenchmarkName=character(), NumberOfFeatures=integer(), NumberOfFeatureVectors=integer(), NumberOfClusters=integer(), UserTime=numeric(), SystemTime=numeric(), WallClockTime=numeric(), DateStarted=character(), DateFinished=character(), stringsAsFactors=FALSE) parameterCheck <- tryCatch({ cat(sprintf("Running clustering microbenchmark: %s\n", benchmarkParameters$benchmarkName)) cat(sprintf("Microbenchmark description: %s\n", benchmarkParameters$benchmarkDescription)) allocator <- match.fun(benchmarkParameters$allocatorFunction) benchmark <- match.fun(benchmarkParameters$benchmarkFunction) numberOfTrials <- benchmarkParameters$numberOfTrials numberOfWarmupTrials <- benchmarkParameters$numberOfWarmupTrials benchmarkName <- benchmarkParameters$benchmarkName csvResultsBaseFileName <- benchmarkParameters$benchmarkName csvResultsFileName <- file.path(resultsDirectory, paste(csvResultsBaseFileName, "_", runIdentifier, ".csv", sep="")) if (length(numberOfTrials) != length(numberOfWarmupTrials)) { stop(sprintf("ERROR: Input checking failed for clustering microbenchmark '%s' -- lengths of numberOfTrials and numberOfWarmupTrials arrays must be equal", benchmarkName)) } dir.create(resultsDirectory, showWarnings=FALSE, recursive=TRUE) TRUE }, warning = function(war) { write(sprintf("%s", war), stderr()) return(FALSE) }, error = function(err) { write(sprintf("%s", err), stderr()) return(FALSE) }) if (!parameterCheck) { return(resultsFrame) } maximumNumberOfTrials <- max(numberOfTrials) trialTimes <- rep(NA_real_, maximumNumberOfTrials) dim(trialTimes) <- c(maximumNumberOfTrials,1) numberOfSuccessfulTrials <- 0 for (i in 1:(numberOfTrials+numberOfWarmupTrials)) { cat(sprintf("Running performance trial %d...\n", i)) allocationSuccessful <- tryCatch({ RNGkind(kind=RBenchmarkOptions$rng.kind, normal.kind=RBenchmarkOptions$rng.normal.kind) set.seed(RBenchmarkOptions$rng.seed, kind=RBenchmarkOptions$rng.kind, normal.kind=RBenchmarkOptions$rng.normal.kind) kernelParameters <- allocator(benchmarkParameters) numberOfFeatures <- kernelParameters$numberOfFeatures numberOfFeatureVectors <- kernelParameters$numberOfFeatureVectors numberOfClusters <- kernelParameters$numberOfClusters TRUE }, warning = function(war) { msg <- sprintf("ERROR: allocator threw a warning -- %s", war) write(msg, stderr()) return(FALSE) }, error = function(err) { msg <- sprintf("ERROR: allocator threw an error -- %s", err) write(msg, stderr()) return(FALSE) }) if (!allocationSuccessful) { break; } dateStarted <- date() timings <- c(NA_real_, NA_real_, NA_real_) benchmarkSuccessful <- tryCatch({ timings <- benchmark(benchmarkParameters, kernelParameters) TRUE }, warning = function(war) { msg <- sprintf("WARN: benchmark threw a warning -- %s", war) write(msg, stderr()) return(FALSE) }, error = function(err) { msg <- sprintf("ERROR: benchmark threw an error -- %s", err) write(msg, stderr()) return(FALSE) }) if (!benchmarkSuccessful) { break; } dateFinished <- date() userTime <- timings[1] systemTime <- timings[2] wallClockTime <- timings[3] if (i > numberOfWarmupTrials) { numberOfSuccessfulTrials <- numberOfSuccessfulTrials + 1 resultsFrame[nrow(resultsFrame)+1, ] <- list( benchmarkName, as.integer(numberOfFeatures), as.integer(numberOfFeatureVectors), as.integer(numberOfClusters), userTime, systemTime, wallClockTime, dateStarted, dateFinished) } remove(kernelParameters) invisible(gc()) if (i > numberOfWarmupTrials) { trialTimes[i-numberOfWarmupTrials,1] <- wallClockTime } cat(sprintf("done: %f(sec)\n", wallClockTime)) } averageWallClockTime <- ComputeAverageTime(numberOfSuccessfulTrials, trialTimes) standardDeviation <- ComputeStandardDeviation(numberOfSuccessfulTrials, trialTimes) WriteClusteringPerformanceResultsCsv(numberOfThreads, numberOfFeatures, numberOfFeatureVectors, numberOfClusters, averageWallClockTime, standardDeviation, csvResultsFileName) PrintClusteringMicrobenchmarkResults(benchmarkName, numberOfThreads, numberOfFeatures, numberOfFeatureVectors, numberOfClusters, numberOfSuccessfulTrials, trialTimes, averageWallClockTime, standardDeviation) return (resultsFrame) }
"boa.importMatrix" <- function(prefix) { link <- NULL import <- try({ if(length(prefix) && exists(prefix)) link <- as.matrix(get(prefix)) else cat("Warning: import failed\n Could not find '", prefix, "'.\n", sep = "") }, TRUE) if(inherits(import, "try-error")) cat("Warning: import failed\n", " Object type is not supported. Confirm that '", prefix, "' is a\n", " numeric matrix.\n", sep = "") return(link) }
quo <- function(expr, env = arg_env_(quote(expr), environment()), force = FALSE) { quo_(arg_expr_(quote(expr), environment()), env = env, force = force) } quo_ <- function(expr, env, force = FALSE) { if(force) { .Call("_quotation", NULL, expr, eval(expr, env)); } else { .Call("_quotation", env, expr, missing_value()); } } env <- function(q) UseMethod("env") env.quotation <- function(q) { environment(q) } `env<-` <- function(q, value) { UseMethod("env<-") } `env<-.quotation` <- function(q, value) { quo_(expr(q), value); } expr <- function(q) UseMethod("expr") expr.quotation <- function(q) { .Call("_expr_quotation", q) } `expr<-` <- function(q, value) { UseMethod("expr<-") } `expr<-.quotation` <- function(q, value) { quo_(value, env(q)) } is.quotation <- function(x) { inherits(x, "quotation") } as.quo <- function(x) { UseMethod("as.quo") } as.quo.function <- function(x) { if (is.primitive(x)) stop("can't convert primitive to quotation") f <- formals(x) if (length(f) != 0) { stop("can only convert function to quotation if it has no args") } quo_(body(x), environment(x)) } as.quo.quotation <- identity as.quo.dots <- function(x) { if (length(x) == 1) x[[1]] else stop("can't convert nonscalar dots to a quotation") } as.quo.formula <- function(x) { expr <- x[[2]] env <- attr(x, ".Environment") quo_(expr, env) } as.quo.lazy <- function(x) { quo_(x$expr, x$env) } as.quo.default <- function(x) { if (mode(x) == "list") { expr <- x$expr env <- x$env } else { stop(paste0("can't convert ", class(x)[1] ," to a quo")) } quo_(expr, env) }
linearKdot <- function(X, i, r=NULL, ..., correction="Ang") { if(!is.multitype(X, dfok=FALSE)) stop("Point pattern must be multitype") marx <- marks(X) lev <- levels(marx) if(missing(i)) i <- lev[1L] else if(!(i %in% lev)) stop(paste("i = ", i , "is not a valid mark")) I <- (marx == i) J <- rep(TRUE, npoints(X)) result <- linearKmulti(X, I, J, r=r, correction=correction, ...) correction <- attr(result, "correction") type <- if(correction == "Ang") "L" else "net" result <- rebadge.as.dotfun(result, "K", type, i) return(result) } linearKcross <- function(X, i, j, r=NULL, ..., correction="Ang") { if(!is.multitype(X, dfok=FALSE)) stop("Point pattern must be multitype") marx <- marks(X) lev <- levels(marx) if(missing(i)) i <- lev[1L] else if(!(i %in% lev)) stop(paste("i = ", i , "is not a valid mark")) if(missing(j)) j <- lev[2L] else if(!(j %in% lev)) stop(paste("j = ", j , "is not a valid mark")) if(i == j) { result <- linearK(X[marx == i], r=r, correction=correction, ...) } else { I <- (marx == i) J <- (marx == j) result <- linearKmulti(X, I, J, r=r, correction=correction, ...) } correction <- attr(result, "correction") type <- if(correction == "Ang") "L" else "net" result <- rebadge.as.crossfun(result, "K", type, i, j) return(result) } linearKmulti <- function(X, I, J, r=NULL, ..., correction="Ang") { stopifnot(inherits(X, "lpp")) correction <- pickoption("correction", correction, c(none="none", Ang="Ang", best="Ang"), multi=FALSE) np <- npoints(X) lengthL <- volume(domain(X)) if(!is.logical(I) || !is.logical(J)) stop("I and J must be logical vectors") if(length(I) != np || length(J) != np) stop(paste("The length of I and J must equal", "the number of points in the pattern")) if(!any(I)) stop("no points satisfy I") nI <- sum(I) nJ <- sum(J) nIandJ <- sum(I & J) denom <- (nI * nJ - nIandJ)/lengthL K <- linearKmultiEngine(X, I, J, r=r, denom=denom, correction=correction, ...) correction <- attr(K, "correction") type <- if(correction == "Ang") "L" else "net" K <- rebadge.as.crossfun(K, "K", type, "I", "J") attr(K, "correction") <- correction return(K) } linearKdot.inhom <- function(X, i, lambdaI, lambdadot, r=NULL, ..., correction="Ang", normalise=TRUE) { if(!is.multitype(X, dfok=FALSE)) stop("Point pattern must be multitype") marx <- marks(X) lev <- levels(marx) if(missing(i)) i <- lev[1L] else if(!(i %in% lev)) stop(paste("i = ", i , "is not a valid mark")) I <- (marx == i) J <- rep(TRUE, npoints(X)) result <- linearKmulti.inhom(X, I, J, lambdaI, lambdadot, r=r, correction=correction, normalise=normalise, ...) correction <- attr(result, "correction") type <- if(correction == "Ang") "L, inhom" else "net, inhom" result <- rebadge.as.dotfun(result, "K", type, i) attr(result, "correction") <- correction return(result) } linearKcross.inhom <- function(X, i, j, lambdaI, lambdaJ, r=NULL, ..., correction="Ang", normalise=TRUE) { if(!is.multitype(X, dfok=FALSE)) stop("Point pattern must be multitype") marx <- marks(X) lev <- levels(marx) if(missing(i)) i <- lev[1L] else if(!(i %in% lev)) stop(paste("i = ", i , "is not a valid mark")) if(missing(j)) j <- lev[2L] else if(!(j %in% lev)) stop(paste("j = ", j , "is not a valid mark")) if(i == j) { I <- (marx == i) result <- linearKinhom(X[I], lambda=lambdaI, r=r, correction=correction, normalise=normalise, ...) } else { I <- (marx == i) J <- (marx == j) result <- linearKmulti.inhom(X, I, J, lambdaI, lambdaJ, r=r, correction=correction, normalise=normalise, ...) } correction <- attr(result, "correction") type <- if(correction == "Ang") "L, inhom" else "net, inhom" result <- rebadge.as.crossfun(result, "K", type, i, j) attr(result, "correction") <- correction return(result) } linearKmulti.inhom <- function(X, I, J, lambdaI, lambdaJ, r=NULL, ..., correction="Ang", normalise=TRUE) { stopifnot(inherits(X, "lpp")) correction <- pickoption("correction", correction, c(none="none", Ang="Ang", best="Ang"), multi=FALSE) np <- npoints(X) lengthL <- volume(domain(X)) if(!is.logical(I) || !is.logical(J)) stop("I and J must be logical vectors") if(length(I) != np || length(J) != np) stop(paste("The length of I and J must equal", "the number of points in the pattern")) if(!any(I)) stop("no points satisfy I") lambdaI <- getlambda.lpp(lambdaI, X, subset=I, ...) lambdaJ <- getlambda.lpp(lambdaJ, X, subset=J, ...) weightsIJ <- outer(1/lambdaI, 1/lambdaJ, "*") denom <- if(!normalise) lengthL else sum(1/lambdaI) K <- linearKmultiEngine(X, I, J, r=r, reweight=weightsIJ, denom=denom, correction=correction, ...) correction <- attr(K, "correction") type <- if(correction == "Ang") "L, inhom" else "net, inhom" K <- rebadge.as.crossfun(K, "K", type, "I", "J") attr(K, "dangerous") <- union(attr(lambdaI, "dangerous"), attr(lambdaJ, "dangerous")) attr(K, "correction") <- correction return(K) } linearKmultiEngine <- function(X, I, J, ..., r=NULL, reweight=NULL, denom=1, correction="Ang", showworking=FALSE) { X <- as.lpp(X, sparse=FALSE) np <- npoints(X) L <- domain(X) W <- Window(L) rmaxdefault <- 0.98 * boundingradius(L) breaks <- handle.r.b.args(r, NULL, W, rmaxdefault=rmaxdefault) r <- breaks$r rmax <- breaks$max if(correction == "Ang") { fname <- c("K", "list(L, I, J)") ylab <- quote(K[L,I,J](r)) } else { fname <- c("K", "list(net, I, J)") ylab <- quote(K[net,I,J](r)) } if(np < 2) { zeroes <- rep(0, length(r)) df <- data.frame(r = r, est = zeroes) K <- fv(df, "r", ylab, "est", . ~ r, c(0, rmax), c("r", makefvlabel(NULL, "hat", fname)), c("distance argument r", "estimated %s"), fname = fname) attr(K, "correction") <- correction return(K) } clash <- I & J has.clash <- any(clash) DIJ <- crossdist(X[I], X[J], check=FALSE) if(has.clash) { Iclash <- which(clash[I]) Jclash <- which(clash[J]) DIJ[cbind(Iclash,Jclash)] <- Inf } if(correction == "none" && is.null(reweight)) { K <- compileK(DIJ, r, denom=denom, check=FALSE, fname=fname) K <- rebadge.as.crossfun(K, "K", "net", "I", "J") unitname(K) <- unitname(X) attr(K, "correction") <- correction return(K) } if(correction == "none") { edgewt <- 1 } else { toler <- default.linnet.tolerance(L) m <- DoCountCrossEnds(X, I, J, DIJ, toler) edgewt <- 1/m } wt <- if(!is.null(reweight)) edgewt * reweight else edgewt K <- compileK(DIJ, r, weights=wt, denom=denom, check=FALSE, fname=fname) K <- rebadge.as.crossfun(K, "K", "L", "I", "J") fname <- attr(K, "fname") K <- bind.fv(K, data.frame(theo=r), makefvlabel(NULL, NULL, fname, "pois"), "theoretical Poisson %s") unitname(K) <- unitname(X) fvnames(K, ".") <- rev(fvnames(K, ".")) if(showworking) attr(K, "working") <- list(DIJ=DIJ, wt=wt) attr(K, "correction") <- correction return(K) } DoCountCrossEnds <- function(X, I, J, DIJ, toler) { stopifnot(is.lpp(X)) stopifnot(is.logical(I) && is.logical(J)) stopifnot(is.matrix(DIJ)) nI <- sum(I) nJ <- sum(J) whichI <- which(I) whichJ <- which(J) m <- matrix(1, nI, nJ) easy <- list(is.connected=TRUE) L <- domain(X) if(is.connected(L)) { for(k in seq_len(nJ)) { j <- whichJ[k] I.j <- (whichI != j) i.j <- setdiff(whichI, j) m[I.j, k] <- countends(L, X[i.j], DIJ[I.j,k], toler=toler, internal=easy) } } else { vlab <- connected(L, what="labels") subsets <- split(seq_len(nvertices(L)), factor(vlab)) for(s in subsets) { Xs <- thinNetwork(X, retainvertices=s) ns <- npoints(Xs) if(ns >= 2) { Ls <- domain(Xs) relevant <- attr(Xs, "retainpoints") Xindex <- which(relevant) Isub <- I[relevant] rowsub <- relevant[I] colsub <- relevant[J] for(k in which(colsub)) { j <- whichJ[k] I.j <- rowsub & (whichI != j) i.j <- Isub & (Xindex != j) m[ I.j, k ] <- countends(Ls, Xs[i.j], DIJ[I.j, k], toler=toler, internal=easy) } } } } if(any(uhoh <- (m == 0) & is.finite(DIJ))) { warning("Internal error: disc boundary count equal to zero") m[uhoh] <- 1 } return(m) }
fpower <- function (p, lambda, eps) if(lambda==0)log((p+eps)/(1-p+eps)) else sign(lambda)*((p+eps)/(1-p+eps))^lambda
context("test-make-formula.R") test_that("make.formula works", { model <- c("y1 ~ x1 + x2 + x3", "y2 ~ x1 + x2 + x3") vars.temp <- paste0("x", 1:3) y <- paste0("y", 1:2) out <- make.formula(y, vars.temp) expect_equal(out, noquote(model)) })
print.clime <- function(x,digits = max(3, getOption("digits") - 3), ... ) { cat("\n clime options summary: \n") cat(" perturb=", signif(x$perturb, digits), "\t standardize=", x$standardize) cat("\n lambdas used:\n") print(signif(x$lambda,digits)) }
"Emiliania_huxleyi"
optimize_n <- function(nequalsMminus1=NULL,nequalsM=NULL,nequalsMplus1=NULL){ snp.df<- data.frame(var=character(), snps=numeric()) loci.df<- data.frame(var=character(), loci=numeric()) snp.80.df<- data.frame(var=character(), snps.80=numeric()) loci.80.df<- data.frame(var=character(), loci.80=numeric()) ms<-c("n=M-1","n=M","n=M+1") j=1 for(x in list(nequalsMminus1,nequalsM,nequalsMplus1)){ if(is.null(x)){j=j+1} else{ invisible(utils::capture.output(vcf.r<- vcfR::read.vcfR(x))) snps<- vector("numeric", length = ncol(vcf.r@gt)-1) poly.loci<- vector("numeric", length = ncol(vcf.r@gt)-1) m<- rep(ms[j], times = ncol(vcf.r@gt)-1) k=1 for (i in 2:ncol(vcf.r@gt)){ snps[k]<-sum(is.na(vcf.r@gt[,i]) == FALSE) poly.loci[k]<-length(unique(vcf.r@fix[,1][is.na(vcf.r@gt[,i]) == FALSE])) k=k+1 } snp.df<- rbind(snp.df, as.data.frame(cbind(m, snps))) loci.df<- rbind(loci.df, as.data.frame(cbind(m, poly.loci))) snps.80<-nrow(vcf.r@gt[(rowSums(is.na(vcf.r@gt))/ncol(vcf.r@gt) <= .2),]) poly.loci.80<-length(unique(vcf.r@fix[,1][(rowSums(is.na(vcf.r@gt))/ncol(vcf.r@gt) <= .2)])) snp.80.df<- rbind(snp.80.df, as.data.frame(cbind(ms[j], snps.80))) loci.80.df<- rbind(loci.80.df, as.data.frame(cbind(ms[j], poly.loci.80))) j=j+1 } } colnames(snp.80.df)<-c("var","snps.80") colnames(loci.80.df)<-c("var","poly.loci.80") colnames(snp.df)<-c("var","snps") colnames(loci.df)<-c("var","poly.loci") out <- list() out$snp<-snp.df out$loci<-loci.df out$snp.R80<-snp.80.df out$loci.R80<-loci.80.df return(out) }
test_that("teardown adds to queue", { local_edition(2) on.exit(teardown_reset()) expect_length(file_teardown_env$queue, 0) teardown({}) expect_length(file_teardown_env$queue, 1) teardown({}) expect_length(file_teardown_env$queue, 2) }) test_that("teardowns runs in order", { local_edition(2) on.exit(teardown_reset()) a <- 1 teardown(a <<- 2) teardown(a <<- 3) expect_length(file_teardown_env$queue, 2) teardown_run() expect_equal(a, 3) expect_length(file_teardown_env$queue, 0) }) test_that("teardown run after tests complete", { test_file(test_path("test-teardown/test-teardown.R"), "silent") expect_false(file.exists(test_path("test-teardown/teardown.txt"))) })
plotTP <- function (TPdist = NULL, ...) { siberDensityPlot <- function (dat, probs = c(95, 75, 50), xlab = "Group", ylab = "Value", xticklabels = NULL, yticklabels = NULL, clr = grDevices::gray((9:1)/10), scl = 1, xspc = 0.5, prn = FALSE, ct = "mode", ylims = NULL, lbound = -Inf, ubound = Inf, main = "", ylab.line = 2, ...) { n <- ncol(dat) if (is.null(ylims)) { ylims <- c(min(dat) - 0.1 * min(dat), max(dat) + 0.1 * (max(dat))) } graphics::plot(1, 1, xlab = "", ylab = "", main = main, xlim = c(1 - xspc, n + xspc), ylim = ylims, type = "n", xaxt = "n", ...) graphics::title(xlab = xlab) graphics::title(ylab = ylab, line = ylab.line) if (is.null(xticklabels)) { graphics::axis(side = 1, at = 1:n, labels = (as.character(names(dat)))) } else { graphics::axis(side = 1, at = 1:n, labels = (xticklabels)) } clrs <- rep(clr, 5) for (j in 1:n) { temp <- hdrcde::hdr(dat[, j], probs, h = stats::bw.nrd0(dat[, j])) line_widths <- seq(2, 20, by = 4) * scl bwd <- c(0.1, 0.15, 0.2, 0.25, 0.3) * scl if (prn == TRUE) { cat(paste("Probability values for Column", j, "\n")) cat(paste("\t", "Mode", format(temp$mode, digits = 3, scientific = FALSE), "Mean", format(mean(dat[, j]), digits = 3, scientific = FALSE), "Median", format(stats::median(dat[,j]), digits = 3, scientific = FALSE), "\n")) } for (k in seq_along(probs)) { temp2 <- temp$hdr[k, ] graphics::polygon(c(j - bwd[k], j - bwd[k], j + bwd[k], j + bwd[k]), c(max(c(min(temp2[!is.na(temp2)]), lbound)), min(c(max(temp2[!is.na(temp2)]), ubound)), min(c(max(temp2[!is.na(temp2)]), ubound)), max(c(min(temp2[!is.na(temp2)]), lbound))), col = clrs[k]) if (ct == "mode") { graphics::points(j, temp$mode, pch = 19) } if (ct == "mean") { graphics::points(j, mean(dat[, j]), pch = 19) } if (ct == "median") { graphics::points(j, stats::median(dat[, j]), pch = 19) } if (prn == TRUE) { cat(paste("\t", probs[k], "% lower =", format(max(min(temp2[!is.na(temp2)]), lbound), digits = 3, scientific = FALSE), "upper =", format(min(max(temp2[!is.na(temp2)]), ubound), digits = 3, scientific = FALSE), "\n")) } } } } siberDensityPlot(TPdist, ylab = "Trophic Position", ...) }
cdf_prob <- function(c, method = c("Fleishman", "Polynomial"), delta = 0.5, mu = 0, sigma = 1, lower = -1e06, upper = 1e06) { check <- suppressWarnings(pdf_check(c, method)) if (check$valid.pdf == FALSE) { warning('This is NOT a valid pdf.') } cdf_root <- function(z, c, method, delta, mu, sigma) { if (method == "Fleishman") { y <- c[1] + c[2] * z + c[3] * z^2 + c[4] * z^3 } if (method == "Polynomial") { y <- c[1] + c[2] * z + c[3] * z^2 + c[4] * z^3 + c[5] * z^4 + c[6] * z^5 } return((sigma * y + mu) - delta) } R <- uniroot(cdf_root, lower = lower, upper = upper, c = c, method = method, delta = delta, mu = mu, sigma = sigma) cum_prob <- pnorm(R$root[1]) return(list(cumulative_prob = cum_prob, roots = R$root)) }
test_that("regular skip", { skip("regular skip") }) test_that("skip with details", { skip("longer skip:\nthis is what happened") })
con.search.E1E1.D <- function(x, y, n, jlo, jhi) { fjk <- matrix(0, n) fxy <- matrix(0, jhi - jlo + 1) jkgrid <- expand.grid(jlo:jhi) res <- data.frame(j = jkgrid, k.ll = apply(jkgrid, 1, con.parmsFUN.E1E1.D, x = x, y = y, n = n)) fxy <- matrix(res$k.ll, nrow = jhi-jlo+1) rownames(fxy) <- jlo:jhi z <- findmax(fxy) jcrit <- z$imax + jlo - 1 list(jhat = jcrit, value = max(fxy)) } con.parmsFUN.E1E1.D <- function(j, x, y, n){ a <- con.parms.D.E1E1(x,y,n,j,1,1) nr <- nrow(a$theta) est <- a$theta[nr, ] b<-con.est.D.E1E1(x[j],est) s2<-1/b$eta1 t2<-1/b$eta2 return(p.ll.D(n, j, s2, t2)) } con.parms.D.E1E1 <- function(x,y,n,j0,e10,e20){ th <- matrix(0,100,5) th[1,1] <- e10 th[1,2] <- e20 bc <- beta.calc.E1E1.D(x,y,n,j0,e10,e20) th[1,3:5] <- bc$B for (iter in 2:100){ m <- iter-1 ec <- eta.calc.D.E1E1(x,y,n,j0,th[m,3:5]) th[iter,1] <- ec$eta1 th[iter,2] <- ec$eta2 bc <- beta.calc.E1E1.D(x,y,n,j0,ec$eta1,ec$eta2) th[iter,3:5] <- bc$B theta <- th[1:iter,] delta <- abs(th[iter,]-th[m,])/th[m,] if( (delta[1]<.001) & (delta[2]<.001) & (delta[3]<.001) & (delta[4]<.001) & (delta[5]<.001) ) break } list(theta=theta) } con.est.D.E1E1 <- function(xj, est) { eta1 <- est[1] eta2 <- est[2] a0 <- est[3] a1 <- est[4] b1 <- est[5] b0 <- a0 + a1 * exp(xj)- b1 * exp(xj) list(eta1 = eta1, eta2 = eta2, a0 = a0, a1 = a1, b0 = b0, b1 = b1) } con.vals.E1E1.D <- function(x, y, n, j, k) { a <- con.parms.D.E1E1(x, y, n, j, 1, 1) nr <- nrow(a$theta) est <- a$theta[nr, ] b <- con.est.D.E1E1(x[j], est) eta <- c(b$eta1, b$eta2) beta <- c(b$a0, b$a1, b$b0, b$b1) tau <- x[j] list(eta = eta, beta = beta, tau = tau) } p.ll.D <-function(n, j, s2, t2){ q1 <- n * log(sqrt(2 * pi)) q2 <- 0.5 * j * (1 + log(s2)) q3 <- 0.5 * (n - j) * (1 + log(t2)) - (q1 + q2 + q3) } findmax <-function(a){ maxa<-max(a) imax<- which(a==max(a),arr.ind=TRUE)[1] jmax<-which(a==max(a),arr.ind=TRUE)[2] list(imax = imax, jmax = jmax, value = maxa) } beta.calc.E1E1.D <- function(x, y, n, j, e1, e2) { aa <- wmat.E1E1.D(x, y, n, j, e1, e2) W <- aa$w bb <- rvec.E1E1.D(x, y, n, j, e1, e2) R <- bb$r beta <- solve(W, R) list(B = beta) } eta.calc.D.E1E1 <- function(x, y, n, j, theta) { jp1 <- j + 1 a0 <- theta[1] a1 <- theta[2] b1 <- theta[3] b0 <- a0 + (a1 - b1) * exp(x[j]) rss1 <- sum((y[1:j] - a0 - a1 * exp(x[1:j]))^2) rss2 <- sum((y[jp1:n] - b0 - b1 * exp(x[jp1:n]))^2) e1 <- j/rss1 e2 <- (n - j)/rss2 list(eta1 = e1, eta2 = e2) } wmat.E1E1.D <- function(x, y, n, j, e1, e2) { W <- matrix(0, 3, 3) jp1 <- j + 1 W[1, 1] <- e1 * j + e2 * (n - j) W[1, 2] <- e1 * sum(exp(x[1:j])) + e2 * (n - j) * exp(x[j]) W[1, 3] <- e2 * sum(exp(x[jp1:n]) - exp(x[j])) W[2, 2] <- e1 * sum(exp(x[1:j])^2) + e2 * (n-j) * exp(x[j])^2 W[2, 3] <- e2 * exp(x[j]) * sum(exp(x[jp1:n]) - exp(x[j])) W[3, 3] <-e2 * sum((exp(x[jp1:n]) - exp(x[j])) * (exp(x[jp1:n]) - exp(x[j]))) W[2, 1] <- W[1, 2] W[3, 1] <- W[1, 3] W[3, 2] <- W[2, 3] list(w = W) } rvec.E1E1.D <- function(x, y, n, j, e1, e2) { R <- array(0, 3) jp1 <- j + 1 y1j <- sum(y[1:j]) yjn <- sum(y[jp1:n]) xy1j <- sum(exp(x[1:j]) * y[1:j]) xyjn <- sum(exp(x[jp1:n]) * y[jp1:n]) R[1] <- e1 * y1j + e2 * yjn R[2] <- e1 * xy1j + e2 * exp(x[j]) * yjn R[3] <- e2 * (xyjn - yjn * exp(x[j])) list(r = R) }
getFMfun <- function(FM, LB_pars, Control=list()) { LB_pars@FM <- FM (LB_pars@SPR - LBSPRsim_(LB_pars, Control=Control, verbose=FALSE)@SPR)^2 }
kinesis_dataset <- function( stream, shard = "", read_indefinitely = TRUE, interval = 100000) { dataset <- tfio_lib$kinesis$KinesisDataset( stream = stream, shard = shard, read_indefinitely = cast_logical(read_indefinitely), interval = cast_scalar_integer(interval) ) as_tf_dataset(dataset) }
kluster <- function(x, bw = "SJ", fixed = FALSE) { tryCatch( warning = function(cnd) { stop("input x must be coercible to <numeric>") }, x <- as.numeric(x) ) if (length(x) < 1) { stop("input x must contain at least 1 non-missing value") } if (fixed) { tryCatch( warning = function(cnd) { stop("input bw must be coercible to <numeric> if fixed = TRUE") }, bw <- as.numeric(bw[[1]]) ) } xdf <- data.frame(i = seq_along(x), x = x, out = NA_integer_) xnm <- xdf[!is.na(xdf$x), ] xnm <- xnm[order(xnm$x), ] nnm <- nrow(xnm) if (nnm < 1) { stop("input x must contain at least 1 non-missing value") } xnm$x <- xnm$x - min(xnm$x) if (nnm == 1) { xdf$out[xnm$i] <- 1L return(xdf$out) } if (!fixed) { d <- stats::density(xnm$x, bw = bw) d$y <- d$y / max(d$y) d$y[d$y < 0.00001] <- 0 tp <- pastecs::turnpoints(d$y) boundaries <- d$x[tp$pos[tp$pits]] xnm$out <- findInterval(xnm$x, boundaries) + 1 } else { xnm$out <- xnm$x - dplyr::lag(xnm$x, default = xnm$x[1]) xnm$out <- cumsum(xnm$out > bw) + 1 } result <- rbind(xdf[is.na(xdf$x), ], xnm) return(result[order(result$i), ]$out) }
order_burr <- function(size,k,shape1,shape2,scale,n,alpha=0.05,...){ sample <- qburr(initial_order(size,k,n),shape1,shape2,scale,...) pdf <- factorial(size)*cumprod(dburr(sample,shape1,shape2,scale,...))[size] if(size>5){ return(list(sample=sample,pdf=pdf,ci_median=interval_median(size,sample,alpha))) } cat("---------------------------------------------------------------------------------------------\n") cat("We cannot report the confidence interval. The size of the sample is less or equal than five.\n") return(list(sample=sample,pdf=pdf)) }
"efficiency.criteria" <- function(efficiencies) { daeTolerance <- get("daeTolerance", envir=daeEnv) criteria <- vector(mode="list", length = 7) names(criteria) <- c('aefficiency','mefficiency','sefficiency','eefficiency', "xefficiency",'order',"dforthog") df.orthog <- sum(abs(1-efficiencies) < daeTolerance[["eigen.tol"]]) eff.unique <- remove.repeats(efficiencies, daeTolerance[["eigen.tol"]]) K <- length(eff.unique) if (K == 1) { if (eff.unique == 0) { criteria["aefficiency"] <- 0 criteria["mefficiency"] <- 0 criteria["sefficiency"] <- 0 criteria["eefficiency"] <- 0 criteria["xefficiency"] <- 0 criteria["order"] <- 0 criteria["dforthog"] <- 0 } else { criteria["aefficiency"] <- eff.unique criteria["mefficiency"] <- eff.unique criteria["sefficiency"] <- 0 criteria["eefficiency"] <- eff.unique criteria["xefficiency"] <- eff.unique criteria["order"] <- K criteria["dforthog"] <- df.orthog } } else { criteria["aefficiency"] <- harmonic.mean(efficiencies) criteria["mefficiency"] <- mean(efficiencies) criteria["sefficiency"] <- var(efficiencies) criteria["eefficiency"] <- min(efficiencies) criteria["xefficiency"] <- max(efficiencies) criteria["order"] <- K criteria["dforthog"] <- df.orthog } return(criteria) } print.summary.p2canon <- function(x, ...) { if (!inherits(x, "summary.p2canon")) stop("Must supply an object of class summary.p2canon") cat(attr(x, which="title")) y <- x nlines <- nrow(y) repeats <- c(FALSE, y[2:nlines,"Source"] == y[1:(nlines-1),"Source"]) y[repeats, "Source"] <- " " if ("aefficiency" %in% names(y)) { y$aefficiency <- formatC(y$aefficiency, format="f", digits=4, width=11) y$aefficiency <- gsub("NA", " ", y$aefficiency) } if ("mefficiency" %in% names(y)) { y$mefficiency <- formatC(y$mefficiency, format="f", digits=4, width=11) y$mefficiency <- gsub("NA", " ", y$mefficiency) } if ("eefficiency" %in% names(y)) { y$eefficiency <- formatC(y$eefficiency, format="f", digits=4, width=11) y$eefficiency <- gsub("NA", " ", y$eefficiency) } if ("xefficiency" %in% names(y)) { y$xefficiency <- formatC(y$xefficiency, format="f", digits=4, width=11) y$xefficiency <- gsub("NA", " ", y$xefficiency) } if ("sefficiency" %in% names(y)) { y$sefficiency <- formatC(y$sefficiency, format="f", digits=4, width=11) y$sefficiency <- gsub("NA", " ", y$sefficiency) } if ("order" %in% names(y)) { y$order <- formatC(y$order, format="f", digits=0, width=5) y$order <- gsub("NA", " ", y$order) } if ("dforthog" %in% names(y)) { y$dforthog <- formatC(y$dforthog, format="f", digits=0, width=8) y$dforthog <- gsub("NA", " ", y$dforthog) } print.data.frame(y, na.print=" ", right=FALSE, row.names=FALSE) if (!attr(x, which="orthogonal")) cat("\nThe design is not orthogonal\n\n") invisible(x) } "proj2.sweep" <- function(Q1, Q2, Eff.Q1.Q2) { n <- nrow(Q1) if (n != nrow(Q2)) stop("Matrices not conformable.") isproj <- is.projector(Q1) & is.projector(Q2) if (length(Eff.Q1.Q2) == 1 & Eff.Q1.Q2[1]==0) { Qconf <- projector(matrix(0, nrow = n, ncol = n)) Qres <- Q1 Eff.Q1.Q2 <- 0 warning("Matrices are orthogonal.") } else { daeTolerance <- get("daeTolerance", envir=daeEnv) EffUnique.Q1.Q2 <-remove.repeats(Eff.Q1.Q2, daeTolerance[["eigen.tol"]]) K <- length(EffUnique.Q1.Q2) if (K == 1 & EffUnique.Q1.Q2[1] == 1 & length(Eff.Q1.Q2) == degfree(Q2)) { Qconf <- projector(Q2) Qres <- projector(Q1 - Q2) } else { I <- diag(1, nrow = n, ncol = n) Qres <- I Q121 <- Q1 %*% Q2 %*% Q1 for(i in 1:K) Qres <- Qres %*% (Q1 - (Q121/EffUnique.Q1.Q2[i])) Qres <- projector(Qres) Qconf <- projector(Q1 - Qres) } } list(Qconf = Qconf, Qres = Qres) } "projs.2canon" <- function(Q1, Q2) { if (!is.list(Q1) | !is.list(Q2)) stop("Both Q1 and Q2 must be lists") daeTolerance <- get("daeTolerance", envir=daeEnv) nQ1 <- length(Q1) nQ2 <- length(Q2) n <- nrow(Q1[1]) Q1labels <- names(Q1) if (is.null(Q1labels)) Q1labels <- as.character(1:nQ1) Q2labels <- names(Q2) if (is.null(Q2labels)) Q2labels <- as.character(1:nQ2) criteria <- c('aefficiency','mefficiency','sefficiency','eefficiency',"xefficiency", 'order',"dforthog") nc <- 4 + length(criteria) aliasing <- data.frame(matrix(nrow = 0, ncol=nc)) colnames(aliasing) <- c("Source", "df", "Alias", "In", criteria) kQ1Q2 <- 0 multieffic <- FALSE results <- vector(mode = "list", length = 0) for (i in Q1labels) { results[[i]][["Q1res"]] <- Q1[[i]] rdf <- degfree(Q1[[i]]) for (j in Q2labels) { if (rdf >0) { Q1Q2.eff <- suppressWarnings(proj2.efficiency(Q1[[i]], Q2[[j]])) if (Q1Q2.eff[1] > 0) { adj.Q1Q2 <- suppressWarnings(proj2.combine(results[[i]][["Q1res"]], Q2[[j]])) if (degfree(adj.Q1Q2$Qconf) > 0) { Qfitlab <- names(results[[i]])[-1] if (length(Qfitlab) > 0) { for (k in Qfitlab) { Qjik <- Q2[[k]] %*% Q1[[i]] %*% Q2[[j]] if (!is.allzero(Qjik)) { Qij <- proj2.combine(Q1[[i]], Q2[[j]])$Qconf Qik <- proj2.combine(Q1[[i]], Q2[[k]])$Qconf Qikj <- proj2.combine(Qik, Qij) warning(paste(j,"and",k,"are partially aliased in",i, sep=" ")) eff.crit <- efficiency.criteria(Qikj$efficiencies) aliasing <- rbind(aliasing, data.frame(c(list(Source = j, df = degfree(Qikj$Qconf), Alias = k, In = i), eff.crit[criteria]), stringsAsFactors = FALSE)) } } } results[[i]][[j]] <- vector(mode = "list", length = 0) results[[i]][[j]][["pairwise"]][["efficiencies"]] <- Q1Q2.eff results[[i]][[j]][["pairwise"]][criteria] <- efficiency.criteria(Q1Q2.eff) if (degfree(adj.Q1Q2$Qres) == 0) { adj.Q1Q2$Qres <- matrix(0, nrow=nrow(adj.Q1Q2$Qres), ncol=ncol(adj.Q1Q2$Qres)) adj.Q1Q2$Qres <- projector(adj.Q1Q2$Qres) } results[[i]][["Q1res"]] <- adj.Q1Q2$Qres results[[i]][[j]][["adjusted"]][["efficiencies"]] <- adj.Q1Q2$efficiencies results[[i]][[j]][["adjusted"]][criteria] <- efficiency.criteria(adj.Q1Q2$efficiencies) if (results[[i]][[j]][["adjusted"]][["aefficiency"]] - results[[i]][[j]][["adjusted"]][["eefficiency"]] > daeTolerance[["eigen.tol"]]) multieffic <- TRUE results[[i]][[j]][["Qproj"]] <- adj.Q1Q2$Qconf rdf <- degfree(adj.Q1Q2$Qres) } else { warning(paste(j,"is aliased with previous terms in",i, sep=" ")) eff.crit <- rep(0, length(criteria)) names(eff.crit) <- criteria aliasing <- rbind(aliasing, data.frame(c(list(Source = j, df = 0, Alias = " In = i), eff.crit), stringsAsFactors = FALSE)) } } } } } if (nrow(aliasing) == 0 ) aliasing <- NULL p2can <- list(decomp = results, aliasing = aliasing) class(p2can) <- "p2canon" return(p2can) } "summary.p2canon" <- function(object, which.criteria = c("aefficiency", "eefficiency", "order"), ...) { if (!inherits(object, "p2canon")) stop("object must be of class p2canon as produced by projs.2canon") criteria <- c("aefficiency", "eefficiency", "mefficiency", "sefficiency", "xefficiency", "order", "dforthog") options <- c(criteria, "none", "all") kcriteria <- options[unlist(lapply(which.criteria, check.arg.values, options=options))] if ("all" %in% kcriteria) kcriteria <- criteria anycriteria <- !("none" %in% kcriteria) orthogonaldesign <- TRUE nc <- 3 if (anycriteria) { nc <- nc + length(kcriteria) res.criteria <- vector(mode = "list", length = length(kcriteria)) names(res.criteria) <- kcriteria res.criteria[kcriteria] <- NA summary <- data.frame(matrix(nrow = 0, ncol=nc)) colnames(summary) <- c("Source", "Confounded.source", "df", kcriteria) } else { summary <- data.frame(matrix(nrow = 0, ncol=nc)) colnames(summary) <- c("Source", "Confounded.source", "df") } Q1labels <- names(object$decomp) for (i in Q1labels) { Q2labels <- names(object$decomp[[i]])[-1] nconf.terms <- 0 if (length(Q2labels) > 0) { for (j in Q2labels) { kdf <- degfree(object$decomp[[i]][[j]]$Qproj) if (kdf > 0) { nconf.terms <- nconf.terms + 1 if (abs(1 - unlist(object$decomp[[i]][[j]][["adjusted"]]["aefficiency"])) > 1e-04) orthogonaldesign <- FALSE if (anycriteria) summary <- rbind(summary, data.frame(Source = i, Confounded.source = j, df = kdf, object$decomp[[i]][[j]][["adjusted"]][kcriteria], stringsAsFactors = FALSE)) else summary <- rbind(summary, data.frame(Source = i, Confounded.source = j, df = kdf, stringsAsFactors = FALSE)) } } } kdf <- degfree(object$decomp[[i]]$Q1res) if (kdf > 0) if (nconf.terms > 0) { if (anycriteria) summary <- rbind(summary, data.frame(Source = i, Confounded.source = "Residual", df = kdf, res.criteria[kcriteria], stringsAsFactors = FALSE)) else summary <- rbind(summary, data.frame(Source = i, Confounded.source = "Residual", df = kdf, stringsAsFactors = FALSE)) } else { if (anycriteria) summary <- rbind(summary, data.frame(Source = i, Confounded.source = " ", df = kdf, res.criteria[kcriteria], stringsAsFactors = FALSE)) else summary <- rbind(summary, data.frame(Source = i, Confounded.source = " ", df = kdf, stringsAsFactors = FALSE)) } } summary <- as.data.frame(summary) class(summary) <- c("summary.p2canon", "data.frame") titl <- "\n\nSummary table of the decomposition" if (!orthogonaldesign) titl <- paste(titl, " (based on adjusted quantities)\n\n", sep = "") else titl <- paste(titl, "\n\n", sep = "") attr(summary, which = "title") <- titl attr(summary, which = "orthogonal") <- orthogonaldesign return(summary) } "efficiencies.decomp" <- function(decomp, which = "adjusted", ...) { options <- c("adjusted", "pairwise") opt <- options[check.arg.values(which, options)] Q1labels <- names(decomp) efficiencies <- vector(mode = "list", length = 0) for (i in Q1labels) { Q2labels <- names(decomp[[i]])[-1] if (length(Q2labels) > 0) { efficiencies[[i]] <- vector(mode = "list", length = 0) for (j in Q2labels) efficiencies[[i]][[j]] <- decomp[[i]][[j]][[opt]][["efficiencies"]] } } return(efficiencies) } "efficiencies.p2canon" <- function(object, which = "adjusted", ...) { if (!inherits(object, "p2canon")) stop("object must be of class p2canon as produced by projs.2canon") options <- c("adjusted", "pairwise") opt <- options[check.arg.values(which, options)] efficiencies <- efficiencies.decomp(object$decomp, which = which) return(efficiencies) } "projs.combine.p2canon" <- function(object) { Q1combineQ2 <- vector(mode = "list", length = 0) Q1labels <- names(object$decomp) efficiencies <- vector(mode = "list", length = 0) for (i in Q1labels) { Q2labels <- names(object$decomp[[i]])[-1] if (length(Q2labels) > 0) { for (j in Q2labels) { Q1Q2label <- paste(Q1labels[[match(i, Q1labels)]], Q2labels[[match(j, Q2labels)]], sep="&") Q1combineQ2[[Q1Q2label]] <-object$decomp[[i]][[j]][["Qproj"]] } if (degfree(object$decomp[[i]][["Q1res"]]) > 0) { Q1Q2label <- paste(Q1labels[[match(i, Q1labels)]],"Residual", sep="&") Q1combineQ2[[Q1Q2label]] <- object$decomp[[i]][["Q1res"]] } } else Q1combineQ2[[i]] <- object$decomp[[i]][["Q1res"]] } return(Q1combineQ2) }
context("Visual Test") model <- lm(mpg ~ disp + hp + wt, data = mtcars) test_that("residual histogram plot is as expected", { skip_on_cran() p <- ols_plot_resid_hist(model) vdiffr::expect_doppelganger("ggplot2 histogram", p) }) test_that("hadi plot is as expected", { skip_on_cran() p <- ols_plot_hadi(model) vdiffr::expect_doppelganger("hadi plot", p) }) test_that("observed vs predicted plot is as expected", { skip_on_cran() p <- ols_plot_obs_fit(model) vdiffr::expect_doppelganger("ovsp plot", p) }) test_that("potential residual plot is as expected", { skip_on_cran() p <- ols_plot_resid_pot(model) vdiffr::expect_doppelganger("potential residual plot", p) }) test_that("residual box plot is as expected", { skip_on_cran() p <- ols_plot_resid_box(model) vdiffr::expect_doppelganger("residual box plot", p) }) test_that("residual fit spread plot 1 is as expected", { skip_on_cran() p <- ols_plot_resid_spread(model) vdiffr::expect_doppelganger("residual fit spread plot", p) }) test_that("residual fit spread plot 2 is as expected", { skip_on_cran() p <- ols_plot_fm(model) vdiffr::expect_doppelganger("residual fit spread plot 2", p) }) test_that("residual qq plot is as expected", { skip_on_cran() p <- ols_plot_resid_qq(model) vdiffr::expect_doppelganger("residual qq plot", p) }) test_that("residual vs fitted plot is as expected", { skip_on_cran() p <- ols_plot_resid_fit(model) vdiffr::expect_doppelganger("residual vs fitted plot", p) }) test_that("residual vs regressor plot is as expected", { skip_on_cran() p <- ols_plot_resid_regressor(model, 'drat') vdiffr::expect_doppelganger("residual vs regressor plot", p) }) test_that("cooks d bar plot is as expected", { skip_on_cran() p <- ols_plot_cooksd_bar(model, print_plot = FALSE) vdiffr::expect_doppelganger("cooks d bar plot", p$plot) }) test_that("cooks d bar chart is as expected", { skip_on_cran() p <- ols_plot_cooksd_chart(model, print_plot = FALSE) vdiffr::expect_doppelganger("cooks d bar chart", p$plot) }) test_that("dffits plot is as expected", { skip_on_cran() p <- ols_plot_dffits(model, print_plot = FALSE) vdiffr::expect_doppelganger("dffits plot", p$plot) }) test_that("deleted studentized residual vs fitted plot is as expected", { skip_on_cran() p <- ols_plot_resid_stud_fit(model, print_plot = FALSE) vdiffr::expect_doppelganger("dsrvsp plot", p$plot) }) test_that("residual vs regressor shiny plot is as expected", { skip_on_cran() p <- rvsr_plot_shiny(model, mtcars, "drat") vdiffr::expect_doppelganger("residual vs regressor shiny plot", p) }) test_that("residual fit spread plot is as expected", { skip_on_cran() p <- ols_plot_resid_fit_spread(model, print_plot = TRUE) vdiffr::expect_doppelganger("fm_plot", p$fm_plot) vdiffr::expect_doppelganger("rsd_plot", p$rsd_plot) }) test_that("response profile plot is as expected", { skip_on_cran() p <- ols_plot_response(model, print_plot = FALSE) vdiffr::expect_doppelganger("resp viz dot plot", p$dot_plot) vdiffr::expect_doppelganger("resp viz trend plot", p$trend_plot) vdiffr::expect_doppelganger("resp viz histogram", p$histogram) vdiffr::expect_doppelganger("resp viz boxplot", p$boxplot) }) test_that("stepAIC backward regression plot is as expected", { skip_on_cran() model <- lm(y ~ ., data = surgical) p <- plot(ols_step_backward_aic(model)) vdiffr::expect_doppelganger("stepaic backward regression plot", p) }) test_that("stepAIC forward regression plot is as expected", { skip_on_cran() model <- lm(y ~ ., data = surgical) p <- plot(ols_step_forward_aic(model)) vdiffr::expect_doppelganger("stepaic forward regression plot", p) }) test_that("stepAIC both direction regression plot is as expected", { skip_on_cran() model <- lm(y ~ ., data = surgical) p <- plot(ols_step_both_aic(model)) vdiffr::expect_doppelganger("stepaic both regression plot", p) }) test_that("added variable plot is as expected", { skip_on_cran() p <- ols_plot_added_variable(model, print_plot = FALSE) vdiffr::expect_doppelganger("avplot_1", p[[1]]) vdiffr::expect_doppelganger("avplot_2", p[[2]]) vdiffr::expect_doppelganger("avplot_3", p[[3]]) }) test_that("all possible regression plots are as expected", { skip_on_cran() model <- lm(mpg ~ disp + hp, data = mtcars) k <- ols_step_all_possible(model) p <- plot(k, print_plot = FALSE) vdiffr::expect_doppelganger("allplot_1", p$plot_1) vdiffr::expect_doppelganger("allplot_2", p$plot_2) vdiffr::expect_doppelganger("allplot_3", p$plot_3) vdiffr::expect_doppelganger("allplot_4", p$plot_4) vdiffr::expect_doppelganger("allplot_5", p$plot_5) vdiffr::expect_doppelganger("allplot_6", p$plot_6) }) test_that("best subset regression plots are as expected", { skip_on_cran() model <- lm(mpg ~ disp + hp + wt + qsec, data = mtcars) k <- ols_step_best_subset(model) p <- plot(k, print_plot = FALSE) vdiffr::expect_doppelganger("bestplot_1", p$plot_1) vdiffr::expect_doppelganger("bestplot_2", p$plot_2) vdiffr::expect_doppelganger("bestplot_3", p$plot_3) vdiffr::expect_doppelganger("bestplot_4", p$plot_4) vdiffr::expect_doppelganger("bestplot_5", p$plot_5) vdiffr::expect_doppelganger("bestplot_6", p$plot_6) }) test_that("dfbetas plot is as expected", { skip_on_cran() model <- lm(mpg ~ disp + hp + wt + qsec, data = mtcars) p <- ols_plot_dfbetas(model, print_plot = FALSE) vdiffr::expect_doppelganger("dfbetas_1", p$plots[[1]]) vdiffr::expect_doppelganger("dfbetas_2", p$plots[[2]]) vdiffr::expect_doppelganger("dfbetas_3", p$plots[[3]]) vdiffr::expect_doppelganger("dfbetas_4", p$plots[[4]]) vdiffr::expect_doppelganger("dfbetas_5", p$plots[[5]]) }) test_that("diagnostics panel is as expected", { skip_on_cran() model <- lm(mpg ~ disp + hp + wt + qsec, data = mtcars) p <- ols_plot_diagnostics(model, print_plot = FALSE) vdiffr::expect_doppelganger("diag_1", p[[1]]) vdiffr::expect_doppelganger("diag_2", p[[2]]) vdiffr::expect_doppelganger("diag_3", p[[3]]) vdiffr::expect_doppelganger("diag_4", p[[4]]) vdiffr::expect_doppelganger("diag_5", p[[5]]) vdiffr::expect_doppelganger("diag_6", p[[6]]) vdiffr::expect_doppelganger("diag_7", p[[7]]) vdiffr::expect_doppelganger("diag_8", p[[8]]) vdiffr::expect_doppelganger("diag_9", p[[9]]) vdiffr::expect_doppelganger("diag_10", p[[10]]) }) test_that("fitted line plot is as expected", { skip_on_cran() p <- ols_plot_reg_line(mtcars$mpg, mtcars$disp, print_plot = FALSE) vdiffr::expect_doppelganger("reg_line_plot", p) }) test_that("residual plus component plot is as expected", { skip_on_cran() model <- lm(mpg ~ disp + hp + wt + qsec, data = mtcars) p <- ols_plot_comp_plus_resid(model, print_plot = FALSE) vdiffr::expect_doppelganger("rpcplot_1", p[[1]]) vdiffr::expect_doppelganger("rpcplot_2", p[[2]]) vdiffr::expect_doppelganger("rpcplot_3", p[[3]]) vdiffr::expect_doppelganger("rpcplot_4", p[[4]]) }) test_that("rstud vs lev plot is as expected", { skip_on_cran() model <- lm(read ~ write + math + science, data = hsb) p <- ols_plot_resid_lev(model, print_plot = FALSE) vdiffr::expect_doppelganger("rslev_1", p$plot) }) test_that("standardized residual plot is as expected", { skip_on_cran() model <- lm(mpg ~ disp + hp + wt, data = mtcars) p <- ols_plot_resid_stand(model, print_plot = FALSE) vdiffr::expect_doppelganger("stanres_1", p$plot) }) test_that("studentized residual plot is as expected", { skip_on_cran() model <- lm(mpg ~ disp + hp + wt, data = mtcars) p <- ols_plot_resid_stud(model, print_plot = FALSE) vdiffr::expect_doppelganger("studres_1", p$plot) }) test_that("stepwise backward regression plots are as expected", { skip_on_cran() model <- lm(y ~ ., data = surgical) k <- ols_step_backward_p(model) p <- plot(k, print_plot = FALSE) vdiffr::expect_doppelganger("step_back_1", p$plot_1) vdiffr::expect_doppelganger("step_back_2", p$plot_2) vdiffr::expect_doppelganger("step_back_3", p$plot_3) vdiffr::expect_doppelganger("step_back_4", p$plot_4) vdiffr::expect_doppelganger("step_back_5", p$plot_5) vdiffr::expect_doppelganger("step_back_6", p$plot_6) }) test_that("stepwise forward regression plots are as expected", { skip_on_cran() model <- lm(y ~ ., data = surgical) k <- ols_step_forward_p(model) p <- plot(k, print_plot = FALSE) vdiffr::expect_doppelganger("step_forward_1", p$plot_1) vdiffr::expect_doppelganger("step_forward_2", p$plot_2) vdiffr::expect_doppelganger("step_forward_3", p$plot_3) vdiffr::expect_doppelganger("step_forward_4", p$plot_4) vdiffr::expect_doppelganger("step_forward_5", p$plot_5) vdiffr::expect_doppelganger("step_forward_6", p$plot_6) }) test_that("stepwise both regression plots are as expected", { skip_on_cran() model <- lm(y ~ ., data = surgical) k <- ols_step_both_p(model) p <- plot(k, print_plot = FALSE) vdiffr::expect_doppelganger("step_both_1", p$plot_1) vdiffr::expect_doppelganger("step_both_2", p$plot_2) vdiffr::expect_doppelganger("step_both_3", p$plot_3) vdiffr::expect_doppelganger("step_both_4", p$plot_4) vdiffr::expect_doppelganger("step_both_5", p$plot_5) vdiffr::expect_doppelganger("step_both_6", p$plot_6) })
.onLoad <- function(libname, pkgname) { if (requireNamespace("emmeans", quietly = TRUE)) { emmeans::.emm_register(c("bootstrap_model", "bootstrap_parameters"), pkgname) } }
is_predraft <- function(dat) { if ("draftDetail" %in% names(dat)) { if (!dat$draftDetail$drafted) { message("League has not yet drafted this season") return(TRUE) } } return(FALSE) } skip_predraft <- function(dat) { if (is_installed("testthat") & "draftDetail" %in% names(dat)) { if (!dat$draftDetail$drafted) { testthat::skip(message = "League has not drafted") } } }
setClass(Class="Haplotype", representation=representation(haplist ="list",hapind ="list", uniquehapind="numeric",sequence="matrix",d="matrix",freq="numeric",nhap="numeric")) setMethod("initialize", "Haplotype", function(.Object,haplist= list(),hapind =list(),uniquehapind=numeric(),sequence=matrix(,0,0),d=matrix(,0,0),freq=sapply(.Object@haplist,length),nhap=length(.Object@haplist)) { .Object@haplist<-haplist .Object@hapind<-hapind .Object@uniquehapind<-uniquehapind .Object@sequence<-sequence .Object@d<-d .Object@freq<-freq .Object@nhap<-nhap .Object }) setMethod("show","Haplotype", function(object) { cat("*** S4 Object of Class Haplotype ***\n\n") show(object@haplist) cat("\nNumber of haplotypes : ", object@nhap) cat("\n\nslots of an object Haplotype:\n") cat(slotNames(object),"\n") }) haplo<-function(x) { x <- as.matrix(x) diag(x)<-0 nseq<-nrow(x) whap<-x[1,]==0 haploind<-list(which(whap)) haplovec<-which(whap) if(length(x)>1) { for(i in 2:nseq) { whap<-x[i,]==0 whap[haplovec]<-FALSE haploind<-c(haploind,list(which(whap))) haplovec<-unique(c(haplovec,which(whap))) } } empthaplo<-sapply(haploind,length) haploind<-unique(haploind[empthaplo>0]) haplolist<-lapply(haploind,names) uniqhapindex<-sapply(haploind,"[",1) hapdistmat<-as.matrix(x[uniqhapindex,uniqhapindex]) freq<-sapply(haplolist,length) hapnum<-length(freq) names(haploind)<-paste("haplotype",1:hapnum,sep="") names(haplolist)<-names(haploind) hapobj<-new("Haplotype",haplist=haplolist,hapind=haploind,uniquehapind=uniqhapindex,d=hapdistmat,freq=freq,nhap=hapnum) hapobj } setGeneric ( name= "haplotype", def=function(x,...)standardGeneric("haplotype") ) setMethod("haplotype","Dna", function(x,indels="sic") { d<-distance(x,indels=indels) if(length(d)==0) stop("at least two DNA sequences are required") h<-haplo(d) h@sequence<-x@sequence[h@uniquehapind,,drop=FALSE] h }) setMethod("haplotype","matrix", function(x) { if(nrow(x)==1) stop("dimension of the distance matrix (x) must be greater than one") haplo(x) }) setMethod("haplotype","dist", function(x) { if(length(x)==0) stop("length of the distance object (x) must be greater than zero") haplo(x) }) setMethod("as.list","Haplotype", function(x) { l<-list(x@haplist,x@hapind, x@uniquehapind,x@sequence,x@d,x@freq,x@nhap) names(l)<-c("haplist","hapind","uniquehapind","sequence","d","freq","nhap") l }) setMethod("length","Haplotype", function(x) { x@nhap }) setGeneric ( name= "hapreord", def=function(x,...)standardGeneric("hapreord") ) setMethod(f="hapreord", signature= "Haplotype", definition=function(x,order=c(1:x@nhap)) { if(length(order)!=length(x)) stop(paste("'order' must be vector of length",length(x))) if(any(order<1)|any(order>length(x))) stop(paste("elements of 'order' must be integers in the range [1,",length(x),"]",sep="")) haplolist<-x@haplist[order] names(haplolist)<-paste("haplotype",1:x@nhap,sep="") haploind<-x@hapind[order] names(haploind)<-names(haplolist) if(nrow(x@sequence)>0) { hapobj<-new("Haplotype",haplist=haplolist,hapind=haploind,uniquehapind=x@uniquehapind[order],sequence=x@sequence[order,,drop=FALSE],d=x@d[order,order],freq=x@freq[order]) } else { hapobj<-new("Haplotype",haplist=haplolist,hapind=haploind,uniquehapind=x@uniquehapind[order],d=x@d[order,order],freq=x@freq[order]) } return(hapobj) }) setGeneric ( name= "grouping", def=function(x,...)standardGeneric("grouping") ) setMethod(f="grouping", signature= "Haplotype", definition=function(x,factors) { l<-x@nhap flevels<-levels(factor(factors)) hapmat<-matrix(0, l, length(flevels)) hapvec<-vector("numeric",length(factors)) rownames(hapmat)<-1:l colnames(hapmat)<-flevels for(i in 1:l) { hind<- x@hapind[[i]] fstab<-table(factor(factors[hind])) hapmat[i,names(fstab)]<-fstab hapvec[hind]<-i } return(list(hapmat=hapmat,hapvec=hapvec)) }) setMethod(f="as.dna", signature= "Haplotype", definition=function(x) { seq<-x@sequence if(!nrow(seq)) stop("Haplotype object does not contain DNA sequences") dnaobj<-new("Dna",sequence=seq,seqlengths=rep(ncol(seq),nrow(seq)),seqnames=rownames(seq)) dnaobj } )
plot_annual_means <- function(data, dates = Date, values = Value, groups = STATION_NUMBER, station_number, roll_days = 1, roll_align = "right", water_year_start = 1, start_year, end_year, exclude_years, months = 1:12, ignore_missing = FALSE, allowed_missing = ifelse(ignore_missing,100,0), include_title = FALSE){ if (missing(data)) { data <- NULL } if (missing(station_number)) { station_number <- NULL } if (missing(start_year)) { start_year <- 0 } if (missing(end_year)) { end_year <- 9999 } if (missing(exclude_years)) { exclude_years <- NULL } include_title_checks(include_title) flow_data <- flowdata_import(data = data, station_number = station_number) flow_data <- format_all_cols(data = flow_data, dates = as.character(substitute(dates)), values = as.character(substitute(values)), groups = as.character(substitute(groups)), rm_other_cols = TRUE) annual_stats <- calc_annual_stats(data = flow_data, roll_days = roll_days, roll_align = roll_align, water_year_start = water_year_start, start_year = start_year, end_year = end_year, exclude_years = exclude_years, months = months, ignore_missing = ignore_missing, allowed_missing = allowed_missing) annual_stats <- dplyr::select(annual_stats, STATION_NUMBER, Year, Mean) lt_mad <- dplyr::group_by(annual_stats, STATION_NUMBER) lt_mad <- dplyr::summarise(lt_mad, LTMAD = mean(Mean, na.rm = TRUE)) annual_stats <- dplyr::left_join(annual_stats, lt_mad, by = "STATION_NUMBER") annual_stats <- dplyr::mutate(annual_stats, MAD_diff = Mean - LTMAD) annual_stats <- annual_stats[stats::complete.cases(annual_stats$Mean), ] tidy_plots <- dplyr::group_by(annual_stats, STATION_NUMBER) tidy_plots <- tidyr::nest(tidy_plots) tidy_plots <- dplyr::mutate( tidy_plots, plot = purrr::map2(data, STATION_NUMBER, ~ggplot2::ggplot(data = ., ggplot2::aes(x = Year, y = MAD_diff)) + ggplot2::geom_bar(stat = "identity", fill = "cornflowerblue", na.rm = TRUE) + ggplot2::geom_hline(yintercept = 0, size = 0.1) + ggplot2::scale_y_continuous(labels = function(x) round(x + unique(.$LTMAD),3), breaks = scales::pretty_breaks(n = 10)) + ggplot2::scale_x_continuous(breaks = scales::pretty_breaks(n = 8))+ {if(length(unique(annual_stats$Year)) < 8) ggplot2::scale_x_continuous(breaks = unique(annual_stats$Year))}+ ggplot2::ylab("Mean Annual Discharge (cms)") + {if (include_title & .y != "XXXXXXX") ggplot2::ggtitle(paste(.y)) } + ggplot2::theme_bw() + ggplot2::theme(panel.border = ggplot2::element_rect(colour = "black", fill = NA, size = 1), panel.grid = ggplot2::element_line(size = .2), axis.title = ggplot2::element_text(size = 12), axis.text = ggplot2::element_text(size = 10), plot.title = ggplot2::element_text(hjust = 1, size = 9, colour = "grey25")) )) plots <- tidy_plots$plot if (nrow(tidy_plots) == 1) { names(plots) <- "Annual_Means" } else { names(plots) <- paste0(tidy_plots$STATION_NUMBER, "_Annual_Means") } plots }
gf_point(Sepal.Length ~ Sepal.Width, data = iris)
fpath = system.file("testdata", "ploglik_cmodStd_r_lambda_ratio_par3.rda", package = "gear") load(fpath) scmod = cmod_std(model = "matern", psill = 1, r = 1, par3 = 1, angle = pi/8, ratio = 1/1.5, radians = TRUE, invert = TRUE) weights = rep(1, length(y)) gear_ml = optimx::optimx(par = c(1, 1, 1/1.5, 1), fn = ploglik_cmodStd_r_lambda_ratio_par3, lower = c(0.001, 0, 0.001, 0.001), upper = c(2, 2, 1, 2.5), method = "L-BFGS-B", x = x, y = y, d = d, weights = weights, scmod = scmod, reml = FALSE, control = list(dowarn = FALSE)) sigmasq_ml = ploglik_cmodStd_r_lambda_ratio_par3(with(gear_ml, c(p1, p2, p3, p4)), x = x, y = y, d = d, weights = weights, scmod = scmod, return_ll = FALSE) gear_reml = optimx::optimx(par = c(1, 1, 1/1.5, 1), fn = ploglik_cmodStd_r_lambda_ratio_par3, lower = c(0.001, 0, 0.001, 0.001), upper = c(15, 5, 1, 2.5), method = "L-BFGS-B", x = x, y = y, d = d, nugget = geoR_reml$nugget, weights = weights, scmod = scmod, reml = TRUE, control = list(dowarn = FALSE)) sigmasq_reml = ploglik_cmodStd_r_lambda_ratio_par3(with(gear_ml, c(p1, p2, p3, p4)), x = x, y = y, d = d, weights = weights, scmod = scmod, reml = TRUE, return_ll = FALSE) test_that("ploglik_cmodStd_r_lambda_ratio_par3 accuracy (geoR)", { expect_true(abs(geoR_ml$cov.pars[1] - sigmasq_ml) < 1e-1) expect_true(abs(geoR_ml$cov.pars[2] - gear_ml$p1 * gear_ml$p3) < 1e-3) expect_true(abs(geoR_ml$nugget - sigmasq_ml * gear_ml$p2) < 1e-2) expect_true(abs(geoR_ml$aniso.pars[2] - 1/gear_ml$p3) < 1e-2) expect_true(abs(geoR_ml$kappa - gear_ml$p4) < 1e-2) expect_true(abs(geoR_ml$loglik - gear_ml$value/-2) < 1e-5) expect_true(abs(geoR_reml$cov.pars[1] - sigmasq_reml) < 1e-1/2) expect_true(abs(geoR_reml$cov.pars[2] - gear_reml$p1 * gear_reml$p3) < 1e-3) expect_true(abs(geoR_reml$nugget - sigmasq_reml * gear_reml$p2) < 1e-2) expect_true(abs(geoR_reml$aniso.pars[2] - 1/gear_reml$p3) < 1e-2) expect_true(abs(geoR_reml$kappa - gear_reml$p4) < 1e-2) expect_true(abs(geoR_reml$loglik - gear_reml$value/-2) < 1e-5) }) cmod = scmod cmod$evar = scmod$psill data = data.frame(y = y, x1 = coords[,1], x2 = coords[,2]) object = geolm(y ~ 1, data = data, coordnames = c("x1", "x2"), mod = cmod) object_ml = estimate(object, method = "L-BFGS-B", lower = list(r = 0.001, lambda = 0, angle = 0, ratio = 0.001, par3 = 0.001), upper = list(r = 2, lambda = 2, angle = pi - .001, ratio = 1, par3 = 2.5), est_nugget = TRUE, est_par3 = TRUE, est_angle = FALSE, est_ratio = TRUE, verbose = FALSE) object_reml = estimate(object, method = "L-BFGS-B", lower = list(r = 0.001, lambda = 0, angle = 0, ratio = 0.001, par3 = 0.001), upper = list(r = 15, lambda = 5, angle = pi - .001, ratio = 1, par3 = 2.5), est_nugget = TRUE, est_par3 = TRUE, est_angle = FALSE, est_ratio = TRUE, verbose = FALSE, reml = TRUE) test_that("estimate r_lambda_angle_par3 accuracy (geoR)", { expect_true(abs(geoR_ml$sigmasq - object_ml$mod$psill) < 1e-1) expect_true(abs(geoR_ml$phi - object_ml$mod$r*object_ml$mod$ratio) < 1e-2) expect_true(abs(geoR_ml$aniso.pars[1] - object_ml$mod$angle) < 1e-2) expect_true(abs(geoR_ml$aniso.pars[2] - 1/object_ml$mod$ratio) < 1e-1/2) expect_true(abs(geoR_ml$kappa - object_ml$mod$par3) < 1e-1) expect_true(abs(geoR_ml_beta - object_ml$coeff) < 1e-2) expect_equal(gear_ml$value/-2, object_ml$loglik) expect_equivalent(gear_ml[1:5], object_ml$optimx[1:5]) expect_true(abs(geoR_reml$sigmasq - object_reml$mod$psill) < 1e-1) expect_true(abs(geoR_reml$phi - object_reml$mod$r*object_reml$mod$ratio) < 1e-4) expect_true(abs(geoR_reml$aniso.pars[1] - object_reml$mod$angle) < 1e-3) expect_true(abs(geoR_reml$aniso.pars[2] - 1/object_reml$mod$ratio) < 1e-2) expect_true(abs(geoR_reml$kappa - object_reml$mod$par3) < 1e-2) expect_true(abs(geoR_reml_beta - object_reml$coeff) < 1e-2) expect_equivalent(gear_reml[1:5], object_reml$optimx[1:5]) }) cmod_radians = scmod cmod_radians$evar = 1 cmod_radians$angle = scmod$angle * 180/pi cmod_radians$radians = FALSE object_radians = geolm(y ~ 1, data = data, coordnames = c("x1", "x2"), mod = cmod_radians) object_ml_radians = estimate(object_radians, method = "L-BFGS-B", lower = list(r = 0.001, lambda = 0, ratio = 0.001, par3 = 0.001), upper = list(r = 2, lambda = 2, ratio = 1, par3 = 2.5), est_nugget = TRUE, est_par3 = TRUE, est_angle = FALSE, est_ratio = TRUE, verbose = FALSE) test_that("estimate w/ and w/o radians r_lambda_ratio_par3 accuracy", { expect_equal(object_ml$mod$angle, object_ml_radians$mod$angle * pi/180) expect_equal(object_ml$mod$ratio, object_ml_radians$mod$ratio) expect_equal(object_ml$mod$psill, object_ml_radians$mod$psill) expect_equal(object_ml$mod$r, object_ml_radians$mod$r) expect_equal(object_ml$mod$par3, object_ml_radians$mod$par3) expect_equal(object_ml$coeff, object_ml_radians$coeff) expect_equal(object_ml$loglik, object_ml_radians$loglik) object_ml_radians$optimx$xtime = object_ml$optimx$xtime expect_equal(object_ml$optimx, object_ml_radians$optimx) })
write.cross <- function(cross, format=c("csv", "csvr", "csvs", "csvsr", "mm", "qtlcart", "gary", "qtab", "mapqtl", "tidy"), filestem="data", chr, digits=NULL, descr) { if(!inherits(cross, "cross")) stop("Input should have class \"cross\".") format <- match.arg(format) if(!missing(chr)) cross <- subset(cross,chr=chr) chr_type <- sapply(cross$geno,chrtype) crosstype <- crosstype(cross) if((crosstype=="bc" || crosstype=="f2") && any(chr_type=="X")) { sexpgm <- getsex(cross) sex <- sexpgm$sex pgm <- sexpgm$pgm for(i in which(chr_type=="X")) cross$geno[[i]]$data <- fixX4write(cross$geno[[i]]$data,sex,pgm,crosstype) } if(crosstype == "bcsft") class(cross) <- c("f2", "cross") if(format=="csv") write.cross.csv(cross,filestem,digits,FALSE,FALSE) else if(format=="csvr") write.cross.csv(cross,filestem,digits,TRUE,FALSE) else if(format=="csvs") write.cross.csv(cross,filestem,digits,FALSE,TRUE) else if(format=="csvsr") write.cross.csv(cross,filestem,digits,TRUE,TRUE) else if(format=="mm") write.cross.mm(cross,filestem,digits) else if(format=="qtlcart") write.cross.qtlcart(cross, filestem) else if(format=="gary") write.cross.gary(cross, digits) else if(format=="tidy") write.cross.tidy(cross, filestem, digits) else if(format=="qtab") { if(missing(descr)) descr <- paste(deparse(substitute(cross)), "from R/qtl") write.cross.qtab(cross, filestem, descr, verbose=FALSE) } else if(format == "mapqtl") write.cross.mq(cross, filestem, digits) } write.cross.mm <- function(cross, filestem="data", digits=NULL) { n.ind <- nind(cross) tot.mar <- totmar(cross) n.phe <- nphe(cross) n.chr <- nchr(cross) n.mar <- nmar(cross) type <- crosstype(cross) if(type=="riself" || type=="risib" || type=="dh" || type=="haploid") type <- "bc" if(type != "f2" && type != "bc") stop("write.cross.mm only works for intercross, backcross, doubled haploid and RI data.") file <- paste(filestem, ".raw", sep="") if(type == "f2") write("data type f2 intercross", file, append=FALSE) else write("data type f2 backcross", file, append=FALSE) write(paste(n.ind, tot.mar, n.phe), file, append=TRUE) mlmn <- max(nchar(unlist(lapply(cross$geno,function(a) colnames(a$data)))))+1 for(i in 1:n.chr) { for(j in 1:n.mar[i]) { mn <- paste("*", colnames(cross$geno[[i]]$data)[j], sep="") if(nchar(mn) < mlmn) mn <- paste(mn,paste(rep(" ", mlmn-nchar(mn)),collapse=""),sep="") g <- cross$geno[[i]]$data[,j] x <- rep("", n.ind) x[is.na(g)] <- "-" x[!is.na(g) & g==1] <- "A" x[!is.na(g) & g==2] <- "H" if(type == "f2") { x[!is.na(g) & g==3] <- "B" x[!is.na(g) & g==4] <- "D" x[!is.na(g) & g==5] <- "C" } if(n.ind < 60) write(paste(mn, paste(x,collapse="")), file, append=TRUE) else { lo <- seq(1,n.ind-1,by=60) hi <- c(lo[-1]-1,n.ind) for(k in seq(along=lo)) { if(k==1) write(paste(mn,paste(x[lo[k]:hi[k]],collapse="")),file,append=TRUE) else write(paste(paste(rep(" ", mlmn),collapse=""), paste(x[lo[k]:hi[k]],collapse="")),file,append=TRUE) } } } } mlpn <- max(nchar(colnames(cross$pheno)))+1 for(i in 1:n.phe) { pn <- paste("*",colnames(cross$pheno)[i],sep="") if(nchar(pn) < mlpn) pn <- paste(pn, paste(rep(" ", mlpn-nchar(pn)),collapse=""),sep="") if(!is.factor(cross$pheno[,i])) { if(is.null(digits)) x <- as.character(cross$pheno[,i]) else x <- as.character(round(cross$pheno[,i],digits)) } else x <- as.character(cross$pheno[,i]) x[is.na(x)] <- "-" if(n.ind < 10) write(paste(pn, paste(x,collapse="")), file, append=TRUE) else { lo <- seq(1,n.ind-1,by=10) hi <- c(lo[-1]-1,n.ind) for(k in seq(along=lo)) { if(k==1) write(paste(pn,paste(x[lo[k]:hi[k]],collapse=" ")),file,append=TRUE) else write(paste(paste(rep(" ", mlpn),collapse=""), paste(x[lo[k]:hi[k]],collapse=" ")),file,append=TRUE) } } } file <- paste(filestem, ".prep", sep="") for(i in 1:n.chr) { cname <- paste("chr", names(cross$geno)[i], sep="") line <- paste("make chromosome", cname) if(i==1) write(line, file, append=FALSE) else write(line, file, append=TRUE) mn <- names(cross$geno[[i]]$map) write(paste(paste("sequence", mn[1]), paste(mn[-1],collapse=" ")), file, append=TRUE) write(paste("anchor", cname), file, append=TRUE) write(paste("framework", cname), file, append=TRUE) } } write.cross.csv <- function(cross, filestem="data", digits=NULL, rotate=FALSE, split=FALSE) { type <- crosstype(cross) if(type != "f2" && type != "bc" && type != "riself" && type != "risib" && type != "dh" && type != "haploid") stop("write.cross.csv only works for intercross, backcross, RI, doubled haploid, and haploid data.") if(!split) file <- paste(filestem, ".csv", sep="") else { genfile <- paste(filestem, "_gen.csv", sep="") phefile <- paste(filestem, "_phe.csv", sep="") } if(split) { id <- getid(cross) if(is.null(id)) { cross$pheno$id <- 1:nind(cross) id <- getid(cross) } id.col <- which(colnames(cross$pheno)==attr(id,"phenam")) } n.ind <- nind(cross) tot.mar <- totmar(cross) n.phe <- nphe(cross) n.chr <- nchr(cross) n.mar <- nmar(cross) geno <- matrix(ncol=tot.mar,nrow=n.ind) if("alleles" %in% names(attributes(cross))) { alle <- attr(cross, "alleles") alleles <- c(paste(alle[1],alle[1],sep=""), paste(alle[1],alle[2],sep=""), paste(alle[2],alle[2],sep=""), paste("not ", alle[2],alle[2],sep=""), paste("not ", alle[1],alle[1],sep="")) } else alleles <- c("A","H","B","D","C") if(type=="dh" || type=="riself" || type=="risib") alleles[2:3] <- alleles[3:2] else if(type=="haploid") alleles <- alle firstmar <- 1 for(i in 1:n.chr) { geno[,firstmar:(firstmar+n.mar[i]-1)] <- alleles[match(cross$geno[[i]]$data,1:5)] firstmar <- firstmar + n.mar[i] } if(any(is.na(geno))) geno[is.na(geno)] <- "-" pheno <- cross$pheno for(i in 1:nphe(cross)) { if(is.factor(pheno[,i])) pheno[,i] <- as.character(pheno[,i]) else if(is.numeric(pheno[,i])) { if(!is.null(digits)) pheno[,i] <- round(pheno[,i], digits) pheno[,i] <- as.character(pheno[,i]) } } pheno <- matrix(unlist(pheno), nrow=n.ind) if(any(is.na(pheno))) pheno[is.na(pheno)] <- "-" thedata <- cbind(pheno,geno) colnames(thedata) <- c(colnames(cross$pheno), unlist(lapply(cross$geno, function(a) colnames(a$data)))) chr <- rep(names(cross$geno),n.mar) pos <- unlist(lapply(cross$geno,function(a) a$map)) chr <- c(rep("",n.phe),chr) if(!is.null(digits)) pos <- c(rep("",n.phe),as.character(round(pos,digits))) else pos <- c(rep("",n.phe),as.character(pos)) thenames <- colnames(thedata) thedata <- matrix(as.character(thedata), ncol=ncol(thedata)) thedata <- rbind(thenames, chr, pos, thedata) if(!split) { if(!rotate) write.table(thedata, file, quote=FALSE, sep=",", row.names=FALSE, col.names=FALSE) else write.table(t(thedata), file, quote=FALSE, sep=",", row.names=FALSE, col.names=FALSE) } else { n.phe <- nphe(cross) phe <- thedata[-(2:3),1:n.phe] gen <- cbind(thedata[,id.col], thedata[,-(1:n.phe)]) if(!rotate) { write.table(gen, genfile, quote=FALSE, sep=",", row.names=FALSE, col.names=FALSE) write.table(phe, phefile, quote=FALSE, sep=",", row.names=FALSE, col.names=FALSE) } else { write.table(t(gen), genfile, quote=FALSE, sep=",", row.names=FALSE, col.names=FALSE) write.table(t(phe), phefile, quote=FALSE, sep=",", row.names=FALSE, col.names=FALSE) } } } write.cross.gary <- function(cross, digits=NULL) { n.ind <- nind(cross) tot.mar <- totmar(cross) n.phe <- nphe(cross) n.chr <- nchr(cross) n.mar <- nmar(cross) chrid <- NULL for(i in 1:n.chr) { chrname <- names(cross$geno[i]) chrid <- c(chrid, rep(chrname, n.mar[i])) } write.table(chrid, file="chrid.dat", quote=FALSE, row.names=FALSE, col.names=FALSE) markpos <- NULL for(i in 1:n.chr) markpos <- c(markpos, cross$geno[[i]]$map) write.table(markpos, file="markerpos.txt", quote=FALSE, sep="\t", row.names=TRUE, col.names=FALSE) mnames <- names(markpos) write.table(mnames, file="mnames.txt", quote=FALSE, row.names=FALSE, col.names=FALSE) geno <- NULL for(i in 1:n.chr) geno <- cbind(geno, cross$geno[[i]]$data) geno <- geno - 1 write.table(geno, file="geno.dat", quote=FALSE, row.names=FALSE, col.names=FALSE, sep="\t", na="9") pheno <- cross$pheno for(i in 1:nphe(cross)) { if(is.factor(pheno[,i])) pheno[,i] <- as.character(pheno[,i]) else if(is.numeric(pheno[,i])) { if(is.null(digits)) pheno[,i] <- as.character(pheno[,i]) else pheno[,i] <- as.character(round(pheno[,i], digits)) } } pheno <- matrix(unlist(pheno), nrow=nrow(pheno)) write.table(pheno, file="pheno.dat", quote=FALSE, row.names=FALSE, col.names=FALSE, sep="\t", na="-999") write.table(names(cross$pheno), file="pnames.txt", quote=FALSE, row.names=FALSE, col.names=FALSE, sep="\t", na="-999") } write.cross.tidy <- function(cross, filestem="data", digits=NULL) { genfile <- paste(filestem, "_gen.csv", sep="") phefile <- paste(filestem, "_phe.csv", sep="") mapfile <- paste(filestem, "_map.csv", sep = "") type <- crosstype(cross) id <- getid(cross) if(is.null(id)) { cross$pheno$id <- 1:nind(cross) id <- getid(cross) } id.col <- which(colnames(cross$pheno) == attr(id,"phenam")) if("alleles" %in% names(attributes(cross))) { alle <- attr(cross, "alleles") alleles <- c(paste(alle[1],alle[1],sep=""), paste(alle[1],alle[2],sep=""), paste(alle[2],alle[2],sep=""), paste("not ", alle[2],alle[2],sep=""), paste("not ", alle[1],alle[1],sep="")) } else alleles <- c("A","H","B","D","C") if (type %in% c("dh", "riself", "risib")) alleles[2:3] <- alleles[3:2] else if (type == "haploid") alleles <- alle geno <- pull.geno(cross) geno <- matrix(alleles[geno], ncol = nind(cross), byrow = TRUE, dimnames = list(markernames(cross), make.names(id))) if(any(is.na(geno))) geno[is.na(geno)] <- "-" pheno <- cross$pheno[-id.col] for(i in 1:ncol(pheno)) { if(is.factor(pheno[,i])) pheno[,i] <- as.character(pheno[,i]) else if(is.numeric(pheno[,i])) { if(!is.null(digits)) pheno[,i] <- round(pheno[,i], digits) pheno[,i] <- as.character(pheno[,i]) } } pheno <- matrix(unlist(pheno), nrow=nind(cross), dimnames = list(make.names(id), phenames(cross)[-id.col])) pheno <- t(pheno) if(any(is.na(pheno))) pheno[is.na(pheno)] <- "-" map <- pull.map(cross, as.table = TRUE) if(!is.null(digits)) map$pos <- as.character(round(map$pos, digits)) else map$pos <- as.character(map$pos) write.table(geno, genfile, quote = FALSE, sep = ",", col.names = NA) write.table(pheno, phefile, quote = FALSE, sep = ",", col.names = NA) write.table(map, mapfile, quote = FALSE, sep = ",", col.names = NA) } fixX4write <- function(geno,sex,pgm,crosstype) { if(!is.null(sex) & any(sex==1)) { temp <- geno[sex==1,,drop=FALSE] temp[temp==2] <- 3 geno[sex==1,] <- temp } if(crosstype == "f2") { if(!is.null(pgm)) { if(!is.null(sex)) { if(any(pgm==1 & sex==0)) { temp <- geno[sex==0 & pgm==1,,drop=FALSE] temp[temp==1] <- 3 geno[sex==0 & pgm==1,] <- temp } } else { if(any(pgm==1)) { temp <- geno[pgm==1,,drop=FALSE] temp[temp==1] <- 3 geno[pgm==1,] <- temp } } } } geno }
isStrictlyNegativeIntegerOrNaScalar <- function(argument, default = NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL) { checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = FALSE, n = 1, zeroAllowed = FALSE, negativeAllowed = TRUE, positiveAllowed = FALSE, nonIntegerAllowed = FALSE, naAllowed = TRUE, nanAllowed = FALSE, infAllowed = FALSE, message = message, argumentName = argumentName) }
context("ML Result") test_that("multilabel_prediction", { set.seed(1) colrows <- list(as.character(11:20), paste("lbl", 1:10, sep='')) probs <- matrix(stats::runif(100), ncol = 10, dimnames = colrows) classes <- ifelse(probs >= 0.5, 1, 0) mres1 = multilabel_prediction(classes, probs, TRUE) mres2 = multilabel_prediction(classes, probs, FALSE) expect_is(mres1, "mlresult") expect_is(mres2, "mlresult") expect_true(is.probability(mres1)) expect_true(is.bipartition(mres2)) expect_false(is.probability(mres2)) expect_false(is.bipartition(mres1)) expect_equal(as.bipartition(mres1), classes) expect_equal(as.bipartition(mres1), as.bipartition(mres2)) expect_equal(as.probability(mres1), probs) expect_equal(as.probability(mres1), as.probability(mres2)) expect_equal(dimnames(mres1), colrows) expect_equal(dimnames(mres1), dimnames(mres2)) colrows <- list(as.character(11:20), paste("lbl", 1:5, sep='')) probs <- matrix(stats::runif(50, min = 0, max = 0.4), ncol = 5, dimnames = colrows) classes <- ifelse(probs >= 0.5, 1, 0) mres3 = multilabel_prediction(classes, probs, FALSE) expect_true(all(rowSums(mres3) == 1)) probs[1:5, c(1,2)] <- 0.45 probs[6:10, -c(1,2)] <- 0.47 mres4 = multilabel_prediction(classes, probs, FALSE) expect_true(all(rowSums(mres4[1:5, c(1,2)]) == 1)) expect_true(all(rowSums(mres4[6:10, c(1,2)]) == 0)) expect_true(all(rowSums(mres4[1:5, -c(1,2)]) == 0)) expect_true(all(rowSums(mres4[6:10, -c(1,2)]) == 1)) }) test_that("as.ranking", { rowcol <- list(as.character(1:5), c("lA", "lB")) mlres <- as.mlresult(matrix(seq(0.1, 1, by = 0.1), ncol=2, byrow = TRUE, dimnames = rowcol)) rk <- as.ranking(mlres) exp.rk <- matrix(c(rep(2, 5), rep(1, 5)), ncol = 2, dimnames = rowcol) expect_is(rk, "matrix") expect_equal(rk, exp.rk) expect_equal(dimnames(rk), rowcol) mlres2 <- as.mlresult(cbind(mlres, 1 - mlres)) rk <- as.ranking(mlres2) expect_equal(rk[1, ], rk[2, ]) expect_equal(rk[4, ], rk[5, ]) expect_equal(rowSums(rk), c(10, 10, 9, 10, 10), check.names = FALSE) rk <- as.ranking(mlres2, ties = "average") expect_equal(rowSums(rk), c(10, 10, 10, 10, 10), check.names = FALSE) rk <- as.ranking(mlres2, ties = "max") expect_equal(rowSums(rk), c(10, 10, 11, 10, 10), check.names = FALSE) }) test_that("as.mlresult", { set.seed(1234) predictions <- matrix(stats::runif(100), ncol = 10) colnames(predictions) <- paste('label', 1:10, sep='') mlresult <- as.mlresult(predictions) mlresult2 <- as.mlresult(mlresult, prob = FALSE) mlresult3 <- as.mlresult(predictions, threshold = 0.3) expect_is(mlresult, "mlresult") expect_is(mlresult2, "mlresult") expect_is(mlresult3, "mlresult") expect_equal(as.probability(mlresult), predictions) expect_equal(as.mlresult(as.data.frame(predictions)), mlresult) expect_equal(as.mlresult(mlresult), mlresult) expect_true(attr(mlresult, "type") == attr(mlresult3, "type")) expect_false(attr(mlresult, "type") == attr(mlresult2, "type")) expect_equal(as.bipartition(mlresult), as.bipartition(fixed_threshold(predictions, 0.5))) expect_equal(as.bipartition(mlresult3), as.bipartition(fixed_threshold(predictions, 0.3))) }) test_that("Filter ML Result", { set.seed(1234) labels <- matrix(stats::runif(150), ncol = 10) colnames(labels) <- paste("label", 1:10, sep='') mlres <- as.mlresult(labels) bipartition <- as.bipartition(mlres) mlres1 <- multilabel_prediction(bipartition, labels, TRUE) mlres2 <- multilabel_prediction(bipartition, labels, FALSE) expect_is(mlres1[1:3, ], "mlresult") expect_is(mlres1[1:3], "mlresult") expect_equal(mlres1[1:3, ], mlres1[1:3]) expect_is(mlres1[1:3, 1:3], "matrix") expect_is(mlres1[, 1:5], "matrix") expect_is(mlres1[, 1, drop = FALSE], "matrix") expect_is(mlres1[, 1], "numeric") expect_true(is.probability(mlres1[1:3, ])) expect_true(is.bipartition(mlres2[1:3, ])) expect_equal(mlres1[, c("label1", "label3")], labels[, c("label1", "label3")]) expect_equal(mlres2[, c("label1", "label3")], bipartition[, c("label1", "label3")]) expect_equal(mlres1[, 3:6], labels[, 3:6]) expect_equal(mlres2[, 2:8], bipartition[, 2:8]) expect_equal(mlres1[1:5, 1:5], labels[1:5, 1:5]) expect_equal(mlres2[2:8, 2:8], bipartition[2:8, 2:8]) mlres3 <- mlres1[1:8] expect_equal(as.probability(mlres3), labels[1:8, ]) expect_equal(as.bipartition(mlres3), bipartition[1:8, ]) })
BlackScholesCallESSim <- function(amountInvested, stockPrice, strike, r, mu, sigma, maturity, numberTrials, cl, hp){ annualMaturity <- maturity / 360 annualHp <- hp / 360 N <- 1 dt <- annualHp / N nudt <- (mu - .5 * sigma^2) * dt sigmadt <- sigma * sqrt(dt) lnS <- log(stockPrice) M <- numberTrials initialOptionPrice <- BlackScholesCallPrice(stockPrice, strike, r, sigma, maturity) numberOfOptions <- abs(amountInvested) / initialOptionPrice lnSt <- matrix(0, M, N) newStockPrice <- matrix(0, M, N) for (i in 1:M){ lnSt[i] <- lnS + rnorm(1, nudt, sigmadt) newStockPrice[i] <- exp(lnSt[i, 1]) } profitOrLoss <- double(M) if (amountInvested > 0) { for (i in 1:M) { profitOrLoss[i] <- (BlackScholesCallPrice(newStockPrice[i], strike, r, sigma, maturity - hp) - initialOptionPrice) * numberOfOptions } } if (amountInvested < 0) { for (i in 1:M) { profitOrLoss[i] <- (-BlackScholesCallPrice(newStockPrice[i], strike, r, sigma, maturity - hp) + initialOptionPrice) * numberOfOptions } } y <- HSES(profitOrLoss, cl) return(y) }
rvifelse <- function (test, yes, no) { rvmapply(ifelse, test=test, yes=yes, no=no) }
NULL NULL NULL NULL NULL NULL NULL NULL SeuratObject::AddMetaData SeuratObject::as.Graph SeuratObject::as.Neighbor SeuratObject::as.Seurat SeuratObject::as.sparse SeuratObject::Assays SeuratObject::Cells SeuratObject::CellsByIdentities SeuratObject::Command SeuratObject::CreateAssayObject SeuratObject::CreateDimReducObject SeuratObject::CreateSeuratObject SeuratObject::DefaultAssay SeuratObject::`DefaultAssay<-` SeuratObject::Distances SeuratObject::Embeddings SeuratObject::FetchData SeuratObject::GetAssayData SeuratObject::GetImage SeuratObject::GetTissueCoordinates SeuratObject::HVFInfo SeuratObject::Idents SeuratObject::`Idents<-` SeuratObject::Images SeuratObject::Index SeuratObject::`Index<-` SeuratObject::Indices SeuratObject::IsGlobal SeuratObject::JS SeuratObject::`JS<-` SeuratObject::Key SeuratObject::`Key<-` SeuratObject::Loadings SeuratObject::`Loadings<-` SeuratObject::LogSeuratCommand SeuratObject::Misc SeuratObject::`Misc<-` SeuratObject::Neighbors SeuratObject::Project SeuratObject::`Project<-` SeuratObject::Radius SeuratObject::Reductions SeuratObject::RenameCells SeuratObject::RenameIdents SeuratObject::ReorderIdent SeuratObject::RowMergeSparseMatrices SeuratObject::SetAssayData SeuratObject::SetIdent SeuratObject::SpatiallyVariableFeatures SeuratObject::StashIdent SeuratObject::Stdev SeuratObject::SVFInfo SeuratObject::Tool SeuratObject::`Tool<-` SeuratObject::UpdateSeuratObject SeuratObject::VariableFeatures SeuratObject::`VariableFeatures<-` SeuratObject::WhichCells
context("Test for lets.overlap") data(PAM) test_that("lets.overlap works fine, Chesser&Zink", { resu_test <- lets.overlap(PAM, method = "Chesser&Zink") expect_equal(class(resu_test)[1], "matrix") expect_true(all(dim(resu_test) == length(PAM[[3]]))) expect_true(!any(is.na(resu_test))) }) test_that("lets.overlap works fine, xy = FALSE", { resu_test <- lets.overlap(PAM[[1]][, -c(1, 2)], method = "Chesser&Zink", xy = FALSE) expect_equal(class(resu_test)[1], "matrix") expect_true(all(dim(resu_test) == length(PAM[[3]]))) expect_true(!any(is.na(resu_test))) }) test_that("lets.overlap works fine, xy = TRUE", { resu_test <- lets.overlap(PAM[[1]], method = "Chesser&Zink", xy = TRUE) expect_equal(class(resu_test)[1], "matrix") expect_true(all(dim(resu_test) == length(PAM[[3]]))) expect_true(!any(is.na(resu_test))) }) test_that("lets.overlap works fine, Cells", { resu_test <- lets.overlap(PAM, method = "Cells") expect_equal(class(resu_test)[1], "matrix") expect_true(all(dim(resu_test) == length(PAM[[3]]))) expect_true(!any(is.na(resu_test))) }) test_that("lets.overlap works fine, Proportional", { resu_test <- lets.overlap(PAM, method = "Proportional") expect_equal(class(resu_test)[1], "matrix") expect_true(all(dim(resu_test) == length(PAM[[3]]))) expect_true(!any(is.na(resu_test))) }) test_that("lets.overlap error method", { expect_error(lets.overlap(PAM, method = "testerror")) }) test_that("lets.overlap error xy", { expect_error(lets.overlap(PAM[[1]], method = "Cells")) })
library(hamcrest) library(stats) library(methods) test.setClassInheritRepresentationAndContains <- function() { setClass("A", representation(a="numeric")) a1 <- new("A", a=1.5) m1 <- as.matrix(1) setClass("M", contains = "matrix", representation(fuzz = "numeric")) set.seed(113) f1 <- runif(3) assertThat( as(new("M", 1:12, nrow = 3, fuzz = f1), "matrix"), identicalTo(matrix(1:12, nrow=3)) ) assertThat( as(new("M", 1:12, 3, fuzz = f1), "matrix"), identicalTo(matrix(1:12, 3)) ) assertThat( as(new("M", 1:12, ncol = 3, fuzz = f1), "matrix"), identicalTo(matrix(1:12, ncol=3)) ) } test.setClassCallSlots <- function() { setClass("A", representation(a="numeric")) a1 <- new("A", a=1.5) m1 <- as.matrix(1) setClass("M", contains = "matrix", representation(fuzz = "numeric")) set.seed(113) f1 <- runif(3) setClass("B", contains = c("matrix", "A")) assertThat( new("B", m1, a1)@a, identicalTo(a1@a) ) assertThat( as(new("B", m1),"matrix"), identicalTo(m1) ) assertThat( new("B", matrix(m1, nrow = 2), a1, a=pi)@a, identicalTo(pi) ) } test.setClassValidateSlots <- function() { setClass("A", representation(a="numeric")) a1 <- new("A", a=1.5) m1 <- as.matrix(1) setClass("M", contains = "matrix", representation(fuzz = "numeric")) set.seed(113) f1 <- runif(3) setClass("B", contains = c("matrix", "A")) setClass("C", contains = "B", representation(c = "character")) setValidity("B", function(object) { if(all(is.na(object@a) | (object@a > 0))) TRUE else FALSE }) assertThat( try(validObject(new("B", a= c(NA,3, -1, 2))),silent=TRUE), instanceOf("try-error") ) assertThat( try(validObject(new("A", a= c(NA,3, -1, 2))),silent=TRUE), instanceOf("try-error") ) assertThat( try(validObject(new("B", m1, a2)),silent=TRUE), instanceOf("try-error") ) } test.setClassValidateSlots <- function() { a3 <- array(1:24, 2:4) a2 <- array(1:12, 3:4) assertTrue( is(tryCatch(as(a3, "matrix"), error = function(e)e), "error") ) assertTrue( is(as(a2 <- array(1:12, 3:4), "matrix"), "matrix") ) assertTrue( is(a2, "matrix") ) assertTrue( is(a2, "array") ) assertTrue( is(a3, "array") ) assertTrue( !is(a3, "matrix") ) assertTrue( identical(a2, matrix(1:12, 3) ) ) } test.setClassUnion <- function() { assertFalse( is(tryCatch(setClassUnion("mn", c("matrix","numeric")), error = function(e)e), "error") ) assertFalse( is(tryCatch(setClassUnion("an", c("array", "integer")), error = function(e)e), "error") ) assertFalse( is(tryCatch(setClassUnion("AM", c("array", "matrix")), error = function(e)e), "error") ) } test.setClassMix <- function() { f = setClass("BAR", slots = c(y="integer")) a1 <- new("BAR") a1@y <- 10L assertFalse( is(tryCatch(setClass("BAR", slots = c(y="integer")), error = function(e)e), "error") ) assertTrue( is(f, "classGeneratorFunction") ) assertTrue( is(a1@y, "integer") ) assertTrue( is(a1@y, "numeric") ) assertTrue( is(a1, "BAR") ) assertThat( a1@y, identicalTo(10L) ) f = function() { setMethod("initialize", "BAR", function(.Object, Y) {.Object@y <- Y; .Object}) } f_out = f() a2 <- new("BAR", 5L) assertFalse( is(tryCatch(f(), error = function(e)e), "error") ) assertThat( f_out, identicalTo("initialize") ) assertTrue( is(a2, "BAR") ) assertTrue( is(a2@y, "integer") ) assertTrue( is(a2@y, "numeric") ) g = setClass("BAR3", contains = "BAR") b <- new("BAR3", 7L) assertFalse( is(tryCatch(setClass("BAR3", contains = "BAR"), error = function(e)e), "error") ) assertTrue( is(g, "classGeneratorFunction") ) assertTrue( is(b@y, "integer") ) assertTrue( is(b@y, "numeric") ) assertTrue( is(b, "BAR3") ) assertThat( b@y, identicalTo(7L) ) assertTrue( is(tryCatch(new("BAR3", 7), error = function(e)e), "error") ) assertTrue( is(tryCatch(b@y <- 9, error = function(e)e), "error") ) assertTrue( is(tryCatch(b@y <- "CHAR", error = function(e)e), "error") ) }
setAs( from = "CompactStratification", to = "data.frame", def = function(from) { as(as(from, "SpatialPixelsDataFrame"), "data.frame") } ) setAs( from = "CompactStratification", to = "SpatialPixels", def = function(from) { tmp <- from@cells gridded(tmp) <- FALSE suppressWarnings(as(tmp, "SpatialPixels")) } ) setAs( from = "CompactStratification", to = "SpatialPixelsDataFrame", def = function(from) { suppressWarnings( SpatialPixelsDataFrame( points = as(from, "SpatialPixels"), data = data.frame(stratumId = from@stratumId) ) ) } ) setAs( from = "SamplingPattern", to = "data.frame", def = function(from) { as(from@sample, "data.frame") } ) setAs( from = "SamplingPatternRandomComposite", to = "data.frame", def = function(from) { as(as(from, "SpatialPointsDataFrame"), "data.frame") } ) setAs( from = "SamplingPatternRandomComposite", to = "SpatialPointsDataFrame", def = function(from) { SpatialPointsDataFrame( coords = as(from, "SpatialPoints"), data = data.frame(composite = from@composite) ) } ) setAs( from = "SamplingPattern", to = "SpatialPoints", def = function(from) { from@sample } )
source("ESEUR_config.r") library("bitops") library("plyr") library("png") map_RGB=function(color) { return(bitOr(as.numeric(255*color[ , 1]), bitOr(bitShiftL(as.numeric(255*color[ , 2]), 8), bitShiftL(as.numeric(255*color[ , 3]), 16)))) } hm=readPNG(paste0(ESEUR_dir, "evolution/heatmap2.png"), FALSE) xbounds=c(1, ncol(hm)) ybounds=c(1, nrow(hm)) plot(1, type="n", xaxt="n", yaxt="n", xlim=xbounds, ylim=ybounds, xlab="", ylab="") rasterImage(hm, xbounds[1], ybounds[1], xbounds[2], ybounds[2]) black_white_RGB=rbind(c(0, 0, 0), c(1, 1, 1)) black_white=map_RGB(black_white_RGB) white_RGB=black_white[2] hm_RGB=hm[5925, 580:3204, ] hm_scale=data.frame(RGB=map_RGB(hm_RGB), scale=(1:nrow(hm_RGB))/nrow(hm_RGB)) uniq_scale=hm_scale[with(hm_scale, c((RGB[-1] != head(RGB, n=-1)), TRUE)), ] uniq_scale$scale[uniq_scale$RGB == white_RGB]=0 th=hm[1:5450,551:6000,] col_edge=aaply(th, 1, function(df) (df[ , 1] != df[ , 2])) t1_ce=aaply(col_edge, 1, function(df) tail(which(c(TRUE, df)), n=1))-1 t2_ce=t1_ce[t1_ce != 0] ce_offset=t2_ce[c((t2_ce[-1] != head(t2_ce, n=-1)), TRUE)] ce_row=as.numeric(names(ce_offset)) col_map=aaply(th, 1, map_RGB) col_val=col_map[ce_row, ce_offset] t1_v=aaply(col_val, 1, function(df) t=mapvalues(df, from=uniq_scale$RGB, to=uniq_scale$scale, warn_missing=FALSE)) version_p=t(apply(t1_v, 2, rev)) write.csv(version_p, file="linux-src-evol.csv.xz", row.names=FALSE) pal_col=rainbow(30, end=26/30) pal_col=c(" image(version_p, col=pal_col)
context("eib_plot") library(ggplot2) library(dplyr) library(reshape2) library(purrr) library(vdiffr) load("ce.RData") he <- BCEA::bcea(eff, cost) test_that("eib.plot_ggplot draws correctly", { eib_plot <- eib.plot(he, graph = "ggplot2", title = "my title") })
NULL . = NULL test_rqdatatable <- function() { d = data.frame(x = c(1, 2)) x = NULL d %.>% extend(., y = x*x) return(d) }
progress_time <- function() { n <- 0 txt <- NULL list( init = function(x) { txt <<- txtTimerBar(x) utils::setTxtProgressBar(txt, 0) }, step = function() { n <<- n + 1 utils::setTxtProgressBar(txt, n) }, term = function() close(txt) ) } txtTimerBar <- function(n = 1) { start <- .last_update_time <- proc.time()[3] times <- numeric(n) value <- NULL killed <- FALSE width <- getOption("width") - nchar('||100% ~ 999.9 h remaining.') update <- function(i) { if (i == 0) return() value <<- i times[i] <- proc.time()[3] - start avg <- times[i] / i time_left <- (n - i) * avg nbars <- trunc(i / n * width) cat_line("|", str_rep("=", nbars), str_rep(" ", width - nbars), "|", format(i / n * 100, width = 3), "% ~", show_time(time_left), " remaining") } getVal <- function() value kill <- function(){ if (killed) return() killed <<- TRUE if (value == n) { cat_line("|", str_rep("=", width), "|100%") cat("Completed after", show_time(proc.time()[3] - start), "\n") } else { cat("Killed after", show_time(proc.time()[3] - start), "\n") } } cat_line("|", str_rep(" ", width), "| 0%") structure( list(getVal = getVal, up = update, kill = kill), class = "txtProgressBar") } show_time <- function(x) { if (x < 60) { paste(round(x), "s") } else if (x < 60 * 60) { paste(round(x / 60), "m") } else { paste(round(x / (60 * 60)), "h") } } cat_line <- function(...) { msg <- paste(..., sep = "", collapse = "") gap <- max(c(0, getOption("width") - nchar(msg, "width"))) cat("\r", msg, rep.int(" ", gap), sep = "") utils::flush.console() } str_rep <- function(x, i) { paste(rep.int(x, i), collapse = "") }
rescale_img = function(filename, pngname = NULL, write.nii = FALSE, outfile = NULL, min.val = -1024, max.val = 3071, ROIformat=FALSE, drop_dim = TRUE, writer = "dcm2nii", ...){ if (write.nii){ stopifnot(!is.null(outfile)) } img = check_nifti(filename) r = range(c(img)) if (!(r[1] >= min.val & r[2] <= max.val)) { img[img < min.val] = min.val img[img > max.val] = max.val } img = zero_trans(img) if (ROIformat) { img[img < 0] = 0 } img = cal_img(img) descrip(img) = paste0("written by ", writer, " - ", descrip(img)) if (drop_dim) { img = drop_img_dim(img) } if (!is.null(pngname)){ options(bitmapType = 'cairo') print(pngname) pngname = gsub("%", "", pngname) grDevices::png(pngname) graphics::hist(img) grDevices::dev.off() } if (write.nii) { writenii(img, filename = outfile, drop_dim = drop_dim, ...) } return(img) } datatyper = function(img, type_string = NULL, datatype = NULL, bitpix=NULL, trybyte=TRUE, warn = TRUE){ img = check_nifti(img) if (!is.null(type_string)) { accepted = names(convert.datatype()) type_string = toupper(type_string) stopifnot(type_string %in% accepted) datatype = convert.datatype()[[type_string]] bitpix = convert.bitpix()[[type_string]] } if (!is.null(datatype) & !is.null(bitpix)) { datatype(img) <- datatype bitpix(img) <- bitpix return(img) } if (!is.null(datatype) & is.null(bitpix)) { stop("Both bitpix and datatype need to be specified if one is") } if (is.null(datatype) & !is.null(bitpix)) { stop("Both bitpix and datatype need to be specified if one is") } arr = as(img, "array") is.log = inherits(arr[1], "logical") any_na = anyNA(arr) if (any_na) { warn_them = img@datatype < 64L img@"datatype" = max(64L, img@datatype) warn_them = warn_them | img@bitpix < 64L img@bitpix = max(64L, img@bitpix) if (warn_them) { warning("Need to change bitpix and datatype to FLOAT64 due to NAs") } return(img) } if (is.log) { datatype(img) <- convert.datatype()$UINT8 bitpix(img) <- convert.bitpix()$UINT8 return(img) } testInteger <- function(img){ x = c(as(img, "array")) test <- all.equal(x, as.integer(x), check.attributes = FALSE) return(isTRUE(test)) } is.int = testInteger(img) if (is.int) { rr = range(img, na.rm = TRUE) if (all(rr == c(0, 1)) & trybyte) { if (all(img %in% c(0, 1))) { datatype(img) <- convert.datatype()$UINT8 bitpix(img) <- convert.bitpix()$UINT8 return(img) } } signed = FALSE if (any(rr < 0)) { signed = TRUE } trange = diff(rr) mystr = NULL num = 16 if (is.null(mystr) & trange <= (2 ^ num) - 1 ) { mystr = "INT16" } num = 32 if (is.null(mystr) & trange <= (2 ^ num) - 1 ) { mystr = "INT32" } num = 64 if (is.null(mystr) & trange <= (2 ^ num) - 1 ) { mystr = "FLOAT64" } if (is.null(mystr)) { stop(paste0("Cannot determine integer datatype, ", "may want to recheck data or not use datatyper!")) } datatype(img) <- oro.nifti::convert.datatype()[[mystr]] bitpix(img) <- oro.nifti::convert.bitpix()[[mystr]] return(img) } else { if (warn) { warning("Assuming FLOAT32 - changing @bitpix and @datatype in header") } mystr = "FLOAT32" datatype(img) <- convert.datatype()[[mystr]] bitpix(img) <- convert.bitpix()[[mystr]] return(img) } } newnii = function(img, ...){ img = check_nifti(img) img = zero_trans(img) img = cal_img(img) img = datatyper(img, ...) return(img) }
Geweke.Diagnostic <- function(x) { x <- as.matrix(x) if(nrow(x) < 100) return(rep(NA, ncol(x))) frac1 <- 0.1; frac2 <- 0.5 startx <- 1; endx <- nrow(x) xstart <- c(startx, endx - frac2 * {endx - startx}) xend <- c(startx + frac1 * {endx - startx}, endx) y.variance <- y.mean <- vector("list", 2) for (i in 1:2) { y <- x[xstart[i]:xend[i],] y.mean[[i]] <- colMeans(as.matrix(y)) yy <- as.matrix(y) y <- as.matrix(y) max.freq <- 0.5; order <- 1; max.length <- 200 if(nrow(yy) > max.length) { batch.size <- ceiling(nrow(yy) / max.length) yy <- aggregate(ts(yy, frequency=batch.size), nfreq=1, FUN=mean)} else {batch.size <- 1} yy <- as.matrix(yy) fmla <- switch(order + 1, spec ~ one, spec ~ f1, spec ~ f1 + f2) if(is.null(fmla)) stop("Invalid order.") N <- nrow(yy) Nfreq <- floor(N/2) freq <- seq(from=1/N, by=1/N, length=Nfreq) f1 <- sqrt(3) * {4 * freq - 1} f2 <- sqrt(5) * {24 * freq * freq - 12 * freq + 1} v0 <- numeric(ncol(yy)) for (j in 1:ncol(yy)) { zz <- yy[,j] if(var(zz) == 0) v0[j] <- 0 else { yfft <- fft(zz) spec <- Re(yfft * Conj(yfft)) / N spec.data <- data.frame(one=rep(1, Nfreq), f1=f1, f2=f2, spec=spec[1 + {1:Nfreq}], inset=I(freq <= max.freq)) glm.out <- try(glm(fmla, family=Gamma(link="log"), data=spec.data), silent=TRUE) if(!inherits(glm.out, "try-error")) v0[j] <- predict(glm.out, type="response", newdata=data.frame(spec=0, one=1, f1=-sqrt(3), f2=sqrt(5))) } } spec <- list(spec=v0) spec$spec <- spec$spec * batch.size y.variance[[i]] <- spec$spec / nrow(y) } z <- {y.mean[[1]] - y.mean[[2]]} / sqrt(y.variance[[1]] + y.variance[[2]]) return(z) }
nowcast.plot <- function(out, type = "fcst"){ if(type == "fcst"){ data <- data.frame(date = as.Date(out$yfcst), out$yfcst) data[max(which(is.na(data$out))),"out"] <- data[max(which(is.na(data$out))),"in."] graphics::par(mar=c(5.1, 4.1, 4.1, 5), xpd = F) graphics::plot(data[,"y"], xaxt = "n", main = "", bty = "l", col = " graphics::axis(1, at = seq(1,nrow(data),frequency(out$yfcst)), labels = substr(data[seq(1,nrow(data),frequency(out$yfcst)),"date"],1,7), las=1, cex = 0.7) graphics::abline(v = seq(1,nrow(data),frequency(out$yfcst)), lty = 3, col = " graphics::grid(col = " graphics::lines(data[,"y"], type = "l", lty = 1, col = 1) graphics::lines(data[,"in."], type = "l", lty = 1, lwd = 2, col = "dodgerblue") graphics::lines(data[,"out"], type = "l", lty = 4, lwd = 2, col = "orangered") graphics::par(xpd = T) add_legend("topright", legend=c("y","yhat","fcst"), bty = "n", lty = c(1,1,4), lwd = c(1,2,2), col = c(1,"dodgerblue","orangered")) graphics::title(main = list("Forecasting", font = 1, cex = 0.9)) }else if(type == "eigenvalues"){ if(!("reg" %in% names(out))){ stop('Graph not available for EM method') } graphics::par(mar = c(5.1,4.1,4.1,2.1), xpd = F) eig <- out$factors$eigen$values/sum(out$factors$eigen$values)*100 n <- min(20,length(eig)) graphics::barplot(eig[1:n], col = " xlab = "eigenvalues", ylab = "%") graphics::grid(col = " graphics::title(main = list("eigenvalues: percentage variance", font = 1, cex = 0.9)) }else if(type == "eigenvectors"){ if(!("reg" %in% names(out))){ stop('Graph not available for EM method') } graphics::par(mar = c(5.1,4.1,4.1,5), xpd = F) vec <- out$factors$eigen$vectors[,1] pvec <- (out$factors$eigen$vectors[,1]^2)*100 color <- ifelse(vec >= 0, "dodgerblue", "orangered") graphics::plot(pvec, main = "", bty = "l", xaxt = "n", type = "h", ylab = "weight (%)", xlab = "variable", col = color) graphics::axis(1, at = seq(1,length(vec),1), labels = seq(1,length(vec),1), las=1, cex = 0.7) graphics::title(main = list("Variable Percentage Weight in Factor 1", font = 1, cex = 0.9)) graphics::par(xpd = T) graphics::text(y = max(pvec), x = length(pvec)*1.1, labels = "signal weights:", col = 1, cex = 0.8) graphics::text(y = max(pvec)*0.94, x = length(pvec)*1.1, labels = "positive", col = "dodgerblue", cex = 0.8) graphics::text(y = max(pvec)*0.88, x = length(pvec)*1.1, labels = "negative", col = "orangered", cex = 0.8) }else if(type == "factors"){ graphics::par(mar=c(5.1, 4.1, 4.1, 5), xpd = F) n <- ncol(data.frame(out$factors$dynamic_factors)) stats::ts.plot(out$factors$dynamic_factors, col = c(1,"orangered","blue"), lty = c(1,2,3), gpars = list(bty = "l")) anos <- unique(as.numeric(substr(as.Date(out$factors$dynamic_factors),1,4))) graphics::grid() graphics::par(xpd = T) graphics::title(main = list("Estimated Factors", font = 1, cex = 1)) if("month_y" %in% names(out)){ leg <- colnames(out$factors$dynamic_factors) }else{ leg <- paste("Factor", 1:n) } add_legend("topright", legend = leg, bty = "n", col = c(1,"orangered","blue"), lty = c(1,2,3), lwd = c(1,1,1,2,2,2), cex = 0.9) } }
library(shiny.fluent) if (interactive()) { tokens <- list(childrenGap = 20) shinyApp( ui = div( Stack( DefaultButton.shinyInput("button1", text = "Default Button", styles = list("background: green")), PrimaryButton.shinyInput("button2", text = "Primary Button"), CompoundButton.shinyInput("button3", secondaryText = "Compound Button has additional text", text = "Compound Button"), ActionButton.shinyInput("button4", iconProps = list("iconName" = "AddFriend"), text = "Action Button"), horizontal = TRUE, tokens = tokens ), textOutput("text") ), server = function(input, output) { clicks <- reactiveVal(0) addClick <- function() { clicks(isolate(clicks() + 1)) } observeEvent(input$button1, addClick()) observeEvent(input$button2, addClick()) observeEvent(input$button3, addClick()) observeEvent(input$button4, addClick()) output$text <- renderText({ paste("Clicks:", clicks()) }) } ) }
contrastHipotesisProporcion <- function () { defaults <- list (initial.nexitos="",initial.nfracasos="",initial.nconf="0.95",initial.alternative = "two.sided",initial.p0 = "0.5") dialog.values <- getDialog ("contrastHipotesisProporcion", defaults) initializeDialog(title = gettext("Hypothesis Testing for a proportion",domain="R-RcmdrPlugin.TeachStat")) selectFactorsFrame<-tkframe(top) comboBoxFrame<-tkframe(selectFactorsFrame) twoOrMoreLevelFactors<-twoOrMoreLevelFactors() if (length(twoOrMoreLevelFactors())!=0){ mostrar<-"readonly" }else { mostrar<-"disabled" } valuescombo_box<-c(gettext("<no variable selected>",domain="R-RcmdrPlugin.TeachStat"),twoOrMoreLevelFactors()) varcombo_box=tclVar(valuescombo_box[1]) combo_box<-ttkcombobox(comboBoxFrame,values=valuescombo_box,textvariable=varcombo_box,state=mostrar) tkgrid(labelRcmdr(comboBoxFrame, text=gettext("Variable (pick one)",domain="R-RcmdrPlugin.TeachStat"), foreground=getRcmdr("title.color") ), sticky="nw") tkgrid(combo_box,sticky="nw") tkbind(combo_box, "<<ComboboxSelected>>",function(){ value<-tclvalue(varcombo_box) if(value!=gettext("<no variable selected>",domain="R-RcmdrPlugin.TeachStat")){ datasetactivo <- ActiveDataSet() datasetactivo<-get(datasetactivo) niveles<-levels(datasetactivo[,value]) tkconfigure(combo_box2,values=niveles) tclvalue(varcombo_box2)<-niveles[1] tk2state.set(combo_box2, state="readonly") tkfocus(combo_box2)} else{tk2state.set(combo_box2, state="disabled") niveles<-gettext("<no variable selected>",domain="R-RcmdrPlugin.TeachStat") tkconfigure(combo_box2,values=niveles) tclvalue(varcombo_box2)<-niveles}}) varcombo_box2=tclVar(gettext("<no variable selected>",domain="R-RcmdrPlugin.TeachStat")) combo_box2<-ttkcombobox(comboBoxFrame,values=varcombo_box2,textvariable=varcombo_box2,state="disabled") tkgrid(labelRcmdr(comboBoxFrame, text=gettext("Proportion for the level (pick one)",domain="R-RcmdrPlugin.TeachStat"), foreground=getRcmdr("title.color") ), sticky="nw") tkgrid(combo_box2, sticky="nw") exitosFracasosFrame<-tkframe(top) nExitosVar<-tclVar(dialog.values$initial.nexitos) nExitosEntry<-ttkentry(exitosFracasosFrame,width="5",textvariable=nExitosVar) tkgrid(labelRcmdr(exitosFracasosFrame, text=gettext("No. successes",domain="R-RcmdrPlugin.TeachStat"), foreground=getRcmdr("title.color")),nExitosEntry, sticky="nw") nFracasosVar<-tclVar(dialog.values$initial.nfracasos) nFracasosEntry<-ttkentry(exitosFracasosFrame,width="5",textvariable=nFracasosVar) tkgrid(labelRcmdr(exitosFracasosFrame, text=gettext("No. failures",domain="R-RcmdrPlugin.TeachStat"), foreground=getRcmdr("title.color") ),nFracasosEntry, sticky="nw") optionsFrame <- tkframe(top) radioButtons(optionsFrame, name = "alternative", buttons = c("twosided", "less", "greater"), values = c("two.sided", "less", "greater"), labels = gettext(c("Population proportion != p0", "Population proportion < p0", "Population proportion > p0"),domain="R-RcmdrPlugin.TeachStat"), title = gettext("Alternative hypothesis",domain="R-RcmdrPlugin.TeachStat"), initialValue = dialog.values$initial.alternative) rightFrame<-tkframe(top) p0Frame <- tkframe(rightFrame) p0Variable <- tclVar(dialog.values$initial.p0) p0Field <- ttkentry(p0Frame, width = "5", textvariable = p0Variable) tkgrid(labelRcmdr(p0Frame, text=gettext("Null hypothesis: p =",domain="R-RcmdrPlugin.TeachStat"), foreground=getRcmdr("title.color") ), p0Field, sticky="nw") nConfianzaFrame<-tkframe(rightFrame) nConfianzaVar<-tclVar(dialog.values$initial.nconf) nConfianzaEntry<-ttkentry(nConfianzaFrame,width="5",textvariable=nConfianzaVar) onOK <- function(){ varICProporcion<-tclvalue(varcombo_box) if ((length(twoOrMoreLevelFactors)!=0)&&(varICProporcion !=gettext("<no variable selected>",domain="R-RcmdrPlugin.TeachStat"))){ activeDataSet <- ActiveDataSet() activeDataSet<-get(activeDataSet) variableICProporcion<-activeDataSet[,varICProporcion] variableLevelICProporcion<-tclvalue(varcombo_box2)} else { variableICProporcion<-NULL variableLevelICProporcion<-NULL } valornexitos<-tclvalue(nExitosVar) if( (valornexitos!="") && (is.na(as.integer(valornexitos)) || (as.integer(valornexitos)<0) || !(isTRUE(all.equal(as.numeric(valornexitos),as.integer(valornexitos)))) )) { valornexitos="" errorCondition(recall=contrastHipotesisProporcion, message=gettext("Successes number value must be a positive integer number",domain="R-RcmdrPlugin.TeachStat")) return() } else{if(valornexitos!=""){valornexitos<-as.integer(valornexitos)}} valornfracasos<-tclvalue(nFracasosVar) if((valornfracasos!="") && (is.na(as.integer(valornfracasos)) || (as.integer(valornfracasos)<0) || !(isTRUE(all.equal(as.numeric(valornfracasos),as.integer(valornfracasos)))) )){ valornfracasos="" errorCondition(recall=contrastHipotesisProporcion, message=gettext("Failures number value must be a positive integer number",domain="R-RcmdrPlugin.TeachStat")) return() } else{if(valornfracasos!=""){valornfracasos<-as.integer(valornfracasos)}} if ((is.null(variableICProporcion))&&((valornexitos=="")||(valornfracasos==""))){ errorCondition(recall=contrastHipotesisProporcion, message=gettext("A variable or successes number and failures number must be selected",domain="R-RcmdrPlugin.TeachStat")) return() } sumaexitosfracasos<-sum(as.integer(valornexitos),as.integer(valornfracasos)) if ((is.null(variableICProporcion))&&(sumaexitosfracasos==0)){ errorCondition(recall=contrastHipotesisProporcion, message=gettext("A variable must be selected or the sum of successes and failures numbers must be positive",domain="R-RcmdrPlugin.TeachStat")) return() } muestrasnulas <- ((valornexitos=="")&(valornfracasos=="")) muestrasrellenas <- ((!valornexitos=="")&(!valornfracasos=="")) if (!(is.null(variableICProporcion)) && (!(muestrasnulas | muestrasrellenas))){ errorCondition(recall=contrastHipotesisProporcion, message=gettext("Successes number and failures number must be provided",domain="R-RcmdrPlugin.TeachStat")) return() } valornConfianza<-tclvalue(nConfianzaVar) if(is.na(as.numeric(valornConfianza)) || (as.numeric(valornConfianza)<=0)||(as.numeric(valornConfianza)>=1)) { valornConfianza=0.95 errorCondition(recall=contrastHipotesisProporcion, message=gettext("Confidence level must be between 0 and 1",domain="R-RcmdrPlugin.TeachStat")) return() } else{valornConfianza<-as.numeric(valornConfianza)} valorp0<-tclvalue(p0Variable) if((is.na(as.numeric(valorp0))) || (as.numeric(valorp0)<0)||(as.numeric(valorp0)>1)){ valorp0="0.0" errorCondition(recall=contrastHipotesisProporcion, message=gettext("Value for the null hypothesis must be between 0 and 1 (and not be)",domain="R-RcmdrPlugin.TeachStat")) return() } else{ valorp0<-as.numeric(valorp0)} varHAlternativa<-tclvalue(alternativeVariable) putDialog ("contrastHipotesisProporcion", list(initial.nexitos=valornexitos,initial.nfracasos=valornfracasos,initial.nconf=valornConfianza,initial.alternative = varHAlternativa,initial.p0 = valorp0)) closeDialog() valornexitos<-as.integer(valornexitos) valornfracasos<-as.integer(valornfracasos) valornConfianza<-as.numeric(valornConfianza) .activeDataSet<-ActiveDataSet() if ((length(twoOrMoreLevelFactors)!=0)&&(varICProporcion !=gettext("<no variable selected>",domain="R-RcmdrPlugin.TeachStat"))){ vICProporcion<-paste(.activeDataSet,"$",varICProporcion, sep="") vLevelICProporcion<-paste('"',tclvalue(varcombo_box2),'"',sep="")} else { vICProporcion<-NULL vLevelICProporcion<-NULL } Haltern<-paste('"',varHAlternativa,'"',sep="") tipointervalo<-paste("\\n",gettext("Hypothesis Testing for a proportion",domain="R-RcmdrPlugin.TeachStat"),"\\n", sep="") linaux<-paste(rep(c("-"," "),(nchar(tipointervalo)/2)),collapse="") tipointervalo<-paste(tipointervalo, linaux,sep="") if(!is.null(vICProporcion)){ command<- paste("exitos<-sum(",vICProporcion," == ", vLevelICProporcion,",na.rm = TRUE)",sep="") command<- paste(command,"\n","total<-length(",vICProporcion,")",sep="") command<-paste(command,"\n","aux<- Cprop.test(ex=exitos, nx=total, p.null=",valorp0,", alternative=",Haltern,")",sep="") command<- paste(command,"\n","levelsaux<-levels(",vICProporcion,")",sep="") command<- paste(command,"\n","levelsaux<-levelsaux[levelsaux!=",vLevelICProporcion,"]",sep="") command<- paste("local({\n",command,"\n",sep="") if(length(levels(variableICProporcion))<=2){ resultado<-paste('cat("',tipointervalo, '\\n',gettext("No. successes",domain="R-RcmdrPlugin.TeachStat"),': ', varICProporcion,' [',tclvalue(varcombo_box2),' vs.", levelsaux,"] --> ',gettext("No. successes",domain="R-RcmdrPlugin.TeachStat"),' = ",exitos," -- ',gettext("No. attempts",domain="R-RcmdrPlugin.TeachStat"),' =", total,"\\n"',')', sep="" )} else{resultado<-paste('cat("',tipointervalo, '\\n',gettext("No. successes",domain="R-RcmdrPlugin.TeachStat"),': ', varICProporcion,' [',tclvalue(varcombo_box2),'"," vs. ', gettext("Other levels",domain="R-RcmdrPlugin.TeachStat"), '] --> ',gettext("No. successes",domain="R-RcmdrPlugin.TeachStat"),' = ",exitos," -- ',gettext("No. attempts",domain="R-RcmdrPlugin.TeachStat"),' =", total,"\\n"',')', sep="" )} command<- paste(command, resultado,"\n",sep="" ) distribucion<-paste('cat("',gettext("Distribution",domain="R-RcmdrPlugin.TeachStat"),':","Normal(0,1)\\n")',sep="") e.contraste<- paste('\n cat("',gettext("Test statistics value",domain="R-RcmdrPlugin.TeachStat"),':",as.numeric(aux$statistic),"\\n")',sep="") p.valor<-paste('\n if(aux$p.value>0.05){cat("',gettext("p-value",domain="R-RcmdrPlugin.TeachStat"),':",format.pval(aux$p.value),"\\n")} if(aux$p.value>=0.025 && aux$p.value<=0.05){cat("',gettext("p-value",domain="R-RcmdrPlugin.TeachStat"),':",format.pval(aux$p.value),"*\\n")} if(aux$p.value>=0.0001 && aux$p.value<=0.025){cat("',gettext("p-value",domain="R-RcmdrPlugin.TeachStat"),':",format.pval(aux$p.value),"**\\n")} if(aux$p.value>=0 && aux$p.value<=0.0001){cat("',gettext("p-value",domain="R-RcmdrPlugin.TeachStat"),':",format.pval(aux$p.value),"***\\n")}\n',sep="") if (varHAlternativa == "two.sided"){h.alt<-paste(gettext("Population proportion is not equal to",domain="R-RcmdrPlugin.TeachStat"),valorp0,sep=" ")} if (varHAlternativa == "less"){h.alt<-paste(gettext("Population proportion is less than",domain="R-RcmdrPlugin.TeachStat"),valorp0,sep=" ")} if (varHAlternativa == "greater"){h.alt<- paste(gettext("Population proportion is greater than",domain="R-RcmdrPlugin.TeachStat"),valorp0,sep=" ")} h.alt<-paste('\n cat("',gettext("Alternative hypothesis",domain="R-RcmdrPlugin.TeachStat"),':","',h.alt,'","\\n")',sep="") e.muestral<-paste('\n cat("',gettext("Sample estimate",domain="R-RcmdrPlugin.TeachStat"),':",names(aux$estimate),as.numeric(aux$estimate),"\\n")',sep="") command<- paste(command, distribucion,e.contraste,p.valor, h.alt,e.muestral,"\n})",sep="" ) doItAndPrint(command) } if(!is.na(valornexitos)){ if((valornexitos==0)||(valornfracasos==0)){ errorCondition(recall=contrastHipotesisProporcion, message=gettext("There must be at least 1 success and 1 failure",domain="R-RcmdrPlugin.TeachStat")) return() } command2<- paste("aux<- Cprop.test(ex=",valornexitos,", nx=",valornexitos + valornfracasos,",p.null=",valorp0,", alternative=",Haltern,")",sep="" ) command2<- paste("local({\n",command2,"\n",sep="") resultado<-paste('cat("',tipointervalo,'\\n',gettext("Sample",domain="R-RcmdrPlugin.TeachStat"),': ',gettext("No. successes",domain="R-RcmdrPlugin.TeachStat"),' = ', valornexitos, ' -- ',gettext("No. attempts",domain="R-RcmdrPlugin.TeachStat"),' = ', valornexitos + valornfracasos, '\\n")', sep="" ) command2<- paste(command2, resultado,"\n",sep="" ) distribucion<-paste('cat("',gettext("Distribution",domain="R-RcmdrPlugin.TeachStat"),':","Normal(0,1)\\n")',sep="") e.contraste<- paste('\n cat("',gettext("Test statistics value",domain="R-RcmdrPlugin.TeachStat"),':",as.numeric(aux$statistic),"\\n")',sep="") p.valor<-paste('\n if(aux$p.value>0.05){cat("',gettext("p-value",domain="R-RcmdrPlugin.TeachStat"),':",format.pval(aux$p.value),"\\n")} if(aux$p.value>=0.025 && aux$p.value<=0.05){cat("',gettext("p-value",domain="R-RcmdrPlugin.TeachStat"),':",format.pval(aux$p.value),"*\\n")} if(aux$p.value>=0.0001 && aux$p.value<=0.025){cat("',gettext("p-value",domain="R-RcmdrPlugin.TeachStat"),':",format.pval(aux$p.value),"**\\n")} if(aux$p.value>=0 && aux$p.value<=0.0001){cat("',gettext("p-value",domain="R-RcmdrPlugin.TeachStat"),':",format.pval(aux$p.value),"***\\n")}\n',sep="") if (varHAlternativa == "two.sided"){h.alt<-paste(gettext("Population proportion is not equal to",domain="R-RcmdrPlugin.TeachStat"),valorp0,sep=" ")} if (varHAlternativa == "less"){h.alt<-paste(gettext("Population proportion is less than",domain="R-RcmdrPlugin.TeachStat"),valorp0,sep=" ")} if (varHAlternativa == "greater"){h.alt<- paste(gettext("Population proportion is greater than",domain="R-RcmdrPlugin.TeachStat"),valorp0,sep=" ")} h.alt<-paste('\n cat("',gettext("Alternative hypothesis",domain="R-RcmdrPlugin.TeachStat"),':","',h.alt,'","\\n")',sep="") e.muestral<-paste('\n cat("',gettext("Sample estimate",domain="R-RcmdrPlugin.TeachStat"),':",names(aux$estimate),as.numeric(aux$estimate),"\\n")',sep="") command2<- paste(command2, distribucion,e.contraste,p.valor, h.alt,e.muestral,"\n})",sep="" ) doItAndPrint(command2) } tkfocus(CommanderWindow()) } OKCancelHelp(helpSubject = "Cprop.test", reset="contrastHipotesisProporcion", apply="contrastHipotesisProporcion") tkgrid(comboBoxFrame,labelRcmdr(selectFactorsFrame, text=" "),exitosFracasosFrame, sticky="nw") tkgrid(selectFactorsFrame, sticky="nw") tkgrid(labelRcmdr(top, text=" ")) tkgrid(labelRcmdr(rightFrame, text=" "),sticky="nw") tkgrid(p0Frame,sticky="nw") tkgrid(nConfianzaFrame, sticky="nw") tkgrid(alternativeFrame,labelRcmdr(optionsFrame, text=" "),rightFrame, sticky="nw") tkgrid(optionsFrame,sticky="nw") tkgrid(buttonsFrame, sticky="w") dialogSuffix() }
genConfig1D <- function(n) { x <- rep(0.0,n) out <- .C("genConfig1D", n=as.integer(n), x=as.double(x)); out$x } flipConfig1D <- function(x) { out <- .C("flipConfig1D", n=as.integer(length(x)), x=as.double(x)); out$x } flipConfig1Dmany <- function(x, upperF) { out <- .C("flipConfig1Dmany", n=as.integer(length(x)), x=as.double(x), upperF=as.integer(upperF)); out$x } lattice1DenergyNN <- function(x) { energy <-0 if(!is.numeric(x)) stop("argument x must be numeric"); out <- .C("lattice1DenergyNN", n=as.integer(length(x)), vec=as.double(x), energy=as.double(energy)); out$energy } sumVec <- function(x) { sum <-0 if(!is.numeric(x)) stop("argument x must be numeric"); out <- .C("sumVec", n=as.integer(length(x)), vec=as.double(x), sum=as.double(sum)); out$sum } totalEnergy1D <- function(x, J, H) { energy <- 0 if(!is.numeric(x)) stop("argument x must be numeric"); out <- .C("totalEnergy1D", n=as.integer(length(x)), vec=as.double(x), J=as.double(J), H=as.double(H), totalEnergy=as.double(energy)); out$totalEnergy } transitionProbability1D <- function(ikBT, x, xflip, J, H, probSel) { prob <- 0.0; if(!is.numeric(x)) stop("argument x must be numeric"); if(!is.numeric(xflip)) stop("argument xflip must be numeric"); out <- .C("transitionProbability1D", ikBT=as.double(ikBT), n=as.integer(length(x)), vec=as.double(x), vecFlip=as.double(xflip), J=as.double(J), H=as.double(H), prob=as.double(prob), probSel=as.integer(probSel)); out$prob } isStep1D <- function(ikBT, x, J, H, probSel) { prob <- 0.0; accept <- 0.0; if(!is.numeric(x)) stop("argument x must be numeric"); out <- .C("isStep1D", ikBT=as.double(ikBT), n=as.integer(length(x)), vec=as.double(x), J=as.double(J), H=as.double(H), prob=as.double(prob), accept=as.integer(accept), probSel=as.integer(probSel)); rout <- list(vec=out$vec, accept=out$accept) rout } isPerform1D <- function(ikBT, x, J, H, nstep, ensembleM, probSel) { if(!is.numeric(x)) stop("argument x must be numeric"); omegaM <- rep(0.0, nstep); times <- rep(1.0, nstep); naccept <- 0; nreject <- 0; out <- .C("isPerform1D", ikBT=as.double(ikBT), n=as.integer(length(x)), vec=as.double(x), J=as.double(J), H=as.double(H), ensembleM=as.double(ensembleM), omegaM=as.double(omegaM), nstep=as.integer(nstep), naccept=as.integer(naccept), nreject=as.integer(nreject), times=as.integer(times), probSel=as.integer(probSel)); rout <- list(omegaM=out$omegaM, nreject=out$nreject, naccept=out$naccept, times=out$times); rout }
collect <- function(x, n = NULL) { steps <- n %&&% iter_take(n) reduce_steps(x, steps, along_builder(list())) } loop <- function(loop) { loop <- substitute(loop) if (!is_call(loop, "for")) { abort("`loop` must be a `for` expression.") } env <- caller_env() if (is_true(env$.__generator_instance__.)) { abort(c( "Can't use `loop()` within a generator.", i = "`for` loops already support iterators in generator functions." )) } args <- node_cdr(loop) var <- as_string(node_car(args)) iterator <- as_iterator(eval_bare(node_cadr(args), env)) body <- node_cadr(node_cdr(args)) elt <- NULL advance <- function() !is_exhausted(elt <<- iterator()) update <- function() env[[var]] <- elt loop <- expr( while (!!call2(advance)) { !!call2(update) !!body } ) eval_bare(loop, env) invisible(exhausted()) } async_collect <- function(x, n = NULL) { steps <- n %&&% iter_take(n) async_reduce_steps(x, steps, along_builder(list())) }
mtcars_short <- mtcars[1:5, ] check_suggests <- function() { skip_if_not_installed("rvest") skip_if_not_installed("xml2") } selection_value <- function(html, key) { selection <- paste0("[", key, "]") html %>% rvest::html_nodes(selection) %>% rvest::html_attr(key) } selection_text <- function(html, selection) { html %>% rvest::html_nodes(selection) %>% rvest::html_text() } test_that("the `text_transform()` function works correctly", { check_suggests() tbl_html <- mtcars_short %>% gt() %>% text_transform( locations = cells_body(columns = mpg), fn = function(x) paste0(x, " mpg") ) tbl_html %>% render_as_html() %>% xml2::read_html() %>% selection_text("tr td:first-child") %>% expect_match(".* mpg$") tbl_html <- mtcars_short %>% gt() %>% text_transform( locations = cells_body(columns = mpg), fn = function(x) { paste0(x, " ", ifelse(x >= 20, "(good)", "(bad)")) } ) tbl_html %>% render_as_html() %>% xml2::read_html() %>% selection_text("tr td:first-child") %>% expect_match(".*(\\(good\\)|\\(bad\\))$") tbl_html <- mtcars_short %>% gt() %>% text_transform( locations = cells_body(columns = mpg), fn = function(x) { ifelse(x >= 20, 25, 15) } ) tbl_html %>% render_as_html() %>% xml2::read_html() %>% selection_text("tr td:first-child") %>% unique() %>% expect_equal(c("25", "15")) tbl_html <- mtcars_short %>% gt() %>% fmt_number( columns = mpg, decimals = 4, pattern = "{x} miles") %>% text_transform( locations = cells_body(columns = mpg), fn = function(x) { paste(x, "per gallon") } ) tbl_html %>% render_as_html() %>% xml2::read_html() %>% selection_text("tr td:first-child") %>% expect_match(".*miles per gallon$") tbl_html <- mtcars_short %>% gt() %>% text_transform( locations = cells_body(columns = mpg), fn = function(x) { paste(x, "miles") } ) %>% text_transform( locations = cells_body(columns = mpg), fn = function(x) { paste(x, "per gallon") } ) tbl_html %>% render_as_html() %>% xml2::read_html() %>% selection_text("tr td:first-child") %>% expect_match(".*miles per gallon$") transforms <- dt_transforms_get(data = tbl_html) transforms %>% length() %>% expect_equal(2) transforms[[1]] %>% names() %>% expect_equal(c("resolved", "fn")) transforms[[2]] %>% names() %>% expect_equal(c("resolved", "fn")) transforms[[1]]$resolved %>% names() %>% expect_equal(c("columns", "rows", "colnames")) transforms[[2]]$resolved %>% names() %>% expect_equal(c("columns", "rows", "colnames")) transforms[[1]]$resolved %>% expect_is(c("resolved", "cells_body", "location_cells")) transforms[[2]]$resolved %>% expect_is(c("resolved", "cells_body", "location_cells")) transforms[[1]]$fn %>% expect_is("function") transforms[[2]]$fn %>% expect_is("function") round_mult <- function(x, multiple = 0.25) { x <- as.numeric(x) format(multiple * round(x / multiple)) } tbl_html <- mtcars_short %>% gt() %>% text_transform( locations = cells_body(columns = mpg), fn = round_mult ) tbl_html %>% render_as_html() %>% xml2::read_html() %>% selection_text("tr td:first-child") %>% expect_match(".*\\.(00|25|50|75)$") }) test_that("`text_transform()` works in the body even when rows/columns are reordered", { tbl_html <- mtcars_short %>% gt(rownames_to_stub = TRUE) %>% tab_row_group( label = md("**Mazda**"), rows = starts_with("Maz"), id = "Mazda" ) %>% tab_row_group( label = md("**2 Hornets + a Datsun**"), rows = matches("Datsun|Hornet"), id = "DatsunHornet" ) %>% text_transform( locations = cells_body(columns = mpg, rows = "Datsun 710"), fn = function(x) paste0(x, "!") ) %>% text_transform( locations = cells_body(columns = mpg, rows = starts_with("Mazda")), fn = function(x) round(as.numeric(x), 0) ) tbl_html %>% render_as_html() %>% xml2::read_html() %>% selection_text("tr td:nth-child(2)") %>% expect_equal(c("22.8!", "21.4", "18.7", "21", "21")) tbl_html <- tbl_html %>% row_group_order(groups = c("Mazda", "DatsunHornet")) tbl_html %>% render_as_html() %>% xml2::read_html() %>% selection_text("tr td:nth-child(1)") %>% expect_equal( c( "Mazda", "Mazda RX4", "Mazda RX4 Wag", "2 Hornets + a Datsun", "Datsun 710", "Hornet 4 Drive", "Hornet Sportabout" ) ) tbl_html %>% render_as_html() %>% xml2::read_html() %>% selection_text("tr td:nth-child(2)") %>% expect_equal(c("21", "21", "22.8!", "21.4", "18.7")) tbl_html <- tbl_html %>% cols_move(columns = mpg, after = cyl) tbl_html %>% render_as_html() %>% xml2::read_html() %>% selection_text("tr td:nth-child(3)") %>% expect_equal(c("21", "21", "22.8!", "21.4", "18.7")) }) test_that("`text_transform()` works in column labels", { tbl_html <- mtcars_short %>% gt(rownames_to_stub = TRUE) %>% tab_row_group( label = md("**Mazda**"), rows = starts_with("Maz"), id = "Mazda" ) %>% tab_row_group( label = md("**2 Hornets + a Datsun**"), rows = matches("Datsun|Hornet"), id = "DatsunHornet" ) %>% cols_move_to_end(columns = cyl) %>% text_transform( locations = cells_column_labels(columns = c(mpg, cyl)), fn = toupper ) tbl_html %>% render_as_html() %>% xml2::read_html() %>% selection_text("th") %>% expect_equal( c( "", "MPG", "disp", "hp", "drat", "wt", "qsec", "vs", "am", "gear", "carb", "CYL" ) ) }) test_that("`text_transform()` works on row labels in the stub", { tbl_html <- mtcars_short %>% gt(rownames_to_stub = TRUE) %>% tab_row_group( label = md("**Mazda**"), rows = starts_with("Maz"), id = "Mazda" ) %>% tab_row_group( label = md("**2 Hornets + a Datsun**"), rows = matches("Datsun|Hornet"), id = "DatsunHornet" ) %>% cols_move_to_end(columns = cyl) %>% text_transform( locations = cells_stub(rows = c("Mazda RX4 Wag", "Hornet Sportabout")), fn = toupper ) tbl_html %>% render_as_html() %>% xml2::read_html() %>% selection_text("[class='gt_row gt_right gt_stub']") %>% expect_equal( c( "Datsun 710", "Hornet 4 Drive", "HORNET SPORTABOUT", "Mazda RX4", "MAZDA RX4 WAG" ) ) })
SchumakerIndInterval = function(z,s,Smallt){ if (sum(s)*(Smallt[2]-Smallt[1]) == 2*(z[2]-z[1])){ tsi = Smallt[2] } else { delta = (z[2] -z[1])/(Smallt[2]-Smallt[1]) Condition = ((s[1]-delta)*(s[2]-delta) >= 0) Condition2 = abs(s[2]-delta) < abs(s[1]-delta) if (Condition){ tsi = sum(Smallt)/2 } else { if (Condition2){ tsi = (Smallt[1] + (Smallt[2]-Smallt[1])*(s[2]-delta)/(s[2]-s[1])) } else { tsi = (Smallt[2] + (Smallt[2]-Smallt[1])*(s[1]-delta)/(s[2]-s[1])) } } } alpha = tsi-Smallt[1] beta = Smallt[2]-tsi sbar = (2*(z[2]-z[1])-(alpha*s[1]+beta*s[2]))/(Smallt[2]-Smallt[1]) Coeffs1 = c((sbar-s[1])/(2*alpha), s[1], z[1]) if (beta == 0){ Coeffs2 = c(Coeffs1) } else { Coeffs2 = c((s[2]-sbar)/(2*beta), sbar , Coeffs1 %*% c(alpha^2, alpha, 1)) } data.frame(tsi = c(tsi, tsi), C = c(Coeffs1[1], Coeffs2[1]), B = c(Coeffs1[2], Coeffs2[2]), A = c(Coeffs1[3], Coeffs2[3]) ) }
library(randtoolbox) if(FALSE) { RNGkind() set.generator(name="congruRand", mod=2^31-1, mult=16807, incr=0, seed=12345) get.description() runif(5) setSeed(12345) congruRand(5, dim=1, mod=2^31-1, mult=16807, incr=0) RNGkind() 4294967296 == 2^32 set.generator(name="congruRand", mod="4294967296", mult="1664525", incr="1013904223", seed=1) runif(5) setSeed(1) congruRand(5, dim=1, mod=4294967296, mult=1664525, incr=1013904223) 281474976710656 == 2^48 set.generator(name="congruRand", mod="281474976710656", mult="25214903917", incr="11", seed=1) runif(5) setSeed(1) congruRand(5, dim=1, mod=281474976710656, mult=25214903917, incr=11) 18446744073709551616 == 2^64 set.generator(name="congruRand", mod="18446744073709551616", mult="1442695040888963407", incr="1013904223", seed=1) runif(5) (1442695040888963407 * 1 + 1013904223) / 2^64 setSeed(1) congruRand(5, dim=1, mod=18446744073709551616, mult=1442695040888963407, incr=1013904223) set.generator(name="congruRand", mod="18446744073709551616", mult="636412233846793005", incr="1", seed=1) res <- get.description() runif(1) setSeed(1) congruRand(2, dim=1, mod=18446744073709551616, mult=636412233846793005, incr=1, echo = TRUE) }
transform_rows_unit_norm = function(x, norm = 1) { if(!inherits(x, "matrix") && !inherits(x, "sparseMatrix")) stop("x should inherit from `matrix`` or `Matrix::sparseMatrix`") if(!is.numeric(norm) || length(norm) != 1) stop("`norm` should be numeric of length 1") rs = rowSums(x ^ norm) if(isTRUE(all.equal(rep(1, length(rs)), rs, tolerance = 1e-5, check.attributes = FALSE))) return(x) norm_vec = 1 / rs ^ (1 / norm) norm_vec[is.infinite(norm_vec)] = 0 if(inherits(x, "sparseMatrix")) Diagonal(x = norm_vec) %*% x else x * norm_vec } normalize = function(m, norm = c("l1", "l2", "none")) { stopifnot(inherits(m, "matrix") || inherits(m, "sparseMatrix")) norm = match.arg(norm) if (norm == "none") return(m) norm_vec = switch(norm, l1 = 1 / rowSums(m), l2 = 1 / sqrt(rowSums(m ^ 2)) ) norm_vec[is.infinite(norm_vec)] = 0 if(inherits(m, "sparseMatrix")) Diagonal(x = norm_vec) %*% m else m * norm_vec } as.lda_c = function(X) { if (is.list(X) && all(vapply(X, function(x) is.matrix(x) && is.integer(x), FALSE)) ) { class(X) = "lda_c" return(X) } if (!inherits(X, "RsparseMatrix")) X = as( X, "RsparseMatrix") len = nrow(X) input_ids = rownames(X) m_lda_c = vector("list", len) for(i in seq_len(len)) { i_start = X@p[i] + 1L i_end = X@p[i + 1L] if(i_start <= i_end) { i_range = i_start:i_end m_lda_c[[i]] = rbind(X@j[i_range], as.integer(X@x[i_range])) } else { m = integer() dim(m) = c(2L, 0L) m_lda_c[[i]] = m } } names(m_lda_c) = input_ids class(m_lda_c) = 'lda_c' m_lda_c } to_lda_c = function(X) { .Deprecated("as.lda_c") as.lda_c(X) } rbind_dgTMatrix = function(...) { res = new('dgTMatrix') mat_list = list(...) ncols = vapply(mat_list, ncol, FUN.VALUE = 0L) stopifnot( length(unique(ncols)) == 1) all_colnames = lapply(mat_list, colnames) stopifnot( length(unique(all_colnames)) == 1) nrows = vapply(mat_list, nrow, FUN.VALUE = 0L) offset = cumsum(c(0L, nrows[-length(nrows)])) res@i = do.call(c, Map(function(m, offs) m@i + offs, mat_list, offset)) res@j = do.call(c, lapply(mat_list, function(m) m@j) ) res@x = do.call(c, lapply(mat_list, function(m) m@x) ) res_rownames = do.call(c, lapply(mat_list, rownames) ) res@Dim = c(sum(nrows), ncols[[1]]) res@Dimnames = list(res_rownames, all_colnames[[1]] ) res }
order_betaexpg <- function(size,spec,lambda,a,b,k,n,alpha=0.05,...){ sample <- qbetaexpg(initial_order(size,k,n),spec,lambda,a,b,...) pdf <- factorial(size)*cumprod(dbetaexpg(sample,spec,...))[size] if(size>5){ return(list(sample=sample,pdf=pdf,ci_median=interval_median(size,sample,alpha))) } cat("---------------------------------------------------------------------------------------------\n") cat("We cannot report the confidence interval. The size of the sample is less or equal than five.\n") return(list(sample=sample,pdf=pdf)) }
Huggins89.t1 <- structure(list(x2 = c(6.3, 4, 4.7, 4.8, 6.6, 3.9, 5.9, 5, 5.6, 4.6, 5.9, 4.4, 4.6, 4.4, 5.6, 3.6, 3.7, 4.4, 3.6, 4.4), y01 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), y02 = c(1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0), y03 = c(0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0), y04 = c(1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0), y05 = c(1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0), y06 = c(0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0), y07 = c(0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1), y08 = c(1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0), y09 = c(0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), y10 = c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0), z01 = c(5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8, 5.8), z02 = c(2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9, 2.9), z03 = c(3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7), z04 = c(2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2), z05 = c(3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5), z06 = c(3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6), z07 = c(1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9), z08 = c(3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3), z09 = c(4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8, 4.8), z10 = c(4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7, 4.7)), .Names = c("x2", "y01", "y02", "y03", "y04", "y05", "y06", "y07", "y08", "y09", "y10", "z01", "z02", "z03", "z04", "z05", "z06", "z07", "z08", "z09", "z10"), row.names = c(NA, -20L), class = "data.frame")
getSupportedPreparations <- function() { allSupportedPreparations <- list( supportedImputeTS = c("ImputeTSInterpolation", "ImputeTSKalman", "ImputeTSLOCF", "ImputeTSMA", "ImputeTSMean", "ImputeTSRandom", "ImputeTSReplace" ), other = c() ) return(allSupportedPreparations) } getSupportedModels <- function() { allSupportedModels <- list( supportedUnivariateForeCastModels = c("ForecastETS", "ForecastArima", "ForecastBats", "ForecastHolt", "ForecastMeanf", "ForecastRWF", "ForecastSplineF", "ForecastThetaf", "ForecastSES" ), supportedMultivariateModels=c("NeuralNetwork"), other = c() ) return(allSupportedModels) } getSupportedPostProcessors <- function() { allSupportedPostProcessors <- list( other = c("bedAlgo") ) return(allSupportedPostProcessors) }
[ { "title": "The Frisch–Waugh–Lovell Theorem for Both OLS and 2SLS", "href": "https://diffuseprior.wordpress.com/2013/06/05/the-frisch-waugh-lovell-theorem-for-both-ols-and-2sls/" }, { "title": "Predictive analysis on Web Analytics tool data", "href": "http://www.tatvic.com/blog/predictive-analysis-on-web-analytics-tool-data/" }, { "title": "Universal portfolio, part 8", "href": "http://optimallog.blogspot.com/2012/07/universal-portfolio-part-8.html" }, { "title": "Aspirational & Useful: deck.rb with RStudio/knitr & Go2Shell", "href": "http://christophergandrud.blogspot.com/2012/05/aspirational-useful-deckrb-with.html" }, { "title": "Emacs, ESS and R for Zombies", "href": "http://blog.revolutionanalytics.com/2014/03/emacs-ess-and-r-for-zombies.html" }, { "title": "Biblical kings and boxplots", "href": "http://computersandbuildings.com/biblical-kings-and-boxplots/" }, { "title": "What makes a good academic conference?", "href": "http://www.decisionsciencenews.com/2014/09/11/makes-good-academic-conference/" }, { "title": "the spatial concentration of Green support", "href": "https://web.archive.org/web/http://jackman.stanford.edu/blog/?p=1810" }, { "title": "Simulated War", "href": "http://www.premiersoccerstats.com/wordpress/?p=825&utm_source=rss&utm_medium=rss&utm_campaign=simulated-war-2" }, { "title": "Images as Voronoi tesselations", "href": "http://is-r.tumblr.com/post/36732821806/images-as-voronoi-tesselations" }, { "title": "Bootstrap Confidence Intervals", "href": "http://statistical-research.com/bootstrap-confidence-intervals/?utm_source=rss&utm_medium=rss&utm_campaign=bootstrap-confidence-intervals" }, { "title": "Dollars and cents: How are you at estimating the total bill?", "href": "http://www.decisionsciencenews.com/2011/09/30/dollars-and-cents-how-are-you-at-estimating-the-total-bill/" }, { "title": "Principal component analysis to yield curve change", "href": "http://mockquant.blogspot.com/2010/12/principal-component-analysis-to-yield.html" }, { "title": "Eclipse and StatET 2.0 Install For Running R", "href": "http://lukemiller.org/index.php/2012/01/eclipse-and-statet-2-0-install-for-running-r/" }, { "title": "Do your \"data janitor work\" like a boss with dplyr", "href": "http://www.gettinggeneticsdone.com/2014/08/do-your-data-janitor-work-like-boss.html" }, { "title": "My day out at "href": "https://nsaunders.wordpress.com/2012/05/11/my-day-out-at-osddmalaria/" }, { "title": "\"The Dude\" takes the Tarantino threshold", "href": "http://rcrastinate.blogspot.com/2013/01/the-dude-takes-tarantino-threshold.html" }, { "title": "How to win the KDD Cup Challenge with R and gbm", "href": "http://www.cybaea.net/Blogs/Data/How-to-win-the-KDD-Cup-Challenge-with-R-and-gbm.html" }, { "title": "11 Million Yellow Slips – City of Toronto Parking Tickets, 2008-2011", "href": "http://www.everydayanalytics.ca/2012/06/11-million-parking-tickets.html" }, { "title": "Bayesian vs. Frequentist Intervals: Which are more natural to scientists?", "href": "http://biostatmatt.com/archives/1812" }, { "title": "Getting indices of top elements from a vector using a priority queue", "href": "http://gallery.rcpp.org/articles/top-elements-from-vectors-using-priority-queue/" }, { "title": "Installing Pandoc from R (on Windows) – using the {installr} package", "href": "https://www.r-statistics.com/2013/02/installing-pandoc-from-r-on-windows/" }, { "title": "New R Software/Methodology for Handling Missing Dat", "href": "https://matloff.wordpress.com/2015/09/16/new-r-softwaremethodology-for-handling-missing-dat/" }, { "title": "Tibshirani’s original paper on the lasso.\r\nBreiman’s…", "href": "http://isomorphism.es/post/37362497363/tibshirani-lasso" }, { "title": "White House taps Edward Tufte to explain the stimulus", "href": "https://web.archive.org/web/http://blog.revolution-computing.com/2010/03/white-house-taps-edward-tufte-to-explain-the-stimulus.html" }, { "title": "A slightly different introduction to R, part I", "href": "https://martinsbioblogg.wordpress.com/2013/01/19/a-slightly-different-introduction-to-r-part-i/" }, { "title": "Rcpp vs. R implementation of cosine similarity", "href": "http://brainchronicle.blogspot.com/2012/06/rcpp-vs-r-implementation-of-cosine.html" }, { "title": "data.frame objects in R (via “R in Action”)", "href": "https://www.r-statistics.com/2011/12/data-frame-objects-in-r-via-r-in-action/" }, { "title": "Simulating the Rule of Five", "href": "http://datadrivensecurity.info/blog/posts/2014/Nov/hubbard/" }, { "title": "Tools for Hacking R: Subversion", "href": "http://biostatmatt.com/archives/686" }, { "title": "Extension to an R Package: brew gets a weave", "href": "http://biostatmatt.com/archives/573" }, { "title": "Introductory Time-Series analysis of US Environmental Protection Agency (EPA) pollution data", "href": "http://r-video-tutorial.blogspot.com/2015/05/introductory-time-series-analysis-of-us.html" }, { "title": "Clegg vs Pleb: An XKCD-esque chart", "href": "http://www.drunks-and-lampposts.com/" }, { "title": "A set of "href": "http://www.christopherlortie.info/a-set-of-rstats-adventuretime-themed-openscience-slide-decks/" }, { "title": "RSAP, Rook and ERP", "href": "http://blagrants.blogspot.com/2012/07/rsap-rook-and-erp.html" }, { "title": "An experience of EARL", "href": "http://www.burns-stat.com/experience-earl/" }, { "title": "Visualizing a flood with R", "href": "http://blog.revolutionanalytics.com/2016/06/visualizing-a-flood-with-r.html" }, { "title": "Extracting reflectance data from SpectraSuite JCAMP files in R", "href": "https://web.archive.org/web/http://planetflux.adamwilson.us/2011/05/extracting-reflectance-data-from.html" }, { "title": "Upgrade and update R 2.15 to R 3.0 in Debian Wheezy", "href": "http://tata-box-blog.blogspot.com/2014/02/upgrade-and-update-r-215-to-r-30-in.html" }, { "title": "Release of XLConnect 0.1-3", "href": "https://miraisolutions.wordpress.com/2011/02/28/xlconnect/" }, { "title": "The opinionated estimator", "href": "http://computersandbuildings.com/the-opinionated-estimator/" }, { "title": "Enron Email Corpus Topic Model Analysis Part 2 – This Time with Better regex", "href": "https://rforwork.info/2013/11/04/enron-email-corpus-topic-model-analysis-part-2-this-time-with-better-regex/" }, { "title": "Finding outliers in numerical data", "href": "http://exploringdatablog.blogspot.com/2013/02/finding-outliers-in-numerical-data.html" }, { "title": "jsonlite gets a triple mushroom boost!", "href": "https://www.opencpu.org/posts/jsonlite-release-0-9-11/" }, { "title": "Using miniCRAN in Azure ML", "href": "http://blog.revolutionanalytics.com/2015/10/using-minicran-in-azure-ml.html" }, { "title": "ReactomePA: an R/Bioconductor package for reactome pathway analysis and visualization", "href": "http://guangchuangyu.github.io/2016/02/reactomepa-an-r/bioconductor-package-for-reactome-pathway-analysis-and-visualization/" }, { "title": "BayesFactor version 0.9.8 released to CRAN", "href": "http://bayesfactor.blogspot.com/2014/08/bayesfactor-version-0.html" }, { "title": "Plotting texts as graphs with R and igraph", "href": "https://www.r-bloggers.com/" }, { "title": "Examples using R – Analysis of Variance", "href": "http://www.studytrails.com/blog/examples-using-r-analysis-of-variance/" }, { "title": "Data Science MD July Recap: Python and R Meetup", "href": "http://www.datacommunitydc.org/blog/2013/08/data-science-md-july-recap-python-and-r-meetup/?utm_source=rss&utm_medium=rss&utm_campaign=data-science-md-july-recap-python-and-r-meetup" } ]
wboot.twfe.panel <- function(nn, n, y, dd, post, x, i.weights){ v <- stats::rexp(n) v <- as.matrix(c(v, v)) b.weights <- as.vector(i.weights * v) reg.b <- stats::lm(y ~ dd:post + post + dd + x, weights = b.weights) twfe.att.b <- reg.b$coefficients["dd:post"] return(twfe.att.b) }
testPathBase <- normalizePath(path = "../files") bookdownFile <- file.path(testPathBase, "_bookdown.yml") file.create(bookdownFile) write_yaml( list( SAS_dir = "path/to/data", patient_profile_path = "./patient_profiles/" ), bookdownFile )
porosity <- function(IN=data$rst, PLOT=TRUE, NEIGH=4) { opar <- par(no.readonly=TRUE) on.exit(par(opar)) oldw <- getOption("warn") options(warn = -1) on.exit(options(warn=oldw)) if(PLOT) { plot.new() } if(PLOT) { par(mfrow=c(3,4), pty="s") plot(IN, main="Original") } imgpad <- extend(x=IN, y=1, value=0) if(PLOT) { plot(imgpad, main="imgpad") } spres <- res(imgpad)[1] north <- shift(imgpad, dy=spres) south <- shift(imgpad, dy=-spres) west <- shift(imgpad, dx=-spres) east <- shift(imgpad, dx=spres) if(PLOT) { plot(north, main="North") plot(south, main="South") plot(west, main="West") plot(east, main="East") } neighnorth <- imgpad * north neighsouth <- imgpad * south neighwest <- imgpad * west neigheast <- imgpad * east if(PLOT) { plot(neighnorth) plot(neighsouth) plot(neighwest) plot(neigheast) } out <- neighnorth + neighsouth + neighwest + neigheast if(PLOT) { plot(out, main="Out") } tab <- freq(out) tab <- tab[tab[,1] != 0,] tot2wayjoins <- sum(tab[,1]*tab[,2]) tot1wayjoins <- tot2wayjoins/2 zones <- clump(IN, directions=NEIGH) N <- as.data.frame(freq(zones)) N <- N[!is.na(N[,1]),] if(PLOT) { plot(zones, main="Zones") } joins2way <- zonal(out, zones, fun=sum) joins1way <- joins2way[,2]/2 joins <- as.data.frame(cbind(N, joins2way[,2]/2, 0, 0)) names(joins) <- c("Zone", "N", "Jact", "Jmax", "Porosity") joins$Jmax <- trunc((4 * joins$N - 4 * sqrt(joins$N)) / 2) joins$Porosity <- 1 - (joins$Jact / joins$Jmax) return(joins) }
context('functions') test_that('monoUpDown', { expect_error(monoUpDown(block_length = 10)) expect_error(monoUpDown(demo_returns, difference = "FALSE")) expect_error(monoUpDown(demo_returns, bootstrapRep = "100")) expect_error(monoUpDown(demo_returns, bootstrapRep = -1)) expect_error(monoUpDown(demo_returns)) expect_error(monoUpDown(demo_returns, block_length = 7)) expect_error(monoUpDown(demo_returns)) expect_error(monoUpDown(data = cbind(demo_returns, demo_returns), block_length = 10)) expect_equal(dim(monoUpDown(demo_returns,block_length = 10)),as.integer(c(4,2))) expect_gte(monoUpDown(demo_returns,block_length = 10)[1,1],expected = 0) expect_gte(monoUpDown(demo_returns,block_length = 10)[2,1],expected = 0) expect_gte(monoUpDown(demo_returns,block_length = 10)[3,1],expected = 0) expect_gte(monoUpDown(demo_returns,block_length = 10)[4,1],expected = 0) expect_gte(monoUpDown(demo_returns,block_length = 10)[1,2],expected = 0) expect_gte(monoUpDown(demo_returns,block_length = 10)[2,2],expected = 0) expect_gte(monoUpDown(demo_returns,block_length = 10)[3,2],expected = 0) expect_gte(monoUpDown(demo_returns,block_length = 10)[4,2],expected = 0) expect_lte(monoUpDown(demo_returns,block_length = 10)[1,1],expected = 1) expect_lte(monoUpDown(demo_returns,block_length = 10)[2,1],expected = 1) expect_lte(monoUpDown(demo_returns,block_length = 10)[3,1],expected = 1) expect_lte(monoUpDown(demo_returns,block_length = 10)[4,1],expected = 1) expect_lte(monoUpDown(demo_returns,block_length = 10)[1,2],expected = 1) expect_lte(monoUpDown(demo_returns,block_length = 10)[2,2],expected = 1) expect_lte(monoUpDown(demo_returns,block_length = 10)[3,2],expected = 1) expect_lte(monoUpDown(demo_returns,block_length = 10)[4,2],expected = 1) })
Read.IC.info.BADM <-function(lat, long){ cov.factor <-1 U.S.SB <- read.csv(system.file("data","BADM.csv", package = "PEcAn.data.land")) Regions <- EPA_ecoregion_finder(lat, long) Code_Level <- Regions$L2 biomass.df <- U.S.SB %>% dplyr::filter( NA_L2CODE == Code_Level, VARIABLE %>% grepl("ROOT_|AG_BIOMASS|SOIL_STOCK|SOIL_CHEM", .) ) %>% dplyr::select(SITE_ID, GROUP_ID, VARIABLE_GROUP, VARIABLE, DATAVALUE) if (nrow(biomass.df) < 3) { Code_Level <- Regions$L1 biomass.df <- U.S.SB %>% dplyr::filter( NA_L1CODE == Code_Level, VARIABLE %>% grepl("ROOT_|AG_BIOMASS|SOIL_STOCK|SOIL_CHEM", .) ) %>% dplyr::select(SITE_ID, GROUP_ID, VARIABLE_GROUP, VARIABLE, DATAVALUE) } if (nrow(biomass.df) < 3) { Code_Level <- "ALL" biomass.df <- U.S.SB %>% dplyr::filter(VARIABLE %>% grepl("ROOT_|AG_BIOMASS|SOIL_STOCK|SOIL_CHEM", .)) %>% dplyr::select(SITE_ID, GROUP_ID, VARIABLE_GROUP, VARIABLE, DATAVALUE) } entries <- biomass.df %>% split(.$GROUP_ID) %>% purrr::map_dfr( function(Gdf) { PlantWoodIni <- NA SoilIni <- NA litterIni <- NA Rootini <- NA litterIni <- NA Date.in <- NA Oregan.in <- NA if (nrow(Gdf) > 0) { type <- sapply(c( "*LIT", "*SOIL", "*_BIOMASS", "*_ROOT_BIOMASS", "*_LIT_BIOMASS" ), grepl, Gdf[1, 3]) type <- names(type)[type] } else{ return(NULL) } if (length(type) > 1) type <- type[-which(type == "*_BIOMASS")] unit.in <- Gdf %>% dplyr::filter(VARIABLE %>% grepl("UNIT", .)) %>% dplyr::pull(DATAVALUE) %>% as.character() if (length(unit.in) > 0) if (unit.in =="kgDM m-2") cov.factor <- cov.factor *0.48 unit.ready <- ifelse(unit.in == "gC m-2", "g/m^2", ifelse(unit.in == "kgDM m-2", "kg/m^2", "kg/m^2")) if (length(unit.in) == 0) unit.ready <- "kg/m^2" Date.in <- Gdf %>% dplyr::filter(VARIABLE %>% grepl("DATE", .)) %>% dplyr::pull(DATAVALUE) %>% as.Date() if (length(Date.in) == 0) Date.in <- NA if (type == "*_BIOMASS") { Oregan.in <- Gdf %>% dplyr::filter(VARIABLE %>% grepl("ORGAN", .)) %>% dplyr::pull(DATAVALUE) PlantWoodIni <- udunits2::ud.convert(Gdf$DATAVALUE[1]%>% as.numeric()*cov.factor, unit.ready, "kg/m^2") } else if (type == "*SOIL") { val <- Gdf %>% dplyr::filter(VARIABLE %>% grepl("SOIL_STOCK_C_ORG", .)) %>% dplyr::pull(DATAVALUE) %>% as.numeric() if (length(val) > 0) SoilIni <- udunits2::ud.convert(val*cov.factor, "g/m^2", "kg/m^2") } else if (type == "*_LIT_BIOMASS") { litterIni <- udunits2::ud.convert(Gdf$DATAVALUE[1] %>% as.numeric()*cov.factor, unit.ready, "kg/m^2") } else if (type == "*_ROOT_BIOMASS") { Rootini <- udunits2::ud.convert(Gdf$DATAVALUE[1]%>% as.numeric()*cov.factor, unit.ready, "kg/m^2") } return( data.frame( Site = Gdf$SITE_ID %>% unique(), Var = Gdf$VARIABLE[1], Date = Date.in, Organ = Oregan.in, AGB = PlantWoodIni, soil_organic_carbon_content = SoilIni, litter_carbon_content = litterIni ) ) }) ind <- apply(entries[,5:7], 1, function(x) all(is.na(x))) entries <- entries[-which(ind),] return(entries) } netcdf.writer.BADM <- function(lat, long, siteid, outdir, ens){ entries <- Read.IC.info.BADM (lat, long) input <- list() dims <- list(lat = lat , lon = long, time = 1) PWI <- entries$AGB[!is.na(entries$AGB)] LIn <- entries$litter_carbon_content[!is.na(entries$litter_carbon_content)] SIn <- entries$soil_organic_carbon_content[!is.na(entries$soil_organic_carbon_content)] variables <- list(SoilMoistFrac = 1, SWE = 0) if (length(PWI) > 0) variables <- c(variables, wood_carbon_content = sample(PWI, 1, replace = T)) if (length(LIn) > 0) variables <- c(variables, litter_carbon_content = sample(LIn, 1, replace = T)) if (length(SIn) > 0) variables <- c(variables, soil_organic_carbon_content = sample(SIn, 1, replace = T)) input$dims <- dims input$vals <- variables return(pool_ic_list2netcdf( input = input, outdir = outdir, siteid = siteid, ens )$file) } BADM_IC_process <- function(settings, dir, overwrite=TRUE){ new.site <- data.frame( id = settings$run$site$id %>% as.numeric(), lat = settings$run$site$lat , lon = settings$run$site$lon %>% as.numeric() ) out.ense <- seq_len(settings$ensemble$size) %>% purrr::map(~ netcdf.writer.BADM(new.site$lat, new.site$lon, new.site$id, outdir=dir, ens=.x)) out.ense <- out.ense %>% stats::setNames(rep("path", length(out.ense))) return(out.ense) } EPA_ecoregion_finder <- function(Lat, Lon){ U.S.SB.sp <- data.frame(Lati = Lat %>% as.numeric(), Long = Lon %>% as.numeric()) sp::coordinates(U.S.SB.sp) <- ~ Long + Lati L1 <- sf::read_sf(system.file("data","eco-region.json", package = "PEcAn.data.land")) %>% sf::st_set_crs( "+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs" ) %>% sf::st_transform("+proj=longlat +datum=WGS84") L2 <- sf::read_sf(system.file("data","eco-regionl2.json", package = "PEcAn.data.land")) %>% sf::st_set_crs( "+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs" ) %>% sf::st_transform("+proj=longlat +datum=WGS84") sp::proj4string(U.S.SB.sp) <- sp::proj4string(sf::as_Spatial(L1)) over.out.L1 <- sp::over(U.S.SB.sp, sf::as_Spatial(L1)) over.out.L2 <- sp::over(U.S.SB.sp, sf::as_Spatial(L2)) return(data.frame(L1 = over.out.L1$NA_L1CODE, L2 = over.out.L2$NA_L2CODE)) }
df1 <- data.frame(x = rnorm(100), y = rnorm(100)) df2 <- data.frame(x = rnorm(100), y = rnorm(100)) df3 <- data.frame(x = rnorm(100), y = rnorm(100)) df4 <- data.frame(x = rnorm(100), y = rnorm(100)) mylist <- list(df1, df2, df3, df4) resultDF <- mylist[[1]] for (i in 2:4) resultDF <- rbind(resultDF, mylist[[i]]) resultDF2 <- rbind( mylist[[1]], mylist[[2]], mylist[[3]], mylist[[4]]) resultDF3 <- do.call("rbind", mylist) all.equal( resultDF2, resultDF3) m <- 4 nr <- nrow(df1) nc <- ncol(df1) resultDF4 <- as.data.frame(matrix(0, nrow = nr*m, ncol = nc)) for (j in 1:m) resultDF4[(((j-1)*nr) + 1):(j*nr), ] <- mylist[[j]] library("plyr") resultDF5 <- ldply(mylist, rbind) all.equal(resultDF, resultDF5) resultDF6 <- rbind.fill(mylist) all.equal(resultDF, resultDF6) mylist2 <- lapply(mylist, as.matrix) matrixDoCall <- do.call("rbind", mylist2) all.equal(as.data.frame(matrixDoCall), resultDF) phony <- function(i){ data.frame(w = rnorm(1000), x = rnorm(1000), y = rnorm(1000), z = rnorm(1000)) } mylist <- lapply(1:1000, phony) resultDF <- mylist[[1]] system.time( for (i in 2:1000) resultDF <- rbind(resultDF, mylist[[i]]) ) system.time( resultDF3 <- do.call("rbind", mylist) ) all.equal(resultDF, resultDF3) m <- length(mylist) nr <- nrow(mylist[[1]]) nc <- ncol(mylist[[1]]) system.time( resultDF4 <- as.data.frame(matrix(0, nrow = nr*m, ncol = nc)) ) colnames(resultDF4) <- colnames(mylist[[1]]) system.time( for (j in 1:m) resultDF4[(((j-1)*nr) + 1):(j*nr), ] <- mylist[[j]] ) all.equal(resultDF, resultDF4) mylist2 <- lapply(mylist, as.matrix) m <- length(mylist2) nr <- nrow(mylist2[[1]]) nc <- ncol(mylist2[[1]]) system.time( resultDF4B <- matrix(0, nrow = nr*m, ncol = nc) ) colnames(resultDF4B) <- colnames(mylist[[1]]) system.time( for (j in 1:m) resultDF4B[(((j-1)*nr) + 1):(j*nr), ] <- mylist2[[j]] ) all.equal(resultDF, as.data.frame(resultDF4B)) system.time( resultDF5 <- ldply(mylist, rbind)) all.equal(resultDF, resultDF5) system.time(resultDF6 <- rbind.fill(mylist)) all.equal(resultDF, resultDF6) system.time(matrixDoCall <- do.call("rbind", mylist2) ) all.equal(as.data.frame(matrixDoCall), resultDF)
rels = function(path) UseMethod("rels") rels.path = function(path) { urls = attr(path, "relationships") FUN <- function(x) { url = x result = http_request(url, "GET") rel = configure_result(result) return(rel) } rels = lapply(urls, FUN) return(rels) }
tau3scen2<- function(X, digits = 3) { nn <- dim(X) ni <- nn[1] ui <- rep(1, ni) nj <- nn[2] nk <- nn[3] n <- sum(X) p3 <- X/n if(length(dim(X)) != 3) stop("X is not a three-way table \n") pi <- apply(p3, 1, sum) pj <- apply(p3, 2, sum) pk <- apply(p3, 3, sum) pijk <- pi %o% pj %o% pk p1jk <- ui %o% pj %o% pk devt <- 1 - sum(pi^2) tau3 <- sum(((p3 - pijk)^2/p1jk)) itau3 <- tau3/devt pij <- apply(p3, c(1, 2), sum) pik <- apply(p3, c(1, 3), sum) pjk <- apply(p3, c(2, 3), sum) p1j <- ui %o% pj p1k <- ui %o% pk p2ij <- pi %o% pj p2ik <- pi %o% pk tauij <- sum(((pij - p2ij)^2/p1j)) itauij <- tauij/devt tauik <- sum(((pik - p2ik)^2/p1k)) itauik <- tauik/devt khjk <- 1/ni * (sum((pjk - (pj %o% pk))^2/(pj %o% pk))) ikhjk<-khjk/devt khin3 <- tau3 - tauij - tauik - khjk ikhin3 <-khin3/devt nom <- c("IJ", "IK", "JK", "IJK", "M") x <- c(tauij, tauik, khjk, khin3, tau3) y <- (100 * x)/tau3 dres<-(ni-1)*(nj-1)*(nk-1) dij<-(ni-1)*(nj-1) dik<-(ni-1)*(nk-1) djk<-(nj-1)*(nk-1) dtot<-dij+dik+djk+dres CM <- (n - 1) *(ni-1)* itau3 Cij<-(n-1)*(ni-1)*itauij Cik<-(n-1)*(ni-1)*itauik Cjk<-(n-1)*(ni-1)*ikhjk Cijk<-(n-1)*(ni-1)*ikhin3 zz <- c(itauij, itauik, ikhjk, ikhin3,itau3) zz2<-c(Cij,Cik,Cjk,Cijk,CM) zz3<-c(dij,dik,djk,dres,dtot) pvalue= 1 - pchisq(zz2, zz3) z <- rbind(x, zz,y,zz2,zz3,pvalue) nomr <- c("Numerator","Index", "% of Inertia","C-statistic","df","p-value") dimnames(z) <- list(nomr, nom) z<-round(z,digits=digits) list(z=z) }
RelTableModel <- function(l){ tableInfo <- c( "tableName", "fields", "primaryKey", "foreignKeys", "indexes", "display" ) fieldInfo <- c("name", "type", "nullable", "unique", "comment") stopifnot( all(tableInfo %in% names(l)), all(names(l) %in% tableInfo), is.character(l$tableName), length(l$tableName)==1, !is.na(l$tableName), is.data.frame(l$fields), all(fieldInfo %in% colnames(l$fields)), all(colnames(l$fields) %in% fieldInfo), is.character(l$fields$name), all(!is.na(l$fields$name)), !any(duplicated(l$fields$name)), is.character(l$fields$type), all(!is.na(l$fields$type)), is.logical(l$fields$nullable), all(!is.na(l$fields$nullable)), is.logical(l$fields$unique), all(!is.na(l$fields$unique)), is.character(l$fields$comment), is.null(l$primaryKey) || is.character(l$primaryKey), all(!is.na(l$primaryKey)), all(l$primaryKey %in% l$fields$name) ) for( att in setdiff( names(attributes(l$fields)), c("row.names", "names", "class") ) ){ attr(l$fields, att) <- NULL } l$fields <- dplyr::as_tibble(l$fields) %>% dplyr::select(c("name", "type", "nullable", "unique", "comment")) %>% dplyr::mutate("comment"=as.character( ifelse(is.na(.data$comment), "", .data$comment) )) l$primaryKey <- sort(l$primaryKey) if(length(l$primaryKey)==1){ l$fields[ which(l$fields$name==l$primaryKey), "unique" ] <- TRUE } if(any(l$fields$type %in% c("row", "column"))){ if(!all(c("row", "column") %in% l$fields$type)){ stop("Both row and column should be provided when modelling a matrix") } if(nrow(l$fields) !=3 ){ stop("A matrix model should have 3 and only 3 fields") } if(length(unique(l$fields$type)) != 3){ stop(paste( "A matrix model should have 3 fields": "2 of types 'row' and 'column' and the 3rd of your choice" )) } rcfields <- l$fields %>% dplyr::filter(.data$type %in% c("row", "column")) if(any(rcfields$nullable)){ stop("Matrix row and column cannot be nullable") } if(any(rcfields$unique)){ stop(paste( "The combination of row and column is unique (primary key)", " but not row names and column names independently" )) } l$primaryKey <- rcfields$name if(setdiff(l$fields$type, c("row", "column"))=="base64"){ stop("A matrix cannot store base64 documents") } check_types(setdiff(l$fields$type, c("row", "column"))) }else{ check_types(l$fields$type) } if(!is.null(l$foreignKeys)){ stopifnot(is.list(l$foreignKeys)) fkn <- c("refTable", "key") l$foreignKeys <- lapply( l$foreignKeys, function(fko){ fk <- fko[fkn] stopifnot( all(names(fk) %in% fkn), all(fkn %in% names(fk)), !is.na(fk$refTable), is.character(fk$refTable), length(fk$refTable)==1, !is.na(fk$refTable), is.data.frame(fk$key), all(c("from", "to") %in% names(fk$key)), all(names(fk$key) %in% c("from", "to")), is.character(fk$key$from), all(!is.na(fk$key$from)), is.character(fk$key$to), all(!is.na(fk$key$to)), all(fk$key$from %in% l$fields$name) ) for( att in setdiff( names(attributes(fk$key)), c("row.names", "names", "class") ) ){ attr(fk$key, att) <- NULL } fk$key <- dplyr::as_tibble(fk$key) cnames <- c("fmin", "fmax", "tmin", "tmax") if("cardinality" %in% names(fko)){ stopifnot( is.integer(fko$cardinality), length(fko$cardinality)==4, all( cnames %in% names(fko$cardinality) ), all(!is.na(fko$cardinality)), all(fko$cardinality >= -1), fko$cardinality["fmin"] > -1, fko$cardinality["tmin"] > -1, fko$cardinality["fmax"]==-1 || ( fko$cardinality["fmax"] > 0 && fko$cardinality["fmax"] >= fko$cardinality["fmin"] ), fko$cardinality["tmax"]==-1 || ( fko$cardinality["tmax"] > 0 && fko$cardinality["tmax"] >= fko$cardinality["tmin"] ) ) fk$cardinality <- fko$cardinality[cnames] }else{ fk$cardinality <- c(0, -1, 1, 1) names(fk$cardinality) <- cnames } return(fk) } ) names(l$foreignKeys) <- NULL } if(!is.null(l$indexes)){ stopifnot(is.list(l$indexes)) idn <- c("fields", "unique") l$indexes <- lapply( l$indexes, function(ind){ stopifnot( is.list(ind), all(names(ind) %in% idn), all(idn %in% names(ind)), is.character(ind$fields), all(!is.na(ind$fields)), is.logical(ind$unique), all(!is.na(ind$unique)), length(ind$unique)==1, all(ind$fields %in% l$fields$name) ) ind$fields <- sort(unique(ind$fields)) return(ind) } ) } if(!is.null(l$display)){ stopifnot(is.list(l$display)) dn <- c("x", "y", "color", "comment") stopifnot( all(names(l$display) %in% dn), all(dn %in% names(l$display)), is.numeric(l$display$x), is.numeric(l$display$y), is.character(l$display$color), is.character(l$display$comment), all(unlist(lapply(l$display, length))==1) ) } toRet <- l class(toRet) <- c("RelTableModel", class(toRet)) toRet <- correct_constraints(toRet) return(toRet) } is.RelTableModel <- function(x){ inherits(x, "RelTableModel") } is.MatrixModel <- function(x){ inherits(x, "RelTableModel") && "row" %in% x$fields$type } format.RelTableModel <- function(x, ...){ f <- x$fields pk <- x$primaryKey it <- index_table(x) ind <- NULL if(!is.null(it)){ it <- it %>% dplyr::filter(.data$index!=0) ind <- unique(it$field) } f$i <- unlist(lapply( f$name, function(n){ paste(sort(it$index[which(it$field==n)]), collapse=",") } )) toRet <- paste0( sprintf( "Table name: %s%s", x$tableName, ifelse(is.MatrixModel(x), " (matrix)", "") ), "\n", paste( apply( f, 1, function(y){ toRet <- " " toRet <- paste0( toRet, ifelse(y[1] %in% pk, "*", " "), ifelse(y[4]=="TRUE" & !y[1] %in% pk, "+ ", " "), y[1] ) toRet <- paste0( toRet, " (", y[2], ifelse( y[1] %in% ind, paste0(", idx.", y[6]), "" ), ifelse(y[3]=="FALSE", ", not", ","), " nullable", ")" ) return(toRet) } ), collapse="\n" ) ) if(length(x$foreignKeys)>0){ toRet <- paste0( toRet, "\n", "Referenced tables:\n", paste(unlist(lapply( x$foreignKeys, function(y){ y$refTable } )), collapse="\n") ) } return(toRet) } print.RelTableModel <- function(x, ...){ cat(format(x, ...), "\n") } length.RelTableModel <- function(x){ nrow(x$fields) } lengths.RelTableModel <- function(x, use.names=TRUE){ lengths(unclass(x), use.names=use.names) } index_table <- function(x){ stopifnot(is.RelTableModel(x)) pk <- x$primaryKey ind <- x$indexes toRet <- NULL i <- 0 if(length(pk)>0){ toRet <- dplyr::tibble( index=i, field=pk, uniqueIndex=TRUE ) } for(ci in ind){ i <- i+1 toRet <- dplyr::bind_rows( toRet, dplyr::tibble( index=i, field=ci$fields, uniqueIndex=ci$unique ) ) } return(toRet) } col_types <- function(x){ stopifnot(is.RelTableModel(x)) do.call( readr::cols, structure( lapply( x$fields$type, function(y){ switch( y, "row"=readr::col_character(), "column"=readr::col_character(), "integer"=readr::col_integer(), "numeric"=readr::col_double(), "logical"=readr::col_logical(), "character"=readr::col_character(), "Date"=readr::col_date(), "POSIXct"=readr::col_datetime(), "base64"=readr::col_character() ) } ), .Names=x$fields$name ) ) } correct_constraints <- function(x){ stopifnot(is.RelTableModel(x)) if(length(x$primaryKey)==1){ x$fields[which(x$fields$name==x$primaryKey), "unique"] <- TRUE x$fields[which(x$fields$name==x$primaryKey), "nullable"] <- FALSE } if(length(x$primaryKey)>0){ ei <- lapply( x$indexes, function(y){ identical(sort(y$fields), sort(x$primaryKey)) } ) %>% unlist() %>% as.logical() %>% which() if(length(ei)>1) stop("Check this part of code") if(length(ei)==0){ x$indexes <- unique(c( x$indexes, list( list( fields=sort(x$primaryKey), unique=TRUE ) ) )) }else{ x$indexes[[ei]]$unique <- TRUE } } if(length(x$indexes)>0){ for(i in 1:length(x$indexes)){ if(x$indexes[[i]]$unique && length(x$indexes[[i]]$fields)==1){ if( x$fields[ which(x$fields$name==x$indexes[[i]]$fields), "type" ] %in% c("row", "column") ){ stop("Matrix row and column cannot be unique individually") } x$fields[ which(x$fields$name==x$indexes[[i]]$fields), "unique" ] <- TRUE } } } uniqueFields <- x$fields %>% dplyr::filter(.data$unique) %>% dplyr::pull("name") if(length(x$indexes)>0 && length(uniqueFields)>0){ for(i in 1:length(x$indexes)){ if(any(x$indexes[[i]]$fields %in% uniqueFields)){ x$indexes[[i]]$unique <- TRUE } } } return(x) } confront_table_data <- function( x, d, checks=c("unique", "not nullable") ){ if(length(checks)>0){ checks <- match.arg( checks, c("unique", "not nullable"), several.ok=TRUE ) } stopifnot(is.RelTableModel(x)) if(is.MatrixModel(x)){ vf <- x$fields %>% dplyr::filter(!.data$type %in% c("row", "column")) toRet <- list( missingFields = character(0), suppFields = character(0), availableFields = vf$name, fields=list(), success=TRUE ) toRet$fields[[vf$name]] <- list(success=TRUE, message=NULL) if(!inherits(d[1], vf$type)){ toRet$fields[[vf$name]]$success <- FALSE toRet$success <- FALSE toRet$fields[[vf$name]]$message <- paste(c( toRet$fields[[vf$name]]$message, sprintf( 'Unexpected "%s"', paste(class(d[1]), collapse=", ") ) ), collapse=" ") } if("not nullable" %in% checks){ mis <- sum(is.na(d)) if(mis!=0){ toRet$fields[[vf$name]]$message <- paste(c( toRet$fields[[vf$name]]$message, sprintf( 'Missing values %s/%s = %s%s', mis, length(d), round(mis*100/length(d)), "%" ) ), collapse=" ") if(!vf$nullable){ toRet$fields[[vf$name]]$success <- FALSE toRet$success <- FALSE } } } if("unique" %in% checks && vf$unique && any(duplicated(d))){ toRet$fields[[vf$name]]$success <- FALSE toRet$success <- FALSE toRet$fields[[vf$name]]$message <- paste(c( toRet$fields[[vf$name]]$message, "Some values are duplicated" ), collapse=" ") } return(toRet) } stopifnot( is.data.frame(d) ) missingFields <- setdiff(x$fields$name, colnames(d)) suppFields <- setdiff(colnames(d), x$fields$name) availableFields <- intersect(colnames(d), x$fields$name) toRet <- list( missingFields=missingFields, suppFields=suppFields, availableFields=availableFields, fields=list(), success=length(missingFields)==0 && length(suppFields)==0 ) for(fn in availableFields){ ft <- x$fields$type[which(x$fields$name==fn)] ft <- ifelse(ft %in% c("row", "column"), "character", ft) fe <- x$fields$nullable[which(x$fields$name==fn)] fu <- x$fields$unique[which(x$fields$name==fn)] toRet$fields[[fn]] <- list(success=TRUE, message=NULL) if(!inherits(dplyr::pull(d, !!fn), ft)){ if(ft!="base64" || !inherits(dplyr::pull(d, !!fn), "character")){ toRet$fields[[fn]]$success <- FALSE toRet$success <- FALSE toRet$fields[[fn]]$message <- paste(c( toRet$fields[[fn]]$message, sprintf( 'Unexpected "%s"', paste(class(dplyr::pull(d, !!fn)), collapse=", ") ) ), collapse=" ") } } if("not nullable" %in% checks){ mis <- sum(is.na(dplyr::pull(d, !!fn))) if(mis!=0){ toRet$fields[[fn]]$message <- paste(c( toRet$fields[[fn]]$message, sprintf( 'Missing values %s/%s = %s%s', mis, nrow(d), round(mis*100/nrow(d)), "%" ) ), collapse=" ") if(!fe){ toRet$fields[[fn]]$success <- FALSE toRet$success <- FALSE } } } if("unique" %in% checks && fu && any(duplicated(dplyr::pull(d, !!fn)))){ toRet$fields[[fn]]$success <- FALSE toRet$success <- FALSE toRet$fields[[fn]]$message <- paste(c( toRet$fields[[fn]]$message, "Some values are duplicated" ), collapse=" ") } } if("unique" %in% checks && length(x$indexes)>0){ toRet$indexes <- list() for(i in 1:length(x$indexes)){ toRet$indexes[[i]] <- list() idx <- x$indexes[[i]] if(any(idx$fields %in% missingFields)){ toRet$indexes[[i]]$success <- FALSE toRet$indexes[[i]]$message <- paste(c( toRet$indexes[[i]]$message, "Missing field" ), collapse=" ") toRet$success <- FALSE }else{ if(!idx$unique){ toRet$indexes[[i]]$success <- TRUE }else{ if(any(duplicated(d[,idx$fields]))){ toRet$indexes[[i]]$success <- FALSE toRet$indexes[[i]]$message <- paste(c( toRet$indexes[[i]]$message, "Some values are duplicated" ), collapse=" ") toRet$success <- FALSE }else{ toRet$indexes[[i]]$success <- TRUE } } } } } if("not nullable" %in% checks && is.MatrixModel(x)){ if(!"indexes" %in% names(toRet)){ toRet$indexes <- list() } i <- length(toRet$indexes)+1 rf <- x$fields %>% dplyr::filter(.data$type=="row") %>% dplyr::pull("name") cf <- x$fields %>% dplyr::filter(.data$type=="column") %>% dplyr::pull("name") fe <- x$fields %>% dplyr::filter(!.data$type %in% c("row", "column")) %>% dplyr::pull("nullable") ncells <- length(unique(d[,rf])) * length(unique(d[,cf])) mis <- ncells - nrow(d) if(mis > 0 ){ toRet$indexes[[i]]$message <- paste(c( toRet$indexes[[i]]$message, sprintf( 'Missing cells %s/%s = %s%s', mis, ncells, round(mis*100/ncells), "%" ) ), collapse=" ") if(!fe){ toRet$indexes[[i]]$success <- FALSE toRet$success <- FALSE } } } return(toRet) } identical_RelTableModel <- function(x, y, includeDisplay=TRUE){ stopifnot(is.RelTableModel(x), is.RelTableModel(y)) toRet <- x$tableName==y$tableName toRet <- toRet && identical( x$fields %>% dplyr::arrange(.data$name), y$fields %>% dplyr::arrange(.data$name) ) toRet <- toRet && length(x$primaryKey)==length(y$primaryKey) && all(x$primaryKey==y$primaryKey) toRet <- toRet && length(x$indexes)==length(y$indexes) if(toRet && length(x$indexes)>0){ xidx <- lapply( x$indexes, function(z){ z$fields <- sort(z$fields) return(z) } ) xidx <- xidx[order(unlist(lapply( xidx, function(z) paste(z$fields, collapse=", ") )))] yidx <- lapply( y$indexes, function(z){ z$fields <- sort(z$fields) return(z) } ) yidx <- yidx[order(unlist(lapply( yidx, function(z) paste(z$fields, collapse=", ") )))] toRet <- identical(xidx, yidx) } toRet <- toRet && length(x$foreignKeys)==length(y$foreignKeys) if(toRet && length(x$foreignKeys)>0){ xfk <- lapply( x$foreignKeys, function(z){ z$key <- z$key %>% dplyr::arrange(.data$from, .data$to) return(z) } ) xfk <- xfk[order(unlist(lapply( xfk, function(z){ paste0( z$refTable, " [", paste( paste(z$key$from, z$key$to, sep="->"), collapse=", " ), "]" ) } )))] yfk <- lapply( y$foreignKeys, function(z){ z$key <- z$key %>% dplyr::arrange(.data$from, .data$to) return(z) } ) yfk <- yfk[order(unlist(lapply( yfk, function(z){ paste0( z$refTable, " [", paste( paste(z$key$from, z$key$to, sep="->"), collapse=", " ), "]" ) } )))] toRet <- identical(xfk, yfk) } if(includeDisplay){ toRet <- toRet && length(x$display)==length(y$display) && (length(x$display)==0 || identical( x$display[order(names(x$display))], y$display[order(names(y$display))] )) } return(toRet) } get_foreign_keys.RelTableModel <- function(x){ tn <- x$tableName fk <- x$foreignKeys if(length(fk)==0){ return(NULL) } toRet <- do.call(rbind, lapply( fk, function(k){ to <- k$refTable kt <- k$key %>% dplyr::arrange(.data$from, .data$to) dplyr::tibble( to=to, ff=list(kt$from), tf=list(kt$to) ) %>% dplyr::bind_cols(dplyr::as_tibble(t(k$cardinality))) %>% return() } )) toRet %>% dplyr::mutate( from=tn ) %>% dplyr::select( "from", "ff", "to", "tf", "fmin", "fmax", "tmin", "tmax" ) %>% return() }
getTaxonTable <- function( taxonType = NA, recordReturnLimit = NA, stream = 'true', token = NA ){ options(stringsAsFactors = FALSE) requireNamespace('httr') requireNamespace('jsonlite') url_prefix = 'http://data.neonscience.org/api/v0/taxonomy?taxonTypeCode=' url_to_get <- as.character(paste0(url_prefix, taxonType)) if(!is.na(recordReturnLimit)) url_to_get <- paste0(url_to_get,'&limit=',recordReturnLimit) if(!is.na(stream)) url_to_get <- paste0(url_to_get,'&stream=',stream) req.df <- data.frame() req <- NULL req <- getAPI(apiURL = url_to_get, token = token) if(is.null(req)) { message(paste("No data were returned")) return(invisible()) } if (req$status_code == 204) { message(paste("No data are available")) return(invisible()) }else if (req$status_code == 413) { message(paste("Data GET failed with status code ", req$status_code, ": Payload Too Large. Query a smaller dataset.", sep = "")) return(invisible()) }else { if (req$status_code != 200) { message(paste("Data GET failed with status code ", req$status_code, ". Check the formatting of your inputs.", sep = "")) return(invisible()) } } if(!is.null(req)){ taxa_list <- jsonlite::fromJSON(httr::content(req, as='text', encoding="UTF-8")) taxa_table <- taxa_list$data names(taxa_table) <- gsub('.+?\\:','',names(taxa_table)) } return(taxa_table) }
caretStack <- function(all.models, ...){ predobs <- makePredObsMatrix(all.models) model <- train(predobs$preds, predobs$obs, ...) out <- list(models=all.models, ens_model=model, error=model$results) class(out) <- "caretStack" return(out) } predict.caretStack <- function( object, newdata=NULL, se=FALSE, level=0.95, return_weights=FALSE, na.action=na.omit, ...){ stopifnot(is(object$models, "caretList")) type <- extractModelTypes(object$models) preds <- predict(object$models, newdata=newdata, na.action=na.action) if(type == "Classification"){ out <- predict(object$ens_model, newdata=preds, na.action=na.action, ...) if(inherits(out, c("data.frame", "matrix"))){ est <- out[, getBinaryTargetLevel(), drop = TRUE] } else{ est <- out } } else{ est <- predict(object$ens_model, newdata=preds, ...) } if(se | return_weights){ imp <- varImp(object$ens_model)$importance weights <- imp$Overall weights[!is.finite(weights)] <- 0 weights <- weights / sum(weights) names(weights) <- row.names(imp) methods <- colnames(preds) for(m in setdiff(methods, names(weights))){ weights[m] <- 0 } } out <- est if(se){ if(!is.numeric(est)){ message("Standard errors not available.") out <- est } else{ weights <- weights[methods] std_error <- apply(preds, 1, wtd.sd, w = weights) std_error <- (qnorm(level) * std_error) out <- data.frame( fit = est, lwr = est - std_error, upr = est + std_error ) } } if(return_weights) { attr(out, "weights") <- weights } return(out) } is.caretStack <- function(object){ is(object, "caretStack") } summary.caretStack <- function(object, ...){ summary(object$ens_model) } print.caretStack <- function(x, ...){ base.models <- paste(names(x$models), collapse=", ") cat(sprintf("A %s ensemble of %s base models: %s", x$ens_model$method, length(x$models), base.models)) cat("\n\nEnsemble results:\n") print(x$ens_model) } plot.caretStack <- function(x, ...){ plot(x$ens_model, ...) } dotplot.caretStack <- function(x, data=NULL, ...){ dotplot(resamples(x$models), data=data, ...) }
adjOutl <- function(x, z = NULL, options = list()){ if (missing(x)) { stop("Input argument x is required.") } x <- data.matrix(x) if (!is.numeric(x)) { stop("The input argument x must be a numeric data matrix.") } n1 <- nrow(x) p1 <- ncol(x) if (n1 > sum(complete.cases(x))) { stop("Missing values in x are not allowed.") } if (is.null(z)) { z <- x } z <- data.matrix(z) if (!is.numeric(z)) { stop("The input argument z must be a numeric data matrix.") } n2 <- nrow(z) p2 <- ncol(z) if (p1 != p2) { stop("The data dimension has to be the same for x and z.") } if (n2 > sum(complete.cases(z))) { stop("Missing values in z are not allowed.") } if (is.null(options)) { options <- list() } if (!is.list(options)) { stop("options must be a list") } if ("type" %in% names(options)) { type <- options[["type"]] } else { type <- "Affine" } if ("ndir" %in% names(options)) { ndir <- options[["ndir"]] } else { ndir <- NULL } if ("seed" %in% names(options)) { seed <- options[["seed"]] } else { seed <- NULL } type.id <- match(type, c("Affine", "Rotation", "Shift"))[1] if (is.na(type.id)) { stop("The input parameter type must be one of: Affine, Rotation or Shift.") } if (is.null(ndir)) { if (type.id == 1) { ndir <- 250 * p1 } else if (type.id == 2) { ndir <- 250 * 20 } else { ndir <- 250 * 50 } } calc.all <- 0 if (is.numeric(ndir)) { if (ndir < 1) { stop("The number of directions must be a positive integer.") } if (type.id == 1) { ndir0 <- choose(n1, p1) if (ndir0 <= ndir) { ndir <- ndir0 calc.all <- 1 } } if (type.id == 2) { ndir0 <- choose(n1, 2) if (ndir0 <= ndir) { ndir <- ndir0 calc.all <- 1 } } } if (!is.numeric(ndir)) { if (ndir == "all") { if (type.id == 1) { ndir <- choose(n1, p1) calc.all <- 1 if (ndir > 1e7) { stop("ndir is larger than 1e7. Try a smaller value of ndir.") } } if (type.id == 2) { ndir <- choose(n1, 2) calc.all <- 1 if (ndir > 1e7) { stop("ndir is larger than 1e7. Try a smaller value of ndir.") } } if (type.id == 3) { stop("Cannot compute all directions for type Shift.") } } else stop("The input parameter ndir is not recognized.") } if (type.id == 1 & (n1 < (p1 + 1))) { stop("When type is affine, n should be larger than p.") } if (is.null(seed)) { seed <- 10 } if (!is.numeric(seed)) { stop("The seed must be a strictly positive integer.") } if (seed <= 0) { stop("The seed must be a strictly positive integer.") } tol <- 1e-7 scaled.x <- scale(x) temp <- attributes(scaled.x) column.sd <- temp[["scaled:scale"]] if (sum(column.sd <= 1e-14) > 0) { warning("One of the variables has zero standard deviation. Check the data matrix x.") returned.result <- list(outlyingnessX = NULL, outlyingnessZ = NULL, cutoff = NULL, flagX = NULL, flagZ = NULL, singularSubsets = NULL, dimension = sum(column.sd > 1e-14), hyperplane = as.numeric(column.sd <= 1e-14), inSubspace = NULL) class(returned.result) <- c("mrfDepth", "adjOutl") return(returned.result) } w1 <- try(svd(scaled.x / sqrt(n1 - 1)), silent = TRUE) if (!is.list(w1)) { warning("The singular-value decomposition of the data matrix x could not be computed.") returned.result <- list(outlyingnessX = NULL, outlyingnessZ = NULL, cutoff = NULL, flagX = NULL, flagZ = NULL, singularSubsets = NULL, dimension = NULL, hyperplane = NULL, inSubspace = NULL) class(returned.result) <- c("mrfDepth", "adjOutl") return(returned.result) } if (min(w1$d) < tol) { warning("An exact fit is found. Check the output for more details.") returned.result <- list(outlyingnessX = NULL, outlyingnessZ = NULL, cutoff = NULL, flagX = NULL, flagZ = NULL, singularSubsets = NULL, dimension = sum(w1$d > tol), hyperplane = w1$v[, which(w1$d == min(w1$d))[1]], inSubspace = NULL) class(returned.result) <- c("mrfDepth", "adjOutl") return(returned.result) } x <- rbind(x, z) n <- nrow(x) p <- ncol(x) result <- .C("adjprojout", as.integer(n), as.integer(p), as.integer(ndir), as.double(x), as.double(rep(0, n)), as.double(0), as.integer(0), as.integer(type.id), as.integer(n1), as.integer(calc.all), as.double(rep(0, p1)), as.integer(seed), PACKAGE = "mrfDepth") adj.outlyingness <- result[[5]] if (sum(abs(result[[11]])) > tol) { warning("A direction was found for which the robust scale estimate equals zero. See the help page for more details.", call. = FALSE) returned.result <- list(outlyingnessX = NULL, outlyingnessZ = NULL, cutoff = NULL, flagX = NULL, flagZ = NULL, singularSubsets = NULL, dimension = NULL, hyperplane = result[[11]], inSubspace = as.logical(adj.outlyingness[1:n1])) class(returned.result) <- c("mrfDepth", "adjOutl") return(returned.result) } LAO <- log(0.1 + adj.outlyingness[1:n1]) cutoff <- exp(median(LAO) + mad(LAO) * qnorm(0.995)) - 0.1 flag.X <- adj.outlyingness[1:n1] <= cutoff flag.Z <- adj.outlyingness[(n1 + 1):(n1 + n2)] <= cutoff returned.result <- list(outlyingnessX = adj.outlyingness[1:n1], outlyingnessZ = adj.outlyingness[(n1 + 1):(n1 + n2)], cutoff = cutoff, flagX = flag.X, flagZ = flag.Z, singularsubsets = result[[7]], dimension = NULL, hyperplane = NULL, inSubspace = NULL) class(returned.result) <- c("mrfDepth", "adjOutl") return(returned.result) }