code
stringlengths
1
13.8M
dCTS <- function(x, alpha, c=1, ell=1, mu=0){ if(c<= 0){ stop("c must be greater than 0") } if(ell<= 0){ stop("ell must be greater than 0") } if(alpha < 0 | alpha >= 2){ stop("alpha must be greater than or equal to 0 and less than or equal to 2") } if(alpha == 0){ result = .C(C_dCTS0, as.double(x), as.integer(length(x)), as.double(mu), as.double(alpha), as.double(c), as.double(ell), as.double(vector("double", length(x))))[[7]] if(c <= 0.5){ result[abs(x-mu)<.00001] = Inf } } else .C(C_dCTS, as.double(x), as.integer(length(x)), as.double(mu), as.double(alpha), as.double(c), as.double(ell), as.double(vector("double", length(x))))[[7]] } pCTS <- function(x, alpha, c=1, ell=1, mu=0){ if(c<= 0){ stop("c must be greater than 0") } if(ell<= 0){ stop("ell must be greater than 0") } if(alpha < 0 | alpha >= 2){ stop("alpha must be greater than or equal to 0 and less than or equal to 2") } .C(C_pCTS, as.double(x), as.integer(length(x)), as.double(mu), as.double(alpha), as.double(c), as.double(ell), as.double(vector("double", length(x))))[[7]] } qCTS <- function(x, alpha, c=1, ell=1, mu=0){ if(sum(x<=0)>0 | sum(x>=1)>0){ stop("x must be between 0 and 1") } if(c<= 0){ stop("c must be greater than 0") } if(ell<= 0){ stop("ell must be greater than 0") } if(alpha < 0 | alpha >= 2){ stop("alpha must be greater than or equal to 0 and less than or equal to 2") } .C(C_qCTS, as.double(x), as.integer(length(x)), as.double(mu), as.double(alpha), as.double(c), as.double(ell), as.double(vector("double", length(x))))[[7]] } dPowTS <- function(x, alpha, c=1, ell=1, mu=0){ if(c<= 0){ stop("c must be greater than 0") } if(ell<= 0){ stop("ell must be greater than 0") } if(alpha < 0 | alpha >= 2){ stop("alpha must be greater than or equal to 0 and less than or equal to 2") } if(alpha <= .01 & c <= 0.5*(1+ell)){ stop("when alpha is close to 0, c/(1+ell) must be greater than 0.5") } .C(C_dPowTS, as.double(x), as.integer(length(x)), as.double(mu), as.double(alpha), as.double(c), as.double(ell), as.double(vector("double", length(x))))[[7]] } pPowTS <- function(x, alpha, c=1, ell=1, mu=0){ if(c<= 0){ stop("c must be greater than 0") } if(ell<= 0){ stop("ell must be greater than 0") } if(alpha < 0 | alpha >= 2){ stop("alpha must be greater than or equal to 0 and less than or equal to 2") } .C(C_pPowTS, as.double(x), as.integer(length(x)), as.double(mu), as.double(alpha), as.double(c), as.double(ell), as.double(vector("double", length(x))))[[7]] } qPowTS <- function(x, alpha, c=1, ell=1, mu=0){ if(sum(x<=0)>0 | sum(x>=1)>0){ stop("x must be between 0 and 1") } if(c<= 0){ stop("c must be greater than 0") } if(ell<= 0){ stop("ell must be greater than 0") } if(alpha < 0 | alpha >= 2){ stop("alpha must be greater than or equal to 0 and less than or equal to 2") } .C(C_qPowTS, as.double(x), as.integer(length(x)), as.double(mu), as.double(alpha), as.double(c), as.double(ell), as.double(vector("double", length(x))))[[7]] } dSaS <- function(x, alpha, c=1, mu=0){ if(c<= 0){ stop("c must be greater than 0") } if(alpha <= 0 | alpha >= 2){ stop("alpha must be greater than 0 and less than 2") } if(alpha == 1) dcauchy(x, location = mu, scale = c) else .C(C_dSaS, as.double(x), as.integer(length(x)), as.double(mu), as.double(alpha), as.double(c), as.double(vector("double", length(x))))[[6]] } pSaS <- function(x, alpha, c=1, mu=0){ if(c<= 0){ stop("c must be greater than 0") } if(alpha <= 0 | alpha >= 2){ stop("alpha must be greater than 0 and less than 2") } if(alpha == 1) pcauchy(x, location = mu, scale = c) else .C(C_pSaS, as.double(x), as.integer(length(x)), as.double(mu), as.double(alpha), as.double(c), as.double(vector("double", length(x))))[[6]] } qSaS <- function(x, alpha, c=1, mu=0){ if(sum(x<=0)>0 | sum(x>=1)>0){ stop("x must be between 0 and 1") } if(c<= 0){ stop("c must be greater than 0") } if(alpha <= 0 | alpha >= 2){ stop("alpha must be greater than 0 and less than 2") } if(alpha == 1) qcauchy(x, location = mu, scale = c) else .C(C_qSaS, as.double(x), as.integer(length(x)), as.double(mu), as.double(alpha), as.double(c), as.double(vector("double", length(x))))[[6]] } rPowTS <- function(r, alpha, c=1, ell=1, mu=0){ qPowTS(runif(r), alpha, c, ell, mu) } rCTS <- function(r, alpha, c=1, ell=1, mu=0){ qCTS(runif(r), alpha, c, ell, mu) } rSaS <- function(r, alpha, c=1, mu=0){ g <- runif(r)*pi-pi/2 W <- rexp(r) c^(1/alpha) * sin(alpha*g) * (cos(g))^(-1/alpha) *(cos((1-alpha)*g)/W)^(-1+1/alpha) + mu }
test_that("Generate Basic MSPE Plot", { skip_on_cran() suppressPackageStartupMessages(library(Synth)) data(synth.data) set.seed(42) dataprep.out<- dataprep( foo = synth.data, predictors = c("X1", "X2", "X3"), predictors.op = "mean", dependent = "Y", unit.variable = "unit.num", time.variable = "year", special.predictors = list( list("Y", 1991, "mean"), list("Y", 1985, "mean"), list("Y", 1980, "mean") ), treatment.identifier = 7, controls.identifier = c(29, 2, 13, 17, 32, 38), time.predictors.prior = c(1984:1989), time.optimize.ssr = c(1984:1990), unit.names.variable = "name", time.plot = 1984:1996 ) synth.out <- synth(dataprep.out) tdf<-generate.placebos(dataprep.out, synth.out, Sigf.ipop = 2) output <- plot_placebos(tdf) expect_true("ggplot" %in% class(output)) })
findwtdinteraction <- function(x, across, by=NULL, at=NULL, acrosslevs=NULL, bylevs=NULL, atlevs=NULL, weight=NULL, dvname=NULL, acclevnames=NULL, bylevnames=NULL, atlevnames=NULL, stdzacross=FALSE, stdzby=FALSE, stdzat=FALSE, limitlevs=20, type="response", approach="prototypical", data=NULL, nsim=100){ UseMethod("findwtdinteraction") }
NULL .onLoad <- function(libname, pkgname) { } .onAttach <- function(libname, pkgname) { }
`print.smacofSP` <- function(x,...) { cat("\nCall: ") print(x$call) cat("\n") cat("Model:",x$model,"\n") cat("Number of objects:",x$nobj,"\n") cat("\nStress-1 value:",round(x$stress,3),"\n") cat("Number of iterations:",x$niter,"\n") cat("\n") }
test_that("counts are as expected", { fruit <- c("apple", "banana", "pear", "pineapple") expect_equal(str_count(fruit, "a"), c(1, 3, 1, 1)) expect_equal(str_count(fruit, "p"), c(2, 0, 1, 3)) expect_equal(str_count(fruit, "e"), c(1, 0, 1, 2)) expect_equal(str_count(fruit, c("a", "b", "p", "n")), c(1, 1, 1, 1)) }) test_that("uses tidyverse recycling rules", { expect_error(str_count(1:2, 1:3), class = "vctrs_error_incompatible_size") })
summary.slca <- function( object, file=NULL, ... ) { osink( file=file, suffix=paste0( "__SUMMARY.Rout") ) display <- cdm_summary_display() cat(display) cdm_print_summary_package(pack="CDM") cat("\n") cdm_print_summary_call(object=object) cdm_print_summary_computation_time(object=object) cat("Structured Latent Class Analysis - Function 'slca' \n") modeltype <- object$irtmodel cat( " ", object$N, "Cases, ", object$I, "Items, ", object$G, "Group(s)", ",", object$TP, "Skill classes\n") cat("\n **** Check carefully the number of parameters and identifiability of the model. ***\n") if (object$G > 1 ){ cat("\nGroup statistics\n") print( object$group.stat ) } cat(display) cat( "Number of iterations=", object$iter, "\n" ) if ( ! object$converged ){ cat("Maximum number of iterations was reached.\n") } cat( "Iteration with minimal deviance","=", object$iter.min, "\n" ) cat( "\nDeviance","=", round( object$deviance, 2 ), " | " ) cat( "Log Likelihood","=", round( -object$deviance/2, 2 ), "\n" ) cat( "Penalty","=", round( object$regular_penalty, 2 ), "\n" ) cat( "Number of persons","=", object$ic$n, "\n" ) cat( "Number of estimated parameters","=", object$ic$np, "\n" ) cat( " Number of estimated lambda parameters","=", object$ic$itempars, "\n" ) cat( " Number of non-active lambda parameters","=", object$ic$nonactive, "\n" ) cat( " Number of estimated distribution parameters","=", object$ic$traitpars, "\n\n" ) cat( "Regularization","=", object$regularization, "\n" ) cat( " Regularization method","=", object$regular_type, "\n" ) cat( " Regularization parameter lambda","=", object$regular_lam, "\n\n" ) cdm_print_summary_information_criteria(object=object) cat(display) cat("Xlambda Parameters \n") obji <- object$Xlambda cdm_print_summary_data_frame(obji, digits=3) cat(display) cat("Conditional Item Probabilities \n") obji <- object$item cdm_print_summary_data_frame(obji, from=3, digits=3) cat(display) cat("Skill Class Parameters \n") obji <- object$delta cdm_print_summary_data_frame(obji, digits=3) cat(display) cat("Skill Class Probabilities \n") obji <- object$pi.k cdm_print_summary_data_frame(obji, digits=4) csink( file=file ) }
nAuditAttr <- function(TolRate = 0.05, AccDev, CL, N = 5000){ if(N <= 0) stop("N must be positive.\n") if(TolRate <= 0 | TolRate >= 1) stop("Tolerable rate of deviation must be between 0 and 1.\n") if(AccDev < 0) stop("The acceptable number of deviations must be positive.\n") if(CL <= 0 | CL >= 1) stop("Confidence level must be between 0 and 1.\n") n.sam <- 1:N K <- ceiling(N * TolRate) cdf <- phyper(q=AccDev, m=K, n=N-K, k=n.sam) if (any(cdf <= 1 - CL)) {min.nhyper <- min(n.sam[cdf <= 1 - CL])} else {min.nhyper <- NA} cdf <- pbinom(q=AccDev, size=n.sam, prob=TolRate) if (any(cdf <= 1 - CL)) {min.nbinom <- min(n.sam[cdf <= 1 - CL])} else {min.nbinom <- NA} list("Pop.Size" = N, "Tol.Dev.Rate" = TolRate, "Acceptable.Errors" = AccDev, "Sample.Size.Hypergeometric" = min.nhyper, "Sample.Size.Binomial" = min.nbinom ) }
plot.elect <- function(x,which=NULL,kernel="gaussian",col="red", lwd=2,cex.lab=1,...){ LEs <- x is.wholenumber <- function(x, tol = .Machine$double.eps^0.5){ abs(x - round(x)) < tol } gdim <- function(A){ sqA <- sqrt(A) fl.sqA <- floor(sqA) if(is.wholenumber(sqA)){ dims <- c(sqA,sqA) }else{ ind <- 1 dims <- c(fl.sqA, fl.sqA + ind) while( (fl.sqA * (fl.sqA+ind)) < A){ ind <- ind + 1 dims <- c(fl.sqA, fl.sqA + ind) } } return(dims) } if(LEs$S==0){ cat("\nNo simulated LEs so no plot. \n\n") } if(LEs$S > 0){ model <- LEs$model nstates <- nrow(model$Qmatrices$baseline) if(length(LEs$pnt)==((nstates-1)^2+nstates)){ if(is.null(which)){ if(nstates <= 4){ mfrow.dim <- c(nstates-1,nstates+1) }else{ mfrow.dim <- c(nstates-2,nstates+2) } opar <- par(mfrow=mfrow.dim, mex=0.8,mar=c(5,5,2,1)+.1) for(i in 1:((nstates-1)^2+nstates)){ plot(density(LEs$sim[,i],kernel=kernel),main=names(LEs$pnt[i]), ylab="density",xlab="years",col=col,lwd=lwd) } opar <- par(mfrow=c(1,1), mex= 1, mar=c(5, 4, 4, 2) + 0.1) } if(!is.null(which)){ mfrow.dim <- gdim(length(which)) opar <- par(mfrow=mfrow.dim, mex=0.8,mar=c(5,5,2,1)+.1) for(i in which){ plot(density(LEs$sim[,i],kernel=kernel),main=names(LEs$pnt[i]), ylab="density",xlab="years",col=col,lwd=lwd) } opar <- par(mfrow=c(1,1), mex= 1, mar=c(5, 4, 4, 2) + 0.1) } } } invisible(x) }
tabPanel('Independent Sample t', value = 'tab_indttest', fluidPage( fluidRow( column(6, align = 'left', h4('Independent Sample t Test'), p('Compare the means of two independent groups in order to determine whether there is statistical evidence that the associated population means are significantly different.') ), column(6, align = 'right', actionButton(inputId='indttest1', label="Help", icon = icon("question-circle"), onclick ="window.open('https://inferr.rsquaredacademy.com/reference/infer_ts_ind_ttest.html', '_blank')"), actionButton(inputId='indttest3', label="Demo", icon = icon("video-camera"), onclick ="window.open('https://www.youtube.com/watch?v=iKFFzv9WiUo', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Variable 1:')), column(4, align = 'left', selectInput("var_itest1", label = '', width = '200px', choices = "", selected = ""), bsTooltip("var_itest1", "Select a variable.", "left", options = list(container = "body"))), column(2, align = 'right', br(), h5('Variable 2:')), column(4, align = 'left', selectInput("var_itest2", label = '', width = '200px', choices = "", selected = ""), bsTooltip("var_itest2", "Select a variable.", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('alpha:')), column(4, align = 'left', numericInput('itest_conf', label = '', width = '200px', min = 0, value = 0.95, step = 0.01), bsTooltip("itest_conf", "Confidence Level", "bottom", options = list(container = "body"))), column(2, align = 'right', br(), h5('Alternative:')), column(4, align = 'left', selectInput('itest_type', '', width = '200px', choices = c("both", "less", "greater", "all"), selected = "both"), bsTooltip("itest_type", "Alternative hypothesis", "bottom", options = list(container = "body")) ) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_itest', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submitittest", "Click here to view t test result.", "bottom", options = list(container = "body")) ) ), fluidRow( br(), column(12, align = 'center', verbatimTextOutput('itest_out') ) ) ) )
kpPlotNames <- function(karyoplot, data=NULL, chr=NULL, x0=NULL, x1=x0, y0=NULL, y1=NULL, labels=NULL, position="left", ymax=NULL, ymin=NULL, r0=NULL, r1=NULL, data.panel=1, clipping=TRUE, ...) { if(missing(karyoplot)) stop("The parameter 'karyoplot' is required") if(!methods::is(karyoplot, "KaryoPlot")) stop("'karyoplot' must be a valid 'KaryoPlot' object") position <- match.arg(position, c("left", "right", "top", "bottom", "center")) if(length(data)==0 && length(chr)==0) return(invisible(karyoplot)) pp <- prepareParameters4("kpPlotNames", karyoplot=karyoplot, data=data, chr=chr, x0=x0, x1=x1, y0=y0, y1=y1, ymin=0, ymax=1, r0=0, r1=1, data.panel=data.panel, ...) if(length(pp$chr)==0) { invisible(karyoplot) } switch(position, left=kpText(karyoplot, chr=pp$chr, x=pp$x0, y=pp$y0+(pp$y1-pp$y0)/2, labels=labels, pos=2, ymin=ymin, ymax=ymax, r0=r0, r1=r1, clipping=clipping, data.panel=data.panel, ...), right=kpText(karyoplot, chr=pp$chr, x=pp$x1, y=pp$y0+(pp$y1-pp$y0)/2, labels=labels, pos=4, ymin=ymin, ymax=ymax, r0=r0, r1=r1, clipping=clipping, data.panel=data.panel, ...), top=kpText(karyoplot, chr=pp$chr, x=pp$x0+(pp$x1-pp$x0)/2, y=pp$y1, labels=labels, pos=3, ymin=ymin, ymax=ymax, r0=r0, r1=r1, clipping=clipping, data.panel=data.panel, ...), bottom=kpText(karyoplot, chr=pp$chr, x=pp$x0+(pp$x1-pp$x0)/2, y=pp$y0, labels=labels, pos=1, ymin=ymin, ymax=ymax, r0=r0, r1=r1, clipping=clipping, data.panel=data.panel, ...), center=kpText(karyoplot, chr=pp$chr, x=pp$x0+(pp$x1-pp$x0)/2, y=pp$y0+(pp$y1-pp$y0)/2, labels=labels, ymin=ymin, ymax=ymax, r0=r0, r1=r1, clipping=clipping, data.panel=data.panel, ...) ) invisible(karyoplot) }
library(logger) library(testthat) appender <- log_appender() log_appender(appender_stdout) context('helpers') test_that('separator', { original_layout <- log_layout() log_layout(layout_blank) expect_output(log_separator(), '={80,80}') log_layout(original_layout) expect_output(log_separator(separator = '-'), '---') expect_output(log_separator(), 'INFO') expect_output(log_separator(WARN), 'WARN') }) test_that('tictoc', { expect_output(log_tictoc(), 'timer') }) test_that('log with separator', { expect_output(log_with_separator(42), '===') logger <- layout_glue_generator(format = '{node}/{pid}/{namespace}/{fn} {time} {level}: {msg}') layout_original <- log_layout() log_layout(logger) expect_output(log_with_separator('Boo!', level = FATAL, width = 120), width = 120) log_layout(layout_original) }) test_that('log failure', { expect_output(log_failure("foobar"), NA) expect_output(try(log_failure(foobar), silent = TRUE), 'ERROR.*foobar') expect_error(log_failure('foobar'), NA) expect_match(capture.output(expect_error(log_failure(foobar))), 'not found') }) log_appender(appender)
fn_wr <- function(yor, dor, zor, ak) { n <- length(yor) o <- order(yor) oy <- yor[o] od <- dor[o] oz <- zor[o] zd1 <- which(oz == 0) zd2 <- which(oz == 1) n1 <- length(zd1) n2 <- length(zd2) z1 <- rep(1, n1) z2 <- rep(0, n2) y1 <- oy[zd1] y2 <- oy[zd2] d1 <- od[zd1] d2 <- od[zd2] yk1 <- n1:1 yk2 <- n2:1 ky <- n:1 x <- exp(-cumsum(od/ky)) xat1 <- x[zd1] xat2 <- x[zd2] yk2at1 <- rep(1, n1) for (ik in 1:n1) { yk2at1[ik] <- sum(y2 >= y1[ik]) } yk1at2 <- rep(1, n2) for (ik in 1:n2) { yk1at2[ik] <- sum(y1 >= y2[ik]) } f1 <- yk2at1/n f2 <- yk1at2/n los <- as.numeric(t(d2)%*%f2/n) win <- as.numeric(t(d1)%*%f1/n) wr <- los/win ph11 <- n/(yk2at1 + yk1) ph12 <- n/(yk2 + yk1at2) ph21 <- xat1 * ph11 ph22 <- xat2 * ph12 losp1 <- as.numeric(t(d2) %*% (ph12 * f2)/n) winp1 <- as.numeric(t(d1) %*% (ph11 * f1)/n) wrp1 <- losp1/winp1 losp2 <- as.numeric(t(d2) %*% (ph22 * f2)/n) winp2 <- as.numeric(t(d1) %*% (ph21 * f1)/n) wrp2 <- losp2/winp2 wrall <- c(wr, wrp1, wrp2) ff1 <- -wr * f1 ff2 <- f2 mhat <- fn_gmhat(d1, d2, zd1, zd2, ff1, ff2, yk1, yk2, n) stnd <- sqrt(mean(mhat^2))/win/sqrt(n) mhat0 <- mhat/win zva <- (wr - 1)/stnd qt <- (exp(wr)-1)/(exp(wr)+1) qt0 <- (exp(1)-1)/(exp(1)+1) tqt <- log(-log(qt)) tdif <- 2*exp(wr)/log(qt)/qt/(1+exp(wr))^2 zvat4 <- (tqt-log(-log(qt0)))/tdif/stnd pvalt <- mean(abs(ak) > abs(zvat4)) zvapvalt <- c(zvat4, pvalt) ff1 <- -wrp1 * f1 * ph11 ff2 <- f2 * ph12 mhat <- fn_gmhat(d1, d2, zd1, zd2, ff1, ff2, yk1, yk2, n) stndp1 <- sqrt(mean(mhat^2))/winp1/sqrt(n) mhatp10 <- mhat/winp1 zvap1 <- (wrp1-1)/stndp1 ff1 <- -wrp2 * f1 * ph21 ff2 <- f2* ph22 mhat <- fn_gmhat(d1, d2, zd1, zd2, ff1, ff2, yk1, yk2, n) stndp2 <- sqrt(mean(mhat^2))/winp2/sqrt(n) mhatp20 <- mhat/winp2 zvap2 <- (wrp2-1)/stndp2 stall <- c(stnd, stndp1, stndp2) zvaall <- c(zva, zvap1, zvap2) mhatph <- mhatp20 - mhatp10 stndph <- sqrt(mean(mhatph^2))/sqrt(n) zvaph <- (wrp2-wrp1)/stndph rk <- rep(0, n); for (i in 1:n) { rk[i] <- sum(yor[i] >= yor) } pval <- mean(abs(ak) > abs(zva)) pvalp1 <- mean(abs(ak) > abs(zvap1)) pvalp2 <- mean(abs(ak) > abs(zvap2)) pvalph <- mean(abs(ak) > abs(zvaph)) pvall <- c(pval, pvalp1, pvalp2) res <- list() res$wrall <- wrall res$zvaall <- zvaall res$stall <- stall res$zvaph <- zvaph res$zvat4 <- zvat4 res$stnd <- stnd res$tqt <- tqt res$tdif <- tdif res$mhat0 <- mhat0[rk] res$mhatp10 <- mhatp10[rk] res$mhatp20 <- mhatp20[rk] res$mhatph <- mhatph[rk] res$pval <- pval res$pvalp1 <- pvalp1 res$pvalp2 <- pvalp2 res$pvalph <- pvalph res$pvall <- pvall res }
subplot_K <- function(subnic, main=NULL, xlab=NULL, ylab=NULL, col.axis="azure3", lty.axis=2, lwd.axis=2, border.E="black", col.E=" lty.E=1, lwd.E=1, border.K ="black", col.K =" lty.K=1, lwd.K=1, col.Gk.pos= "red", col.Gk.pt= "black", cex.Gk.pos=1, pch.Gk.pos=21, col.Gk.lab="black", cex.Gk.lab= 0.8, fac.Gk.lab=1.5, col.su=" pt.su="black", cex.su=0.7, pch.su=1, leg=T, posi.leg="topleft", bty.leg="n", ...){ fac <- subnic$factor lev <- levels(fac) eig <- round(subnic$eig/sum(subnic$eig)*100,2)[1:2] if(is.null(xlab)){ xlab=paste(paste("OMI1",eig[1], sep=" "),"%",sep="")} if(is.null(ylab)){ ylab=paste(paste("OMI2",eig[2], sep=" "),"%",sep="")} N <- length(lev) plot(subnic$ls, main=main, xlab=xlab, ylab=ylab, type="n",...) E <- convexhull(subnic$ls[,1], subnic$ls[,2]) polygon(E$xcoords,E$ycoords, border=border.E, col=col.E, lty=lty.E, lwd=lwd.E) for (i in 1:N){ subnici <- subnic$ls[which(fac==lev[i]),] G_k <- subnic$G_k[grep(lev[i],rownames(subnic$G_k)),] K <- convexhull(subnici[,1], subnici[,2]) polygon(K$xcoords,K$ycoords, border=border.K, col=col.K, lty=lty.K, lwd=lwd.K) points(subnici,cex=cex.su, col=pt.su, bg=col.su, pch=pch.su) points(G_k[,1], G_k[,2], col=col.Gk.pt, bg=col.Gk.pos, pch=pch.Gk.pos, cex= cex.Gk.pos) if(!is.na(cex.Gk.lab)){ text(G_k[,1]*fac.Gk.lab, G_k[,2]*fac.Gk.lab, lev[i], col=col.Gk.lab, cex=cex.Gk.lab) } } M <- nrow(subnic$c1) abline(h=0, lty=lty.axis, lwd=lwd.axis, col=col.axis) abline(v=0, lty=lty.axis, lwd=lwd.axis, col=col.axis) if(isTRUE(leg)){ filli <- c(col.E, col.K, NA, NA) borderi <- c(border.E, border.K, NA, NA) col.leg <- c(NA,NA, col.Gk.pt, pt.su) col.bg <- c(NA,NA, col.Gk.pos,col.su) pch.leg <- c(NA,NA,pch.Gk.pos,pch.su) tex.leg <- c("E","K","GK","SU") lty.leg <- c(0,0,0,0) lwd.leg <- c(0,0,0,0) posi.cex <-c(NA,NA,1,1) if(is.na(col.E)){ filli[1] <- NA borderi[1] <- NA tex.leg[1] <- NA } if(is.na(col.K)){ filli[2] <- NA borderi[2] <- NA tex.leg[2] <- NA } if(anyNA(cex.Gk.pos)){ posi.cex[3] <- NA tex.leg[3] <- NA } if(anyNA(cex.su)){ posi.cex[3] <- NA tex.leg[3] <- NA } if(lty.E>1){ pch.leg[1] <- NA lty.leg[1] <- lty.E lwd.leg[1] <- lwd.E } if(lty.K>1){ pch.leg[2] <- NA lty.leg[2] <- lty.E lwd.leg[2] <- lwd.E } legend(posi.leg, legend=tex.leg,fill =filli, border=borderi, pch=pch.leg, col=col.leg, pt.cex = posi.cex, pt.bg=col.bg,lty=lty.leg,pt.lwd=c(NA,NA,1,1), lwd=lwd.leg, bty=bty.leg,...) } }
MLE.Frank.Pareto = function(t.event,event1,event2,Theta,Alpha1.0 = 1,Alpha2.0 = 1, Gamma1.0 = 1,Gamma2.0 = 1,epsilon = 1e-5,d = exp(10), r.1 = 6,r.2 = 6,r.3 = 6,r.4 = 6) { n = length(t.event) if (length(t.event[t.event < 0]) != 0) {stop("t.event must be non-negative")} if (length(event1) != n) {stop("the length of event1 is different from t.event")} if (length(event2) != n) {stop("the length of event2 is different from t.event")} if (length(event1[event1 == 0 | event1 == 1]) != n) {stop("elements in event1 must be either 0 or 1")} if (length(event2[event2 == 0 | event2 == 1]) != n) {stop("elements in event2 must be either 0 or 1")} temp.event = event1+event2 if (length(temp.event[temp.event == 2]) != 0) {stop("event1 and event2 cannot be 1 simultaneously")} if (Theta == 0) {stop("Theta cannot be zero")} if (Alpha1.0 <= 0) {stop("Alpha1.0 must be positive")} if (Alpha2.0 <= 0) {stop("Alpha2.0 must be positive")} if (Gamma1.0 <= 0) {stop("Alpha1.0 must be positive")} if (Gamma2.0 <= 0) {stop("Alpha2.0 must be positive")} if (epsilon <= 0) {stop("epsilon must be positive")} if (d <= 0) {stop("d must be positive")} if (r.1 <= 0) {stop("r.1 must be positive")} if (r.2 <= 0) {stop("r.2 must be positive")} if (r.3 <= 0) {stop("r.3 must be positive")} if (r.4 <= 0) {stop("r.3 must be positive")} log_L = function(par){ Alpha1 = exp(par[1]) Alpha2 = exp(par[2]) Gamma1 = exp(par[3]) Gamma2 = exp(par[4]) h1 = Alpha1*Gamma1/(1+Alpha1*t.event) h2 = Alpha2*Gamma2/(1+Alpha2*t.event) S1 = (1+Alpha1*t.event)^(-Gamma1) S2 = (1+Alpha2*t.event)^(-Gamma2) ST = -(1/Theta)*log(1+(exp(-Theta*S1)-1)*(exp(-Theta*S2)-1)/(exp(-Theta)-1)) f1 = h1*S1*exp(-Theta*S1)*(exp(-Theta*S2)-1)/((exp(-Theta)-1)*exp(-Theta*ST)) f2 = h2*S2*exp(-Theta*S2)*(exp(-Theta*S1)-1)/((exp(-Theta)-1)*exp(-Theta*ST)) sum((1-event1-event2)*log(ST))+sum(event1*log(f1))+sum(event2*log(f2)) } SL_function = function(par){ Alpha1 = exp(par[1]) Alpha2 = exp(par[2]) Gamma1 = exp(par[3]) Gamma2 = exp(par[4]) h1 = Alpha1*Gamma1/(1+Alpha1*t.event) h2 = Alpha2*Gamma2/(1+Alpha2*t.event) S1 = (1+Alpha1*t.event)^(-Gamma1) S2 = (1+Alpha2*t.event)^(-Gamma2) p0 = exp(-Theta) p1 = exp(-Theta*S1) p2 = exp(-Theta*S2) ST = -(1/Theta)*log(1+(exp(-Theta*S1)-1)*(exp(-Theta*S2)-1)/(exp(-Theta)-1)) der_h1_Alpha1 = Gamma1/(1+Alpha1*t.event)^2 der_h2_Alpha2 = Gamma2/(1+Alpha2*t.event)^2 der_S1_Alpha1 = -Gamma1*t.event*(1+Alpha1*t.event)^(-Gamma1-1) der_S2_Alpha2 = -Gamma2*t.event*(1+Alpha2*t.event)^(-Gamma2-1) der_h1_Gamma1 = Alpha1/(1+Alpha1*t.event) der_h2_Gamma2 = Alpha2/(1+Alpha2*t.event) der_S1_Gamma1 = -(1+Alpha1*t.event)^(-Gamma1)*log(1+Alpha1*t.event) der_S2_Gamma2 = -(1+Alpha2*t.event)^(-Gamma2)*log(1+Alpha2*t.event) der_ST_Alpha1 = der_S1_Alpha1*p1*(p2-1)/(p0-1+(p1-1)*(p2-1)) der_ST_Alpha2 = der_S2_Alpha2*p2*(p1-1)/(p0-1+(p1-1)*(p2-1)) der_ST_Gamma1 = der_S1_Gamma1*p1*(p2-1)/(p0-1+(p1-1)*(p2-1)) der_ST_Gamma2 = der_S2_Gamma2*p2*(p1-1)/(p0-1+(p1-1)*(p2-1)) d11 = sum(event1*(der_h1_Alpha1/h1+der_S1_Alpha1/S1-Theta*der_S1_Alpha1+Theta*der_ST_Alpha1)) d12 = sum(event2*(-Theta*der_S1_Alpha1*p1/(p1-1)+Theta*der_ST_Alpha1)) d13 = sum((1-event1-event2)*(der_ST_Alpha1/ST)) d1 = d11+d12+d13 d21 = sum(event1*(-Theta*der_S2_Alpha2*p2/(p2-1)+Theta*der_ST_Alpha2)) d22 = sum(event2*(der_h2_Alpha2/h2+der_S2_Alpha2/S2-Theta*der_S2_Alpha2+Theta*der_ST_Alpha2)) d23 = sum((1-event1-event2)*(der_ST_Alpha2/ST)) d2 = d21+d22+d23 d31 = sum(event1*(der_h1_Gamma1/h1+der_S1_Gamma1/S1-Theta*der_S1_Gamma1+Theta*der_ST_Gamma1)) d32 = sum(event2*(-Theta*der_S1_Gamma1*p1/(p1-1)+Theta*der_ST_Gamma1)) d33 = sum((1-event1-event2)*(der_ST_Gamma1/ST)) d3 = d31+d32+d33 d41 = sum(event1*(-Theta*der_S2_Gamma2*p2/(p2-1)+Theta*der_ST_Gamma2)) d42 = sum(event2*(der_h2_Gamma2/h2+der_S2_Gamma2/S2-Theta*der_S2_Gamma2+Theta*der_ST_Gamma2)) d43 = sum((1-event1-event2)*(der_ST_Gamma2/ST)) d4 = d41+d42+d43 c(exp(par[1])*d1,exp(par[2])*d2,exp(par[3])*d3,exp(par[4])*d4) } HL_function = function(par){ Alpha1 = exp(par[1]) Alpha2 = exp(par[2]) Gamma1 = exp(par[3]) Gamma2 = exp(par[4]) h1 = Alpha1*Gamma1/(1+Alpha1*t.event) h2 = Alpha2*Gamma2/(1+Alpha2*t.event) S1 = (1+Alpha1*t.event)^(-Gamma1) S2 = (1+Alpha2*t.event)^(-Gamma2) p0 = exp(-Theta) p1 = exp(-Theta*S1) p2 = exp(-Theta*S2) ST = -(1/Theta)*log(1+(exp(-Theta*S1)-1)*(exp(-Theta*S2)-1)/(exp(-Theta)-1)) der_h1_Alpha1 = Gamma1/(1+Alpha1*t.event)^2 der_h2_Alpha2 = Gamma2/(1+Alpha2*t.event)^2 der_S1_Alpha1 = -Gamma1*t.event*(1+Alpha1*t.event)^(-Gamma1-1) der_S2_Alpha2 = -Gamma2*t.event*(1+Alpha2*t.event)^(-Gamma2-1) der_h1_Gamma1 = Alpha1/(1+Alpha1*t.event) der_h2_Gamma2 = Alpha2/(1+Alpha2*t.event) der_S1_Gamma1 = -(1+Alpha1*t.event)^(-Gamma1)*log(1+Alpha1*t.event) der_S2_Gamma2 = -(1+Alpha2*t.event)^(-Gamma2)*log(1+Alpha2*t.event) der_ST_Alpha1 = der_S1_Alpha1*p1*(p2-1)/(p0-1+(p1-1)*(p2-1)) der_ST_Alpha2 = der_S2_Alpha2*p2*(p1-1)/(p0-1+(p1-1)*(p2-1)) der_ST_Gamma1 = der_S1_Gamma1*p1*(p2-1)/(p0-1+(p1-1)*(p2-1)) der_ST_Gamma2 = der_S2_Gamma2*p2*(p1-1)/(p0-1+(p1-1)*(p2-1)) der_h1_Alpha1_Alpha1 = -2*Gamma1*t.event/(1+Alpha1*t.event)^3 der_h2_Alpha2_Alpha2 = -2*Gamma2*t.event/(1+Alpha2*t.event)^3 der_S1_Alpha1_Alpha1 = Gamma1*(Gamma1+1)*t.event^2*(1+Alpha1*t.event)^(-Gamma1-2) der_S2_Alpha2_Alpha2 = Gamma2*(Gamma2+1)*t.event^2*(1+Alpha2*t.event)^(-Gamma2-2) der_h1_Gamma1_Gamma1 = 0 der_h2_Gamma2_Gamma2 = 0 der_S1_Gamma1_Gamma1 = (1+Alpha1*t.event)^(-Gamma1)*(log(1+Alpha1*t.event))^2 der_S2_Gamma2_Gamma2 = (1+Alpha2*t.event)^(-Gamma2)*(log(1+Alpha2*t.event))^2 der_h1_Alpha1_Gamma1 = (1+Alpha1*t.event)^(-2) der_h2_Alpha2_Gamma2 = (1+Alpha2*t.event)^(-2) der_S1_Alpha1_Gamma1 = t.event*(Gamma1*log(1+Alpha1*t.event)-1)/(1+Alpha1*t.event)^(Gamma1+1) der_S2_Alpha2_Gamma2 = t.event*(Gamma2*log(1+Alpha2*t.event)-1)/(1+Alpha2*t.event)^(Gamma2+1) der_ST_Alpha1_Alpha1 = ((p0-1+(p1-1)*(p2-1))*(p2-1)*(der_S1_Alpha1_Alpha1*p1-Theta*der_S1_Alpha1^2*p1)-der_S1_Alpha1*p1*(p2-1)*(-Theta*der_S1_Alpha1*p1*(p2-1)))/(p0-1+(p1-1)*(p2-1))^2 der_ST_Alpha2_Alpha2 = ((p0-1+(p1-1)*(p2-1))*(p1-1)*(der_S2_Alpha2_Alpha2*p2-Theta*der_S2_Alpha2^2*p2)-der_S2_Alpha2*p2*(p1-1)*(-Theta*der_S2_Alpha2*p2*(p1-1)))/(p0-1+(p1-1)*(p2-1))^2 der_ST_Alpha1_Alpha2 = ((p0-1+(p1-1)*(p2-1))*p1*p2*-Theta*der_S1_Alpha1*der_S2_Alpha2+Theta*p1*p2*(p1-1)*(p2-1)*der_S1_Alpha1*der_S2_Alpha2)/(p0-1+(p1-1)*(p2-1))^2 der_ST_Gamma1_Gamma1 = ((p0-1+(p1-1)*(p2-1))*(p2-1)*(der_S1_Gamma1_Gamma1*p1-Theta*der_S1_Gamma1^2*p1)-der_S1_Gamma1*p1*(p2-1)*(-Theta*der_S1_Gamma1*p1*(p2-1)))/(p0-1+(p1-1)*(p2-1))^2 der_ST_Gamma2_Gamma2 = ((p0-1+(p1-1)*(p2-1))*(p1-1)*(der_S2_Gamma2_Gamma2*p2-Theta*der_S2_Gamma2^2*p2)-der_S2_Gamma2*p2*(p1-1)*(-Theta*der_S2_Gamma2*p2*(p1-1)))/(p0-1+(p1-1)*(p2-1))^2 der_ST_Gamma1_Gamma2 = ((p0-1+(p1-1)*(p2-1))*p1*p2*-Theta*der_S1_Gamma1*der_S2_Gamma2+Theta*p1*p2*(p1-1)*(p2-1)*der_S1_Gamma1*der_S2_Gamma2)/(p0-1+(p1-1)*(p2-1))^2 der_ST_Alpha1_Gamma1 = ((p0-1+(p1-1)*(p2-1))*(p2-1)*(der_S1_Alpha1_Gamma1*p1-Theta*der_S1_Alpha1*der_S1_Gamma1*p1)+Theta*der_S1_Alpha1*der_S1_Gamma1*p1^2*(p2-1)^2)/(p0-1+(p1-1)*(p2-1))^2 der_ST_Alpha1_Gamma2 = ((p0-1+(p1-1)*(p2-1))*p1*der_S1_Alpha1*-Theta*der_S2_Gamma2*p2+Theta*der_S1_Alpha1*der_S2_Gamma2*p1*p2*(p1-1)*(p2-1))/(p0-1+(p1-1)*(p2-1))^2 der_ST_Alpha2_Gamma1 = ((p0-1+(p1-1)*(p2-1))*p1*p2*-Theta*der_S1_Gamma1*der_S2_Alpha2+Theta*p1*p2*(p1-1)*(p2-1)*der_S1_Gamma1*der_S2_Alpha2)/(p0-1+(p1-1)*(p2-1))^2 der_ST_Alpha2_Gamma2 = ((p0-1+(p1-1)*(p2-1))*(p1-1)*(der_S2_Alpha2_Gamma2*p2-Theta*der_S2_Alpha2*der_S2_Gamma2*p2)+Theta*der_S2_Alpha2*der_S2_Gamma2*p2^2*(p1-1)^2)/(p0-1+(p1-1)*(p2-1))^2 d11 = sum(event1*(der_h1_Alpha1/h1+der_S1_Alpha1/S1-Theta*der_S1_Alpha1+Theta*der_ST_Alpha1)) d12 = sum(event2*(-Theta*der_S1_Alpha1*p1/(p1-1)+Theta*der_ST_Alpha1)) d13 = sum((1-event1-event2)*(der_ST_Alpha1/ST)) d1 = d11+d12+d13 d21 = sum(event1*(-Theta*der_S2_Alpha2*p2/(p2-1)+Theta*der_ST_Alpha2)) d22 = sum(event2*(der_h2_Alpha2/h2+der_S2_Alpha2/S2-Theta*der_S2_Alpha2+Theta*der_ST_Alpha2)) d23 = sum((1-event1-event2)*(der_ST_Alpha2/ST)) d2 = d21+d22+d23 d31 = sum(event1*(der_h1_Gamma1/h1+der_S1_Gamma1/S1-Theta*der_S1_Gamma1+Theta*der_ST_Gamma1)) d32 = sum(event2*(-Theta*der_S1_Gamma1*p1/(p1-1)+Theta*der_ST_Gamma1)) d33 = sum((1-event1-event2)*(der_ST_Gamma1/ST)) d3 = d31+d32+d33 d41 = sum(event1*(-Theta*der_S2_Gamma2*p2/(p2-1)+Theta*der_ST_Gamma2)) d42 = sum(event2*(der_h2_Gamma2/h2+der_S2_Gamma2/S2-Theta*der_S2_Gamma2+Theta*der_ST_Gamma2)) d43 = sum((1-event1-event2)*(der_ST_Gamma2/ST)) d4 = d41+d42+d43 D111 = sum(event1*((der_h1_Alpha1_Alpha1*h1-der_h1_Alpha1^2)/h1^2+(der_S1_Alpha1_Alpha1*S1-der_S1_Alpha1^2)/S1^2-Theta*der_S1_Alpha1_Alpha1+Theta*der_ST_Alpha1_Alpha1)) D112 = sum(event2*(((p1-1)*(-Theta*der_S1_Alpha1_Alpha1*p1+Theta^2*der_S1_Alpha1^2*p1)-Theta^2*der_S1_Alpha1^2*p1^2)/(p1-1)^2+Theta*der_ST_Alpha1_Alpha1)) D113 = sum((1-event1-event2)*((ST*der_ST_Alpha1_Alpha1-der_ST_Alpha1^2)/ST^2)) D11 = D111+D112+D113 D221 = sum(event1*(((p2-1)*(-Theta*der_S2_Alpha2_Alpha2*p2+Theta^2*der_S2_Alpha2^2*p2)-Theta^2*der_S2_Alpha2^2*p2^2)/(p2-1)^2+Theta*der_ST_Alpha2_Alpha2)) D222 = sum(event2*((der_h2_Alpha2_Alpha2*h2-der_h2_Alpha2^2)/h2^2+(der_S2_Alpha2_Alpha2*S2-der_S2_Alpha2^2)/S2^2-Theta*der_S2_Alpha2_Alpha2+Theta*der_ST_Alpha2_Alpha2)) D223 = sum((1-event1-event2)*((ST*der_ST_Alpha2_Alpha2-der_ST_Alpha2^2)/ST^2)) D22 = D221+D222+D223 D121 = sum(event1*(Theta*der_ST_Alpha1_Alpha2)) D122 = sum(event2*(Theta*der_ST_Alpha1_Alpha2)) D123 = sum((1-event1-event2)*((ST*der_ST_Alpha1_Alpha2-der_ST_Alpha1*der_ST_Alpha2)/ST^2)) D12 = D121+D122+D123 D331 = sum(event1*((der_h1_Gamma1_Gamma1*h1-der_h1_Gamma1^2)/h1^2+(der_S1_Gamma1_Gamma1*S1-der_S1_Gamma1^2)/S1^2-Theta*der_S1_Gamma1_Gamma1+Theta*der_ST_Gamma1_Gamma1)) D332 = sum(event2*(((p1-1)*(-Theta*der_S1_Gamma1_Gamma1*p1+Theta^2*der_S1_Gamma1^2*p1)-Theta^2*der_S1_Gamma1^2*p1^2)/(p1-1)^2+Theta*der_ST_Gamma1_Gamma1)) D333 = sum((1-event1-event2)*((ST*der_ST_Gamma1_Gamma1-der_ST_Gamma1^2)/ST^2)) D33 = D331+D332+D333 D441 = sum(event1*(((p2-1)*(-Theta*der_S2_Gamma2_Gamma2*p2+Theta^2*der_S2_Gamma2^2*p2)-Theta^2*der_S2_Gamma2^2*p2^2)/(p2-1)^2+Theta*der_ST_Gamma2_Gamma2)) D442 = sum(event2*((der_h2_Gamma2_Gamma2*h2-der_h2_Gamma2^2)/h2^2+(der_S2_Gamma2_Gamma2*S2-der_S2_Gamma2^2)/S2^2-Theta*der_S2_Gamma2_Gamma2+Theta*der_ST_Gamma2_Gamma2)) D443 = sum((1-event1-event2)*((ST*der_ST_Gamma2_Gamma2-der_ST_Gamma2^2)/ST^2)) D44 = D441+D442+D443 D341 = sum(event1*(Theta*der_ST_Gamma1_Gamma2)) D342 = sum(event2*(Theta*der_ST_Gamma1_Gamma2)) D343 = sum((1-event1-event2)*((ST*der_ST_Gamma1_Gamma2-der_ST_Gamma1*der_ST_Gamma2)/ST^2)) D34 = D341+D342+D343 D131 = sum(event1*((der_h1_Alpha1_Gamma1*h1-der_h1_Alpha1*der_h1_Gamma1)/h1^2 +(der_S1_Alpha1_Gamma1*S1-der_S1_Alpha1*der_S1_Gamma1)/S1^2-Theta*der_S1_Alpha1_Gamma1+Theta*der_ST_Alpha1_Gamma1)) D132 = sum(event2*(((p1-1)*(-Theta*der_S1_Alpha1_Gamma1*p1)-Theta^2*der_S1_Alpha1*der_S1_Gamma1*p1)/(p1-1)^2+Theta*der_ST_Alpha1_Gamma1)) D133 = sum((1-event1-event2)*((ST*der_ST_Alpha1_Gamma1-der_ST_Alpha1*der_ST_Gamma1)/ST^2)) D13 = D131+D132+D133 D141 = sum(event1*(Theta*der_ST_Alpha1_Gamma2)) D142 = sum(event2*(Theta*der_ST_Alpha1_Gamma2)) D143 = sum((1-event1-event2)*((ST*der_ST_Alpha1_Gamma2-der_ST_Alpha1*der_ST_Gamma2)/ST^2)) D14 = D141+D142+D143 D231 = sum(event1*(Theta*der_ST_Alpha2_Gamma1)) D232 = sum(event2*(Theta*der_ST_Alpha2_Gamma1)) D233 = sum((1-event1-event2)*((ST*der_ST_Alpha2_Gamma1-der_ST_Alpha2*der_ST_Gamma1)/ST^2)) D23 = D231+D232+D233 D241 = sum(event1*(((p2-1)*(-Theta*der_S2_Alpha2_Gamma2*p2+Theta^2*der_S2_Alpha2*der_S2_Gamma2*p2)-Theta^2*der_S2_Alpha2*der_S2_Gamma2*p2^2)/(p2-1)^2+Theta*der_ST_Alpha2_Gamma2)) D242 = sum(event2*((der_h2_Alpha2_Gamma2*h2-der_h2_Alpha2*der_h2_Gamma2)/h2^2+(der_S2_Alpha2_Gamma2*S2-der_S2_Alpha2*der_S2_Gamma2)/S2^2-Theta*der_S2_Alpha2_Gamma2+Theta*der_ST_Alpha2_Gamma2)) D243 = sum((1-event1-event2)*((ST*der_ST_Alpha2_Gamma2-der_ST_Alpha2*der_ST_Gamma2)/ST^2)) D24 = D241+D242+D243 DD11 = exp(2*par[1])*D11+exp(par[1])*d1 DD12 = exp(par[1])*exp(par[2])*D12 DD13 = exp(par[1])*exp(par[3])*D13 DD14 = exp(par[1])*exp(par[4])*D14 DD22 = exp(2*par[2])*D22+exp(par[2])*d2 DD23 = exp(par[2])*exp(par[3])*D23 DD24 = exp(par[2])*exp(par[4])*D24 DD33 = exp(2*par[3])*D33+exp(par[3])*d3 DD34 = exp(par[3])*exp(par[4])*D34 DD44 = exp(2*par[4])*D44+exp(par[4])*d4 matrix(c(DD11,DD12,DD13,DD14,DD12,DD22,DD23,DD24,DD13,DD23,DD33,DD34,DD14,DD24,DD34,DD44),4,4) } H_function = function(par){ Alpha1 = par[1] Alpha2 = par[2] Gamma1 = par[3] Gamma2 = par[4] h1 = Alpha1*Gamma1/(1+Alpha1*t.event) h2 = Alpha2*Gamma2/(1+Alpha2*t.event) S1 = (1+Alpha1*t.event)^(-Gamma1) S2 = (1+Alpha2*t.event)^(-Gamma2) p0 = exp(-Theta) p1 = exp(-Theta*S1) p2 = exp(-Theta*S2) ST = -(1/Theta)*log(1+(exp(-Theta*S1)-1)*(exp(-Theta*S2)-1)/(exp(-Theta)-1)) der_h1_Alpha1 = Gamma1/(1+Alpha1*t.event)^2 der_h2_Alpha2 = Gamma2/(1+Alpha2*t.event)^2 der_S1_Alpha1 = -Gamma1*t.event*(1+Alpha1*t.event)^(-Gamma1-1) der_S2_Alpha2 = -Gamma2*t.event*(1+Alpha2*t.event)^(-Gamma2-1) der_h1_Gamma1 = Alpha1/(1+Alpha1*t.event) der_h2_Gamma2 = Alpha2/(1+Alpha2*t.event) der_S1_Gamma1 = -(1+Alpha1*t.event)^(-Gamma1)*log(1+Alpha1*t.event) der_S2_Gamma2 = -(1+Alpha2*t.event)^(-Gamma2)*log(1+Alpha2*t.event) der_ST_Alpha1 = der_S1_Alpha1*p1*(p2-1)/(p0-1+(p1-1)*(p2-1)) der_ST_Alpha2 = der_S2_Alpha2*p2*(p1-1)/(p0-1+(p1-1)*(p2-1)) der_ST_Gamma1 = der_S1_Gamma1*p1*(p2-1)/(p0-1+(p1-1)*(p2-1)) der_ST_Gamma2 = der_S2_Gamma2*p2*(p1-1)/(p0-1+(p1-1)*(p2-1)) der_h1_Alpha1_Alpha1 = -2*Gamma1*t.event/(1+Alpha1*t.event)^3 der_h2_Alpha2_Alpha2 = -2*Gamma2*t.event/(1+Alpha2*t.event)^3 der_S1_Alpha1_Alpha1 = Gamma1*(Gamma1+1)*t.event^2*(1+Alpha1*t.event)^(-Gamma1-2) der_S2_Alpha2_Alpha2 = Gamma2*(Gamma2+1)*t.event^2*(1+Alpha2*t.event)^(-Gamma2-2) der_h1_Gamma1_Gamma1 = 0 der_h2_Gamma2_Gamma2 = 0 der_S1_Gamma1_Gamma1 = (1+Alpha1*t.event)^(-Gamma1)*(log(1+Alpha1*t.event))^2 der_S2_Gamma2_Gamma2 = (1+Alpha2*t.event)^(-Gamma2)*(log(1+Alpha2*t.event))^2 der_h1_Alpha1_Gamma1 = (1+Alpha1*t.event)^(-2) der_h2_Alpha2_Gamma2 = (1+Alpha2*t.event)^(-2) der_S1_Alpha1_Gamma1 = t.event*(Gamma1*log(1+Alpha1*t.event)-1)/(1+Alpha1*t.event)^(Gamma1+1) der_S2_Alpha2_Gamma2 = t.event*(Gamma2*log(1+Alpha2*t.event)-1)/(1+Alpha2*t.event)^(Gamma2+1) der_ST_Alpha1_Alpha1 = ((p0-1+(p1-1)*(p2-1))*(p2-1)*(der_S1_Alpha1_Alpha1*p1-Theta*der_S1_Alpha1^2*p1)-der_S1_Alpha1*p1*(p2-1)*(-Theta*der_S1_Alpha1*p1*(p2-1)))/(p0-1+(p1-1)*(p2-1))^2 der_ST_Alpha2_Alpha2 = ((p0-1+(p1-1)*(p2-1))*(p1-1)*(der_S2_Alpha2_Alpha2*p2-Theta*der_S2_Alpha2^2*p2)-der_S2_Alpha2*p2*(p1-1)*(-Theta*der_S2_Alpha2*p2*(p1-1)))/(p0-1+(p1-1)*(p2-1))^2 der_ST_Alpha1_Alpha2 = ((p0-1+(p1-1)*(p2-1))*p1*p2*-Theta*der_S1_Alpha1*der_S2_Alpha2+Theta*p1*p2*(p1-1)*(p2-1)*der_S1_Alpha1*der_S2_Alpha2)/(p0-1+(p1-1)*(p2-1))^2 der_ST_Gamma1_Gamma1 = ((p0-1+(p1-1)*(p2-1))*(p2-1)*(der_S1_Gamma1_Gamma1*p1-Theta*der_S1_Gamma1^2*p1)-der_S1_Gamma1*p1*(p2-1)*(-Theta*der_S1_Gamma1*p1*(p2-1)))/(p0-1+(p1-1)*(p2-1))^2 der_ST_Gamma2_Gamma2 = ((p0-1+(p1-1)*(p2-1))*(p1-1)*(der_S2_Gamma2_Gamma2*p2-Theta*der_S2_Gamma2^2*p2)-der_S2_Gamma2*p2*(p1-1)*(-Theta*der_S2_Gamma2*p2*(p1-1)))/(p0-1+(p1-1)*(p2-1))^2 der_ST_Gamma1_Gamma2 = ((p0-1+(p1-1)*(p2-1))*p1*p2*-Theta*der_S1_Gamma1*der_S2_Gamma2+Theta*p1*p2*(p1-1)*(p2-1)*der_S1_Gamma1*der_S2_Gamma2)/(p0-1+(p1-1)*(p2-1))^2 der_ST_Alpha1_Gamma1 = ((p0-1+(p1-1)*(p2-1))*(p2-1)*(der_S1_Alpha1_Gamma1*p1-Theta*der_S1_Alpha1*der_S1_Gamma1*p1)+Theta*der_S1_Alpha1*der_S1_Gamma1*p1^2*(p2-1)^2)/(p0-1+(p1-1)*(p2-1))^2 der_ST_Alpha1_Gamma2 = ((p0-1+(p1-1)*(p2-1))*p1*der_S1_Alpha1*-Theta*der_S2_Gamma2*p2+Theta*der_S1_Alpha1*der_S2_Gamma2*p1*p2*(p1-1)*(p2-1))/(p0-1+(p1-1)*(p2-1))^2 der_ST_Alpha2_Gamma1 = ((p0-1+(p1-1)*(p2-1))*p1*p2*-Theta*der_S1_Gamma1*der_S2_Alpha2+Theta*p1*p2*(p1-1)*(p2-1)*der_S1_Gamma1*der_S2_Alpha2)/(p0-1+(p1-1)*(p2-1))^2 der_ST_Alpha2_Gamma2 = ((p0-1+(p1-1)*(p2-1))*(p1-1)*(der_S2_Alpha2_Gamma2*p2-Theta*der_S2_Alpha2*der_S2_Gamma2*p2)+Theta*der_S2_Alpha2*der_S2_Gamma2*p2^2*(p1-1)^2)/(p0-1+(p1-1)*(p2-1))^2 d11 = sum(event1*(der_h1_Alpha1/h1+der_S1_Alpha1/S1-Theta*der_S1_Alpha1+Theta*der_ST_Alpha1)) d12 = sum(event2*(-Theta*der_S1_Alpha1*p1/(p1-1)+Theta*der_ST_Alpha1)) d13 = sum((1-event1-event2)*(der_ST_Alpha1/ST)) d1 = d11+d12+d13 d21 = sum(event1*(-Theta*der_S2_Alpha2*p2/(p2-1)+Theta*der_ST_Alpha2)) d22 = sum(event2*(der_h2_Alpha2/h2+der_S2_Alpha2/S2-Theta*der_S2_Alpha2+Theta*der_ST_Alpha2)) d23 = sum((1-event1-event2)*(der_ST_Alpha2/ST)) d2 = d21+d22+d23 d31 = sum(event1*(der_h1_Gamma1/h1+der_S1_Gamma1/S1-Theta*der_S1_Gamma1+Theta*der_ST_Gamma1)) d32 = sum(event2*(-Theta*der_S1_Gamma1*p1/(p1-1)+Theta*der_ST_Gamma1)) d33 = sum((1-event1-event2)*(der_ST_Gamma1/ST)) d3 = d31+d32+d33 d41 = sum(event1*(-Theta*der_S2_Gamma2*p2/(p2-1)+Theta*der_ST_Gamma2)) d42 = sum(event2*(der_h2_Gamma2/h2+der_S2_Gamma2/S2-Theta*der_S2_Gamma2+Theta*der_ST_Gamma2)) d43 = sum((1-event1-event2)*(der_ST_Gamma2/ST)) d4 = d41+d42+d43 D111 = sum(event1*((der_h1_Alpha1_Alpha1*h1-der_h1_Alpha1^2)/h1^2+(der_S1_Alpha1_Alpha1*S1-der_S1_Alpha1^2)/S1^2-Theta*der_S1_Alpha1_Alpha1+Theta*der_ST_Alpha1_Alpha1)) D112 = sum(event2*(((p1-1)*(-Theta*der_S1_Alpha1_Alpha1*p1+Theta^2*der_S1_Alpha1^2*p1)-Theta^2*der_S1_Alpha1^2*p1^2)/(p1-1)^2+Theta*der_ST_Alpha1_Alpha1)) D113 = sum((1-event1-event2)*((ST*der_ST_Alpha1_Alpha1-der_ST_Alpha1^2)/ST^2)) D11 = D111+D112+D113 D221 = sum(event1*(((p2-1)*(-Theta*der_S2_Alpha2_Alpha2*p2+Theta^2*der_S2_Alpha2^2*p2)-Theta^2*der_S2_Alpha2^2*p2^2)/(p2-1)^2+Theta*der_ST_Alpha2_Alpha2)) D222 = sum(event2*((der_h2_Alpha2_Alpha2*h2-der_h2_Alpha2^2)/h2^2+(der_S2_Alpha2_Alpha2*S2-der_S2_Alpha2^2)/S2^2-Theta*der_S2_Alpha2_Alpha2+Theta*der_ST_Alpha2_Alpha2)) D223 = sum((1-event1-event2)*((ST*der_ST_Alpha2_Alpha2-der_ST_Alpha2^2)/ST^2)) D22 = D221+D222+D223 D121 = sum(event1*(Theta*der_ST_Alpha1_Alpha2)) D122 = sum(event2*(Theta*der_ST_Alpha1_Alpha2)) D123 = sum((1-event1-event2)*((ST*der_ST_Alpha1_Alpha2-der_ST_Alpha1*der_ST_Alpha2)/ST^2)) D12 = D121+D122+D123 D331 = sum(event1*((der_h1_Gamma1_Gamma1*h1-der_h1_Gamma1^2)/h1^2+(der_S1_Gamma1_Gamma1*S1-der_S1_Gamma1^2)/S1^2-Theta*der_S1_Gamma1_Gamma1+Theta*der_ST_Gamma1_Gamma1)) D332 = sum(event2*(((p1-1)*(-Theta*der_S1_Gamma1_Gamma1*p1+Theta^2*der_S1_Gamma1^2*p1)-Theta^2*der_S1_Gamma1^2*p1^2)/(p1-1)^2+Theta*der_ST_Gamma1_Gamma1)) D333 = sum((1-event1-event2)*((ST*der_ST_Gamma1_Gamma1-der_ST_Gamma1^2)/ST^2)) D33 = D331+D332+D333 D441 = sum(event1*(((p2-1)*(-Theta*der_S2_Gamma2_Gamma2*p2+Theta^2*der_S2_Gamma2^2*p2)-Theta^2*der_S2_Gamma2^2*p2^2)/(p2-1)^2+Theta*der_ST_Gamma2_Gamma2)) D442 = sum(event2*((der_h2_Gamma2_Gamma2*h2-der_h2_Gamma2^2)/h2^2+(der_S2_Gamma2_Gamma2*S2-der_S2_Gamma2^2)/S2^2-Theta*der_S2_Gamma2_Gamma2+Theta*der_ST_Gamma2_Gamma2)) D443 = sum((1-event1-event2)*((ST*der_ST_Gamma2_Gamma2-der_ST_Gamma2^2)/ST^2)) D44 = D441+D442+D443 D341 = sum(event1*(Theta*der_ST_Gamma1_Gamma2)) D342 = sum(event2*(Theta*der_ST_Gamma1_Gamma2)) D343 = sum((1-event1-event2)*((ST*der_ST_Gamma1_Gamma2-der_ST_Gamma1*der_ST_Gamma2)/ST^2)) D34 = D341+D342+D343 D131 = sum(event1*((der_h1_Alpha1_Gamma1*h1-der_h1_Alpha1*der_h1_Gamma1)/h1^2 +(der_S1_Alpha1_Gamma1*S1-der_S1_Alpha1*der_S1_Gamma1)/S1^2-Theta*der_S1_Alpha1_Gamma1+Theta*der_ST_Alpha1_Gamma1)) D132 = sum(event2*(((p1-1)*(-Theta*der_S1_Alpha1_Gamma1*p1)-Theta^2*der_S1_Alpha1*der_S1_Gamma1*p1)/(p1-1)^2+Theta*der_ST_Alpha1_Gamma1)) D133 = sum((1-event1-event2)*((ST*der_ST_Alpha1_Gamma1-der_ST_Alpha1*der_ST_Gamma1)/ST^2)) D13 = D131+D132+D133 D141 = sum(event1*(Theta*der_ST_Alpha1_Gamma2)) D142 = sum(event2*(Theta*der_ST_Alpha1_Gamma2)) D143 = sum((1-event1-event2)*((ST*der_ST_Alpha1_Gamma2-der_ST_Alpha1*der_ST_Gamma2)/ST^2)) D14 = D141+D142+D143 D231 = sum(event1*(Theta*der_ST_Alpha2_Gamma1)) D232 = sum(event2*(Theta*der_ST_Alpha2_Gamma1)) D233 = sum((1-event1-event2)*((ST*der_ST_Alpha2_Gamma1-der_ST_Alpha2*der_ST_Gamma1)/ST^2)) D23 = D231+D232+D233 D241 = sum(event1*(((p2-1)*(-Theta*der_S2_Alpha2_Gamma2*p2+Theta^2*der_S2_Alpha2*der_S2_Gamma2*p2)-Theta^2*der_S2_Alpha2*der_S2_Gamma2*p2^2)/(p2-1)^2+Theta*der_ST_Alpha2_Gamma2)) D242 = sum(event2*((der_h2_Alpha2_Gamma2*h2-der_h2_Alpha2*der_h2_Gamma2)/h2^2+(der_S2_Alpha2_Gamma2*S2-der_S2_Alpha2*der_S2_Gamma2)/S2^2-Theta*der_S2_Alpha2_Gamma2+Theta*der_ST_Alpha2_Gamma2)) D243 = sum((1-event1-event2)*((ST*der_ST_Alpha2_Gamma2-der_ST_Alpha2*der_ST_Gamma2)/ST^2)) D24 = D241+D242+D243 matrix(c(D11,D12,D13,D14,D12,D22,D23,D24,D13,D23,D33,D34,D14,D24,D34,D44),4,4) } par_old = c(log(Alpha1.0),log(Alpha2.0),log(Gamma1.0),log(Gamma2.0)) count = 0 random = 0 repeat{ temp = try(solve(HL_function(par_old),silent = TRUE)) if (is(temp,"try-error")){ random = random+1 count = 0 par_old = c(log(Alpha1.0*exp(runif(1,-r.1,r.1))), log(Alpha2.0*exp(runif(1,-r.2,r.2))), log(Gamma1.0*exp(runif(1,-r.3,r.3))), log(Gamma2.0*exp(runif(1,-r.4,r.4)))) next } par_new = par_old-solve(HL_function(par_old))%*%SL_function(par_old) count = count+1 if (is.na(sum(par_new)) | max(abs(par_new)) > log(d)) { random = random+1 count = 0 par_old = c(log(Alpha1.0*exp(runif(1,-r.1,r.1))), log(Alpha2.0*exp(runif(1,-r.2,r.2))), log(Gamma1.0*exp(runif(1,-r.3,r.3))), log(Gamma2.0*exp(runif(1,-r.4,r.4)))) next } if (max(abs(exp(par_old)-exp(par_new))) < epsilon) {break} par_old = par_new } Alpha1_hat = exp(par_new[1]) Alpha2_hat = exp(par_new[2]) Gamma1_hat = exp(par_new[3]) Gamma2_hat = exp(par_new[4]) Info = solve(-H_function(exp(par_new))) Alpha1_se = sqrt(Info[1,1]) Alpha2_se = sqrt(Info[2,2]) Gamma1_se = sqrt(Info[3,3]) Gamma2_se = sqrt(Info[4,4]) InfoL = solve(-HL_function(par_new)) CI_Alpha1 = c(Alpha1_hat*exp(-qnorm(0.975)*sqrt(InfoL[1,1])), Alpha1_hat*exp(+qnorm(0.975)*sqrt(InfoL[1,1]))) CI_Alpha2 = c(Alpha2_hat*exp(-qnorm(0.975)*sqrt(InfoL[2,2])), Alpha2_hat*exp(+qnorm(0.975)*sqrt(InfoL[2,2]))) CI_Gamma1 = c(Gamma1_hat*exp(-qnorm(0.975)*sqrt(InfoL[3,3])), Gamma1_hat*exp(+qnorm(0.975)*sqrt(InfoL[3,3]))) CI_Gamma2 = c(Gamma2_hat*exp(-qnorm(0.975)*sqrt(InfoL[4,4])), Gamma2_hat*exp(+qnorm(0.975)*sqrt(InfoL[4,4]))) MedX_hat = (2^(1/Gamma1_hat)-1)/Alpha1_hat MedY_hat = (2^(1/Gamma2_hat)-1)/Alpha2_hat transX = c((1-2^(1/Gamma1_hat))/Alpha1_hat^2,0,-2^(1/Gamma1_hat)*log(2)/(Alpha1_hat*Gamma1_hat^2),0) transY = c(0,(1-2^(1/Gamma2_hat))/Alpha2_hat^2,0,-2^(1/Gamma2_hat)*log(2)/(Alpha2_hat*Gamma2_hat^2)) MedX_se = sqrt(t(transX)%*%Info%*%transX) MedY_se = sqrt(t(transY)%*%Info%*%transY) temp_transX = c(-1,0,-2^(1/Gamma1_hat)*log(2)/((2^(1/Gamma1_hat)-1)*Gamma1_hat),0) temp_transY = c(0,-1,0,-2^(1/Gamma2_hat)*log(2)/((2^(1/Gamma2_hat)-1)*Gamma2_hat)) temp_MedX_se = sqrt(t(temp_transX)%*%InfoL%*%temp_transX) temp_MedY_se = sqrt(t(temp_transY)%*%InfoL%*%temp_transY) CI_MedX = c(MedX_hat*exp(-qnorm(0.975)*temp_MedX_se), MedX_hat*exp(+qnorm(0.975)*temp_MedX_se)) CI_MedY = c(MedY_hat*exp(-qnorm(0.975)*temp_MedY_se), MedY_hat*exp(+qnorm(0.975)*temp_MedY_se)) Alpha1.res = c(Estimate = Alpha1_hat,SE = Alpha1_se,CI.lower = CI_Alpha1[1],CI.upper = CI_Alpha1[2]) Alpha2.res = c(Estimate = Alpha2_hat,SE = Alpha2_se,CI.lower = CI_Alpha2[1],CI.upper = CI_Alpha2[2]) Gamma1.res = c(Estimate = Gamma1_hat,SE = Gamma1_se,CI.lower = CI_Gamma1[1],CI.upper = CI_Gamma1[2]) Gamma2.res = c(Estimate = Gamma2_hat,SE = Gamma2_se,CI.lower = CI_Gamma2[1],CI.upper = CI_Gamma2[2]) MedX.res = c(Estimate = MedX_hat,SE = MedX_se,CI.lower = CI_MedX[1],CI.upper = CI_MedX[2]) MedY.res = c(Estimate = MedY_hat,SE = MedY_se,CI.lower = CI_MedY[1],CI.upper = CI_MedY[2]) if (Gamma1_hat < 1 & Gamma2_hat < 1) { return(list(n = n,Iteration = count,Randomization = random, Alpha1 = Alpha1.res,Alpha2 = Alpha2.res,Gamma1 = Gamma1.res,Gamma2 = Gamma2.res, MedX = MedX.res,MedY = MedY.res,MeanX = "Unavaliable",MeanY = "Unavaliable", logL = log_L(par_new),AIC = 2*length(par_new)-2*log_L(par_new), BIC = length(par_new)*log(length(t.event))-2*log_L(par_new))) } else if (Gamma1_hat >= 1 & Gamma2_hat >= 1) { MeanX_hat = 1/(Alpha1_hat*(Gamma1_hat-1)) MeanY_hat = 1/(Alpha2_hat*(Gamma2_hat-1)) trans2X = c(-1/(Alpha1_hat^2*(Gamma1_hat-1)),0,-1/(Alpha1_hat*(Gamma1_hat-1)^2),0) trans2Y = c(0,-1/(Alpha2_hat^2*(Gamma2_hat-1)),0,-1/(Alpha2_hat*(Gamma2_hat-1)^2)) MeanX_se = sqrt(t(trans2X)%*%Info%*%trans2X) MeanY_se = sqrt(t(trans2Y)%*%Info%*%trans2Y) temp_trans2X = c(-1,0,-Gamma1_hat/(Gamma1_hat-1),0) temp_trans2Y = c(0,-1,0,-Gamma2_hat/(Gamma2_hat-1)) temp_MeanX_se = sqrt(t(temp_trans2X)%*%InfoL%*%temp_trans2X) temp_MeanY_se = sqrt(t(temp_trans2Y)%*%InfoL%*%temp_trans2Y) CI_MeanX = c(MeanX_hat*exp(-qnorm(0.975)*temp_MeanX_se), MeanX_hat*exp(+qnorm(0.975)*temp_MeanX_se)) CI_MeanY = c(MeanY_hat*exp(-qnorm(0.975)*temp_MeanY_se), MeanY_hat*exp(+qnorm(0.975)*temp_MeanY_se)) MeanX.res = c(Estimate = MeanX_hat,SE = MeanX_se,CI.lower = CI_MeanX[1],CI.upper = CI_MeanX[2]) MeanY.res = c(Estimate = MeanY_hat,SE = MeanY_se,CI.lower = CI_MeanY[1],CI.upper = CI_MeanY[2]) return(list(n = n,Iteration = count,Randomization = random, Alpha1 = Alpha1.res,Alpha2 = Alpha2.res,Gamma1 = Gamma1.res,Gamma2 = Gamma2.res, MedX = MedX.res,MedY = MedY.res,MeanX = MeanX.res,MeanY = MeanY.res, logL = log_L(par_new),AIC = 2*length(par_new)-2*log_L(par_new), BIC = length(par_new)*log(length(t.event))-2*log_L(par_new))) } else if (Gamma1_hat >= 1 & Gamma2_hat < 1) { MeanX_hat = 1/(Alpha1_hat*(Gamma1_hat-1)) trans2X = c(-1/(Alpha1_hat^2*(Gamma1_hat-1)),0,-1/(Alpha1_hat*(Gamma1_hat-1)^2),0) MeanX_se = sqrt(t(trans2X)%*%Info%*%trans2X) temp_trans2X = c(-1,0,-Gamma1_hat/(Gamma1_hat-1),0) temp_MeanX_se = sqrt(t(temp_trans2X)%*%InfoL%*%temp_trans2X) CI_MeanX = c(MeanX_hat*exp(-qnorm(0.975)*temp_MeanX_se), MeanX_hat*exp(+qnorm(0.975)*temp_MeanX_se)) MeanX.res = c(Estimate = MeanX_hat,SE = MeanX_se,CI.lower = CI_MeanX[1],CI.upper = CI_MeanX[2]) return(list(n = n,Iteration = count,Randomization = random, Alpha1 = Alpha1.res,Alpha2 = Alpha2.res,Gamma1 = Gamma1.res,Gamma2 = Gamma2.res, MedX = MedX.res,MedY = MedY.res,MeanX = MeanX.res,MeanY = "Unavaliable", logL = log_L(par_new),AIC = 2*length(par_new)-2*log_L(par_new), BIC = length(par_new)*log(length(t.event))-2*log_L(par_new))) } else { MeanY_hat = 1/(Alpha2_hat*(Gamma2_hat-1)) trans2Y = c(0,-1/(Alpha2_hat^2*(Gamma2_hat-1)),0,-1/(Alpha2_hat*(Gamma2_hat-1)^2)) MeanY_se = sqrt(t(trans2Y)%*%Info%*%trans2Y) temp_trans2Y = c(0,-1,0,-Gamma2_hat/(Gamma2_hat-1)) temp_MeanY_se = sqrt(t(temp_trans2Y)%*%InfoL%*%temp_trans2Y) CI_MeanY = c(MeanY_hat*exp(-qnorm(0.975)*temp_MeanY_se), MeanY_hat*exp(+qnorm(0.975)*temp_MeanY_se)) MeanY.res = c(Estimate = MeanY_hat,SE = MeanY_se,CI.lower = CI_MeanY[1],CI.upper = CI_MeanY[2]) return(list(n = n,Iteration = count,Randomization = random, Alpha1 = Alpha1.res,Alpha2 = Alpha2.res,Gamma1 = Gamma1.res,Gamma2 = Gamma2.res, MedX = MedX.res,MedY = MedY.res,MeanX = "Unavaliable",MeanY = MeanY.res, logL = log_L(par_new),AIC = 2*length(par_new)-2*log_L(par_new), BIC = length(par_new)*log(length(t.event))-2*log_L(par_new))) } }
set_new_model("linear_reg") set_model_mode("linear_reg", "regression") set_model_engine("linear_reg", "regression", "lm") set_dependency("linear_reg", "lm", "stats") set_fit( model = "linear_reg", eng = "lm", mode = "regression", value = list( interface = "formula", protect = c("formula", "data", "weights"), func = c(pkg = "stats", fun = "lm"), defaults = list() ) ) set_encoding( model = "linear_reg", eng = "lm", mode = "regression", options = list( predictor_indicators = "traditional", compute_intercept = TRUE, remove_intercept = TRUE, allow_sparse_x = FALSE ) ) set_pred( model = "linear_reg", eng = "lm", mode = "regression", type = "numeric", value = list( pre = NULL, post = NULL, func = c(fun = "predict"), args = list( object = expr(object$fit), newdata = expr(new_data), type = "response" ) ) ) set_pred( model = "linear_reg", eng = "lm", mode = "regression", type = "conf_int", value = list( pre = NULL, post = function(results, object) { tibble::as_tibble(results) %>% dplyr::select(-fit) %>% setNames(c(".pred_lower", ".pred_upper")) }, func = c(fun = "predict"), args = list( object = expr(object$fit), newdata = expr(new_data), interval = "confidence", level = expr(level), type = "response" ) ) ) set_pred( model = "linear_reg", eng = "lm", mode = "regression", type = "pred_int", value = list( pre = NULL, post = function(results, object) { tibble::as_tibble(results) %>% dplyr::select(-fit) %>% setNames(c(".pred_lower", ".pred_upper")) }, func = c(fun = "predict"), args = list( object = expr(object$fit), newdata = expr(new_data), interval = "prediction", level = expr(level), type = "response" ) ) ) set_pred( model = "linear_reg", eng = "lm", mode = "regression", type = "raw", value = list( pre = NULL, post = NULL, func = c(fun = "predict"), args = list(object = expr(object$fit), newdata = expr(new_data)) ) ) set_model_engine("linear_reg", "regression", "glm") set_dependency("linear_reg", "glm", "stats") set_fit( model = "linear_reg", eng = "glm", mode = "regression", value = list( interface = "formula", protect = c("formula", "data", "weights"), func = c(pkg = "stats", fun = "glm"), defaults = list(family = expr(stats::gaussian)) ) ) set_encoding( model = "linear_reg", eng = "glm", mode = "regression", options = list( predictor_indicators = "traditional", compute_intercept = TRUE, remove_intercept = TRUE, allow_sparse_x = FALSE ) ) set_pred( model = "linear_reg", eng = "glm", mode = "regression", type = "numeric", value = list( pre = NULL, post = NULL, func = c(fun = "predict"), args = list( object = expr(object$fit), newdata = expr(new_data), type = "response" ) ) ) set_pred( model = "linear_reg", eng = "glm", mode = "regression", type = "conf_int", value = list( pre = NULL, post = linear_lp_to_conf_int, func = c(fun = "predict"), args = list( object = quote(object$fit), newdata = quote(new_data), se.fit = TRUE, type = "link" ) ) ) set_pred( model = "linear_reg", eng = "glm", mode = "regression", type = "raw", value = list( pre = NULL, post = NULL, func = c(fun = "predict"), args = list(object = expr(object$fit), newdata = expr(new_data)) ) ) set_model_engine("linear_reg", "regression", "glmnet") set_dependency("linear_reg", "glmnet", "glmnet") set_fit( model = "linear_reg", eng = "glmnet", mode = "regression", value = list( interface = "matrix", protect = c("x", "y", "weights"), func = c(pkg = "glmnet", fun = "glmnet"), defaults = list(family = "gaussian") ) ) set_encoding( model = "linear_reg", eng = "glmnet", mode = "regression", options = list( predictor_indicators = "traditional", compute_intercept = TRUE, remove_intercept = TRUE, allow_sparse_x = TRUE ) ) set_model_arg( model = "linear_reg", eng = "glmnet", parsnip = "penalty", original = "lambda", func = list(pkg = "dials", fun = "penalty"), has_submodel = TRUE ) set_model_arg( model = "linear_reg", eng = "glmnet", parsnip = "mixture", original = "alpha", func = list(pkg = "dials", fun = "mixture"), has_submodel = FALSE ) set_pred( model = "linear_reg", eng = "glmnet", mode = "regression", type = "numeric", value = list( pre = NULL, post = .organize_glmnet_pred, func = c(fun = "predict"), args = list( object = expr(object$fit), newx = expr(as.matrix(new_data[, rownames(object$fit$beta), drop = FALSE])), type = "response", s = expr(object$spec$args$penalty) ) ) ) set_pred( model = "linear_reg", eng = "glmnet", mode = "regression", type = "raw", value = list( pre = NULL, post = NULL, func = c(fun = "predict"), args = list(object = expr(object$fit), newx = expr(as.matrix(new_data))) ) ) set_model_engine("linear_reg", "regression", "stan") set_dependency("linear_reg", "stan", "rstanarm") set_fit( model = "linear_reg", eng = "stan", mode = "regression", value = list( interface = "formula", protect = c("formula", "data", "weights"), func = c(pkg = "rstanarm", fun = "stan_glm"), defaults = list(family = expr(stats::gaussian), refresh = 0) ) ) set_encoding( model = "linear_reg", eng = "stan", mode = "regression", options = list( predictor_indicators = "traditional", compute_intercept = TRUE, remove_intercept = TRUE, allow_sparse_x = FALSE ) ) set_pred( model = "linear_reg", eng = "stan", mode = "regression", type = "numeric", value = list( pre = NULL, post = NULL, func = c(fun = "predict"), args = list(object = expr(object$fit), newdata = expr(new_data)) ) ) set_pred( model = "linear_reg", eng = "stan", mode = "regression", type = "conf_int", value = list( pre = NULL, post = function(results, object) { res <- tibble( .pred_lower = convert_stan_interval( results, level = object$spec$method$pred$conf_int$extras$level ), .pred_upper = convert_stan_interval( results, level = object$spec$method$pred$conf_int$extras$level, lower = FALSE ), ) if (object$spec$method$pred$conf_int$extras$std_error) res$.std_error <- apply(results, 2, sd, na.rm = TRUE) res }, func = c(pkg = "parsnip", fun = "stan_conf_int"), args = list( object = expr(object$fit), newdata = expr(new_data) ) ) ) set_pred( model = "linear_reg", eng = "stan", mode = "regression", type = "pred_int", value = list( pre = NULL, post = function(results, object) { res <- tibble( .pred_lower = convert_stan_interval( results, level = object$spec$method$pred$pred_int$extras$level ), .pred_upper = convert_stan_interval( results, level = object$spec$method$pred$pred_int$extras$level, lower = FALSE ), ) if (object$spec$method$pred$pred_int$extras$std_error) res$.std_error <- apply(results, 2, sd, na.rm = TRUE) res }, func = c(pkg = "rstanarm", fun = "posterior_predict"), args = list( object = expr(object$fit), newdata = expr(new_data), seed = expr(sample.int(10^5, 1)) ) ) ) set_pred( model = "linear_reg", eng = "stan", mode = "regression", type = "raw", value = list( pre = NULL, post = NULL, func = c(fun = "predict"), args = list(object = expr(object$fit), newdata = expr(new_data)) ) ) set_model_engine("linear_reg", "regression", "spark") set_dependency("linear_reg", "spark", "sparklyr") set_fit( model = "linear_reg", eng = "spark", mode = "regression", value = list( interface = "formula", data = c(formula = "formula", data = "x"), protect = c("x", "formula", "weight_col"), func = c(pkg = "sparklyr", fun = "ml_linear_regression"), defaults = list() ) ) set_encoding( model = "linear_reg", eng = "spark", mode = "regression", options = list( predictor_indicators = "traditional", compute_intercept = TRUE, remove_intercept = TRUE, allow_sparse_x = FALSE ) ) set_model_arg( model = "linear_reg", eng = "spark", parsnip = "penalty", original = "reg_param", func = list(pkg = "dials", fun = "penalty"), has_submodel = FALSE ) set_model_arg( model = "linear_reg", eng = "spark", parsnip = "mixture", original = "elastic_net_param", func = list(pkg = "dials", fun = "mixture"), has_submodel = FALSE ) set_pred( model = "linear_reg", eng = "spark", mode = "regression", type = "numeric", value = list( pre = NULL, post = function(results, object) { results <- dplyr::rename(results, pred = prediction) results <- dplyr::select(results, pred) results }, func = c(pkg = "sparklyr", fun = "ml_predict"), args = list(x = expr(object$fit), dataset = expr(new_data)) ) ) set_model_engine("linear_reg", "regression", "keras") set_dependency("linear_reg", "keras", "keras") set_dependency("linear_reg", "keras", "magrittr") set_fit( model = "linear_reg", eng = "keras", mode = "regression", value = list( interface = "matrix", protect = c("x", "y"), func = c(pkg = "parsnip", fun = "keras_mlp"), defaults = list(hidden_units = 1, act = "linear") ) ) set_encoding( model = "linear_reg", eng = "keras", mode = "regression", options = list( predictor_indicators = "traditional", compute_intercept = TRUE, remove_intercept = TRUE, allow_sparse_x = FALSE ) ) set_model_arg( model = "linear_reg", eng = "keras", parsnip = "penalty", original = "penalty", func = list(pkg = "dials", fun = "penalty"), has_submodel = FALSE ) set_pred( model = "linear_reg", eng = "keras", mode = "regression", type = "numeric", value = list( pre = NULL, post = maybe_multivariate, func = c(fun = "predict"), args = list(object = quote(object$fit), x = quote(as.matrix(new_data))) ) ) set_model_engine("linear_reg", "regression", "brulee") set_dependency("linear_reg", "brulee", "brulee") set_model_arg( model = "linear_reg", eng = "brulee", parsnip = "penalty", original = "penalty", func = list(pkg = "dials", fun = "penalty"), has_submodel = FALSE ) set_model_arg( model = "linear_reg", eng = "brulee", parsnip = "mixture", original = "mixture", func = list(pkg = "dials", fun = "mixture"), has_submodel = FALSE ) set_model_arg( model = "linear_reg", eng = "brulee", parsnip = "epochs", original = "epochs", func = list(pkg = "dials", fun = "epochs"), has_submodel = FALSE ) set_model_arg( model = "linear_reg", eng = "brulee", parsnip = "learn_rate", original = "learn_rate", func = list(pkg = "dials", fun = "learn_rate"), has_submodel = FALSE ) set_model_arg( model = "linear_reg", eng = "brulee", parsnip = "momentum", original = "momentum", func = list(pkg = "dials", fun = "momentum"), has_submodel = FALSE ) set_model_arg( model = "linear_reg", eng = "brulee", parsnip = "stop_iter", original = "stop_iter", func = list(pkg = "dials", fun = "stop_iter"), has_submodel = FALSE ) set_fit( model = "linear_reg", eng = "brulee", mode = "regression", value = list( interface = "data.frame", protect = c("x", "y"), func = c(pkg = "brulee", fun = "brulee_linear_reg"), defaults = list() ) ) set_encoding( model = "linear_reg", eng = "brulee", mode = "regression", options = list( predictor_indicators = "none", compute_intercept = FALSE, remove_intercept = FALSE, allow_sparse_x = FALSE ) ) set_pred( model = "linear_reg", eng = "brulee", mode = "regression", type = "numeric", value = list( pre = NULL, post = NULL, func = c(fun = "predict"), args = list( object = quote(object$fit), new_data = quote(new_data), type = "numeric" ) ) )
vetiver_pr_predict <- function(pr, vetiver_model, path = "/predict", debug = is_interactive(), ...) { rlang::list2(...) pr <- vetiver_pr_post( pr = pr, vetiver_model = vetiver_model, path = path, debug = debug, ... ) pr <- vetiver_pr_docs(pr = pr, vetiver_model = vetiver_model, path = path) pr } vetiver_pr_post <- function(pr, vetiver_model, path = "/predict", debug = is_interactive(), ...) { rlang::list2(...) handler_startup(vetiver_model) pr <- plumber::pr_set_debug(pr, debug = debug) pr <- plumber::pr_get( pr, path = "/ping", function() {list(status = "online", time = Sys.time())} ) if (!is_null(vetiver_model$metadata$url)) { pr <- plumber::pr_get( pr, path = "/pin-url", function() vetiver_model$metadata$url ) } pr <- plumber::pr_post( pr, path = path, handler = handler_predict(vetiver_model, ...) ) } vetiver_pr_docs <- function(pr, vetiver_model, path = "/predict", all_docs = TRUE) { loadNamespace("rapidoc") modify_spec <- function(spec) api_spec(spec, vetiver_model, path, all_docs) pr <- plumber::pr_set_api_spec(pr, api = modify_spec) pr <- plumber::pr_set_docs( pr, "rapidoc", heading_text = paste("vetiver", utils::packageVersion("vetiver")) ) pr }
.onLoad <- function(libname, pkgname) { .jpackage(pkgname, lib.loc = libname) } rkafka.createProducer = function(metadataBrokerList,producerType="sync",compressionCodec="none", serializerClass="kafka.serializer.StringEncoder",partitionerClass="NULL",compressedTopics="NULL", queueBufferingMaxTime="NULL", queueBufferingMaxMessages="NULL", queueEnqueueTimeoutTime="NULL", batchNumMessages="NULL") { producerType=as.character(producerType); compressionCodec=as.character(compressionCodec); serializerClass=as.character(serializerClass); partitionerClass=as.character(partitionerClass); queueBufferingMaxTime=as.character(queueBufferingMaxTime); queueBufferingMaxMessages=as.character(queueBufferingMaxMessages); queueEnqueueTimeoutTime=as.character(queueEnqueueTimeoutTime); batchNumMessages=as.character(batchNumMessages); producerProperties <- .jnew("com/musigma/producer/ProducerProperties") producerPropertiesObj <- .jcall(producerProperties,"Ljava/util/Properties;","setProducerProperties",metadataBrokerList,producerType,compressionCodec,serializerClass,partitionerClass,compressedTopics,queueBufferingMaxTime,queueBufferingMaxMessages,queueEnqueueTimeoutTime,batchNumMessages) producer<- .jnew("com/musigma/producer/MuProducer",producerPropertiesObj) return(producer) } rkafka.send <-function(producer, topicName, ip, message) { topicName <- as.character(topicName) ip <- as.character(ip) message <- as.character(message) .jcall(producer,"V","sendMessage", topicName, ip, message) print("INFO:Remember to close the producer after done sending messages"); } rkafka.closeProducer <-function(producer) { .jcall(producer,"V","close") } rkafka.createConsumer<- function(zookeeperConnect,topicName,groupId="test-consumer-group",zookeeperConnectionTimeoutMs="100000",consumerTimeoutMs="10000",autoCommitEnable="NULL",autoCommitInterval="NULL",autoOffsetReset="NULL"){ zookeeperConnect=as.character(zookeeperConnect) topicName=as.character(topicName) groupId=as.character(groupId) zookeeperConnectionTimeoutMs=as.character(zookeeperConnectionTimeoutMs) consumerTimeoutMs=as.character(consumerTimeoutMs) autoCommitEnable=as.character(autoCommitEnable) autoCommitInterval=as.character(autoCommitInterval) autoOffsetReset=as.character(autoOffsetReset) Consumer<-.jnew("com/musigma/consumer/MuConsumer") print(Consumer) .jcall(Consumer,"V","CreateConsumer",zookeeperConnect,groupId,zookeeperConnectionTimeoutMs,consumerTimeoutMs,autoCommitEnable,autoCommitInterval,autoOffsetReset) success= .jcall(Consumer,"Z","startConsumer",topicName) if(success=="false"){ stop("Consumer didn't start propertly") } return(Consumer) } rkafka.read<-function(ConsumerObj) { message=.jcall(ConsumerObj,"Ljava/lang/String;","tail") print("INFO: Remember to close the consumer after done reading messages") return(message) } rkafka.readPoll<-function(ConsumerObj){ messages=.jcall(ConsumerObj,"[Ljava/lang/String;","poll") print("INFO: Remember to close the consumer after done reading messages") return(messages) } rkafka.closeConsumer<-function(ConsumerObj){ .jcall(ConsumerObj,"V","close") } rkafka.createSimpleConsumer<-function(kafkaServerURL, kafkaServerPort,connectionTimeOut, kafkaProducerBufferSize, clientId){ MuSimpleConsumer<-.jnew("com/musigma/consumer/MuSimpleConsumer") kafkaServerURL<-as.character(kafkaServerURL) kafkaServerPort<-as.character(kafkaServerPort) connectionTimeOut<-as.character(connectionTimeOut) kafkaProducerBufferSize<-as.character(kafkaProducerBufferSize) clientId<-as.character(clientId) .jcall(MuSimpleConsumer,"V","CreateSimpleConsumer",kafkaServerURL,kafkaServerPort,connectionTimeOut,kafkaProducerBufferSize,clientId) return(MuSimpleConsumer) } rkafka.receiveFromSimpleConsumer=function(SimpleConsumerObj,topicName,partition,Offset,msgReadSize){ topicName<-as.character(topicName) partition<-as.character(partition) Offset<-as.character(Offset) msgReadSize<-as.character(msgReadSize) .jcall(SimpleConsumerObj,"V","receive",topicName,partition,Offset,msgReadSize) } rkafka.readFromSimpleConsumer=function(SimpleConsumerObj){ msg=.jcall(SimpleConsumerObj,"Ljava/lang/String;","read") return(msg) } rkafka.closeSimpleConsumer=function(SimpleConsumer){ .jcall(SimpleConsumer,"V","close") }
context("use_analysis()") suppressMessages( rrtools::use_analysis(pkg = package_path) ) test_that("use_analysis generates the template directories and files", { expect_equal(list.files(file.path(package_path, 'analysis')), c("data", "figures", "paper", "supplementary-materials", "templates")) expect_equal(list.files(file.path(package_path, 'analysis', 'paper')), c("paper.Rmd", "references.bib")) }) test_that("use_analysis updates DESCRIPTION correctly", { pkg <- as.package(package_path) expect_equal(sum(grepl("suggests", names(pkg))), 1) expect_equal(sum(grepl("imports", names(pkg))), 1) expect_equal(pkg$suggests , "devtools,\ngit2r") }) suppressMessages( rrtools::use_analysis(pkg = package_path, location = "inst") ) test_that("use_analysis(location = 'inst') generates the template directories and files", { expect_equal(list.files(file.path(package_path, 'inst')), c("data", "figures", "paper", "supplementary-materials", "templates")) expect_equal(list.files(file.path(package_path, 'inst', 'paper')), c("paper.Rmd", "references.bib")) }) suppressMessages( rrtools::use_analysis(pkg = package_path, location = "vignettes") ) unlink(file.path(package_path, "runtime.txt")) test_that("use_analysis(location = 'vignettes') generates the template directories and files", { expect_equal(list.files(file.path(package_path, 'vignettes')), c("data", "figures", "paper", "supplementary-materials", "templates")) expect_equal(list.files(file.path(package_path, 'vignettes', 'paper')), c("paper.Rmd", "references.bib")) })
princomp <- function(x, ...) UseMethod("princomp") princomp.formula <- function(formula, data = NULL, subset, na.action, ...) { mt <- terms(formula, data = data) if(attr(mt, "response") > 0) stop("response not allowed in formula") cl <- match.call() mf <- match.call(expand.dots = FALSE) mf$... <- NULL mf[[1L]] <- quote(stats::model.frame) mf <- eval.parent(mf) if (.check_vars_numeric(mf)) stop("PCA applies only to numerical variables") na.act <- attr(mf, "na.action") mt <- attr(mf, "terms") attr(mt, "intercept") <- 0 x <- model.matrix(mt, mf) res <- princomp.default(x, ...) cl[[1L]] <- as.name("princomp") res$call <- cl if(!is.null(na.act)) { res$na.action <- na.act if(!is.null(sc <- res$scores)) res$scores <- napredict(na.act, sc) } res } princomp.default <- function(x, cor = FALSE, scores = TRUE, covmat = NULL, subset = rep_len(TRUE, nrow(as.matrix(x))), fix_sign = TRUE, ...) { chkDots(...) cl <- match.call() cl[[1L]] <- as.name("princomp") z <- if(!missing(x)) as.matrix(x)[subset, , drop = FALSE] if (is.list(covmat)) { if(any(is.na(match(c("cov", "n.obs"), names(covmat))))) stop("'covmat' is not a valid covariance list") cv <- covmat$cov n.obs <- covmat$n.obs cen <- covmat$center } else if(is.matrix(covmat)) { if(!missing(x)) warning("both 'x' and 'covmat' were supplied: 'x' will be ignored") cv <- covmat n.obs <- NA cen <- NULL } else if(is.null(covmat)){ dn <- dim(z) if(dn[1L] < dn[2L]) stop("'princomp' can only be used with more units than variables") covmat <- cov.wt(z) n.obs <- covmat$n.obs cv <- covmat$cov * (1 - 1/n.obs) cen <- covmat$center } else stop("'covmat' is of unknown type") if(!is.numeric(cv)) stop("PCA applies only to numerical variables") if (cor) { sds <- sqrt(diag(cv)) if(any(sds == 0)) stop("cannot use 'cor = TRUE' with a constant variable") cv <- cv/(sds %o% sds) } edc <- eigen(cv, symmetric = TRUE) ev <- edc$values if (any(neg <- ev < 0)) { if (any(ev[neg] < - 9 * .Machine$double.eps * ev[1L])) stop("covariance matrix is not non-negative definite") else ev[neg] <- 0 } cn <- paste0("Comp.", 1L:ncol(cv)) names(ev) <- cn dimnames(edc$vectors) <- if(missing(x)) list(dimnames(cv)[[2L]], cn) else list(dimnames(x)[[2L]], cn) sdev <- sqrt(ev) sc <- setNames(if (cor) sds else rep.int(1, ncol(cv)), colnames(cv)) fix <- if(fix_sign) function(A) { mysign <- function(x) ifelse(x < 0, -1, 1) A[] <- apply(A, 2L, function(x) x*mysign(x[1L])) A } else identity ev <- fix(edc$vectors) scr <- if (scores && !missing(x) && !is.null(cen)) scale(z, center = cen, scale = sc) %*% ev if (is.null(cen)) cen <- rep(NA_real_, nrow(cv)) edc <- list(sdev = sdev, loadings = structure(ev, class = "loadings"), center = cen, scale = sc, n.obs = n.obs, scores = scr, call = cl) class(edc) <- "princomp" edc } print.princomp <- function(x, ...) { cat("Call:\n"); dput(x$call, control=NULL) cat("\nStandard deviations:\n") print(x$sdev, ...) cat("\n", length(x$scale), " variables and ", x$n.obs, "observations.\n") invisible(x) }
loop_through_pfc_and_call_trafo <- function(pfc, newdata = NULL) { data_list <- list() k <- 1 for(i in 1:length(pfc)) { for(j in 1:length(pfc[[i]])){ if(is.null(newdata)){ data_list[[k]] <- to_matrix(pfc[[i]][[j]]$data_trafo()) }else{ data_list[[k]] <- to_matrix(pfc[[i]][[j]]$predict_trafo(newdata)) } k <- k + 1 } } return(data_list) } prepare_data <- function(pfc) { return( loop_through_pfc_and_call_trafo(pfc = pfc, newdata = NULL) ) } prepare_newdata <- function(pfc, newdata) { return( loop_through_pfc_and_call_trafo(pfc = pfc, newdata = newdata) ) } to_matrix <- function(x) { if(is.list(x)){ if(length(x)==1 & !is.null(dim(x[[1]]))){ return(x[[1]]) }else{ return(do.call("cbind", x)) } } if(is.data.frame(x)) return(as.matrix(x)) return(x) }
ptrapezoid <- function(q, min = 0, mode1 = 1/3, mode2 = 2/3, max = 1, n1 = 2, n3 = 2, alpha = 1, lower.tail = TRUE, log.p = FALSE) { out <- .Call("ptrapezoid", q, min, mode1, mode2, max, n1, n3, alpha) if(!lower.tail) out <- 1 - out if(log.p) out <- log(out) if(any(is.nan(out))) { warning("NaN in dtrapezoid") } else if(any(is.na(out))) { warning("NA in dtrapezoid") } return(out) }
context("test-rx_something") test_that("something rule works", { expect_true(grepl(rx_something(), "something")) expect_true(grepl(rx_something(mode="lazy"), "something")) expect_true(grepl(rx_something(), " ")) expect_true(grepl(rx_something(mode="lazy"), " ")) expect_false(grepl(rx_something(), "")) expect_false(grepl(rx_something(mode = "lazy"), "")) expect_error(rx_something(mode = "whatever")) })
lmmpar <- function( Y, X, Z, subject, beta, R, D, sigma, maxiter = 500, cores = 8, verbose = TRUE ){ iter <- 0 p <- nrow(beta) n <- length(unique(subject)) m <- nrow(Y) / n N <- n * m q <- dim(D)[1] Dinv <- ginv(D) Rinv <- ginv(R) cores <- floor(cores) if (cores > 1) { doParallel::registerDoParallel(cores) } Y_mem <- bigmemory::as.big.matrix(Y) X_mem <- bigmemory::as.big.matrix(X) Z_mem <- bigmemory::as.big.matrix(Z) subject_list <- split(seq_along(subject), subject) verbose <- isTRUE(verbose) nrm <- 1 repeat { if (iter > maxiter || nrm < 0.0005) break if (verbose) cat("iter: ", iter, "\n") core_fn <- function(core_i) { positions <- parallel::splitIndices(n, cores)[[core_i]] ubfi_sum <- array(0, c(p, p)) ubsi_sum <- array(0, c(p, 1)) sigma_sum <- 0 D_sum <- array(0, c(q, q)) for (i in positions) { subject_rows <- subject_list[[i]] Y_i <- Y_mem[subject_rows, , drop = FALSE] X_i <- X_mem[subject_rows, , drop = FALSE] Z_i <- Z_mem[subject_rows, , drop = FALSE] U_i <- MASS::ginv( Dinv + (t(Z_i) %*% Rinv %*% Z_i) ) W_i <- Rinv - (Rinv %*% Z_i %*% U_i %*% t(Z_i) %*% Rinv) ubfi_sum <- ubfi_sum + t(X_i) %*% W_i %*% X_i ubsi_sum <- ubsi_sum + t(X_i) %*% W_i %*% Y_i b_i <- U_i %*% t(Z_i) %*% Rinv %*% (Y_i - X_i %*% beta) sigma_sum <- sigma_sum + as.numeric( t(Y_i - X_i %*% beta) %*% W_i %*% (Y_i - X_i %*% beta) ) D_sum <- D_sum + (1 / sigma) * (b_i %*% t(b_i) + U_i) } list( ubfi_sum = ubfi_sum, ubsi_sum = ubsi_sum, sigma_sum = sigma_sum, D_sum = D_sum ) } if (cores == 1) { answers <- lapply(1, core_fn) } else { answers <- plyr::llply(1:cores, core_fn, .parallel = TRUE) } ubfi_total <- array(0, c(p, p)) + Reduce("+", lapply(answers, `[[`, "ubfi_sum")) ubsi_total <- array(0, c(p, 1)) + Reduce("+", lapply(answers, `[[`, "ubsi_sum")) sigma_total <- 0 + Reduce("+", lapply(answers, `[[`, "sigma_sum")) D_total <- array(0, c(q, q)) + Reduce("+", lapply(answers, `[[`, "D_sum")) final.beta <- ginv(ubfi_total) %*% ubsi_total final.D <- (1 / n) * as.matrix(D_total) final.sigma <- as.numeric( (1 / N) * as.matrix(sigma_total)[1, 1] ) nrm <- norm(final.beta - beta) beta <- final.beta final.D <- round(final.D, 10) final.D[!matrixcalc::is.positive.definite(final.D)] <- D D <- final.D if (any(final.sigma < 0)) { final.sigma[final.sigma < 0] <- sigma[final.sigma < 0] } sigma <- final.sigma Dinv <- ginv(D) iter <- iter + 1 } return(list( iterations = iter, beta = beta, D = D, sigma = sigma, norm = nrm )) }
makeFits = function(paths,amplitude=NULL,intercept=NULL,method = c("OLS", "initial")){ if (method =="OLS") {makeFits_OLS(paths)} else {makeFits_initial(paths,amplitude=amplitude,intercept = intercept)} }
ez_app = function(data = NULL) { ui = ez_ui(data) server = ez_server(data) shiny::runGadget(app = shiny::shinyApp(ui = ui, server = server), viewer = shiny::browserViewer()) }
load("testdata.rda") expect_error(LMMsolve(fixed = pheno ~ cross, data = "testDat"), "data should be a data.frame") expect_error(LMMsolve(fixed = ~ cross, data = testDat), "fixed should be a formula of the form") expect_error(LMMsolve(fixed = pheno ~ cross, random = pheno ~ cross, data = testDat), "random should be a formula of the form") expect_error(LMMsolve(fixed = pheno ~ cross, residual = pheno ~ cross, data = testDat), "residual should be a formula of the form") expect_error(LMMsolve(fixed = pheno ~ tst, data = testDat), "The following variables in the fixed part of the model are not") expect_error(LMMsolve(fixed = pheno ~ cross, random = ~tst, data = testDat), "The following variables in the random part of the model are not") expect_error(LMMsolve(fixed = pheno ~ cross, residual = ~tst, data = testDat), "The following variables in the residual part of the model are not") ginv <- matrix(1:4, nrow = 2) ginvL <- list(ginv = ginv) ginvLS <- list(ginv = ginv %*% t(ginv)) ginvLS2 <- list(ind = ginv %*% t(ginv)) indMat <- diag(nrow = nlevels(testDat$ind)) rownames(indMat) <- colnames(indMat) <- levels(testDat$ind) ginvLS3 <- list(ind = indMat) expect_error(LMMsolve(fixed = pheno ~ cross, ginverse = ginv, data = testDat), "ginverse should be a named list of symmetric matrices") expect_error(LMMsolve(fixed = pheno ~ cross, ginverse = ginvL, data = testDat), "ginverse should be a named list of symmetric matrices") expect_error(LMMsolve(fixed = pheno ~ cross, ginverse = ginvLS, data = testDat), "ginverse element ginv not defined in random part") expect_error(LMMsolve(fixed = pheno ~ cross, random = ~ind, ginverse = ginvLS2, data = testDat), "Dimensions of ind should match number of levels") expect_error(LMMsolve(fixed = pheno ~ cross, data = testDat, tolerance = -1), "tolerance should be a positive numerical value") expect_error(LMMsolve(fixed = pheno ~ cross, data = testDat, maxit= -1), "maxit should be a positive numerical value") expect_warning(LMMsolve(fixed = pheno ~ cross, data = testDat, maxit= 1), "No convergence after 1 iterations") Lgrp <- list(QTL = 3:5) expect_error(LMMsolve(fixed = pheno ~ cross, random = ~grp(QTL2), data = testDat), "The following variables are specified in grp in the random part") expect_error(LMMsolve(fixed = pheno ~ cross, random = ~grp(QTL2), group = Lgrp, data = testDat), "The following variables are specified in grp in the random part") mod0 <- LMMsolve(fixed = pheno ~ cross, data = testDat) mod1 <- LMMsolve(fixed = pheno ~ cross, residual = ~cross, data = testDat) mod2 <- LMMsolve(fixed = pheno ~ cross, random = ~grp(QTL), group = Lgrp, data = testDat) mod3 <- LMMsolve(fixed = pheno ~ cross, random = ~grp(QTL) + ind, group = Lgrp, data = testDat) mod4 <- LMMsolve(fixed = pheno ~ cross, random = ~ind, data = testDat) mod5 <- LMMsolve(fixed = pheno ~ cross, random = ~ind, ginverse = ginvLS3, data = testDat) expect_equivalent_to_reference(mod0, "LMMsolve0") expect_equivalent_to_reference(mod1, "LMMsolve1") expect_equivalent_to_reference(mod2, "LMMsolve2") expect_equivalent_to_reference(mod3, "LMMsolve3") expect_equivalent_to_reference(mod4, "LMMsolve4") expect_equivalent_to_reference(mod5, "LMMsolve5") mod3a <- LMMsolve(fixed = pheno ~ cross, random = ~grp(QTL) + ind, group = c(Lgrp, list(QTL2 = 1:2)), data = testDat) expect_equivalent(mod3, mod3a) expect_stdout(LMMsolve(fixed = pheno ~ cross, data = testDat, trace = TRUE), "iter logLik") expect_stdout(LMMsolve(fixed = pheno ~ cross, data = testDat, trace = TRUE), "2 -207.1218")
estimate.wqs <- function( y, X, Z = NULL, proportion.train = 1L, n.quantiles = 4L, place.bdls.in.Q1 = if (anyNA(X)) TRUE else FALSE, B = 100L, b1.pos = TRUE, signal.fn = c("signal.none", "signal.converge.only", "signal.abs", "signal.test.stat"), family = c("gaussian", "binomial", "poisson"), offset = NULL, verbose = FALSE ) { family <- tolower(family) family <- match.arg(family) signal.fn <- tolower(signal.fn) signal.fn <- match.arg(signal.fn) l <- check_wqs_function(X, y, Z, proportion.train, n.quantiles, place.bdls.in.Q1, B, b1.pos, signal.fn, family, offset, verbose) X <- l$X y <- l$y Z <- l$Z n <- dim(X)[1] C <- dim(X)[2] p <- dim(Z)[2] offset <- if (is.null(offset)) rep(1, n) else offset train <- sample(nrow(X), round(proportion.train * nrow(X), 0), replace = FALSE ) y.train <- y[train] X.train <- X[train, ] Z.train <- Z[train, , drop = FALSE] offset.train <- offset[train] if (0 < proportion.train & proportion.train < 1) { y.valid <- y[-train] X.valid <- X[-train, ] Z.valid <- Z[-train, , drop = FALSE] offset.valid <- offset[-train] } else { y.valid <- y.train X.valid <- X.train Z.valid <- Z.train offset.valid <- offset.train } train.index <- sort(train) if (verbose) { cat(" q.train <- make.quantile.matrix(X.train, n.quantiles, place.bdls.in.Q1, verbose) q.valid <- suppressMessages( make.quantile.matrix(X.valid, n.quantiles, place.bdls.in.Q1, verbose) ) colnames(q.train) <- colnames(X) if (0 < proportion.train & proportion.train < 1) { train.comparison <- summarize.compare(train.index, y, Z, verbose = verbose) } else { train.comparison <- NA } bounds <- specify.bounds(b1.pos, C) init <- specify.init(Z.train, y.train, b1.pos, C, family, offset.train, verbose) l <- wqs_b.est( y.train, q.train, Z.train, B, pars = init, objfn, lincon, ineqcon, ineqLB = bounds$ineqLB, ineqUB = bounds$ineqUB, family, offset.train ) result <- l$out wts.matrix <- result[, -(1:6)] boot.index <- l$boot.index if (sum(result$convergence) < B & signal.fn != "signal.converge.only") { warning(paste(B - sum(result$convergence), "bootstrap regression estimates in the training sets have not converged. Proceed results with caution. \n"), call. = FALSE) } if (b1.pos & min(result$beta_1) < -1e-8 | !b1.pos & max(result$beta_1) > 1e-8) { stop("Error in solnp. The beta1 constaint is violated.") } w.sum <- apply(wts.matrix, 1, sum) d <- data.frame( w.min = min(wts.matrix), w.max = max(wts.matrix), min(w.sum), max(w.sum) ) if (verbose) { cat(" print(d) } se <- function(X) sqrt(var(X)) if (signal.fn == "signal.none") { w <- apply(wts.matrix, 2, mean) se.w <- apply(wts.matrix, 2, se) } else if (signal.fn == "signal.converge.only") { A <- wts.matrix[result$convergence, ] w <- apply(A, 2, mean) se.w <- apply(A, 2, se) } else if (signal.fn == "signal.abs" | signal.fn == "signal.test.stat") { ts_weight <- abs(result$test_stat) / sum(abs(result$test_stat)) A <- ts_weight * wts.matrix w <- apply(A, 2, sum) se.w <- apply(A, 2, se) } else if (signal.fn == "signal.significance") { result$nb <- ifelse(result$pvalue_beta1 < 0.05, TRUE, FALSE) S <- wts.matrix[result$nb, ] w <- apply(S, 2, mean) se.w <- apply(S, 2, se) } fit.val <- wqs.fit(q.valid, Z.valid, y.valid, w, family, offset.valid) WQS <- fit.val$WQS fit <- fit.val$fit if (!fit$converged) stop("The Validation WQS Model did not converge.", call. = FALSE) D <- formals(estimate.wqs) A <- as.list(match.call()) U <- rlist::list.merge(D, A) out <- list(call = U, C = C, n = n, train.index = train.index, q.train = q.train, q.valid = q.valid, train.comparison = train.comparison, initial = init, train.estimates = result, processed.weights = cbind(mean.weights = w, se.weights = se.w), WQS = WQS, fit = fit, boot.index = boot.index ) class(out) <- "wqs" return(out) } summarize.compare <- function(train.index, y, Z, verbose = TRUE) { data.tmp <- if (is.null(Z)) {data.frame(y)} else {data.frame(y, Z)} covariate.num <- data.tmp data.tmp$trained <- as.factor( ifelse(1:nrow(data.tmp) %in% train.index, "trained", "validate") ) suppressWarnings( suppressMessages( compare <- make.descriptive.table( covariate.num = covariate.num, covariate.fac = NULL, treatment = data.tmp$trained, digits = 3 ) ) ) return(compare) } objfn <- function(param, q, Z, y, family, offset) { C <- dim(q)[2] b0 <- param[1] b1 <- param[2] w <- param[3:(2 + C)] if (is.null(Z)) { eta <- b0 + b1 * q %*% w } else { p <- if (is(Z, "numeric")) { 1 } else { dim(Z)[2] } theta <- param[(3 + C):(2 + C + p)] eta <- b0 + b1 * q %*% w + Z %*% theta } if (family == "gaussian") { leastsq <- sum((y - eta)^2) } else if (family == "binomial") { pi <- 1 / (1 + exp(-eta)) loglik <- sum(y * log(pi) + (1 - y) * log(1 - pi)) leastsq <- -loglik } else if (family == "poisson") { lambdai <- offset * exp(eta) loglik <- sum(y * log(lambdai) - lambdai) leastsq <- -loglik } return(leastsq) } lincon <- function(param, q, Z, y, family, offset) { C <- dim(q)[2] weights <- param[3:(2 + C)] return(sum(weights)) } ineqcon <- function(param, q, Z, y, family, offset) { C <- dim(q)[2] b1 <- param[2] weights <- param[3:(2 + C)] return(c(b1, weights)) } specify.bounds <- function(b1.pos, C) { if (b1.pos) { b1.LB <- 0 b1.UB <- Inf } else { b1.LB <- -Inf b1.UB <- 0 } ineqLB <- c(b1.LB, rep(0, C)) ineqUB <- c(b1.UB, rep(1, C)) out <- list(ineqLB, ineqUB) names(out) <- c("ineqLB", "ineqUB") return(out) } wqs_b.est <- function(y.train, q.train, Z.train, B, pars, objfn, lincon, ineqcon, ineqLB, ineqUB, family, offset) { C <- dim(q.train)[2] Z.null <- ifelse(is.null(Z.train), 1, 0) p <- if (Z.null == 0) { dim(Z.train)[2] } else { 0 } result <- matrix(0, nrow = B, ncol = length(pars)); colnames(result) <- names(pars) convergence <- vector(mode = "logical", B) boot.index <- matrix(0, nrow = length(y.train), ncol = B) beta1_glm <- rep(0, B) SE_beta1 <- rep(0, B) test_stat <- rep(0, B) pvalue <- rep(0, B) fit <- vector(mode = "list", B) for (b in 1:B) { boot.index[, b] <- samp <- sample(1:length(y.train), replace = TRUE) y.b <- as.vector(y.train[samp]) q.b <- q.train[samp, ] if (Z.null == 0) { Z.b <- as.matrix(Z.train[samp, ]) rownames(Z.b) <- NULL } else { Z.b <- NULL } result.b <- suppressWarnings( Rsolnp::solnp( pars, fun = objfn, eqfun = lincon, eqB = 1, ineqfun = ineqcon, ineqLB, ineqUB, LB = NULL, UB = NULL, q.b, Z.b, y.b, family, offset, control = list( rho = 1, outer.iter = 400, inner.iter = 800, delta = 1e-10, tol = 1e-10, trace = 0 ) ) ) result[b, ] <- result.b$pars convergence[b] <- ifelse (result.b$convergence == 0, TRUE, FALSE) w <- result.b$pars[3:(2 + C)] fit <- wqs.fit(q.b, Z.b, y.b, w, family, offset)$fit if (!fit$converged) stop("The training WQS Model in the ", scales::ordinal(b), " bootstrap did not converge.", call. = FALSE) beta1_glm[b] <- summary(fit)$coefficients["WQS", 1] SE_beta1[b] <- summary(fit)$coefficients["WQS", 2] test_stat[b] <- summary(fit)$coefficients["WQS", 3] pvalue[b] <- summary(fit)$coefficients["WQS", 4] fit[[b]] <- fit } wts.matrix <- as.matrix(result[, grep("w", colnames(result))]) colnames(wts.matrix) <- if (!is.null(colnames(q.train))) { colnames(q.train) } out <- data.frame(beta_1 = result[, "b1"], beta1_glm = beta1_glm, SE_beta1, pvalue_beta1 = pvalue, test_stat, convergence, wts.matrix) return(list(out = out, boot.index = boot.index, fit = fit)) } signal_tsglmno0 <- function(result, B) { cat("The test statistics from", sum(result$beta_1 < 0.0001), "out of the", B, "bootstraps are ignored in averaging the weights, as these have a b1 estimate of 0 (technically < 0.0001) from solnp in the training dataset") wts.matrix <- result[, -(1:6)] Sb <- ifelse(result$beta_1 < 0.0001, 0, result$test_stat) signal <- Sb / sum(Sb) A <- signal * wts.matrix w <- apply(A, 2, sum) return(w) } wqs.fit <- function(q, Z, y, w, family, offset) { WQS <- as.vector(q %*% w) Z.null <- ifelse(is.null(Z), 1, 0) if (Z.null == 0) { temp <- data.frame(y, Z, WQS) } else { temp <- data.frame(y, WQS) } fit <- glm2::glm2(y ~ ., data = temp, family = family, offset = log(offset)) out <- list(WQS, fit) names(out) <- c("WQS", "fit") return(out) }
context("cmd_interleave") test_that("cmd_interleave", { expect_equal(cmd_interleave("a", "b"), c("a", "b")) expect_equal(cmd_interleave(c("a", "b"), c("c", "d")), c("a", "c", "b", "d")) expect_equal(cmd_interleave("a", list("b")), list("a", "b")) expect_equal(cmd_interleave(c("a", "b"), list("c", "d")), list("a", "c", "b", "d")) expect_equal(cmd_interleave(list("a", "b"), list("c", "d")), list("a", "c", "b", "d")) obj <- lapply(1:2, object_to_bin) expect_equal(cmd_interleave(c("a", "b"), obj), list("a", obj[[1]], "b", obj[[2]])) expect_equal(cmd_interleave("a", obj[[1]]), list("a", obj[[1]])) expect_equal(cmd_interleave(obj[[1]], obj[[2]]), obj) expect_equal(cmd_interleave(obj[[1]], "b"), list(obj[[1]], "b")) expect_equal(cmd_interleave(c(), c()), character(0)) expect_equal(cmd_interleave(list(), list()), list()) expect_equal(cmd_interleave(NULL, NULL), character(0)) expect_equal(cmd_interleave("a", 1L), c("a", "1")) expect_equal(cmd_interleave("a", 1.0), c("a", "1")) expect_equal(cmd_interleave("a", TRUE), c("a", "1")) expect_error(cmd_interleave("a", c()), "b must be length 1") expect_error(cmd_interleave(c(), "b"), "b must be length 0") expect_error(cmd_interleave("a", sin), "cannot coerce type") expect_error(cmd_interleave(c("a", "b"), "c"), "b must be length 2") expect_error(cmd_interleave(runif(length(obj[[1]])), obj[[1]]), "b must be length") expect_error(cmd_interleave(obj[[1]], runif(length(obj[[1]]))), "b must be length") expect_equal(cmd_interleave("a", "b", "c"), c("a", "b", "c")) expect_equal(cmd_interleave("a", "b", NULL), c("a", "b")) expect_equal(cmd_interleave(NULL, NULL, NULL), character(0)) expect_equal(cmd_interleave("a", 1, pi), c("a", 1, pi)) expect_equal(cmd_interleave("a", raw(4), pi), list("a", raw(4), as.character(pi))) })
track.summary <- function(expr, pos=1, envir=as.environment(pos), list=NULL, pattern=NULL, glob=NULL, all.names=FALSE, times=track.options("summaryTimes", envir=envir)[[1]], access=track.options("summaryAccess", envir=envir)[[1]], size=TRUE, cache=FALSE, full=FALSE) { if (full) times <- access <- size <- cache <- TRUE if (is.logical(times)) times <- if (times) 3 else 0 if (!is.numeric(times)) stop("'times' must be logical or numeric") if (is.logical(access)) access <- if (access) 3 else 0 if (!is.numeric(access)) stop("'access' must be logical or numeric") trackingEnv <- getTrackingEnv(envir) opt <- track.options(trackingEnv=trackingEnv) if (!exists(".trackingSummary", envir=trackingEnv, inherits=FALSE)) stop("there is no .trackingSummary in the tracking env on ", envname(envir)) objSummary <- getObjSummary(trackingEnv, opt=opt) if (!is.data.frame(objSummary)) stop(".trackingSummary in ", envname(trackingEnv), " is not a data.frame") if (!all.names && nrow(objSummary) > 0) objSummary <- objSummary[substring(rownames(objSummary), 1, 1)!=".", ] objs <- rownames(objSummary) qexpr <- if (!missing(expr)) substitute(expr) else NULL if (!is.null(qexpr)) { if (is.name(qexpr) || is.character(qexpr)) { objName <- as.character(qexpr) } else { stop("expr argument must be a quoted or unquoted variable name") } list <- c(objName, list) if (!is.null(glob) || !is.null(pattern)) stop("must specify EITHER expr and/or list, OR pattern or glob") vars.how <- " specified" if (length(setdiff(list, objs))) warning("some specified vars are not in the summary: ", paste("'", setdiff(list, objs), "'", sep="", collapse=", ")) } else { vars.how <- "" if (!is.null(glob)) pattern <- glob2rx(glob) if (!is.null(pattern)) { objs <- grep(pattern, objs, value=TRUE) vars.how <- " matching" } } if (!is.null(list)) objs <- intersect(objs, list) tracked.actual <- unique(track.status(envir=envir, qexpr=qexpr, list=list, pattern=pattern, glob=glob, file.status=FALSE, what="tracked", all.names=all.names)) if (length(setdiff(tracked.actual, objs))) warning("some", vars.how, " vars appear to be tracked but are not in the summary: ", paste("'", setdiff(tracked.actual, objs), "'", sep="", collapse=", ")) if (length(setdiff(objs, tracked.actual))) warning("some", vars.how, " vars are in the summary but not tracked (info in summary may be wrong for the visible instances of these vars): ", paste("'", setdiff(objs, tracked.actual), "'", sep="", collapse=", ")) objSummary <- objSummary[objs, ,drop=FALSE] colsWanted <- c("class", "mode", "extent", "length") if (size) colsWanted <- c(colsWanted, "size") if (cache) colsWanted <- c(colsWanted, "cache") if (times > 0) colsWanted <- c(colsWanted, "modified") if (times > 1) colsWanted <- c(colsWanted, "created") if (times > 2) colsWanted <- c(colsWanted, "accessed") if (access == 1) colsWanted <- c(colsWanted, c("TA", "TW")) else if (access == 2) colsWanted <- c(colsWanted, c("ES", "SA", "SW", "PA", "PW")) else if (access >= 3) colsWanted <- c(colsWanted, c("ES", "SA", "SW", "PA", "PW", "TA", "TW")) if (any(is.element(colsWanted, c("TA", "TW")))) objSummary <- cbind(objSummary, TA=objSummary$SA + objSummary$PA, TW=objSummary$SW + objSummary$PW) return(objSummary[order(rownames(objSummary)), colsWanted]) }
preproc <- function(args, ..., na.txt = NULL) { args$na.txt <- na.txt args$n <- length(args$u1) tasks <- list(...) for (i in seq_along(tasks)) { stopifnot(is.function(tasks[[i]])) args <- tasks[[i]](args) } args } check_u <- function(args) { if (is.symbol(args$u1) | is.symbol(args$u2)) stop("\n In ", args$call[1], ": ", "u1 and/or u2 are missing.", call. = FALSE) if (is.null(args$u1) == TRUE || is.null(args$u2) == TRUE) stop("\n In ", args$call[1], ": ", "u1 and/or u2 are not set or have length zero.", call. = FALSE) if (length(args$u1) != length(args$u2)) stop("\n In ", args$call[1], ": ", "Lengths of u1 and u2 do not match.", call. = FALSE) if ((!is.numeric(args$u1) & !all(is.na(args$u1)))) stop("\n In ", args$call[1], ": ", "u1 has to be a numeric vector.", call. = FALSE) if ((!is.numeric(args$u2) & !all(is.na(args$u2)))) stop("\n In ", args$call[1], ": ", "u2 has to be a numeric vector.", call. = FALSE) args } fix_nas <- function(args) { if (!is.null(args$data)) { if (any(is.na(args$data))) { num.na <- sum(!complete.cases(args$data)) freq.na <- round(num.na / nrow(args$data) * 100, 1) args$msg <- paste0(" In ", args$call[1], ": ", num.na, " of the evaluation points", " (", freq.na, "%) contain", ifelse(num.na == 1, "s", ""), " NAs.", args$na.txt) args$na.ind <- which(!complete.cases(args$data)) args$data[args$na.ind, ] <- 0.5 } } else if (any(is.na(args$u1 + args$u2))) { num.na <- sum(!complete.cases(args$u1 + args$u2)) freq.na <- round(num.na / length(args$u1) * 100, 1) args$msg <- paste0(" In ", args$call[1], ": ", num.na, " of the evaluation points", " (", freq.na, "%) contain", ifelse(num.na == 1, "s", ""), " NAs.", args$na.txt) args$na.ind <- which(is.na(args$u1 + args$u2)) args$u1[args$na.ind] <- 0.5 args$u2[args$na.ind] <- 0.5 } else { args$msg <- na.ind <- NULL } args } reset_nas <- function(out, args) { if (is.vector(out)) { if (!is.null(args$na.ind)) out[args$na.ind] <- NA } else { if (length(dim(out)) == 2) out[args$na.ind, ] <- NA if (length(dim(out)) == 3) out[, , args$na.ind] <- NA } if (!is.null(args$msg)) warning(args$msg, call. = FALSE) out } remove_nas <- function(args) { if (!is.null(args$data)) { if (any(is.na(args$data))) { num.na <- sum(!complete.cases(args$data)) freq.na <- round(num.na / nrow(args$data) * 100, 1) warning(" In ", args$call[1], ": ", num.na, " observation", ifelse(num.na > 1, "s", ""), " (", freq.na, "%) contain", ifelse(num.na == 1, "s", ""), " NAs.", args$na.txt, call. = FALSE) args$na.ind <- which(!complete.cases(args$data)) args$data <- args$data[complete.cases(args$data), , drop = FALSE] args$n <- nrow(args$data) } } else { if (any(is.na(args$u1 + args$u2))) { num.na <- sum(!complete.cases(args$u1 + args$u2)) freq.na <- round(num.na / length(args$u1) * 100, 1) warning(" In ", args$call[1], ": ", num.na, " observation", ifelse(num.na > 1, "s", ""), " (", freq.na, "%) contain", ifelse(num.na == 1, "s", ""), " NAs.", args$na.txt, call. = FALSE) args$na.ind <- which(is.na(args$u1 + args$u2)) args$u1 <- args$u1[-args$na.ind] args$u2 <- args$u2[-args$na.ind] } else { args$msg <- na.ind <- NULL } args$n <- length(args$u1) } args } check_if_01 <- function(args) { u <- args$data if (!is.null(u)) { i <- complete.cases(u) if (sum(i) > 0) { if (any(u[i] > 1) || any(u[i] < 0)) stop("\n In ", args$call[1], ": ", "Data have to be in the interval [0,1]^d.", call. = FALSE) } } else { if (any(args$u1 > 1) || any(args$u1 < 0)) stop("\n In ", args$call[1], ": ", "Data have to be in the interval [0,1].", call. = FALSE) if (any(args$u2 > 1) || any(args$u2 < 0)) stop("\n In ", args$call[1], ": ", "Data have to be in the interval [0,1].", call. = FALSE) } args } match_spec_lengths <- function(args) { n <- ifelse(!is.null(args$u1), length(args$u1), max(length(args$family), length(args$par), length(args$par2))) args$family <- c(args$family) args$par <- c(args$par) args$par2 <- c(args$par2) if (any(c(length(args$family), length(args$par), length(args$par2)) == n)) { if (length(args$family) == 1) args$family <- rep(args$family, n) if (length(args$par) == 1) args$par <- rep(args$par, n) if (length(args$par2) == 1) args$par2 <- rep(args$par2, n) } if (!(length(args$family) %in% c(1, n))) stop("\n In ", args$call[1], ": ", "'family' has to be a single number or a size n vector", call. = FALSE) if (!(length(args$par) %in% c(1, n))) stop("\n In ", args$call[1], ": ", "'par' has to be a single number or a size n vector", call. = FALSE) if (!(length(args$par2) %in% c(1, n))) stop("\n In ", args$call[1], ": ", "'par2' has to be a single number or a size n vector", call. = FALSE) args } expand_lengths <- function(args) { n <- ifelse(!is.null(args$u1), length(args$u1), max(length(args$u1), length(args$family), length(args$par), length(args$par2))) args$family <- c(args$family) args$par <- c(args$par) args$par2 <- c(args$par2) if (length(args$family) == 1) args$family <- rep(args$family, n) if (length(args$par) == 1) args$par <- rep(args$par, n) if (length(args$par2) == 1) args$par2 <- rep(args$par2, n) if (!(length(args$family) %in% c(1, n))) stop("\n In ", args$call[1], ": ", "'family' has to be a single number or a size n vector", call. = FALSE) if (!(length(args$par) %in% c(1, n))) stop("\n In ", args$call[1], ": ", "'par' has to be a single number or a size n vector", call. = FALSE) if (!(length(args$par2) %in% c(1, n))) stop("\n In ", args$call[1], ": ", "'par2' has to be a single number or a size n vector", call. = FALSE) args } extract_from_BiCop <- function(args) { if (is.symbol(args$family)) args$family <- NA if (is.symbol(args$par)) args$par <- NA if (class(args$family) == "BiCop") args$obj <- args$family if (!is.null(args$obj)) { stopifnot(class(args$obj) == "BiCop") args$family <- args$obj$family args$par <- args$obj$par args$par2 <- args$obj$par2 } if (is.null(args$par) & (all(args$family == 0))) args$par <- 0 if (any(is.na(args$family)) | any(is.na(args$par))) stop("\n In ", args$call[1], ": ", "Provide either 'family' and 'par' or 'obj'", call. = FALSE) args } check_fam_par <- function(args) { if (args$check.pars) { BiCopCheck(args$family, args$par, args$par2, call = args$call) } else { args$family[(args$family %in% c(3, 13, 23, 33)) & (args$par == 0)] <- 0 args$family[(args$family == 5) & (args$par == 0)] <- 0 } args } check_nobs <- function(args) { if (!is.null(args$data)) { if (nrow(args$data) < 2) stop("\n In ", args$call[1], ": ", "Number of observations has to be at least 2.", call. = FALSE) } else { if (length(args$u1) < 2) stop("\n In ", args$call[1], ": ", "Number of observations has to be at least 2.", call. = FALSE) } args } prep_familyset <- function(args) { if (is.na(args$familyset[1])) args$familyset <- allfams if (!all(abs(args$familyset) %in% allfams)) { wrong_fam <- args$familyset[-which(abs(args$familyset) %in% allfams)] if (length(wrong_fam) == 1) { msg <- paste("Copula family", wrong_fam) } else { msg <- paste("Copula families", paste0(wrong_fam, collapse = ", ")) } stop("\n In ", args$call[1], ": ", msg, " not implemented.", call. = FALSE) } if (args$rotations) args$familyset <- with_rotations(args$familyset) if (length(unique(sign(args$familyset[args$familyset != 0]))) > 1) { stop("\n In ", args$call[1], ": ", "'familyset' must not contain positive AND negative numbers.", call. = FALSE) } if (any(args$familyset < 0)) args$familyset <- setdiff(allfams, -args$familyset) args } check_fam_tau <- function(args) { if (is.null(args$weights)) args$weights <- NA args$emp_tau <- fasttau(args$u1, args$u2, args$weights) if ((args$emp_tau > 0) & !any(args$familyset %in% c(0, posfams))) { stop("\n In ", args$call[1], ": ", "Empirical Kendall's tau is positive, but familyset only ", "contains families for negative dependence.", call. = FALSE) } else if ((args$emp_tau < 0) & !any(args$familyset %in% c(0, negfams))){ stop("\n In ", args$call[1], ": ", "Empirical Kendall's tau is negative, but familyset only ", "contains families for positive dependence.", call. = FALSE) } args } todo_fams <- function(args) { if (args$emp_tau < 0) { todo <- c(0, negfams) } else if (args$emp_tau > 0) { todo <- c(0, posfams) } else { todo <- allfams } args$familyset <- todo[which(todo %in% args$familyset)] args } todo_fams_presel <- function(args) { if (args$emp_tau > 0) { x <- qnorm(cbind(args$u1, args$u2)) e <- try({ c11 <- cor(x[(x[, 1] > 0) & (x[, 2] > 0), ])[1, 2] c00 <- cor(x[(x[, 1] < 0) & (x[, 2] < 0), ])[1, 2] }, silent = TRUE) if (inherits(e, "try-error")) { todo <- c(0, posfams) } else if (any(is.na(c(c11, c00)))) { todo <- c(0, posfams) } else { if (c11 - c00 > 0.3) { todo <- c(0, 2, fams11) } else if (c11 - c00 > 0.05) { todo <- c(0, 1, 2, 5, 20, fams11) } else if (c11 - c00 < -0.3) { todo <- c(0, 2, fams00) } else if (c11 - c00 < -0.05) { todo <- c(0, 1, 2, 5, 10, fams00) } else { todo <- c(0, posfams) } } } else if (args$emp_tau < 0) { x <- qnorm(cbind(args$u1, args$u2)) e <- try({ c10 <- cor(x[(x[, 1] > 0) & (x[, 2] < 0), ])[1, 2] c01 <- cor(x[(x[, 1] < 0) & (x[, 2] > 0), ])[1, 2] }, silent = TRUE) if (inherits(e, "try-error")) { todo <- c(0, negfams) } else if (any(is.na(c(c10, c01)))) { todo <- c(0, negfams) } else { if (c10 - c01 < -0.3) { todo <- c(0, 2, fams10) } else if (c10 - c01 < -0.05) { todo <- c(0, 1, 2, 5, 30, fams10) } else if (c10 - c01 > 0.3) { todo <- c(0, 2, fams01) } else if (c10 - c01 > 0.05) { todo <- c(0, 1, 2, 5, 40, fams01) } else { todo <- c(0, negfams) } } } else { todo <- allfams } tmpfams <- todo[which(todo %in% args$familyset)] if (length(tmpfams) > 0) args$familyset <- tmpfams args } check_est_pars <- function(args) { if (!is.null(args$max.df)) { if (args$max.df <= 2) stop("\n In ", args$call[1], ": ", "The upper bound for the degrees of freedom parameter has to be", "larger than 2.", call. = FALSE) } else { args$max.df <- 30 } if (!is.null(args$max.BB)) { if (!is.list(args$max.BB)) stop("\n In ", args$call[1], ": ", "max.BB has to be a list.", call. = FALSE) if (!all(names(args$max.BB) == c("BB1", "BB6", "BB7", "BB8"))) stop("\n In ", args$call[1], ": ", 'max.BB has to be a named list with entries "BB1", "BB6", "BB7", "BB8".', call. = FALSE) if (any(sapply(args$max.BB, length) != 2)) stop("\n In ", args$call[1], ": ", 'All components of max.BB have to be two-dimensional numeric vectors.', call. = FALSE) if (args$max.BB$BB1[1] < 0.001) stop("\n In ", args$call[1], ": ", "The upper bound for the first parameter of the BB1 copula should ", "be greater than 0.001 (lower bound for estimation).", call. = FALSE) if (args$max.BB$BB1[2] < 1.001) stop("\n In ", args$call[1], ": ", "The upper bound for the second parameter of the BB1 copula should ", "be greater than 1.001 (lower bound for estimation).", call. = FALSE) if (args$max.BB$BB6[1] < 1.001) stop("\n In ", args$call[1], ": ", "The upper bound for the first parameter of the BB6 copula should ", "be greater than 1.001 (lower bound for estimation).", call. = FALSE) if (args$max.BB$BB6[2] < 1.001) stop("\n In ", args$call[1], ": ", "The upper bound for the second parameter of the BB6 copula should ", "be greater than 1.001 (lower bound for estimation).", call. = FALSE) if (args$max.BB$BB7[1] < 1.001) stop("\n In ", args$call[1], ": ", "The upper bound for the first parameter of the BB7 copula should ", "be greater than 1.001 (lower bound for estimation).", call. = FALSE) if (args$max.BB$BB7[2] < 0.001) stop("\n In ", args$call[1], ": ", "The upper bound for the second parameter of the BB7 copula should ", "be greater than 0.001 (lower bound for estimation).", call. = FALSE) if (args$max.BB$BB8[1] < 1.001) stop("\n In ", args$call[1], ": ", "The upper bound for the first parameter of the BB8 copula should ", "be greater than 1.001 (lower bound for estimation).", call. = FALSE) if (args$max.BB$BB8[2] < 0.001 || args$max.BB$BB8[2] > 1) stop("\n In ", args$call[1], ": ", "The upper bound for the second parameter of the BB8 copula should ", "be in the interval [0.001,1].", call. = FALSE) } else { args$max.BB <- list(BB1 = c(5, 6), BB6 = c(6, 6), BB7 = c(5, 6), BB8 = c(6, 1)) } if (!is.null(args$family)) { if (!(all(args$family %in% allfams))) stop("\n In ", args$call[1], ": ", "Copula family not implemented.", call. = FALSE) } if (!is.null(args$familyset)) { if (!(all(abs(args$familyset) %in% allfams))) stop("\n In ", args$call[1], ": ", "Copula family not implemented.", call. = FALSE) } if (!is.null(args$method)) { if (args$method != "mle" && args$method != "itau") stop("\n In ", args$call[1], ": ", "Estimation method has to be either 'mle' or 'itau'.", call. = FALSE) if (!is.null(args$family)) { if ((args$method == "itau") && (!(args$family %in% c(0, 2, allfams[onepar])))) { warning(" In ", args$call[1], ": ", "For two parameter copulas the estimation method 'itau' cannot ", "be used. The method is automatically set to 'mle'.", call. = FALSE) args$method <- "mle" } } if (!is.null(args$familyset)) { if ((args$method == "itau") && (!all(args$familyset %in% c(0, 2, allfams[onepar])))) { warning(" In ", args$call[1], ": ", "For two parameter copulas the estimation method 'itau' cannot ", "be used. The method is automatically set to 'mle'.", call. = FALSE) args$method <- "mle" } } } else { args$method <- "mle" } if (!is.null(args$se)) { if (is.logical(args$se) == FALSE) stop("\n In ", args$call[1], ": ", "se has to be a logical variable (TRUE or FALSE).", call. = FALSE) } else { args$se <- FALSE } if (is.null(args$weights)) args$weights <- NA args } check_twoparams <- function(args) { if (!is.null(args$familyset)) { if ((args$method == "itau") && (!all(args$familyset %in% c(0, 2, allfams[onepar])))) { warning(' In ', args$call[1], ': ', 'Two parameter families (other than the t-copula) cannot', ' be handled by method "itau".', ' They are automatically removed from the familyset.', call. = FALSE) args$familyset <- args$familyset[args$familyset %in% c(0, 2, allfams[onepar])] } } args } check_data <- function(args) { if (is.symbol(args$data)) stop("\n In ", args$call[1], ": ", "Argument data is missing.", call. = FALSE) if (is.null(args$data)) stop("\n In ", args$call[1], ": ", "Argument data is missing.", call. = FALSE) if (is.vector(args$data)) { args$data <- t(as.matrix(args$data)) } else { args$data <- as.matrix(args$data) } if (!is.numeric(args$data) & !all(is.na(args$data))) stop("\n In ", args$call[1], ": ", "Data have to be numeric.", call. = FALSE) if (ncol(args$data) < 2) stop("\n In ", args$call[1], ": ", "Dimension has to be at least 2.", call. = FALSE) if (is.null(colnames(args$data))) colnames(args$data) <- paste("V", seq.int(ncol(args$data)), sep = "") args$n <- nrow(args$data) args$d <- ncol(args$data) args } check_RVMs <- function(args) { if (!is.null(args$RVM)) args$RVM <- check_RVM(args$RVM, "RVM", args$call, args$d, args$check.pars) if (!is.null(args$RVM1)) args$RVM1 <- check_RVM(args$RVM1, "RVM1", args$call, args$d, args$check.pars) if (!is.null(args$RVM2)) args$RVM2 <- check_RVM(args$RVM2, "RVM2", args$call, args$d, args$check.pars) args } check_RVM <- function(RVM, name, call, d, check.pars) { if (!is(RVM, "RVineMatrix")) stop("\n In ", call[1], ": ", name, " has to be an RVineMatrix object.", call. = FALSE) if (!is.null(d)) { if (d != dim(RVM)) stop("\n In ", call[1], ": ", "Dimensions of data and ", name, " do not match.", call. = FALSE) } if (any(!is.na(RVM$par)) & (nrow(RVM$par) != ncol(RVM$par))) stop("\n In ", call[1], ": ", "Parameter matrix has to be quadratic.", call. = FALSE) if (any(!is.na(RVM$par2)) & (nrow(RVM$par2) != ncol(RVM$par2))) stop("\n In ", call[1], ": ", "Second parameter matrix has to be quadratic.", call. = FALSE) if (is.null(check.pars)) check.pars <- TRUE if (!all(RVM$par %in% c(0, NA))) { for (i in 2:dim(RVM$Matrix)[1]) { for (j in 1:(i - 1)) { if (check.pars) { BiCopCheck(RVM$family[i, j], RVM$par[i, j], RVM$par2[i, j], call = call) } else { indep <- (RVM$family[i, j] %in% c(5, 3, 13, 23, 33)) & (RVM$par[i, j] == 0) if (indep) RVM$family[i, j] <- 0 } } } } RVM } prep_RVMs <- function(args) { if (!is.null(args$RVM)) { args$RVM$par[is.na(args$RVM$par)] <- 0 args$RVM$par[upper.tri(args$RVM$par, diag = TRUE)] <- 0 args$RVM$par2[is.na(args$RVM$par2)] <- 0 args$RVM$par2[upper.tri(args$RVM$par2, diag = TRUE)] <- 0 } else { args$RVM1$par[is.na(args$RVM1$par)] <- 0 args$RVM1$par[upper.tri(args$RVM1$par, diag = TRUE)] <- 0 args$RVM1$par2[is.na(args$RVM1$par2)] <- 0 args$RVM1$par2[upper.tri(args$RVM1$par2, diag = TRUE)] <- 0 args$RVM2$par[is.na(args$RVM2$par)] <- 0 args$RVM2$par[upper.tri(args$RVM2$par, diag = TRUE)] <- 0 args$RVM2$par2[is.na(args$RVM2$par2)] <- 0 args$RVM2$par2[upper.tri(args$RVM2$par2, diag = TRUE)] <- 0 } args } check_matrix <- function(args) { if (is.symbol(args$Matrix)) stop("\n In ", args$call[1], ": ", "Matrix is missing.", call. = FALSE) if (nrow(args$Matrix) != ncol(args$Matrix)) stop("\n In ", args$call[1], ": ", "Structure matrix has to be quadratic.", call. = FALSE) if (max(args$Matrix) > nrow(args$Matrix)) stop("\n In ", args$call[1], ": ", "Structure matrix can only contain numbers 0:", nrow(args$Matrix), ".", call. = FALSE) args$Matrix[is.na(args$Matrix)] <- 0 args$Matrix <- ToLowerTri(args$Matrix) if (RVineMatrixCheck(args$Matrix) != 1) stop("\n In ", args$call[1], ": ", "Matrix is not a valid R-vine matrix.", call. = FALSE) args } check_parmat <- function(args) { args$family <- as.matrix(args$family) if (nrow(args$family) != ncol(args$family)) stop("\n In ", args$call[1], ": ", "family has to be quadratic.", call. = FALSE) args$family[is.na(args$family)] <- 0 args$family <- ToLowerTri(args$family) args$family[upper.tri(args$family, diag = T)] <- 0 args } check_fammat <- function(args) { args$par <- as.matrix(args$par) if (nrow(args$par) != ncol(args$par)) stop("\n In ", args$call[1], ": ", "par has to be quadratic.", call. = FALSE) args$par[is.na(args$par)] <- 0 args$par <- ToLowerTri(args$par) args$par[upper.tri(args$par, diag = T)] <- 0 args } check_par2mat <- function(args) { args$par2 <- as.matrix(args$par2) if (nrow(args$par2) != ncol(args$par2)) stop("\n In ", args$call[1], ": ", "par2 has to be quadratic.", call. = FALSE) args$par2[is.na(args$par2)] <- 0 args$par2 <- ToLowerTri(args$par2) args$par2[upper.tri(args$par2, diag = T)] <- 0 args } set_dims <- function(family, par = 0, par2 = 0, tau = 0) { dims <- max(length(family), length(par), length(par2), length(tau)) if (!is.null(dim(family))) dims <- dim(family) if (!is.null(dim(par))) dims <- dim(par) if (!is.null(dim(par2))) dims <- dim(par2) if (!is.null(dim(tau))) dims <- dim(tau) dims }
loglikcub0q <- function(m,ordinal,W,beta0,gama){ pai<-1/(1+exp(-beta0)) W<-as.matrix(W) probn<-probcub0q(m,factor(ordinal,ordered=TRUE),W,pai,gama) sum(log(probn)) }
run_synthetic_forecast <- function( df, col_unit_name, unit_of_interest, col_time, periods_to_forecast, serie_of_interest ){ stopifnot( class(df)=="data.frame", class(col_unit_name)=="character", class(unit_of_interest)%in%c("integer", "character", "numeric"), class(col_time)%in%c("character"), class(periods_to_forecast)%in%c("integer", "numeric"), class(serie_of_interest)%in%c("character") ) out <- tryCatch( { print(paste("Forecasting Unit: ", unit_of_interest, ". Serie: ", serie_of_interest)) intern_max_time_unit_interedt <- intern_get_max_time_unit_of_interest( df = df, col_unit_name = col_unit_name, unit_of_interest = unit_of_interest, col_time = col_time ) intern_elegible_units <- intern_elegile_units( df = df, col_unit_name = col_unit_name, col_time = col_time, max_time_unit_of_interest = intern_max_time_unit_interedt, periods_to_forecast = periods_to_forecast ) intern_dataset_prepared <- prepare_dataset( df = df, df_elegible_units = intern_elegible_units, col_unit_name = col_unit_name, col_time = col_time, unit_of_interest = unit_of_interest, max_time_unit_of_interest = intern_max_time_unit_interedt ) intern_compute_synthetic_control_out <- compute_synthetic_control( prepared_dataset = intern_dataset_prepared, unit_of_interest = unit_of_interest, serie_of_interest = serie_of_interest, col_time = col_time, max_time_unit_of_interest = intern_max_time_unit_interedt ) compute_result_tables_out <- compute_result_tables( synthetic_control_output = intern_compute_synthetic_control_out, unit_of_interest = unit_of_interest, serie_of_interest = serie_of_interest, max_time_unit_of_interest = intern_max_time_unit_interedt, df = df, col_unit_name = col_unit_name, periods_to_forecast = periods_to_forecast, col_time = col_time ) compute_result_tables_out }, error=function(cond){ print('Error in Function run_synthetic_forecast():') cond } ) return(out) }
submit <- local({ getOutput <- function(sid) { if(sid == "pollutantmean-1") { source("pollutantmean.R") pollutantmean("specdata", "sulfate", 1:10) } else if(sid == "pollutantmean-2") { source("pollutantmean.R") pollutantmean("specdata", "nitrate", 70:72) } else if(sid == "pollutantmean-3") { source("pollutantmean.R") pollutantmean("specdata", "sulfate", 34) } else if(sid == "pollutantmean-4") { source("pollutantmean.R") pollutantmean("specdata", "nitrate") } else if(sid == "complete-1") { source("complete.R") cc <- complete("specdata", c(6, 10, 20, 34, 100, 200, 310)) paste(cc$nobs, collapse = "\n") } else if(sid == "complete-2") { source("complete.R") cc <- complete("specdata", 54) cc$nobs } else if(sid == "complete-3") { source("complete.R") set.seed(42) cc <- complete("specdata", 332:1) use <- sample(332, 10) paste(cc[use, "nobs"], collapse = "\n") } else if(sid == "corr-1") { source("corr.R") cr <- corr("specdata") cr <- sort(cr) set.seed(868) out <- round(cr[sample(length(cr), 5)], 4) paste(out, collapse = "\n") } else if(sid == "corr-2") { source("corr.R") cr <- corr("specdata", 129) cr <- sort(cr) n <- length(cr) set.seed(197) out <- c(n, round(cr[sample(n, 5)], 4)) paste(out, collapse = "\n") } else if(sid == "corr-3") { source("corr.R") cr <- corr("specdata", 2000) n <- length(cr) cr <- corr("specdata", 1000) cr <- sort(cr) paste(c(n, round(cr, 4)), collapse = "\n") } else { stop("invalid part number") } } partPrompt <- function() { partlist <- list("pollutantmean-1" = "'pollutantmean' part 1", "pollutantmean-2" = "'pollutantmean' part 2", "pollutantmean-3" = "'pollutantmean' part 3", "pollutantmean-4" = "'pollutantmean' part 4", "complete-1" = "'complete' part 1", "complete-2" = "'complete' part 2", "complete-3" = "'complete' part 3", "corr-1" = "'corr' part 1", "corr-2" = "'corr' part 2", "corr-3" = "'corr' part 3" ) pretty_out("Which part are you submitting?") part <- select.list(partlist, graphics=FALSE) names(part) } getChallenge <- function(email, challenge.url) { params <- list(email_address = email, response_encoding = "delim") result <- getForm(challenge.url, .params = params) s <- strsplit(result, "|", fixed = TRUE)[[1]] list(ch.key = s[5], state = s[7]) } challengeResponse <- function(password, ch.key) { x <- paste(ch.key, password, sep = "") digest(x, algo = "sha1", serialize = FALSE) } submitSolution <- function(email, ch.resp, sid, output, signature, submit.url, src = "", http.version = NULL) { output <- as.character(base64(output)) src <- as.character(base64(src)) params <- list(assignment_part_sid = sid, email_address = email, submission = output, submission_aux = src, challenge_response = ch.resp, state = signature) params <- lapply(params, URLencode) result <- postForm(submit.url, .params = params) s <- strsplit(result, "\\r\\n")[[1]] tail(s, 1) } get_courseid <- function() { pretty_out("The first item I need is your Course ID. For example, if the", "homepage for your Coursera course was", "'https://class.coursera.org/rprog-001',", "then your course ID would be 'rprog-001' (without the quotes).", skip_after=TRUE) repeat { courseid <- readline("Course ID: ") courseid <- gsub("\'|\"", "", courseid) is_url <- str_detect(courseid, "www[.]|http:|https:") is_numbers <- str_detect(courseid, "^[0-9]+$") is_example <- str_detect(courseid, fixed("rprog-001")) if(!any(is_url, is_numbers, is_example)){ break } else { if(is_url) { pretty_out("It looks like you entered a web address, which is not what I'm", "looking for.") } if(is_numbers) { pretty_out("It looks like you entered a numeric ID, which is not what I'm", "looking for.") } if(is_example) { pretty_out("It looks like you entered the Course ID that I used as an", "example, which is not what I'm looking for.") } } pretty_out("Instead, I need your Course ID, which is the last", "part of the web address for your Coursera course.", "For example, if the homepage for your Coursera course was", "'https://class.coursera.org/rprog-001',", "then your course ID would be 'rprog-001' (without the quotes).", skip_after=TRUE) } courseid } pretty_out <- function(..., skip_before=TRUE, skip_after=FALSE) { wrapped <- strwrap(str_c(..., sep = " "), width = getOption("width") - 2) mes <- str_c("| ", wrapped, collapse = "\n") if(skip_before) mes <- paste0("\n", mes) if(skip_after) mes <- paste0(mes, "\n") message(mes) } checkPkgs <- function() { pkg.inst <- installed.packages() pkgs <- c("RCurl", "digest", "stringr") have.pkg <- pkgs %in% rownames(pkg.inst) if(any(!have.pkg)) { message("\nSome packages need to be installed.\n") r <- readline("Install necessary packages [y/n]? ") if(tolower(r) == "y") { need <- pkgs[!have.pkg] message("\nInstalling packages ", paste(need, collapse = ", ")) install.packages(need) } } } loginPrompt <- function() { courseid <- get_courseid() email <- readline("Submission login (email): ") passwd <- readline("Submission password: ") r <- list(courseid = courseid, email = email, passwd = passwd) assign(".CourseraLogin", r, globalenv()) invisible(r) } function(manual = FALSE, resetLogin = FALSE) { checkPkgs() suppressPackageStartupMessages(library(RCurl)) library(digest) library(stringr) readline("\nPress Enter to continue...") if(!manual) { confirmed <- FALSE need2fix <- FALSE while(!confirmed) { if(exists(".CourseraLogin") && !resetLogin && !need2fix) cred <- get(".CourseraLogin") else cred <- loginPrompt() if(!is.list(cred) || !(names(cred) %in% c("email", "passwd", "courseid"))) stop("problem with login/password") courseid <- cred$courseid email <- cred$email password <- cred$passwd pretty_out("Is the following information correct?", skip_after=TRUE) message("Course ID: ", courseid, "\nSubmission login (email): ", email, "\nSubmission password: ", password) yn <- c("Yes, go ahead!", "No, I need to change something.") confirmed <- identical(select.list(yn, graphics=FALSE), yn[1]) if(!confirmed) need2fix <- TRUE } challenge.url <- paste("http://class.coursera.org", courseid, "assignment/challenge", sep = "/") submit.url <- paste("http://class.coursera.org", courseid, "assignment/submit", sep = "/") } sid <- partPrompt() output <- getOutput(sid) if(!manual) { ch <- try(getChallenge(email, challenge.url), silent=TRUE) ch_ok <- !is(ch, "try-error") && exists("ch.key", ch) && !is.na(ch$ch.key) if(!ch_ok) { stop("Either the course ID you entered is not valid or your course site ", "is unreachable at this time. If you'd like to submit manually, you ", "can run submit(manual=TRUE).") } ch.resp <- challengeResponse(password, ch$ch.key) results <- submitSolution(email, ch.resp, sid, output, ch$state, submit.url = submit.url) if(!length(results)) results <- "Incorrect!" cat("Result: ", results, "\n") } else { outfile <- paste(sid, "output.txt", sep = "-") writeLines(as.character(output), outfile) cat(sprintf("Please upload the file '%s' to Coursera\n", outfile)) } invisible() } })
refdata <- system.file("extdata", "ref-results.rdata", package="quantspec") load(refdata)
rare_Rao <- function(comm, dis = NULL, sim = TRUE, resampling = 999, formula = c("QE", "EDI")) { if (!inherits(comm, "matrix") & !inherits(comm, "data.frame")) stop("Non convenient comm") comm <- t(comm) if (any(comm<0)) stop("Negative value in comm") if (any(apply(comm, 2, sum) < 1e-16)) stop("Empty communities") if(!formula[1]%in%c("QE","EDI")) stop("formula can be either QE or EDI") formula <- formula[1] if (!is.null(dis)) { if (!inherits(dis, "dist")) stop("Object of class 'dist' expected for distance") dis <- as.matrix(dis) if (nrow(comm) != nrow(dis)) stop("Non convenient comm") dis <- as.dist(dis) if(formula=="EDI") dis <- dis^2/2 if (!is.euclid(sqrt(dis))) warning("Squared Euclidean or Euclidean property expected for dis") } if (is.null(dis)){ dis <- as.dist((matrix(1, nrow(comm), nrow(comm)) - diag(rep(1, nrow(comm))))) } N <- ncol(comm) rel_abu <- sweep(comm, 2, colSums(comm), "/") if(sim){ p <- resampling result <- matrix(0, p, N) for(j in 1:N){ for(i in 1:p) { if(j==1) newplot <- as.vector(rel_abu[, sample(1:ncol(rel_abu), j)]) else{ subsample <- rel_abu[, sample(1:ncol(rel_abu), j)] newplot <- as.vector(apply(subsample, 1, mean)) } result[i, j] <- (t(newplot) %*% (as.matrix(dis)) %*% newplot) } } aver <- apply(result, 2, mean) IC_plus <- aver + (1.96*(sd(result)/sqrt(p))) IC_neg <- aver - (1.96*(sd(result)/sqrt(p))) rrRao <- data.frame(as.matrix(aver), IC_neg, IC_plus) names(rrRao) <- c("ExpRao", "LeftIC", "RightIC") return(rrRao) } else{ a <- mean(diag(t(rel_abu)%*%as.matrix(dis)%*%as.matrix(rel_abu))) f2 <- apply(rel_abu, 1, sum)/sum(rel_abu) g <- t(f2)%*%as.matrix(dis)%*%f2 b <- g - a rrARao <- cbind.data.frame(sapply(1:N, function(M) return(a + N * (M-1) * b / M / (N-1)))) names(rrARao) <- c("ExpRao") return(rrARao) } }
dlogis.exp <- function (x, alpha, lambda, log = FALSE) { if((!is.numeric(alpha)) || (!is.numeric(lambda)) || (!is.numeric(x))) stop("non-numeric argument to mathematical function") if((min(alpha) <= 0) || (min(lambda) <= 0) || (x <= 0)) stop("Invalid arguments") u <- exp(lambda * x) num <- lambda * alpha * u * ((u - 1.0)^(alpha -1.0)) deno <- (1.0 + (u - 1.0) ^ alpha) ^ 2.0 pdf <- num/deno if(log) pdf <- log(pdf) return(pdf) } plogis.exp <- function (q, alpha, lambda, lower.tail = TRUE, log.p = FALSE) { if((!is.numeric(alpha)) || (!is.numeric(lambda)) || (!is.numeric(q))) stop("non-numeric argument to mathematical function") if((min(alpha) <= 0) || (min(lambda) <= 0) || (q <= 0)) stop("Invalid arguments") u <- exp(lambda * q) tmp <- 1.0 + ((u - 1.0) ^ alpha) cdf <- 1.0 - (1.0/tmp) if(!lower.tail) cdf <- 1.0 - cdf if(log.p) cdf <- log(cdf) return(cdf) } qlogis.exp <- function (p, alpha, lambda, lower.tail = TRUE, log.p = FALSE) { if((!is.numeric(alpha)) || (!is.numeric(lambda)) || (!is.numeric(p))) stop("non-numeric argument to mathematical function") if((min(alpha) <= 0) || (min(lambda) <= 0) || (p <= 0) || (p > 1)) stop("Invalid arguments") qtl <- (1.0/lambda) * log(1.0 +((p/(1.0-p)) ^ (1.0/alpha))) if (!lower.tail) qtl <- (1.0/lambda) * log(1.0 +(((1.0-p)/p) ^ (1.0/alpha))) if (log.p) qtl <- log(qtl) return(qtl) } rlogis.exp<-function(n, alpha, lambda) { if((!is.numeric(alpha)) || (!is.numeric(lambda)) || (!is.numeric(n))) stop("non-numeric argument to mathematical function") if((min(alpha) <= 0) || (min(lambda) <= 0) || (n <= 0)) stop("Invalid arguments") u <- runif(n) return((1.0/lambda) * log(1.0 +((u/(1.0-u)) ^ (1.0/alpha)))) } slogis.exp <- function (x, alpha, lambda) { if((!is.numeric(alpha)) || (!is.numeric(lambda)) || (!is.numeric(x))) stop("non-numeric argument to mathematical function") if((min(alpha) <= 0) || (min(lambda) <= 0) || (x <= 0)) stop("Invalid arguments") u <- exp(lambda * x) tmp <-1.0 +((u - 1.0)^alpha) relia <- 1.0/tmp return(relia) } hlogis.exp <- function (x, alpha, lambda) { if((!is.numeric(alpha)) || (!is.numeric(lambda)) || (!is.numeric(x))) stop("non-numeric argument to mathematical function") if((min(alpha) <= 0) || (min(lambda) <= 0) || (x <= 0)) stop("Invalid arguments") u <- exp(lambda * x) nume <- lambda * alpha * u * ((u - 1.0)^(alpha -1.0)) deno <- 1.0 + (u - 1.0) ^ alpha return(nume/deno) } hra.logis.exp <- function(x, alpha, lambda) { r <- slogis.exp(x, alpha, lambda) fra <- ((-1) * log(r))/x return(fra) } crf.logis.exp <-function(x, t=0, alpha, lambda) { t <- t x <- x nume <- hlogis.exp(x+t, alpha, lambda) deno <- hlogis.exp(x, alpha, lambda) return(nume/deno) } ks.logis.exp <- function(x, alpha.est, lambda.est, alternative = c("less", "two.sided", "greater"), plot = FALSE, ...) { alpha <- alpha.est lambda <- lambda.est res <- ks.test(x, plogis.exp, alpha, lambda, alternative = alternative) if(plot){ plot(ecdf(x), do.points = FALSE, main = 'Empirical and Theoretical cdfs', xlab = 'x', ylab = 'Fn(x)', ...) mini <- min(x) maxi <- max(x) t <- seq(mini, maxi, by = 0.01) y <- plogis.exp(t, alpha, lambda) lines(t, y, lwd = 2, col = 2) } return(res) } qq.logis.exp <- function(x, alpha.est, lambda.est, main = ' ', line.qt = FALSE, ...) { xlab <- 'Empirical quantiles' ylab <- 'Theoretical quantiles' alpha <- alpha.est lambda <- lambda.est n <- length(x) k <- seq(1, n, by = 1) P <- (k-0.5)/n limx <- c(min(x), max(x)) Finv <- qlogis.exp(P, alpha, lambda) quantiles <- sort(x) plot(quantiles, Finv, xlab = xlab, ylab = ylab, xlim = limx, ylim = limx, main = main, col = 4, lwd = 2, ...) lines(c(0,limx), c(0,limx), col = 2, lwd = 2) if(line.qt){ quant <- quantile(x) x1 <- quant[2] x2 <- quant[4] y1 <- qlogis.exp(0.25, alpha, lambda) y2 <- qlogis.exp(0.75, alpha, lambda) m <- ((y2 - y1) / (x2 - x1)) inter <- y1 - (m * x1) abline(inter, m, col = 2, lwd = 2) } invisible(list(x = quantiles, y = Finv)) } pp.logis.exp <- function(x, alpha.est, lambda.est, main=' ', line = FALSE, ...) { xlab <- 'Empirical distribution function' ylab <- 'Theoretical distribution function' alpha <- alpha.est lambda <- lambda.est F <- plogis.exp(x, alpha, lambda) Pemp <- sort(F) n <- length(x) k <- seq(1, n, by = 1) Pteo <- (k - 0.5) / n plot(Pemp, Pteo, xlab = xlab, ylab = ylab, col = 4, xlim = c(0, 1), ylim = c(0, 1), main = main, lwd = 2, ...) if(line) lines(c(0, 1), c(0, 1), col = 2, lwd = 2) Cor.Coeff <- cor(Pemp, Pteo) Determination.Coeff <- (Cor.Coeff^2) * 100 return(list(Cor.Coeff = Cor.Coeff, Determination.Coeff = Determination.Coeff)) } abic.logis.exp<-function(x, alpha.est, lambda.est) { alpha <- alpha.est lambda <- lambda.est n <- length(x) p <- 2 f <- dlogis.exp(x, alpha, lambda) l <- log(f) LogLik <- sum(l) AIC <- - 2 * LogLik + 2 * p BIC <- - 2 * LogLik + p * log(n) return(list(LogLik = LogLik, AIC = AIC, BIC = BIC)) }
boda <- function(sts, control=list(range=NULL, X=NULL, trend=FALSE, season=FALSE, prior=c('iid','rw1','rw2'), alpha=0.05, mc.munu=100, mc.y=10, verbose=FALSE,multicore=TRUE, samplingMethod=c('joint','marginals'), quantileMethod=c("MC","MM"))) { if (!requireNamespace("INLA", quietly = TRUE)) { stop("The boda function requires the INLA package to be installed.\n", " The package is not available on CRAN, but can be easily obtained\n", " from <https://www.r-inla.org/download-install>.") } if (is.null(control[["multicore",exact=TRUE]])) { control$multicore <- TRUE } if (control$multicore) { INLA::inla.setOption("num.threads", parallel::detectCores(logical = TRUE)) } if (ncol(sts)>1) { stop("boda currently only handles univariate sts objects.") } if(is.null(control[["quantileMethod",exact=TRUE]])){ control$quantileMethod <- "MC" } else { control$quantileMethod <- match.arg(control$quantileMethod, c("MC","MM")) } observed <- as.vector(observed(sts)) state <- as.vector(sts@state) time <- 1:length(observed) if(is.null(control[["range",exact=TRUE]])){ warning('No range given. Range is defined as time from second period until end of time series.') control$range <- (sts@freq+1):length(observed) } if(!all(control$range %in% time)){ stop("Evaluation period 'range' has to be vector of time series indices.") } control$range <- sort(control$range) if(is.null(control[["verbose",exact=TRUE]])) { control$verbose <- FALSE } if(is.null(control[["trend",exact=TRUE]])){ control$trend <- FALSE } if(is.null(control[["season",exact=TRUE]])){ control$season <- FALSE } if(!is.logical(control$trend)||!is.logical(control$season)){ stop('trend and season are logical parameters.') } prior <- match.arg(control$prior, c('iid','rw1','rw2')) if(is.vector(control$X)){ control$X <- as.matrix(control$X,ncol=1) } samplingMethod <- match.arg(control$samplingMethod, c('joint','marginals')) if(is.null(control[["alpha",exact=TRUE]])){ control$alpha <- 0.05 } if(control$alpha <= 0 | control$alpha >= 1){ stop("The significance level 'alpha' has to be a probability, and thus has to be between 0 and 1.") } if(is.null(control[["mc.munu",exact=TRUE]])){ control$mc.munu <- 100 } if(is.null(control[["mc.y",exact=TRUE]])){ control$mc.y <- 10 } if(!control$mc.munu>0 || control$mc.munu!=round(control$mc.munu,0) || !control$mc.y>0 || control$mc.y!=round(control$mc.y,0)){ stop('Number of Monte Carlo trials has to be an integer larger than zero') } modelformula <- paste("observed ~ f(time, model='",prior,"', cyclic=FALSE)", sep="") dat <- data.frame(observed=observed, time=time) if(sum(state)>0){ modelformula <- paste(modelformula, "+ f(state, model='linear')", sep="") dat <- data.frame(dat, state=state) } if(control$trend){ modelformula <- paste(modelformula, "+ f(timeT, model='linear')", sep="") dat <- data.frame(dat, timeT=time) } if(control$season){ modelformula <- paste(modelformula, "+ f(timeS, model='seasonal', season.length=",sts@freq,")", sep="") dat <- data.frame(dat, timeS=time) } X.formula <- NULL if(!is.null(control$X)){ if(nrow(control$X)!=length(observed)){ stop("Argument for covariates 'X' has to have the same length like the time series") } for(i in 1:ncol(control$X)){ X.formula <- (paste(X.formula ,'+', colnames(control$X)[i])) } modelformula <- paste(modelformula, X.formula, sep="") dat <- data.frame(dat, control$X) } modelformula <- as.formula(modelformula) useProgressBar <- length(control$range)>1 if (useProgressBar) { pb <- txtProgressBar(min=min(control$range), max=max(control$range), initial=0,style=3) } xi <- rep(NA,length(observed)) for(i in control$range){ dati <- dat[1:i,] dati$observed[i] <- NA dati$state[i] <- 0 xi[i] <- bodaFit(dat=dati, samplingMethod=samplingMethod, modelformula=modelformula, prior=prior, alpha=control$alpha, mc.munu=control$mc.munu, mc.y=control$mc.y, quantileMethod=control$quantileMethod) if (useProgressBar) setTxtProgressBar(pb, i) } if (useProgressBar) close(pb) sts@alarm[,1] <- observed > xi sts@upperbound[,1] <- xi control$name <- paste('boda(prior=',prior,')',sep='') sts@control <- control return(sts[control$range,]) } bodaFit <- function(dat=dat, modelformula=modelformula,prior=prior,alpha=alpha, mc.munu=mc.munu, mc.y=mc.y, samplingMethod=samplingMethod,quantileMethod=quantileMethod,...) { T1 <- nrow(dat) link <- 1 E <- mean(dat$observed, na.rm=TRUE) model <- INLA::inla(modelformula, data=dat, family='nbinomial',E=E, control.predictor=list(compute=TRUE,link=link), control.compute=list(cpo=FALSE,config=TRUE), control.inla = list(int.strategy = "grid",dz=1,diff.logdens = 10)) if(is.null(model)){ return(qi=NA) } if(samplingMethod=='marginals'){ marg <- try(INLA::inla.tmarginal(function(x) x,model$marginals.fitted.values[[T1]]), silent=TRUE) if(inherits(marg,'try-error')){ return(qi=NA) } mT1 <- try(INLA::inla.rmarginal(n=mc.munu,marg), silent=TRUE) if(inherits(mT1,'try-error')){ return(qi=NA) } mtheta <- model$internal.marginals.hyperpar[[1]] theta <- exp(INLA::inla.rmarginal(n=mc.munu,mtheta)) if(inherits(theta,'try-error')){ return(qi=NA) } } if (samplingMethod=='joint'){ jointSample <- INLA::inla.posterior.sample(mc.munu,model, intern = TRUE) theta <- exp(t(sapply(jointSample, function(x) x$hyperpar[[1]]))) mT1 <- exp(t(sapply(jointSample, function(x) x$latent[[T1]]))) yT1 <- rnbinom(n=mc.y*mc.munu,size=theta,mu=E*mT1) } if(quantileMethod=="MC"){ yT1 <- numeric(mc.munu*mc.y) idx <- seq(mc.y) for(j in seq(mc.munu)) { idx <- idx + mc.y yT1[idx] <- rnbinom(n=mc.y,size=theta[j],mu=E*mT1[j]) } qi <- quantile(yT1, probs=(1-alpha), type=3, na.rm=TRUE) } if(quantileMethod=="MM"){ mT1 <- mT1[mT1>=0&theta>0] theta <- theta[mT1>=0&theta>0] minBracket <- qnbinom(p=(1-alpha), mu=E*min(mT1), size=max(theta)) maxBracket <- qnbinom(p=(1-alpha), mu=E*max(mT1), size=min(theta)) qi <- qmix(p=(1-alpha), mu=E*mT1, size=theta, bracket=c(minBracket, maxBracket)) } return(qi) }
searchResultsSummaryTable <- function(aSearchResults) { K <- length(aSearchResults) seedGenes <- aSearchResults[[1]]$signatureName for(k in 2:K) seedGenes <- c(seedGenes, aSearchResults[[k]]$signatureName) tableOfSignatures <- matrix("", ncol = 5, nrow = K) rownames(tableOfSignatures) <- seedGenes colnames(tableOfSignatures) <- c("length", "tValue", "log(pValue)", "tValue improvement", "signature") for (k in 1:K) tableOfSignatures[k, ] <- c(length(aSearchResults[[k]]$signature), round(aSearchResults[[k]]$tValue, 3), round(log(aSearchResults[[k]]$pValue)/log(10), 3), round((1 - aSearchResults[[k]]$startingTValue/aSearchResults[[k]]$tValue) * 100, 2), paste(aSearchResults[[k]]$signature, collapse = ", ")) tableOfSignatures <- as.data.frame(tableOfSignatures) return(tableOfSignatures) }
PathwiseCoordinateOptimization <- function(y, X, beta=NULL, lambda=0.1, tol=0.000001, maxiter=1000, show=FALSE){ n = dim(X)[1] p = dim(X)[2] if (is.null(beta)) beta=as.matrix(ginv(t(X) %*% X) %*% t(X) %*% y) error=sum(beta^2) iter=0 while ((error>tol) & (iter<maxiter)){ iter=iter+1 betaold=beta for (j in 1:p){ r = y - X[,-j] %*% beta[-j,] b= sum(r * X[,j])/n beta[j,]=0 if (b >0 & lambda < abs(b)) beta[j,]=b-lambda if (b <0 & lambda < abs(b)) beta[j,]=b+lambda } error=sum((beta-betaold)^2) if (show) print(c(iter,error)) } return(beta) }
setMethod ('show' , 'Extent', function(object) { cat('class :' , class(object), '\n') cat('xmin :' , xmin(object), '\n') cat('xmax :' , xmax(object), '\n') cat('ymin :' , ymin(object), '\n') cat('ymax :' , ymax(object), '\n') } ) setMethod ('show' , 'BasicRaster', function(object) { cat('class :' , class(object), '\n') cat('dimensions : ', nrow(object), ', ', ncol(object), ', ', ncell(object),' (nrow, ncol, ncell)\n', sep="" ) cat('resolution : ' , xres(object), ', ', yres(object), ' (x, y)\n', sep="") cat('extent : ' , object@extent@xmin, ', ', object@extent@xmax, ', ', object@extent@ymin, ', ', object@extent@ymax, ' (xmin, xmax, ymin, ymax)\n', sep="") cat('crs :' , proj4string(object), '\n') } ) setMethod ('show' , 'RasterLayer', function(object) { cat('class :' , class(object), '\n') if (rotated(object)) { cat('rotated : TRUE\n') } if (nbands(object) > 1) { cat('band :' , bandnr(object), ' (of ', nbands(object), ' bands)\n') } cat('dimensions : ', nrow(object), ', ', ncol(object), ', ', ncell(object),' (nrow, ncol, ncell)\n', sep="" ) cat('resolution : ' , xres(object), ', ', yres(object), ' (x, y)\n', sep="") cat('extent : ' , object@extent@xmin, ', ', object@extent@xmax, ', ', object@extent@ymin, ', ', object@extent@ymax, ' (xmin, xmax, ymin, ymax)\n', sep="") cat('crs :' , proj4string(object), '\n') if (hasValues(object)) { fd <- object@data@fromdisk if (fd) { cat('source :', basename(filename(object)), '\n') } else { cat('source : memory\n') } cat('names :', names(object), '\n') if (object@data@haveminmax) { cat('values : ', minValue(object), ', ', maxValue(object), ' (min, max)\n', sep="") } } if (is.factor(object)) { x <- object@data@attributes[[1]] nc <- NCOL(x) maxnl <- 12 if (nc > maxnl) { x <- x[, 1:maxnl] } if (nrow(x) > 5) { cat('attributes :\n') r <- x[c(1, nrow(x)), ,drop=FALSE] for (j in 1:ncol(r)) { r[is.numeric(r[,j]) & !is.finite(r[,j]), j] <- NA } r <- data.frame(x=c('from:','to :'), r) a <- colnames(x) colnames(r) <- c(' fields :', a) colnames(r) <- c('', a) rownames(r) <- NULL if (nc > maxnl) { r <- cbind(r, '...'=rbind('...', '...')) } print(r, row.names=FALSE) } else { cat('attributes :\n') print(x, row.names=FALSE) } } else { z <- getZ(object) if (length(z) > 0) { name <- names(object@z) if (is.null(name)) name <- 'z-value' name <- paste(sprintf("%-11s", name), ':', sep='') cat(name, as.character(z[1]), '\n') } if (object@file@driver == 'netcdf') { z <- attr(object@data, 'zvar') if (!is.null(z)) { cat('zvar :', z, '\n') } z <- attr(object@data, 'level') if (!is.null(z)) { if (z>0) { cat('level :', z, '\n') } } } } cat ('\n') } ) setMethod ('show' , 'RasterBrick', function ( object ) { cat ('class :' , class ( object ) , '\n') if (rotated(object)) { cat('rotated : TRUE\n') } mnr <- 15 nl <- nlayers(object) cat ('dimensions : ', nrow(object), ', ', ncol(object), ', ', ncell(object), ', ', nl, ' (nrow, ncol, ncell, nlayers)\n', sep="" ) cat ('resolution : ' , xres(object), ', ', yres(object), ' (x, y)\n', sep="") cat ('extent : ' , object@extent@xmin, ', ', object@extent@xmax, ', ', object@extent@ymin, ', ', object@extent@ymax, ' (xmin, xmax, ymin, ymax)\n', sep="") cat ('crs :' , proj4string(object), '\n') ln <- names(object) if (nl > mnr) { ln <- c(ln[1:mnr], '...') } if (hasValues(object)) { fd <- object@data@fromdisk if (fd) { cat('source :', basename(filename(object)), '\n') } else { cat('source : memory\n') } if (object@data@haveminmax) { minv <- format(minValue(object)) maxv <- format(maxValue(object)) minv <- gsub('Inf', '?', minv) maxv <- gsub('-Inf', '?', maxv) if (nl > mnr) { minv <- c(minv[1:mnr], '...') maxv <- c(maxv[1:mnr], '...') } n <- nchar(ln) if (nl > 5) { b <- n > 26 if (any(b)) { mid <- floor(n/2) ln[b] <- paste(substr(ln[b], 1, 9), '//', substr(ln[b], nchar(ln[b])-9, nchar(ln[b])), sep='') } } w <- pmax(nchar(ln), nchar(minv), nchar(maxv)) m <- rbind(ln, minv, maxv) for (i in 1:ncol(m)) { m[,i] <- format(m[,i], width=w[i], justify="right") } cat('names :', paste(m[1,], collapse=', '), '\n') cat('min values :', paste(m[2,], collapse=', '), '\n') cat('max values :', paste(m[3,], collapse=', '), '\n') } else { cat('names :', paste(ln, collapse=', '), '\n') } } z <- getZ(object) if (length(z) > 0) { name <- names(object@z) if (is.null(name)) name <- 'z-value' name <- paste(sprintf("%-11s", name), ':', sep='') if (length(z) < mnr) { cat(name, paste(as.character(z), collapse=', '), '\n') } else { cat(name, paste(as.character(range(z)), collapse=', '), '(min, max)\n') } } if (object@file@driver == 'netcdf') { z <- attr(object@data, 'zvar') if (!is.null(z)) { cat('varname :', z, '\n') } z <- attr(object@data, 'level') if (!is.null(z)) { if (z>0) { cat('level :', z, '\n') } } } cat ('\n') } ) setMethod ('show' , 'RasterStack', function ( object ) { cat ('class :' , class ( object ) , '\n') if (rotated(object)) { cat('rotated : TRUE\n') } mnr <- 15 if (filename(object) != '') { cat ('filename :' , filename(object), '\n') } nl <- nlayers(object) if (nl == 0) { cat ('nlayers :' , nl, '\n') } else { cat ('dimensions : ', nrow(object), ', ', ncol(object), ', ', ncell(object), ', ', nl, ' (nrow, ncol, ncell, nlayers)\n', sep="" ) cat ('resolution : ' , xres(object), ', ', yres(object), ' (x, y)\n', sep="") cat ('extent : ' , object@extent@xmin, ', ', object@extent@xmax, ', ', object@extent@ymin, ', ', object@extent@ymax, ' (xmin, xmax, ymin, ymax)\n', sep="") cat ('crs :' , proj4string(object), '\n') ln <- names(object) if (nl > mnr) { ln <- c(ln[1:mnr], '...') } n <- nchar(ln) if (nl > 5) { b <- n > 26 if (any(b)) { ln[b] <- paste(substr(ln[b], 1, 9), '//', substr(ln[b], nchar(ln[b])-9, nchar(ln[b])), sep='') } } minv <- minValue(object) if (all(is.na(minv))) { cat('names :', paste(ln, collapse=', '), '\n') } else { minv <- format(minv) maxv <- format(maxValue(object)) minv <- gsub('NA', '?', minv) maxv <- gsub('NA', '?', maxv) if (nl > mnr) { minv <- c(minv[1:mnr], '...') maxv <- c(maxv[1:mnr], '...') } w <- pmax(nchar(ln), nchar(minv), nchar(maxv)) m <- rbind(ln, minv, maxv) for (i in 1:ncol(m)) { m[,i] <- format(m[,i], width=w[i], justify="right") } cat('names :', paste(m[1,], collapse=', '), '\n') cat('min values :', paste(m[2,], collapse=', '), '\n') cat('max values :', paste(m[3,], collapse=', '), '\n') } } z <- getZ(object) if (length(z) > 0) { name <- names(object@z) if (is.null(name)) name <- 'z-value' if (name == '') name <- 'z-value' name <- paste(sprintf("%-12s", name), ':', sep='') if (length(z) < mnr) { cat(name, paste(as.character(z), collapse=', '), '\n') } else { z <- range(z) cat(name, paste(as.character(z), collapse=' - '), '(range)\n') } } cat ('\n') } ) setMethod ('show' , '.RasterList', function(object) { cat('class :' , class(object), '\n') cat('length : ', length(object), '\n', sep="" ) } )
expected <- eval(parse(text="c(1, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1)")); test(id=0, code={ argv <- eval(parse(text="list(1, c(FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE))")); do.call(`+`, argv); }, o=expected);
testthat::test_that("Packages are installed", { testthat::skip_on_cran() testthat::skip_on_ci() testthat::skip_on_travis() try(utils::remove.packages("knitr")) modules::depend("knitr", "1.0.3", repos = "https://cloud.r-project.org") testthat::expect_true(require("knitr")) }) testthat::test_that("Throw errors", { testthat::skip_on_cran() testthat::skip_on_ci() testthat::skip_on_travis() testthat::expect_is(suppressWarnings( tmp <- try(modules::depend( "knitr", "999", repos = "https://cloud.r-project.org"), TRUE) ), "try-error") testthat::expect_true(grepl("package installation failed", tmp)) testthat::expect_is(suppressWarnings( tmp <- try(modules::depend( "knitr999", "999", repos = "https://cloud.r-project.org"), TRUE) ), "try-error") testthat::expect_true(grepl("package installation failed", tmp)) })
generatePublicMethodParagraph <- function(object_o_1, methods_s) { beautifier <- beautify() sig <- sapply(methods_s, function(e) { s <- getObjectMethodSignature(object_o_1, e) r <- regexpr('(', s, fixed = TRUE) paste0(beautifier$bold(substr(s, 1, r[1] - 1)), beautifier$code(substring(s, r[1]))) }) paste('\\cr', generateParagraphCR(paste(documentationSymbols()$black_square, sig))) }
regplot.rma <- function(x, mod, pred=TRUE, ci=TRUE, pi=FALSE, shade=TRUE, xlim, ylim, predlim, olim, xlab, ylab, at, digits=2L, transf, atransf, targs, level=x$level, pch=21, psize, plim=c(0.5,3), col="black", bg="darkgray", grid=FALSE, refline, label=FALSE, offset=c(1,1), labsize=1, lcol, lwd, lty, legend=FALSE, xvals, ...) { mstyle <- .get.mstyle("crayon" %in% .packages()) .chkclass(class(x), must="rma", notav=c("rma.mh","rma.peto")) if (x$int.only) stop(mstyle$stop("Plot not applicable to intercept-only models.")) na.act <- getOption("na.action") on.exit(options(na.action=na.act)) if (!is.element(na.act, c("na.omit", "na.exclude", "na.fail", "na.pass"))) stop(mstyle$stop("Unknown 'na.action' specified under options().")) if (missing(transf)) transf <- FALSE if (missing(atransf)) atransf <- FALSE transf.char <- deparse(substitute(transf)) atransf.char <- deparse(substitute(atransf)) if (is.function(transf) && is.function(atransf)) stop(mstyle$stop("Use either 'transf' or 'atransf' to specify a transformation (not both).")) if (missing(targs)) targs <- NULL if (missing(ylab)) ylab <- .setlab(x$measure, transf.char, atransf.char, gentype=1, short=FALSE) if (missing(at)) at <- NULL if (missing(psize)) psize <- NULL if (missing(label)) label <- NULL if (is.logical(grid)) gridcol <- "gray" if (is.character(grid)) { gridcol <- grid grid <- TRUE } if (is.logical(shade)) shadecol <- c("gray85", "gray95") if (is.character(shade)) { if (length(shade) == 1L) shade <- c(shade, shade) shadecol <- shade shade <- TRUE } if (inherits(pred, "list.rma")) { addpred <- TRUE if (missing(xvals)) stop(mstyle$stop("Need to specify the 'xvals' argument.")) if (length(xvals) != length(pred$pred)) stop(mstyle$stop(paste0("Length of the 'xvals' argument (", length(xvals), ") does not correspond to the number of predicted values (", length(pred$pred), ")."))) } else { addpred <- pred } if (missing(refline)) refline <- NA if (missing(lcol)) { lcol <- c("black", "black", "black", "gray40") } else { if (length(lcol) == 1L) lcol <- rep(lcol, 4) if (length(lcol) == 2L) lcol <- c(lcol[c(1,2,2)], "gray40") if (length(lcol) == 3L) lcol <- c(lcol, "gray40") } if (missing(lty)) { lty <- c("solid", "dashed", "dotted", "solid") } else { if (length(lty) == 1L) lty <- rep(lty, 4) if (length(lty) == 2L) lty <- c(lty[c(1,2,2)], "solid") if (length(lty) == 3L) lty <- c(lty, "solid") } if (missing(lwd)) { lwd <- c(3,1,1,2) } else { if (length(lwd) == 1L) lwd <- rep(lwd, 4) if (length(lwd) == 2L) lwd <- c(lwd[c(1,2,2)], 2) if (length(lwd) == 3L) lwd <- c(lwd, 2) } level <- ifelse(level == 0, 1, ifelse(level >= 1, (100-level)/100, ifelse(level > .5, 1-level, level))) if (missing(mod)) { if (x$p == 2L && x$int.incl) { mod <- 2 } else { stop(mstyle$stop("Need to specify the 'mod' argument.")) } } if (length(mod) != 1L) stop(mstyle$stop("Can only specify a single variable via argument 'mod'.")) if (!(is.character(mod) || is.numeric(mod))) stop(mstyle$stop("Argument 'mod' must either be a character string or a scalar.")) if (is.character(mod)) { mod.pos <- charmatch(mod, colnames(x$X)) if (is.na(mod.pos)) stop(mstyle$stop("Argument 'mod' must be the name of a moderator variable in the model.")) if (mod.pos == 0L) stop(mstyle$stop("No ambiguous match found for variable name specified via 'mod' argument.")) } else { mod.pos <- round(mod) if (mod.pos < 1 | mod.pos > x$p) stop(mstyle$stop("Specified position of 'mod' variable does not exist in the model.")) } yi <- c(x$yi.f) vi <- x$vi.f X <- x$X.f slab <- x$slab ids <- x$ids options(na.action = "na.pass") weights <- try(weights(x), silent=TRUE) if (inherits(weights, "try-error")) weights <- rep(1, x$k.f) options(na.action = na.act) if (length(pch) == 1L) pch <- rep(pch, x$k.all) if (length(pch) != x$k.all) stop(mstyle$stop(paste0("Length of the 'pch' argument (", length(pch), ") does not correspond to the size of the original dataset (", x$k.all, ")."))) if (!is.null(x$subset)) pch <- pch[x$subset] psize.char <- FALSE if (!is.null(psize)) { if (is.character(psize)) { psize <- match.arg(psize, c("seinv", "vinv")) if (psize == "seinv") { psize <- 1 / sqrt(vi) } else { psize <- 1 / vi } psize.char <- TRUE } else { if (length(psize) == 1L) psize <- rep(psize, x$k.all) if (length(psize) != x$k.all) stop(mstyle$stop(paste0("Length of the 'psize' argument (", length(psize), ") does not correspond to the size of the original dataset (", x$k.all, ")."))) if (!is.null(x$subset)) psize <- psize[x$subset] } } if (length(col) == 1L) col <- rep(col, x$k.all) if (length(col) != x$k.all) stop(mstyle$stop(paste0("Length of the 'col' argument (", length(col), ") does not correspond to the size of the original dataset (", x$k.all, ")."))) if (!is.null(x$subset)) col <- col[x$subset] if (length(bg) == 1L) bg <- rep(bg, x$k.all) if (length(bg) != x$k.all) stop(mstyle$stop(paste0("Length of the 'bg' argument (", length(bg), ") does not correspond to the size of the original dataset (", x$k.all, ")."))) if (!is.null(x$subset)) bg <- bg[x$subset] if (!is.null(label)) { if (is.character(label)) { label <- match.arg(label, c("all", "ciout", "piout")) if (label == "all") { label <- rep(TRUE, x$k.all) if (!is.null(x$subset)) label <- label[x$subset] } } else if (is.logical(label)) { if (!is.logical(label)) stop(mstyle$stop("Argument 'label' must be a logical vector (or a single character string).")) if (length(label) == 1L) label <- rep(label, x$k.all) if (length(label) != x$k.all) stop(mstyle$stop(paste0("Length of the 'label' argument (", length(label), ") does not correspond to the size of the original dataset (", x$k.all, ")."))) if (!is.null(x$subset)) label <- label[x$subset] } else if (is.numeric(label)) { label <- round(label) label <- seq(x$k.all) %in% label } } has.na <- is.na(yi) | is.na(vi) | apply(is.na(X), 1, any) not.na <- !has.na if (any(has.na)) { yi <- yi[not.na] vi <- vi[not.na] X <- X[not.na,,drop=FALSE] slab <- slab[not.na] ids <- ids[not.na] weights <- weights[not.na] pch <- pch[not.na] psize <- psize[not.na] col <- col[not.na] bg <- bg[not.na] if (!is.character(label)) label <- label[not.na] } k <- length(yi) xi <- X[,mod.pos] if (inherits(pred, "list.rma")) { xs <- xvals ci.lb <- pred$ci.lb ci.ub <- pred$ci.ub if (is.null(pred$pi.lb) || anyNA(pred$pi.lb)) { pi.lb <- pred$ci.lb pi.ub <- pred$ci.ub if (pi) warning(mstyle$warning("Object passed to 'pred' argument does not contain prediction interval information."), call.=FALSE) pi <- FALSE } else { pi.lb <- pred$pi.lb pi.ub <- pred$pi.ub } pred <- pred$pred if (!is.null(label) && is.character(label) && label %in% c("ciout", "piout")) { warning(mstyle$stop("Cannot label points based on the confidence/prediction interval when passing an object to 'pred'.")) label <- NULL } yi.pred <- NULL yi.ci.lb <- NULL yi.ci.ub <- NULL yi.pi.lb <- NULL yi.pi.ub <- NULL } else { if (!missing(xvals)) { xs <- xvals len <- length(xs) predlim <- range(xs) } else { len <- 1000 if (missing(predlim)) { range.xi <- max(xi) - min(xi) predlim <- c(min(xi) - .04*range.xi, max(xi) + .04*range.xi) xs <- seq(predlim[1], predlim[2], length=len) } else { if (length(predlim) != 2L) stop(mstyle$stop("Argument 'predlim' must be of length 2.")) xs <- seq(predlim[1], predlim[2], length=len) } } Xnew <- rbind(colMeans(X))[rep(1,len),,drop=FALSE] Xnew[,mod.pos] <- xs if (x$int.incl) Xnew <- Xnew[,-1,drop=FALSE] tmp <- predict(x, newmods=Xnew, level=level) pred <- tmp$pred ci.lb <- tmp$ci.lb ci.ub <- tmp$ci.ub if (is.null(tmp$pi.lb) || anyNA(tmp$pi.lb)) { pi.lb <- ci.lb pi.ub <- ci.ub if (pi) warning(mstyle$warning("Cannot draw prediction interval for the given model."), call.=FALSE) pi <- FALSE } else { pi.lb <- tmp$pi.lb pi.ub <- tmp$pi.ub } Xnew <- rbind(colMeans(X))[rep(1,k),,drop=FALSE] Xnew[,mod.pos] <- xi if (x$int.incl) Xnew <- Xnew[,-1,drop=FALSE] tmp <- predict(x, newmods=Xnew, level=level) yi.pred <- tmp$pred yi.ci.lb <- tmp$ci.lb yi.ci.ub <- tmp$ci.ub if (is.null(tmp$pi.lb) || anyNA(tmp$pi.lb)) { yi.pi.lb <- yi.ci.lb yi.pi.ub <- yi.ci.ub if (!is.null(label) && is.character(label) && label == "piout") { warning(mstyle$warning("Cannot label points based on the prediction interval for the given model."), call.=FALSE) label <- NULL } } else { yi.pi.lb <- tmp$pi.lb yi.pi.ub <- tmp$pi.ub } } if (is.function(transf)) { if (is.null(targs)) { yi <- sapply(yi, transf) pred <- sapply(pred, transf) ci.lb <- sapply(ci.lb, transf) ci.ub <- sapply(ci.ub, transf) pi.lb <- sapply(pi.lb, transf) pi.ub <- sapply(pi.ub, transf) yi.pred <- sapply(yi.pred, transf) yi.ci.lb <- sapply(yi.ci.lb, transf) yi.ci.ub <- sapply(yi.ci.ub, transf) yi.pi.lb <- sapply(yi.pi.lb, transf) yi.pi.ub <- sapply(yi.pi.ub, transf) } else { yi <- sapply(yi, transf, targs) pred <- sapply(pred, transf, targs) ci.lb <- sapply(ci.lb, transf, targs) ci.ub <- sapply(ci.ub, transf, targs) pi.lb <- sapply(pi.lb, transf, targs) pi.ub <- sapply(pi.ub, transf, targs) yi.pred <- sapply(yi.pred, transf, targs) yi.ci.lb <- sapply(yi.ci.lb, transf, targs) yi.ci.ub <- sapply(yi.ci.ub, transf, targs) yi.pi.lb <- sapply(yi.pi.lb, transf, targs) yi.pi.ub <- sapply(yi.pi.ub, transf, targs) } } tmp <- .psort(ci.lb, ci.ub) ci.lb <- tmp[,1] ci.ub <- tmp[,2] tmp <- .psort(pi.lb, pi.ub) pi.lb <- tmp[,1] pi.ub <- tmp[,2] if (!missing(olim)) { if (length(olim) != 2L) stop(mstyle$stop("Argument 'olim' must be of length 2.")) olim <- sort(olim) yi[yi < olim[1]] <- olim[1] yi[yi > olim[2]] <- olim[2] pred[pred < olim[1]] <- olim[1] pred[pred > olim[2]] <- olim[2] ci.lb[ci.lb < olim[1]] <- olim[1] ci.ub[ci.ub > olim[2]] <- olim[2] pi.lb[pi.lb < olim[1]] <- olim[1] pi.ub[pi.ub > olim[2]] <- olim[2] } if (is.null(psize) || psize.char) { if (length(plim) < 2L) stop(mstyle$stop("Argument 'plim' must be of length 2 or 3.")) if (psize.char) { wi <- psize } else { wi <- sqrt(weights) } if (!is.na(plim[1]) && !is.na(plim[2])) { rng <- max(wi, na.rm=TRUE) - min(wi, na.rm=TRUE) if (rng <= .Machine$double.eps^0.5) { psize <- rep(1, k) } else { psize <- (wi - min(wi, na.rm=TRUE)) / rng psize <- (psize * (plim[2] - plim[1])) + plim[1] } } if (is.na(plim[1]) && !is.na(plim[2])) { psize <- wi / max(wi, na.rm=TRUE) * plim[2] if (length(plim) == 3L) psize[psize <= plim[3]] <- plim[3] } if (!is.na(plim[1]) && is.na(plim[2])) { psize <- wi / min(wi, na.rm=TRUE) * plim[1] if (length(plim) == 3L) psize[psize >= plim[3]] <- plim[3] } if (all(is.na(psize))) psize <- rep(1, k) } if (missing(xlab)) xlab <- colnames(X)[mod.pos] if (!is.expression(xlab) && xlab == "") xlab <- "Moderator" if (missing(xlim)) { xlim <- range(xi) } else { if (length(xlim) != 2L) stop(mstyle$stop("Argument 'xlim' must be of length 2.")) } if (missing(ylim)) { if (pi) { ylim <- range(c(yi, pi.lb, pi.ub)) } else if (ci) { ylim <- range(c(yi, ci.lb, ci.ub)) } else { ylim <- range(yi) } } else { if (length(ylim) != 2L) stop(mstyle$stop("Argument 'ylim' must be of length 2.")) } if (!is.null(at)) { ylim[1] <- min(c(ylim[1], at), na.rm=TRUE) ylim[2] <- max(c(ylim[2], at), na.rm=TRUE) } plot(NA, xlab=xlab, ylab=ylab, xlim=xlim, ylim=ylim, yaxt="n", ...) if (is.null(at)) { at <- axTicks(side=2) } else { at <- at[at > par("usr")[3]] at <- at[at < par("usr")[4]] } at.lab <- at if (is.function(atransf)) { if (is.null(targs)) { at.lab <- formatC(sapply(at.lab, atransf), digits=digits[[1]], format="f", drop0trailing=is.integer(digits[[1]])) } else { at.lab <- formatC(sapply(at.lab, atransf, targs), digits=digits[[1]], format="f", drop0trailing=is.integer(digits[[1]])) } } else { at.lab <- formatC(at.lab, digits=digits[[1]], format="f", drop0trailing=is.integer(digits[[1]])) } axis(side=2, at=at, labels=at.lab, ...) if (shade) { if (pi) polygon(c(xs, rev(xs)), c(pi.lb, rev(pi.ub)), border=NA, col=shadecol[2], ...) if (ci) polygon(c(xs, rev(xs)), c(ci.lb, rev(ci.ub)), border=NA, col=shadecol[1], ...) } if (ci) { lines(xs, ci.lb, col=lcol[2], lty=lty[2], lwd=lwd[2], ...) lines(xs, ci.ub, col=lcol[2], lty=lty[2], lwd=lwd[2], ...) } if (pi) { lines(xs, pi.lb, col=lcol[3], lty=lty[3], lwd=lwd[3], ...) lines(xs, pi.ub, col=lcol[3], lty=lty[3], lwd=lwd[3], ...) } if (.isTRUE(grid)) grid(col=gridcol) abline(h=refline, col=lcol[4], lty=lty[4], lwd=lwd[4], ...) if (addpred) lines(xs, pred, col=lcol[1], lty=lty[1], lwd=lwd[1], ...) box(...) order.vec <- order(psize, decreasing=TRUE) xi.o <- xi[order.vec] yi.o <- yi[order.vec] pch.o <- pch[order.vec] psize.o <- psize[order.vec] col.o <- col[order.vec] bg.o <- bg[order.vec] points(x=xi.o, y=yi.o, pch=pch.o, col=col.o, bg=bg.o, cex=psize.o, ...) if (!is.null(label)) { if (!is.null(label) && is.character(label) && label %in% c("ciout", "piout")) { if (label == "ciout") { label <- yi < yi.ci.lb | yi > yi.ci.ub label[xi < predlim[1] | xi > predlim[2]] <- FALSE } else { label <- yi < yi.pi.lb | yi > yi.pi.ub label[xi < predlim[1] | xi > predlim[2]] <- FALSE } } yrange <- ylim[2] - ylim[1] if (length(offset) == 2L) offset <- c(offset[1]/100 * yrange, offset[2]/100 * yrange, 1) if (length(offset) == 1L) offset <- c(0, offset/100 * yrange, 1) for (i in which(label)) { if (isTRUE(yi[i] > yi.pred[i])) { text(xi[i], yi[i] + offset[1] + offset[2]*psize[i]^offset[3], slab[i], cex=labsize, ...) } else { text(xi[i], yi[i] - offset[1] - offset[2]*psize[i]^offset[3], slab[i], cex=labsize, ...) } } } else { label <- rep(FALSE, k) } if (is.logical(legend) && isTRUE(legend)) lpos <- "topright" if (is.character(legend)) { lpos <- legend legend <- TRUE } if (legend) { pch.l <- NULL col.l <- NULL bg.l <- NULL lty.l <- NULL lwd.l <- NULL tcol.l <- NULL ltxt <- NULL if (length(unique(pch)) == 1L && length(unique(col)) == 1L && length(unique(bg)) == 1L) { pch.l <- NA col.l <- NA bg.l <- NA lty.l <- "blank" lwd.l <- NA tcol.l <- "white" ltxt <- "Studies" } if (addpred) { pch.l <- c(pch.l, NA) col.l <- c(col.l, NA) bg.l <- c(bg.l, NA) lty.l <- c(lty.l, NA) lwd.l <- c(lwd.l, NA) tcol.l <- c(tcol.l, "white") ltxt <- c(ltxt, "Regression Line") } if (ci) { pch.l <- c(pch.l, 22) col.l <- c(col.l, lcol[2]) bg.l <- c(bg.l, shadecol[1]) lty.l <- c(lty.l, NA) lwd.l <- c(lwd.l, 1) tcol.l <- c(tcol.l, "white") ltxt <- c(ltxt, paste0(round(100*(1-level), digits[[1]]), "% Confidence Interval")) } if (pi) { pch.l <- c(pch.l, 22) col.l <- c(col.l, lcol[3]) bg.l <- c(bg.l, shadecol[2]) lty.l <- c(lty.l, NA) lwd.l <- c(lwd.l, 1) tcol.l <- c(tcol.l, "white") ltxt <- c(ltxt, paste0(round(100*(1-level), digits[[1]]), "% Prediction Interval")) } if (length(ltxt) >= 1L) legend(lpos, inset=.01, bg="white", pch=pch.l, col=col.l, pt.bg=bg.l, lty=lty.l, lwd=lwd.l, text.col=tcol.l, pt.cex=1.5, seg.len=3, legend=ltxt) pch.l <- NULL col.l <- NULL bg.l <- NULL lty.l <- NULL lwd.l <- NULL tcol.l <- NULL ltxt <- NULL if (length(unique(pch)) == 1L && length(unique(col)) == 1L && length(unique(bg)) == 1L) { pch.l <- pch[1] col.l <- col[1] bg.l <- bg[1] lty.l <- "blank" lwd.l <- 1 tcol.l <- "black" ltxt <- "Studies" } if (addpred) { pch.l <- c(pch.l, NA) col.l <- c(col.l, lcol[1]) bg.l <- c(bg.l, NA) lty.l <- c(lty.l, lty[1]) lwd.l <- c(lwd.l, lwd[1]) tcol.l <- c(tcol.l, "black") ltxt <- c(ltxt, "Regression Line") } if (ci) { pch.l <- c(pch.l, NA) col.l <- c(col.l, lcol[2]) bg.l <- c(bg.l, NA) lty.l <- c(lty.l, lty[2]) lwd.l <- c(lwd.l, lwd[2]) tcol.l <- c(tcol.l, "black") ltxt <- c(ltxt, paste0(round(100*(1-level), digits[[1]]), "% Confidence Interval")) } if (pi) { pch.l <- c(pch.l, NA) col.l <- c(col.l, lcol[3]) bg.l <- c(bg.l, NA) lty.l <- c(lty.l, lty[3]) lwd.l <- c(lwd.l, lwd[3]) tcol.l <- c(tcol.l, "black") ltxt <- c(ltxt, paste0(round(100*(1-level), digits[[1]]), "% Prediction Interval")) } if (length(ltxt) >= 1L) legend(lpos, inset=.01, bg=NA, pch=pch.l, col=col.l, pt.bg=bg.l, lty=lty.l, lwd=lwd.l, text.col=tcol.l, pt.cex=1.5, seg.len=3, legend=ltxt) } sav <- data.frame(slab, ids, xi, yi, pch, psize, col, bg, label, order=order.vec) class(sav) <- "regplot" invisible(sav) }
`ddst.uniform.Nk` <- function(x, base = ddst.base.legendre, Dmax = 10) { n = length(x) maxN = max(min(Dmax, n-2, 20),1) coord = numeric(maxN) for (j in 1:maxN) coord[j] = ddst.phi(x, j, base) coord= cumsum(coord^2*n) }
cma.mix <- function(dat,model.type=c("single","multilevel"),method=c("HL","TS","HL-TS"),delta=NULL,sens.plot=FALSE, interval=c(-0.90,0.90),tol=10e-4,max.itr=50,conf.level=0.95,optimizer=c("bobyqa","Nelder_Mead","optimx"), mix.pkg=c("lme4","nlme"),random.indep=TRUE,random.var.equal=TRUE,u.int=FALSE,Sigma.update=FALSE, var.constraint=FALSE,random.var.update=TRUE,logLik.type=c("logLik","HL"), legend.pos="topright",xlab=expression(delta),ylab=expression(hat(AB)), cex.lab=1,cex.axis=1,lgd.cex=1,lgd.pt.cex=1,plot.delta0=TRUE,...) { if(model.type[1]=="single") { if(is.null(delta)) { delta<-0 } re<-cma.uni.delta(dat,delta=delta,conf.level=conf.level) if(sens.plot) { re.sens<-cma.uni.sens(dat,conf.level=conf.level) cma.uni.plot(re.sens,re,delta=NULL,legend.pos=legend.pos,xlab=xlab,ylab=ylab, cex.lab=cex.lab,cex.axis=cex.axis,lgd.cex=lgd.cex,lgd.pt.cex=1,plot.delta0=plot.delta0,...) } }else if(model.type[1]=="multilevel") { if(is.null(delta)) { if(method[1]=="TS") { system.time(re1<-optimize(cma.uni.mix.dhl,interval=interval,dat=dat,tol=tol,max.itr=0,optimizer=optimizer, mix.pkg=mix.pkg,random.indep=random.indep,random.var.equal=random.var.equal, u.int=u.int,Sigma.update=Sigma.update,logLik.type=logLik.type,maximum=TRUE)) re<-cma.uni.mix(dat,delta=re1$maximum,conf.level=conf.level,optimizer=optimizer,mix.pkg=mix.pkg, random.indep=random.indep,random.var.equal=random.var.equal,u.int=u.int) }else { system.time(re1<-optimize(cma.uni.mix.dhl,interval=interval,dat=dat,tol=tol,max.itr=max.itr,optimizer=optimizer, mix.pkg=mix.pkg,random.indep=random.indep,random.var.equal=random.var.equal, u.int=u.int,Sigma.update=Sigma.update,var.constraint=var.constraint, random.var.update=random.var.update,logLik.type=logLik.type,maximum=TRUE)) if(method[1]=="HL-TS") { re<-cma.uni.mix(dat,delta=re1$maximum,conf.level=conf.level,optimizer=optimizer,mix.pkg=mix.pkg, random.indep=random.indep,random.var.equal=random.var.equal,u.int=u.int) } if(method[1]=="HL") { re<-cma.uni.mix.hl(dat,delta=re1$maximum,tol=tol,max.itr=max.itr,alpha=1-conf.level,random.indep=random.indep, optimizer=optimizer,mix.pkg=mix.pkg,random.var.equal=random.var.equal,u.int=u.int, Sigma.update=Sigma.update,var.constraint=var.constraint,random.var.update=random.var.update) } } }else { if(method[1]=="TS") { re<-cma.uni.mix(dat,delta=delta,conf.level=conf.level,optimizer=optimizer,mix.pkg=mix.pkg, random.indep=random.indep,random.var.equal=random.var.equal,u.int=u.int) } if(method[1]=="HL") { re<-cma.uni.mix.hl(dat,delta=delta,tol=tol,max.itr=max.itr,alpha=1-conf.level,random.indep=random.indep, optimizer=optimizer,mix.pkg=mix.pkg,random.var.equal=random.var.equal,u.int=u.int, Sigma.update=Sigma.update,var.constraint=var.constraint,random.var.update=random.var.update) } } } return(re) if(as.numeric(re$Var.comp[1])<1e-5) { warning("The variance of A's random effect is less than 1e-5.") } return(re) if(as.numeric(re$Var.comp[2])<1e-5) { warning("The variance of C's random effect is less than 1e-5.") } return(re) if(as.numeric(re$Var.comp[3])<1e-5) { warning("The variance of B's random effect is less than 1e-5.") } }
DK_to_SWC <- function(DK, FUN = c('topp', 'jacobsen', 'jacobsen_soil_prop', 'pepin_5cm', 'pepin', 'roth_org', 'malicki_bd', 'malicki_ths', 'myllys', 'myllys_sphagnum', 'myllys_carex', 'kellner', 'kellner_h2', 'kellner_h3', 'kellner_h4', 'beckwith','yoshikawa_deadmoss', 'yoshikawa_livemoss', 'nagare', 'oleszczuk', 'gs3'), bd, ths, clay, SOM) { FUN <- tolower(FUN) obj <- list() if(any(FUN == 'topp')) { swc <- (-5.3*10^-2) + (2.92*10^-2*DK) - (5.5*10^-4 * DK^2) + (4.3*10^-6*DK^3) obj$Topp <- data.table(DK = DK, SWC = swc, FUN = 'topp') } if(any(FUN == 'jacobsen')) { swc <- (-7.01*10^-2) + (3.47*10^-2*DK) - (11.6*10^-4*DK^2) + (18*10^-6*DK^3) obj$jacobsen <- data.table(DK = DK, SWC = swc, FUN = 'jacobsen') } if(any(FUN == 'jacobsen_soil_prop')) { if(missing(bd)|missing(clay)|missing(SOM)){ warning('bd, clay are SOM is needed for FUN == "jacobson_soil_prop"!') } if(!missing(bd)& !missing(clay) & !missing(SOM)){ swc <- (-3.41* 10^-2) + (3.45*10^-2*DK) - (11.4*10^-4*DK^2) + (17.1*10^-6 * DK^3) - (3.7*10^-2 * bd) + (7.36*10^-4 * clay) + (47.7*10^-4* SOM) obj$jacobsen_soil_prop <- data.table(DK = DK, SWC = swc, FUN = 'jacobsen_soil_prop') } } if(any(FUN =='pepin_5cm')) { swc <- (0.03) + (0.0248*DK) - (-1.48*10^-4*DK^2) obj$pepin_5cm <- data.table(DK = DK, SWC = swc, FUN = 'pepin_5cm') } if(any(FUN =='pepin')) { swc <- (0.085) + (0.0192*DK) - (-0.95*10^-4*DK^2) obj$pepin <- data.table(DK = DK, SWC = swc, FUN = 'pepin') } if(any(FUN =='roth_org')){ swc <- (-0.0233) + (0.0285*DK ) + (-4.31*10^-4*DK^2) + (3.04*10^-6*DK^3) obj$roth_org <- data.table(DK = DK, SWC = swc, FUN = 'roth_org') } if(any(FUN =='malicki_bd')){ if(missing(bd)){ warning('bd is needed for FUN == "malicki_bd"!') } if(!missing(bd)){ swc <- ((sqrt(DK)-0.819-0.168*bd - 0.159*bd^2)/ (7.17+1.18*bd)) obj$malicki_bd <- data.table(DK = DK, SWC = swc, FUN = 'malicki_bd') } } if(any(FUN =='malicki_ths')){ if(missing(ths)){ warning('ths is needed for FUN == "malicki_ths"!') } if(!missing(ths)){ swc <- ((sqrt(DK)- 3.47 + (6.22*ths) - (3.82*ths^2))/ (7.01 + 6.89*ths - 7.83*ths^2)) obj$malicki_ths <- data.table(DK = DK, SWC = swc, FUN = 'malicki_ths') } } if(any(FUN =='myllys')){ swc <- (-0.0733) + (0.0417*DK ) + (-8.01*10^-4*DK^2) + (5.56*10^-6*DK^3) obj$myllys <- data.table(DK = DK, SWC = swc, FUN = 'myllys') } if(any(FUN =='myllys_sphagnum')){ swc <- (-0.0830) + (0.0432*DK ) + (-8.53*10^-4*DK^2) + (5.99*10^-6*DK^3) obj$myllys_sphagnum <- data.table(DK = DK, SWC = swc, FUN = 'myllys_sphagnum') } if(any(FUN =='myllys_carex')){ swc <- (-0.0986) + (0.0428*DK ) + (-8.08*10^-4*DK^2) + (5.52*10^-6*DK^3) obj$myllys_carex <- data.table(DK = DK, SWC = swc, FUN = 'myllys_carex') } if(any(FUN == 'kellner')) { swc <- (3.90*10^-2) + (3.17*10^-2*DK) - (4.50*10^-4*DK^2) + (2.60*10^-6*DK^3) obj$kellner <- data.table(DK = DK, SWC = swc, FUN = 'kellner') } if(any(FUN =='kellner_h2')){ swc <- (-0.061) + (0.029*DK ) + (-4.5*10^-4*DK^2) + (3.0*10^-6*DK^3) obj$kellner_h2 <- data.table(DK = DK, SWC = swc, FUN = 'kellner_h2') } if(any(FUN =='kellner_h3')){ swc <- (0.059) + (0.028*DK ) + (-3.2*10^-4*DK^2) + (1.4*10^-6*DK^3) obj$kellner_h3 <- data.table(DK = DK, SWC = swc, FUN = 'kellner_h3') } if(any(FUN =='kellner_h4')){ swc <- (-0.044) + (0.034*DK ) + (-5.1*10^-4*DK^2) + (3.0*10^-6*DK^3) obj$kellner_h4 <- data.table(DK = DK, SWC = swc, FUN = 'kellner_h4') } if(any(FUN =='beckwith')){ if (any(DK < 29) | any(DK > 75)) { warning('FUN == "beckwith": DK values out of calibration range!') } swc <- (-0.40289) + (0.064591*DK ) + (-12.06*10^-4*DK^2) + (7.92*10^-6*DK^3) obj$beckwith <- data.table(DK = DK, SWC = swc, FUN = 'beckwith') } if(any(FUN =='yoshikawa_deadmoss')){ swc <- (-0.6286) + (0.4337*DK) + (-5.49*10^-2*DK^2) + (0.33*10^-2*DK^3) obj$yoshikawa_deadmoss <- data.table(DK = DK, SWC = swc, FUN = 'yoshikawa_deadmoss') } if(any(FUN == 'yoshikawa_livemoss')){ swc <- (-0.16625) + (0.1108*DK) + (-0.21*10^-2*DK^2) + (4.33*10^-4*DK^3) obj$yoshikawa_livemoss <- data.table(DK = DK, SWC = swc, FUN = 'yoshikawa_livemoss') } if(any(FUN == 'nagare')) { swc <- (-1.89*10^-2) + (3.20*10^-2*DK) - (4.59*10^-4*DK^2) + (2.70*10^-6*DK^3) obj$nagare <- data.table(DK = DK, SWC = swc, FUN = 'nagare') } if(any(FUN =='oleszczuk')){ swc <- (-0.0276) + (0.2477*DK ) + (-3.15*10^-4*DK^2) + (2.00*10^-6*DK^3) obj$oleszczuk <- data.table(DK = DK, SWC = swc, FUN = 'oleszczuk') } if(any(FUN =='gs3')){ swc <- 0.118*sqrt(DK) -0.117 obj$gs3 <- data.table(DK = DK, SWC = swc, FUN = 'gs3') } obj <- rbindlist(obj) }
search_tracks <- function(track_name, output = c("tidy", "raw", "id"), limit = 20, offset = 0, token = my_token){ output <- match.arg(output) response = content(GET("https://api.spotify.com/v1/search/", query = list(q = track_name, type = "track", limit = limit, offset = offset), add_headers(Authorization = token))) items = response$tracks$items tidy <- data.frame( artist = map(items, "artists") %>% modify_depth(2, "name") %>% map_chr(paste, collapse = " ft. "), artist_id = map(items, "artists") %>% modify_depth(2, "id") %>% map_chr(paste, collapse = ","), track = map_chr(items, "name"), track_id = map_chr(items, "id"), type = map_chr(items, "type") ) id <- tidy$track_id out <- switch(output, tidy = tidy, raw = response, id = id) out }
group_split <- function(.tbl, ..., .keep = TRUE) { lifecycle::signal_stage("experimental", "group_split()") UseMethod("group_split") } group_split.data.frame <- function(.tbl, ..., .keep = TRUE, keep = deprecated()) { if (!missing(keep)) { lifecycle::deprecate_warn("1.0.0", "group_split(keep = )", "group_split(.keep = )") .keep <- keep } data <- group_by(.tbl, ...) group_split_impl(data, .keep = .keep) } group_split.rowwise_df <- function(.tbl, ..., .keep = TRUE, keep = deprecated()) { if (dots_n(...)) { warn("... is ignored in group_split(<rowwise_df>), please use as_tibble() %>% group_split(...)") } if (!missing(keep)) { lifecycle::deprecate_warn("1.0.0", "group_split(keep = )", "group_split(.keep = )") .keep <- keep } if (!missing(.keep)) { warn(".keep is ignored in group_split(<rowwise_df>)") } group_split_impl(.tbl, .keep = TRUE) } group_split.grouped_df <- function(.tbl, ..., .keep = TRUE, keep = deprecated()) { if (!missing(keep)) { lifecycle::deprecate_warn("1.0.0", "group_split(keep = )", "group_split(.keep = )") .keep <- keep } if (dots_n(...)) { warn("... is ignored in group_split(<grouped_df>), please use group_by(..., .add = TRUE) %>% group_split()") } group_split_impl(.tbl, .keep = .keep) } group_split_impl <- function(data, .keep) { out <- ungroup(data) indices <- group_rows(data) if (!isTRUE(.keep)) { remove <- group_vars(data) .keep <- names(out) .keep <- setdiff(.keep, remove) out <- out[.keep] } dplyr_chop(out, indices) } dplyr_chop <- function(data, indices) { out <- map(indices, dplyr_row_slice, data = data) out <- new_list_of(out, ptype = vec_ptype(data)) out }
get_final_values <- function(model = NULL) { if (is.null(model)) { return(NULL) }else if (model$parallel){ to_return <- vector("list", length(model$model)) for (i in 1:length(model$model)) { to_return[[i]] <- eval(parse(text = (paste0("as.list(model$model$cluster", i, "$state()[[1]])")))) } return(to_return) }else{ return(as.list(model$model$state())) } }
fanova.tests = function(x = NULL, group.label, test = "ALL", params = NULL, parallel = FALSE, nslaves = NULL){ if(any(is.na(group.label))){ stop("argument group.label can not contain NA values") } if(test[1] == "ALL"){ test = c("FP", "CH", "CS", "L2N", "L2B", "L2b", "FN", "FB", "Fb", "GPF", "Fmaxb", "TRP") }else{ for(i in 1:length(test)){ if(!(test[i] %in% c("FP", "CH", "CS", "L2N", "L2B", "L2b", "FN", "FB", "Fb", "GPF", "Fmaxb", "TRP"))){ stop("argument test must be the subvector of c('FP', 'CH', 'CS', 'L2N', 'L2B', 'L2b', 'FN', 'FB', 'Fb', 'GPF', 'Fmaxb', 'TRP')") } } } group.label0 = unique(group.label) l = length(group.label0) n.i = numeric(l) for(i in 1:l) n.i[i] = sum(group.label == group.label0[i]) anova.statistic.quick = function(x, group.label){ n = length(c(x)) a = length(unique(group.label)) y = data.frame(cbind(x, group.label)) colnames(y) = c("data", "group.label") means = (doBy::summaryBy(data ~ group.label, data = y))[,2] mean.g = mean(x) SSA = sum(table(group.label) * ((means - mean.g)^2)) SST = sum((x - mean.g)^2) SSE = SST - SSA return((n-a)*SSA/SSE/(a-1)) } ATS.simple = function(x, group.label){ N = length(x); n = table(group.label); ng = length(as.vector(n)) means = matrix(tapply(x, group.label, mean), ncol = 1) MM = diag(1, ng) - matrix(1, ncol = ng, nrow = ng)/ng DM = diag(diag(MM)) SN = N * diag(as.vector((tapply(x, group.label, var) * (n - 1)/n^2))) Delta = diag(as.vector(1/(n - 1))) test.stat = N * t(means) %*% MM %*% means/sum(diag(MM %*% SN)) f1 = sum(diag(MM %*% SN))^2/sum(diag(MM %*% SN %*% MM %*% SN)) f0 = sum(diag(MM %*% SN))^2/sum(diag(DM %*% DM %*% SN %*% SN %*% Delta)) return(c(test.stat, 1 - pf(test.stat, f1, f0))) } WTPSp = function(x, group.label, group.label0, n, n.i, l, perm.WTPS, nrTRP){ means = matrix(0, nrow = l, ncol = 1); variances = numeric(l) for(i in 1:l){ means[i,] = mean(x[group.label == group.label0[i]]) variances[i] = var(x[group.label == group.label0[i]]) } V.N = n*diag(variances/n.i) TT = diag(rep(1, l)) - (1/l)*matrix(1, ncol = l, nrow = l) Q.N.T = n * t(means) %*% TT %*% MASS::ginv(TT %*% V.N %*% TT) %*% TT %*% means A = t(rep(1/n.i[1], n.i[1])) A1 = t(rep(1, n.i[1])) for(i in 2:l){ A = magic::adiag(A, t(rep(1/n.i[i], n.i[i]))) A1 = magic::adiag(A1, t(rep(1, n.i[i]))) } xperm = matrix(x[perm.WTPS], ncol = nrTRP) meansP = A %*% xperm varsP = (A1 %*% (xperm^2) - n.i * meansP^2)/(n.i * (n.i - 1)) statistics.p = sapply(1:nrTRP, function(arg){ TP = TT %*% MASS::ginv(TT %*% (n * diag(varsP[, arg])) %*% TT) %*% TT statistics.p = diag(n * t(meansP[, arg]) %*% TP %*% meansP[, arg]) }) return(mean(statistics.p >= c(Q.N.T))) } if(any(c("FP", "CH", "CS", "L2b", "Fb", "Fmaxb", "TRP") %in% test)){ if(!parallel){ parallel.method = "parallel.method0" }else{ if(!("doParallel" %in% rownames(installed.packages()))){ stop("Please install package 'doParallel'") } requireNamespace("foreach", quietly = TRUE) nlp = parallel::detectCores() if(is.null(nslaves)){ if(nlp >= 2){ nslaves = nlp parallel.method = "parallel.method1" }else{ parallel.method = "parallel.method0" } }else{ if(nlp >= 2){ if(nslaves >= 2){ nslaves = nslaves }else{ nslaves = nlp } parallel.method = "parallel.method1" }else{ parallel.method = "parallel.method0" } } if(parallel.method == "parallel.method1"){ cl = parallel::makePSOCKcluster(nslaves) doParallel::registerDoParallel(cl) } } } if("FP" %in% test){ if(is.null(params$paramFP$basis)){ basis = "Fourier" }else{ basis = params$paramFP$basis } if(!(basis %in% c("Fourier", "b-spline", "own"))){ stop("argument params$paramFP$basis must be one of the following: 'Fourier', 'b-spline', 'own'") } if(is.null(params$paramFP$B.FP)){ nrFP = 1000 }else{ nrFP = params$paramFP$B.FP } if(nrFP < 1){ stop("invalid number of permutations (params$paramFP$B.FP)") } if(basis == "Fourier"){ if(!("fda" %in% rownames(installed.packages()))){ stop("Please install package 'fda'") } x = as.matrix(x); n = ncol(x); p = nrow(x) if(is.null(params$paramFP$minK)){ minK = 3 }else{ minK = params$paramFP$minK } if(minK < 1){ stop("invalid argument params$paramFP$minK") } if(is.null(params$paramFP$maxK)){ if(p %% 2 == 1){ maxK = p - 2 }else{ maxK = p - 1 } }else{ maxK = params$paramFP$maxK } if(maxK < 1){ stop("invalid argument params$paramFP$maxK") } if(p <= maxK){ if(p %% 2 == 1){ maxK = p - 2 }else{ maxK = p - 1 } } if((maxK %% 2) == 0){ stop("the maximum number of basis functions (params$paramFP$maxK) is even") } if(n != length(group.label)){ stop("number of observations (number of columns in x) and number of elements in vector of group labels (group.label) must be the same") } if(is.null(params$paramFP$criterion)){ criterion = "BIC" }else{ criterion = params$paramFP$criterion } if(!(criterion %in% c("BIC", "eBIC", "AIC", "AICc", "NO"))){ stop("argument params$paramFP$criterion must be one of the following: 'BIC', 'eBIC', 'AIC', 'AICc', 'NO'") } if(criterion == "eBIC"){ if(is.null(params$paramFP$gamma.eBIC)){ gamma.eBIC = 0.5 }else{ gamma.eBIC = params$paramFP$gamma.eBIC } if((gamma.eBIC < 0)|(gamma.eBIC > 1)){ stop("argument params$paramFP$gamma.eBIC must belong to [0,1]") } } if(criterion != "NO"){ if(is.null(params$paramFP$commonK)){ commonK = "mode" }else{ commonK = params$paramFP$commonK } if(!(commonK %in% c("mode", "min", "max", "mean"))){ stop("argument params$paramFP$commonK must be one of the following: 'mode', 'min', 'max', 'mean'") } if((minK %% 2) == 0){ stop("the minimum number of basis functions (params$paramFP$minK) is even") } if(is.null(params$paramFP$int)){ if(parallel.method == "parallel.method0"){ v = matrix(0, nrow = n, ncol = length(seq(minK, maxK, 2))) for(i in seq(minK, maxK, 2)){ fbasis = fda::create.fourier.basis(c(0, p), i) fdata = fda::smooth.basisPar(1:p, x, fbasis) v[, (i+2-minK)/2] = switch(criterion, "BIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + i*log(p), "eBIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + i*(log(p) + 2*gamma.eBIC*log(maxK)), "AIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*i, "AICc" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*i + (2 * i * (i + 1))/(n - i - 1)) } } if(parallel.method == "parallel.method1"){ v = foreach(i = seq(minK, maxK, 2), .combine = cbind) %dopar% { fbasis = fda::create.fourier.basis(c(0, p), i) fdata = fda::smooth.basisPar(1:p, x, fbasis) switch(criterion, "BIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + i*log(p), "eBIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + i*(log(p) + 2*gamma.eBIC*log(maxK)), "AIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*i, "AICc" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*i + (2 * i * (i + 1))/(n - i - 1)) } } KK = numeric(n) for(j in 1:n) KK[j] = 2*which(v[j,] == min(v[j,])) + minK - 2 if(commonK == "mode"){ temp = table(as.vector(KK)) K = min(as.numeric(names(temp)[temp == max(temp)])) } if(commonK == "min"){ K = min(KK) } if(commonK == "max"){ K = max(KK) } if(commonK == "mean"){ if(floor(mean(KK)) %% 2 == 1){ K = floor(mean(KK)) }else{ K = floor(mean(KK))-1 } } }else{ if(length(params$paramFP$int) != 2){ stop("argument params$paramFP$int must be of length two") } if(parallel.method == "parallel.method0"){ v = matrix(0, nrow = n, ncol = length(seq(minK, maxK, 2))) for(i in seq(minK, maxK, 2)){ fbasis = fda::create.fourier.basis(rangeval = c(params$paramFP$int[1], params$paramFP$int[2]), nbasis = i) fdata = fda::smooth.basisPar(seq(params$paramFP$int[1], params$paramFP$int[2], length = p), x, fbasis) v[, (i+2-minK)/2] = switch(criterion, "BIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + i*log(p), "eBIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + i*(log(p) + 2*gamma.eBIC*log(maxK)), "AIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*i, "AICc" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*i + (2 * i * (i + 1))/(n - i - 1)) } } if(parallel.method == "parallel.method1"){ v = foreach(i = seq(minK, maxK, 2), .combine = cbind) %dopar% { fbasis = fda::create.fourier.basis(rangeval = c(params$paramFP$int[1], params$paramFP$int[2]), nbasis = i) fdata = fda::smooth.basisPar(seq(params$paramFP$int[1], params$paramFP$int[2], length = p), x, fbasis) switch(criterion, "BIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + i*log(p), "eBIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + i*(log(p) + 2*gamma.eBIC*log(maxK)), "AIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*i, "AICc" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*i + (2 * i * (i + 1))/(n - i - 1)) } } KK = numeric(n) for(j in 1:n) KK[j] = 2*which(v[j,] == min(v[j,])) + minK - 2 if(commonK == "mode"){ temp = table(as.vector(KK)) K = min(as.numeric(names(temp)[temp == max(temp)])) } if(commonK == "min"){ K = min(KK) } if(commonK == "max"){ K = max(KK) } if(commonK == "mean"){ if(floor(mean(KK)) %% 2 == 1){ K = floor(mean(KK)) }else{ K = floor(mean(KK))-1 } } } }else{ K = maxK } if(is.null(params$paramFP$int)){ fbasis = fda::create.fourier.basis(c(0, p), K) lfdata = vector("list", l) mfdata = matrix(0, nrow = K, ncol = n) for(i in 1:l){ lfdata[[i]] = fda::Data2fd(1:p, x[, group.label == group.label0[i]], fbasis)$coefs mfdata[, group.label == group.label0[i]] = lfdata[[i]] } }else{ if(length(params$paramFP$int) != 2){ stop("argument params$paramFP$int must be of length two") } fbasis = fda::create.fourier.basis(c(params$paramFP$int[1], params$paramFP$int[2]), K) lfdata = vector("list", l) mfdata = matrix(0, nrow = K, ncol = n) for(i in 1:l){ lfdata[[i]] = fda::Data2fd(seq(params$paramFP$int[1], params$paramFP$int[2], length = p), x[, group.label == group.label0[i]], fbasis)$coefs mfdata[, group.label == group.label0[i]] = lfdata[[i]] } } a = 0; b = 0; c = 0 for(i in 1:l){ a = a + sum(t(lfdata[[i]]) %*% lfdata[[i]])/n.i[i] for(j in 1:l) b = b + sum(t(lfdata[[i]]) %*% (lfdata[[j]])) c = c + sum((lfdata[[i]])^2) } b = b/n; statFP0 = (a-b)/(c-a); statFP = statFP0*(n-l)/(l-1) if(parallel.method == "parallel.method0"){ FP.p = numeric(nrFP) for(ii in 1:nrFP){ a = numeric(l) Perm = sample(1:n) for(j in 1:l){ if(j == 1){ l1 = Perm[1:n.i[1]] }else{ l1 = Perm[(sum(n.i[1:(j-1)])+1):sum(n.i[1:j])] } a[j] = sum(t(mfdata[, l1]) %*% mfdata[, l1])/n.i[j] } FP.p[ii] = (sum(a)-b)/(c-sum(a)) } } if(parallel.method == "parallel.method1"){ FP.p = foreach(ii = 1:nrFP, .combine = "c") %dopar% { a = numeric(l) Perm = sample(1:n) for(j in 1:l){ if(j == 1){ l1 = Perm[1:n.i[1]] }else{ l1 = Perm[(sum(n.i[1:(j-1)])+1):sum(n.i[1:j])] } a[j] = sum(t(mfdata[, l1]) %*% mfdata[, l1])/n.i[j] } (sum(a)-b)/(c-sum(a)) } } pvalueFP = mean(FP.p >= statFP0) } if(basis == "b-spline"){ if(!("fda" %in% rownames(installed.packages()))){ stop("Please install package 'fda'") } x = as.matrix(x); n = ncol(x); p = nrow(x) if(is.null(params$paramFP$norder)){ norder = 4 }else{ norder = params$paramFP$norder } if(norder < 1){ stop("invalid argument params$paramFP$norder") } if(is.null(params$paramFP$minK)){ minK = norder }else{ minK = params$paramFP$minK } if(minK < 1){ stop("invalid argument params$paramFP$minK") } if(minK < norder){ minK = norder } if(is.null(params$paramFP$maxK)){ maxK = p }else{ maxK = params$paramFP$maxK } if(maxK < 1){ stop("invalid argument params$paramFP$maxK") } if(p <= maxK){ maxK = p } if(n != length(group.label)){ stop("number of observations (number of columns in x) and number of elements in vector of group labels (group.label) must be the same") } if(is.null(params$paramFP$criterion)){ criterion = "BIC" }else{ criterion = params$paramFP$criterion } if(!(criterion %in% c("BIC", "eBIC", "AIC", "AICc", "NO"))){ stop("argument params$paramFP$criterion must be one of the following: 'BIC', 'eBIC', 'AIC', 'AICc', 'NO'") } if(criterion == "eBIC"){ if(is.null(params$paramFP$gamma.eBIC)){ gamma.eBIC = 0.5 }else{ gamma.eBIC = params$paramFP$gamma.eBIC } if((gamma.eBIC < 0)|(gamma.eBIC > 1)){ stop("argument params$paramFP$gamma.eBIC must belong to [0,1]") } } if(criterion != "NO"){ if(is.null(params$paramFP$commonK)){ commonK = "mode" }else{ commonK = params$paramFP$commonK } if(!(commonK %in% c("mode", "min", "max", "mean"))){ stop("argument params$paramFP$commonK must be one of the following: 'mode', 'min', 'max', 'mean'") } mmm = minK:maxK if(is.null(params$paramFP$int)){ if(parallel.method == "parallel.method0"){ v = matrix(0, nrow = n, ncol = length(mmm)) for(i in 1:length(mmm)){ fbasis = fda::create.bspline.basis(c(0, p), mmm[i], norder = norder) fdata = fda::smooth.basisPar(1:p, x, fbasis) v[, i] = switch(criterion, "BIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + mmm[i]*log(p), "eBIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + mmm[i]*(log(p) + 2*gamma.eBIC*log(maxK)), "AIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*mmm[i], "AICc" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*mmm[i] + (2 * mmm[i] * (mmm[i] + 1))/(n - mmm[i] - 1)) } } if(parallel.method == "parallel.method1"){ v = foreach(i = 1:length(mmm), .combine = cbind) %dopar% { fbasis = fda::create.bspline.basis(c(0, p), mmm[i], norder = norder) fdata = fda::smooth.basisPar(1:p, x, fbasis) switch(criterion, "BIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + mmm[i]*log(p), "eBIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + mmm[i]*(log(p) + 2*gamma.eBIC*log(maxK)), "AIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*mmm[i], "AICc" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*mmm[i] + (2 * mmm[i] * (mmm[i] + 1))/(n - mmm[i] - 1)) } } KK = numeric(n) for(j in 1:n) KK[j] = mmm[which(v[j,] == min(v[j,]))] if(commonK == "mode"){ temp = table(as.vector(KK)) K = min(as.numeric(names(temp)[temp == max(temp)])) } if(commonK == "min"){ K = min(KK) } if(commonK == "max"){ K = max(KK) } if(commonK == "mean"){ K = floor(mean(KK)) } }else{ if(length(params$paramFP$int) != 2){ stop("argument params$paramFP$int must be of length two") } if(parallel.method == "parallel.method0"){ v = matrix(0, nrow = n, ncol = length(mmm)) for(i in 1:length(mmm)){ fbasis = fda::create.bspline.basis(rangeval = c(params$paramFP$int[1], params$paramFP$int[2]), nbasis = mmm[i], norder = norder) fdata = fda::smooth.basisPar(seq(params$paramFP$int[1], params$paramFP$int[2], length = p), x, fbasis) v[, i] = switch(criterion, "BIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + mmm[i]*log(p), "eBIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + mmm[i]*(log(p) + 2*gamma.eBIC*log(maxK)), "AIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*mmm[i], "AICc" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*mmm[i] + (2 * mmm[i] * (mmm[i] + 1))/(n - mmm[i] - 1)) } } if(parallel.method == "parallel.method1"){ v = foreach(i = 1:length(mmm), .combine = cbind) %dopar% { fbasis = fda::create.bspline.basis(rangeval = c(params$paramFP$int[1], params$paramFP$int[2]), nbasis = mmm[i], norder = norder) fdata = fda::smooth.basisPar(seq(params$paramFP$int[1], params$paramFP$int[2], length = p), x, fbasis) switch(criterion, "BIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + mmm[i]*log(p), "eBIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + mmm[i]*(log(p) + 2*gamma.eBIC*log(maxK)), "AIC" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*mmm[i], "AICc" = p*log(p*(1-fdata$df/p)^2*fdata$gcv/p) + 2*mmm[i] + (2 * mmm[i] * (mmm[i] + 1))/(n - mmm[i] - 1)) } } KK = numeric(n) for(j in 1:n) KK[j] = mmm[which(v[j,] == min(v[j,]))] if(commonK == "mode"){ temp = table(as.vector(KK)) K = min(as.numeric(names(temp)[temp == max(temp)])) } if(commonK == "min"){ K = min(KK) } if(commonK == "max"){ K = max(KK) } if(commonK == "mean"){ K = floor(mean(KK)) } } }else{ K = maxK } if(is.null(params$paramFP$int)){ fbasis = fda::create.bspline.basis(c(0, p), K, norder = norder) lfdata = vector("list", l) mfdata = matrix(0, nrow = K, ncol = n) for(i in 1:l){ lfdata[[i]] = fda::Data2fd(1:p, x[, group.label == group.label0[i]], fbasis)$coefs mfdata[, group.label == group.label0[i]] = lfdata[[i]] } }else{ if(length(params$paramFP$int) != 2){ stop("argument params$paramFP$int must be of length two") } fbasis = fda::create.bspline.basis(c(params$paramFP$int[1], params$paramFP$int[2]), K, norder = norder) lfdata = vector("list", l) mfdata = matrix(0, nrow = K, ncol = n) for(i in 1:l){ lfdata[[i]] = fda::Data2fd(seq(params$paramFP$int[1], params$paramFP$int[2], length = p), x[, group.label == group.label0[i]], fbasis)$coefs mfdata[, group.label == group.label0[i]] = lfdata[[i]] } } bspline.cross.prod.matrix = fda::inprod(fbasis, fbasis) a = 0; b = 0; c = 0 for(i in 1:l){ a = a + sum(t(lfdata[[i]]) %*% bspline.cross.prod.matrix %*% lfdata[[i]])/n.i[i] for(j in 1:l) b = b + sum(t(lfdata[[i]]) %*% bspline.cross.prod.matrix %*% (lfdata[[j]])) c = c + sum(diag(t(lfdata[[i]]) %*% bspline.cross.prod.matrix %*% lfdata[[i]])) } b = b/n; statFP0 = (a-b)/(c-a); statFP = statFP0*(n-l)/(l-1) if(parallel.method == "parallel.method0"){ FP.p = numeric(nrFP) for(ii in 1:nrFP){ a = numeric(l) Perm = sample(1:n) for(j in 1:l){ if(j == 1){ l1 = Perm[1:n.i[1]] }else{ l1 = Perm[(sum(n.i[1:(j-1)])+1):sum(n.i[1:j])] } a[j] = sum(t(mfdata[, l1]) %*% bspline.cross.prod.matrix %*% mfdata[, l1])/n.i[j] } FP.p[ii] = (sum(a)-b)/(c-sum(a)) } } if(parallel.method == "parallel.method1"){ FP.p = foreach(ii = 1:nrFP, .combine = "c") %dopar% { a = numeric(l) Perm = sample(1:n) for(j in 1:l){ if(j == 1){ l1 = Perm[1:n.i[1]] }else{ l1 = Perm[(sum(n.i[1:(j-1)])+1):sum(n.i[1:j])] } a[j] = sum(t(mfdata[, l1]) %*% bspline.cross.prod.matrix %*% mfdata[, l1])/n.i[j] } (sum(a)-b)/(c-sum(a)) } } pvalueFP = mean(FP.p >= statFP0) } if(basis == "own"){ own.basis = params$paramFP$own.basis mfdata = own.basis n = ncol(mfdata); K = nrow(mfdata) if(n != length(group.label)){ stop("the number of observations is not equal to the number of elements in vector of labels") } lfdata = vector("list", l) for(i in 1:l){ lfdata[[i]] = mfdata[, group.label == group.label0[i]] } own.cross.prod.mat = params$paramFP$own.cross.prod.mat if(K != nrow(own.cross.prod.mat)){ stop("invalid argument params$paramFP$own.cross.prod.mat") } if(K != ncol(own.cross.prod.mat)){ stop("invalid argument params$paramFP$own.cross.prod.mat") } a = 0; b = 0; c = 0 for(i in 1:l){ a = a + sum(t(lfdata[[i]]) %*% own.cross.prod.mat %*% lfdata[[i]])/n.i[i] for(j in 1:l) b = b + sum(t(lfdata[[i]]) %*% own.cross.prod.mat %*% (lfdata[[j]])) c = c + sum(diag(t(lfdata[[i]]) %*% own.cross.prod.mat %*% lfdata[[i]])) } b = b/n; statFP0 = (a-b)/(c-a); statFP = statFP0*(n-l)/(l-1) if(parallel.method == "parallel.method0"){ FP.p = numeric(nrFP) for(ii in 1:nrFP){ a = numeric(l) Perm = sample(1:n) for(j in 1:l){ if(j == 1){ l1 = Perm[1:n.i[1]] }else{ l1 = Perm[(sum(n.i[1:(j-1)])+1):sum(n.i[1:j])] } a[j] = sum(t(mfdata[, l1]) %*% own.cross.prod.mat %*% mfdata[, l1])/n.i[j] } FP.p[ii] = (sum(a)-b)/(c-sum(a)) } } if(parallel.method == "parallel.method1"){ FP.p = foreach(ii = 1:nrFP, .combine = "c") %dopar% { a = numeric(l) Perm = sample(1:n) for(j in 1:l){ if(j == 1){ l1 = Perm[1:n.i[1]] }else{ l1 = Perm[(sum(n.i[1:(j-1)])+1):sum(n.i[1:j])] } a[j] = sum(t(mfdata[, l1]) %*% own.cross.prod.mat %*% mfdata[, l1])/n.i[j] } (sum(a)-b)/(c-sum(a)) } } pvalueFP = mean(FP.p >= statFP0) } if(basis == "own"){ resultFP = list(statFP = statFP, pvalueFP = pvalueFP, B.FP = nrFP, basis = basis, own.basis = own.basis, own.cross.prod.mat = own.cross.prod.mat) }else{ if(criterion == "NO"){ if(is.null(params$paramFP$int)){ if(basis == "Fourier"){ resultFP = list(statFP = statFP, pvalueFP = pvalueFP, B.FP = nrFP, basis = basis, criterion = criterion, K = K, maxK = maxK) } if(basis == "b-spline"){ resultFP = list(statFP = statFP, pvalueFP = pvalueFP, B.FP = nrFP, basis = basis, criterion = criterion, K = K, maxK = maxK, norder = norder) } }else{ if(basis == "Fourier"){ resultFP = list(statFP = statFP, pvalueFP = pvalueFP, int = params$paramFP$int, B.FP = nrFP, basis = basis, criterion = criterion, K = K, maxK = maxK) } if(basis == "b-spline"){ resultFP = list(statFP = statFP, pvalueFP = pvalueFP, int = params$paramFP$int, B.FP = nrFP, basis = basis, criterion = criterion, K = K, maxK = maxK, norder = norder) } } }else{ if(is.null(params$paramFP$int)){ if(criterion == "eBIC"){ if(basis == "Fourier"){ resultFP = list(statFP = statFP, pvalueFP = pvalueFP, B.FP = nrFP, basis = basis, criterion = criterion, commonK = commonK, K = K, minK = minK, maxK = maxK, gamma.eBIC = gamma.eBIC) } if(basis == "b-spline"){ resultFP = list(statFP = statFP, pvalueFP = pvalueFP, B.FP = nrFP, basis = basis, criterion = criterion, commonK = commonK, K = K, minK = minK, maxK = maxK, norder = norder, gamma.eBIC = gamma.eBIC) } }else{ if(basis == "Fourier"){ resultFP = list(statFP = statFP, pvalueFP = pvalueFP, B.FP = nrFP, basis = basis, criterion = criterion, commonK = commonK, K = K, minK = minK, maxK = maxK) } if(basis == "b-spline"){ resultFP = list(statFP = statFP, pvalueFP = pvalueFP, B.FP = nrFP, basis = basis, criterion = criterion, commonK = commonK, K = K, minK = minK, maxK = maxK, norder = norder) } } }else{ if(criterion == "eBIC"){ if(basis == "Fourier"){ resultFP = list(statFP = statFP, pvalueFP = pvalueFP, int = params$paramFP$int, B.FP = nrFP, basis = basis, criterion = criterion, commonK = commonK, K = K, minK = minK, maxK = maxK, gamma.eBIC = gamma.eBIC) } if(basis == "b-spline"){ resultFP = list(statFP = statFP, pvalueFP = pvalueFP, int = params$paramFP$int, B.FP = nrFP, basis = basis, criterion = criterion, commonK = commonK, K = K, minK = minK, maxK = maxK, norder = norder, gamma.eBIC = gamma.eBIC) } }else{ if(basis == "Fourier"){ resultFP = list(statFP = statFP, pvalueFP = pvalueFP, int = params$paramFP$int, B.FP = nrFP, basis = basis, criterion = criterion, commonK = commonK, K = K, minK = minK, maxK = maxK) } if(basis == "b-spline"){ resultFP = list(statFP = statFP, pvalueFP = pvalueFP, int = params$paramFP$int, B.FP = nrFP, basis = basis, criterion = criterion, commonK = commonK, K = K, minK = minK, maxK = maxK, norder = norder) } } } } } } if(any(c("CH", "CS") %in% test)){ if(!("MASS" %in% rownames(installed.packages()))){ stop("Please install package 'MASS'") } x = as.matrix(x); n = ncol(x) if(n != length(group.label)){ stop("number of observations (number of columns in x) and number of elements in vector of group labels (group.label) must be the same") } statCHCS = 0 for(i in 1:(l-1)){ for(j in (i+1):l){ statCHCS = statCHCS + n.i[i]*sum((rowMeans(x[, group.label == group.label0[i]]) - rowMeans(x[, group.label == group.label0[j]]))^2) } } if("CH" %in% test){ if(is.null(params$paramCH)){ nrCH = 10000 }else{ nrCH = params$paramCH } if(nrCH < 1){ stop("invalid number of discretized artificial trajectories for each process Z_i(t) (params$paramCH)") } cov.fun = ((n-1)/(n-l))*var(t(x)); Z = vector("list", l) for(i in 1:l) Z[[i]] = MASS::mvrnorm(nrCH, numeric(nrow(cov.fun)), cov.fun) if(parallel.method == "parallel.method0"){ V = numeric(nrCH) for(m in 1:nrCH){ for(i in 1:(l-1)){ for(j in (i+1):l){ V[m] = V[m] + sum((Z[[i]][m,]-sqrt(n.i[i]/n.i[j])*Z[[j]][m,])^2) } } } } if(parallel.method == "parallel.method1"){ V = foreach(m = 1:nrCH, .combine = "c") %dopar% { V = 0 for(i in 1:(l-1)){ for(j in (i+1):l){ V = V + sum((Z[[i]][m,]-sqrt(n.i[i]/n.i[j])*Z[[j]][m,])^2) } } V } } resultCH = list(statCH = statCHCS, pvalueCH = mean(V > statCHCS), paramCH = nrCH) } if("CS" %in% test){ if(is.null(params$paramCS)){ nrCS = 10000 }else{ nrCS = params$paramCS } if(nrCS < 1){ stop("invalid number of discretized artificial trajectories for each process Z_i(t) (params$paramCS)") } Z = vector("list", l) for(i in 1:l){ cov.fun = var(t(x[, group.label == group.label0[i]])) Z[[i]] = MASS::mvrnorm(nrCS, numeric(nrow(cov.fun)), cov.fun) } if(parallel.method == "parallel.method0"){ V = numeric(nrCS) for(m in 1:nrCS){ for(i in 1:(l-1)){ for(j in (i+1):l){ V[m] = V[m] + sum((Z[[i]][m,]-sqrt(n.i[i]/n.i[j])*Z[[j]][m,])^2) } } } } if(parallel.method == "parallel.method1"){ V = foreach(m = 1:nrCS, .combine = "c") %dopar% { V = 0 for(i in 1:(l-1)){ for(j in (i+1):l){ V = V + sum((Z[[i]][m,]-sqrt(n.i[i]/n.i[j])*Z[[j]][m,])^2) } } V } } resultCS = list(statCS = statCHCS, pvalueCS = mean(V > statCHCS), paramCS = nrCS) } } if(any(c("L2N", "L2B", "L2b", "FN", "FB", "Fb", "GPF", "Fmaxb") %in% test)){ x = as.matrix(x); n = ncol(x); p = nrow(x) if(n != length(group.label)){ stop("number of observations (number of columns in x) and number of elements in vector of group labels (group.label) must be the same") } mu0 = rowMeans(x) vmu = matrix(0, nrow = l, ncol = p) z = matrix(0, nrow = n, ncol = p) SSR = 0; SSE = 0 for(i in 1:l){ xi = x[, group.label == group.label0[i]] mui = rowMeans(xi); vmu[i,] = mui zi = t(xi) - as.matrix(rep(1, n.i[i])) %*% mui if(i==1){ z[1:n.i[i],] = zi }else{ z[(cumsum(n.i)[i-1]+1):cumsum(n.i)[i],] = zi } SSR = SSR + n.i[i]*(mui - mu0)^2 SSE = SSE + colSums(zi^2) } if(n > p){ gamma.z = t(z) %*% z/(n-l) }else{ gamma.z = z %*% t(z)/(n-l) } A = sum(diag(gamma.z)); B = sum(diag(gamma.z %*% gamma.z)) A2N = A^2; B2N = B A2B = (n-l)*(n-l+1)/(n-l-1)/(n-l+2)*(A^2-2*B/(n-l+1)) B2B = (n-l)^2/(n-l-1)/(n-l+2)*(B-A^2/(n-l)) if(any(c("L2N", "L2B", "L2b") %in% test)){ statL2 = sum(SSR) if("L2N" %in% test){ betaL2N = B2N/A; kappaL2N = A2N/B2N pvalueL2N = 1-pchisq(statL2/betaL2N, (l-1)*kappaL2N) resultL2N = list(statL2 = statL2, pvalueL2N = pvalueL2N, betaL2N = betaL2N, dL2N = (l-1)*kappaL2N) } if("L2B" %in% test){ betaL2B = B2B/A; kappaL2B = A2B/B2B pvalueL2B = 1-pchisq(statL2/betaL2B, (l-1)*kappaL2B) resultL2B = list(statL2 = statL2, pvalueL2B = pvalueL2B, betaL2B = betaL2B, dL2B = (l-1)*kappaL2B) } if("L2b" %in% test){ if(is.null(params$paramL2b)){ nrL2b = 10000 }else{ nrL2b = params$paramL2b } if(nrL2b < 1){ stop("invalid number of bootstrap replicates (params$paramL2b)") } if(parallel.method == "parallel.method0"){ statL2boot = numeric(nrL2b) for(ii in 1:nrL2b){ vmuboot = matrix(0, nrow = l, ncol = p) for(i in 1:l){ xi = x[, group.label == group.label0[i]] xiboot = xi[, floor(runif(n.i[i])*(n.i[i]-1)) + 1] vmuboot[i,] = rowMeans(xiboot)-vmu[i,] } mu0boot = n.i %*% vmuboot/n SSRboot = 0 for(i in 1:l) SSRboot = SSRboot + n.i[i]*(vmuboot[i,]-mu0boot)^2 statL2boot[ii] = sum(SSRboot) } } if(parallel.method == "parallel.method1"){ statL2boot = foreach(ii = 1:nrL2b, .combine = "c") %dopar% { vmuboot = matrix(0, nrow = l, ncol = p) for(i in 1:l){ xi = x[, group.label == group.label0[i]] xiboot = xi[, floor(runif(n.i[i])*(n.i[i]-1)) + 1] vmuboot[i,] = rowMeans(xiboot)-vmu[i,] } mu0boot = n.i %*% vmuboot/n SSRboot = 0 for(i in 1:l) SSRboot = SSRboot + n.i[i]*(vmuboot[i,]-mu0boot)^2 sum(SSRboot) } } pvalueL2b = mean(statL2boot >= statL2) resultL2b = list(statL2 = statL2, pvalueL2b = pvalueL2b, paramL2b = nrL2b) } } if(any(c("FN", "FB", "Fb") %in% test)){ statF = sum(SSR)/sum(SSE)*(n-l)/(l-1) if("FN" %in% test){ kappaFN = A2N/B2N pvalueFN = 1-pf(statF, (l-1)*kappaFN, (n-l)*kappaFN) resultFN = list(statF = statF, pvalueFN = pvalueFN, d1FN = (l-1)*kappaFN, d2FN = (n-l)*kappaFN) } if("FB" %in% test){ kappaFB = A2B/B2B pvalueFB = 1-pf(statF, (l-1)*kappaFB, (n-l)*kappaFB) resultFB = list(statF = statF, pvalueFB = pvalueFB, d1FB = (l-1)*kappaFB, d2FB = (n-l)*kappaFB) } if("Fb" %in% test){ if(is.null(params$paramFb)){ nrFb = 10000 }else{ nrFb = params$paramFb } if(nrFb < 1){ stop("invalid number of bootstrap replicates (params$paramFb)") } if(parallel.method == "parallel.method0"){ statFboot = numeric(nrFb) for(ii in 1:nrFb){ vmuboot = matrix(0, nrow = l, ncol = p) zboot = matrix(0, nrow = n, ncol = p) for(i in 1:l){ xi = x[, group.label == group.label0[i]] xiboot = xi[, floor(runif(n.i[i])*(n.i[i]-1)) + 1] muiboot = rowMeans(xiboot) ziboot = t(xiboot) - as.matrix(rep(1, n.i[i])) %*% muiboot if(i==1){ zboot[1:n.i[i],] = ziboot }else{ zboot[(cumsum(n.i)[i-1]+1):cumsum(n.i)[i],] = ziboot } vmuboot[i,] = rowMeans(xiboot)-vmu[i,] } mu0boot = n.i %*% vmuboot/n SSRboot = 0 for(i in 1:l) SSRboot = SSRboot + n.i[i]*(vmuboot[i,]-mu0boot)^2 if(n > p){ gammaboot = t(zboot) %*% zboot/(n-l) }else{ gammaboot = zboot %*% t(zboot)/(n-l) } statFboot[ii] = sum(SSRboot)/sum(diag(gammaboot))/(l-1) } } if(parallel.method == "parallel.method1"){ statFboot = foreach(ii = 1:nrFb, .combine = "c") %dopar% { vmuboot = matrix(0, nrow = l, ncol = p) zboot = matrix(0, nrow = n, ncol = p) for(i in 1:l){ xi = x[, group.label == group.label0[i]] xiboot = xi[, floor(runif(n.i[i])*(n.i[i]-1)) + 1] muiboot = rowMeans(xiboot) ziboot = t(xiboot) - as.matrix(rep(1, n.i[i])) %*% muiboot if(i==1){ zboot[1:n.i[i],] = ziboot }else{ zboot[(cumsum(n.i)[i-1]+1):cumsum(n.i)[i],] = ziboot } vmuboot[i,] = rowMeans(xiboot)-vmu[i,] } mu0boot = n.i %*% vmuboot/n SSRboot = 0 for(i in 1:l) SSRboot = SSRboot + n.i[i]*(vmuboot[i,]-mu0boot)^2 if(n > p){ gammaboot = t(zboot) %*% zboot/(n-l) }else{ gammaboot = zboot %*% t(zboot)/(n-l) } sum(SSRboot)/sum(diag(gammaboot))/(l-1) } } pvalueFb = mean(statFboot >= statF) resultFb = list(statF = statF, pvalueFb = pvalueFb, paramFb = nrFb) } } if("GPF" %in% test){ statGPF = mean(SSR/SSE*(n-l)/(l-1)) z = z/(as.matrix(rep(1, n)) %*% sqrt(colSums(z^2))) if(n >= p){ z = t(z) %*% z }else{ z = z %*% t(z) } betaGPF = (sum(diag(z %*% z))/p^2/(l-1))/((n-l)/(n-l-2)) dGPF = ((n-l)/(n-l-2))^2/(sum(diag(z %*% z))/p^2/(l-1)) pvalueGPF = 1-pchisq(statGPF/betaGPF,dGPF) resultGPF = list(statGPF = statGPF, pvalueGPF = pvalueGPF, betaGPF = betaGPF, dGPF = dGPF) } if("Fmaxb" %in% test){ if(is.null(params$paramFmaxb)){ nrFmaxb = 10000 }else{ nrFmaxb = params$paramFmaxb } if(nrFmaxb < 1){ stop("invalid number of bootstrap replicates (params$paramFmaxb)") } statFmax = max(SSR/SSE*(n-l)/(l-1)) xs = matrix(0, nrow = n, ncol = p) for(i in 1:l){ xs[group.label == group.label0[i],] = t(x[, group.label == group.label0[i]]) - as.matrix(rep(1, n.i[i])) %*% vmu[i,] } if(parallel.method == "parallel.method0"){ statFmaxboot = numeric(nrFmaxb) for(ii in 1:nrFmaxb){ vmuboot = matrix(0, nrow = l, ncol = p) zboot = matrix(0, nrow = n, ncol = p) xboot = xs[sample(1:n, replace = TRUE),] mu0boot = colMeans(xboot) SSRboot = 0 for(i in 1:l){ xiboot = xboot[group.label == group.label0[i],] muiboot = colMeans(xiboot) vmuboot[i,] = muiboot ziboot = xiboot - as.matrix(rep(1, n.i[i])) %*% muiboot if(i==1){ zboot[1:n.i[i],] = ziboot }else{ zboot[(cumsum(n.i)[i-1]+1):cumsum(n.i)[i],] = ziboot } SSRboot = SSRboot + n.i[i]*(muiboot - mu0boot)^2 } SSEboot = diag(t(zboot) %*% zboot) statFmaxboot[ii] = max(SSRboot/SSEboot*(n-l)/(l-1)) } } if(parallel.method == "parallel.method1"){ statFmaxboot = foreach(ii = 1:nrFmaxb, .combine = "c") %dopar% { vmuboot = matrix(0, nrow = l, ncol = p) zboot = matrix(0, nrow = n, ncol = p) xboot = xs[sample(1:n, replace = TRUE),] mu0boot = colMeans(xboot) SSRboot = 0 for(i in 1:l){ xiboot = xboot[group.label == group.label0[i],] muiboot = colMeans(xiboot) vmuboot[i,] = muiboot ziboot = xiboot - as.matrix(rep(1, n.i[i])) %*% muiboot if(i==1){ zboot[1:n.i[i],] = ziboot }else{ zboot[(cumsum(n.i)[i-1]+1):cumsum(n.i)[i],] = ziboot } SSRboot = SSRboot + n.i[i]*(muiboot - mu0boot)^2 } SSEboot = diag(t(zboot) %*% zboot) max(SSRboot/SSEboot*(n-l)/(l-1)) } } pvalueFmaxb = mean(statFmaxboot >= statFmax) resultFmaxb = list(statFmax = statFmax, pvalueFmaxb = pvalueFmaxb, paramFmaxb = nrFmaxb) } } if ("TRP" %in% test) { if (!("doBy" %in% rownames(installed.packages()))) { stop("Please install package 'doBY'") } if (!("MASS" %in% rownames(installed.packages()))) { stop("Please install package 'MASS'") } if (!("magic" %in% rownames(installed.packages()))) { stop("Please install package 'magic'") } x <- as.matrix(x); n <- ncol(x); p <- nrow(x) if (n != length(group.label)) { stop("number of observations (number of columns in x) and number of elements in vector of group labels (group.label) must be the same") } if (is.null(params$paramTRP$projection)) { projection <- "GAUSS" }else{ projection <- params$paramTRP$projection } if (!(projection %in% c("GAUSS", "BM"))) { stop("argument params$paramTRP$projection must be one of the following: 'GAUSS', 'BM'") } if (is.null(params$paramTRP$permutation)) { permutationTRP <- FALSE }else{ permutationTRP <- params$paramTRP$permutation } if (! is.logical(permutationTRP)) { stop("argument permutation is not logical (params$paramTRP$permutation)") } if (is.null(params$paramTRP$independent.projection.tests)) { independent.projection.tests <- TRUE }else{ independent.projection.tests <- params$paramTRP$independent.projection.tests } if (! is.logical(independent.projection.tests)) { stop("argument independent.projection.tests is not logical (params$paramTRP$independent.projection.tests)") } if (is.null(params$paramTRP$B.TRP)) { nrTRP <- 10000 }else{ nrTRP <- params$paramTRP$B.TRP } if (nrTRP < 1) { stop("invalid number of permutations (params$paramTRP$B.TRP)") } if (is.null(params$paramTRP$k)) { k <- 30 }else{ k <- params$paramTRP$k } if (any(k < 1)) { stop("invalid number of projections (k)") } pvalues.anova <- numeric(length(k)) pvalues.ATS.simple <- numeric(length(k)) pvalues.WTPS <- numeric(length(k)) modulo <- function(z){ sqrt(sum(z^2)) } if (independent.projection.tests) { all.data.proj <- list() iik <- 0 for(ik in k){ ik.data.proj <- matrix(0, nrow = n, ncol = ik) if(projection == "GAUSS"){ z <- matrix(rnorm(p * ik), nrow = ik, ncol = p) modu <- apply(z, 1, modulo) z <- z/modu if(parallel.method == "parallel.method0"){ anova.p <- numeric(ik) ATS.simple.p <- numeric(ik) WTPS.p <- numeric(ik) for(j in 1:ik){ ik.data.proj[, j] <- t(x) %*% z[j,] data.proj <- ik.data.proj[, j] perm.WTPS <- matrix(0, nrow = n, ncol = nrTRP) for(i.perm in 1:nrTRP){ perm.WTPS[, i.perm] <- sample(1:n) } WTPS.p[j] <- WTPSp(data.proj, group.label, group.label0, n, n.i, l, perm.WTPS = perm.WTPS, nrTRP) if(permutationTRP == FALSE){ anova.p[j] <- 1-pf(anova.statistic.quick(data.proj, group.label), l-1, n-l) ATS.simple.p[j] <- ATS.simple(data.proj, group.label)[2] }else{ anova.s <- anova.statistic.quick(data.proj, group.label) ATS.simple.s <- ATS.simple(data.proj, group.label)[1] anova.perm <- numeric(nrTRP) ATS.simple.perm <- numeric(nrTRP) for(i.perm in 1:nrTRP){ anova.perm[i.perm] <- anova.statistic.quick(data.proj, sample(group.label)) ATS.simple.perm[i.perm] <- ATS.simple(data.proj, sample(group.label))[1] } anova.p[j] <- mean(anova.perm >= anova.s) ATS.simple.p[j] <- mean(ATS.simple.perm >= ATS.simple.s) } } iik <- iik + 1 all.data.proj[[iik]] <- ik.data.proj pvalues.anova[iik] <- min(ik*anova.p[order(anova.p)]/1:ik) pvalues.ATS.simple[iik] <- min(ik*ATS.simple.p[order(ATS.simple.p)]/1:ik) pvalues.WTPS[iik] <- min(ik*WTPS.p[order(WTPS.p)]/1:ik) } if(parallel.method == "parallel.method1"){ rs <- foreach(j = 1:ik, .combine = rbind) %dopar% { ik.data.proj[, j] <- t(x) %*% z[j,] data.proj <- ik.data.proj[, j] perm.WTPS <- matrix(0, nrow = n, ncol = nrTRP) for(i.perm in 1:nrTRP){ perm.WTPS[, i.perm] <- sample(1:n) } WTPS.p <- WTPSp(data.proj, group.label, group.label0, n, n.i, l, perm.WTPS = perm.WTPS, nrTRP) if(permutationTRP == FALSE){ c(1-pf(anova.statistic.quick(data.proj, group.label), l-1, n-l), ATS.simple(data.proj, group.label)[2], WTPS.p, data.proj) }else{ anova.s <- anova.statistic.quick(data.proj, group.label) ATS.simple.s <- ATS.simple(data.proj, group.label)[1] anova.perm <- numeric(nrTRP) ATS.simple.perm <- numeric(nrTRP) for(i.perm in 1:nrTRP){ anova.perm[i.perm] <- anova.statistic.quick(data.proj, sample(group.label)) ATS.simple.perm[i.perm] <- ATS.simple(data.proj, sample(group.label))[1] } c(mean(anova.perm >= anova.s), mean(ATS.simple.perm >= ATS.simple.s), WTPS.p, data.proj) } } if(ik == 1) rs <- matrix(rs, nrow = 1, ncol = n+3) iik <- iik + 1 if(ik == 1){ all.data.proj[[iik]] <- matrix(rs[, 4:(n+3)], ncol = 1) }else{ all.data.proj[[iik]] <- t(rs[, 4:(n+3)]) } pvalues.anova[iik] <- min(ik*(rs[, 1])[order(rs[, 1])]/1:ik) pvalues.ATS.simple[iik] <- min(ik*(rs[, 2])[order(rs[, 2])]/1:ik) pvalues.WTPS[iik] <- min(ik*(rs[, 3])[order(rs[, 3])]/1:ik) } }else{ if(parallel.method == "parallel.method0"){ anova.p <- numeric(ik) ATS.simple.p <- numeric(ik) WTPS.p <- numeric(ik) for(j in 1:ik){ bm.p <- cumsum(rnorm(p, mean = 0, sd = 1))/sqrt(p) bm.p <- bm.p/modulo(bm.p) ik.data.proj[, j] <- t(x) %*% as.matrix(bm.p) data.proj <- ik.data.proj[, j] perm.WTPS <- matrix(0, nrow = n, ncol = nrTRP) for(i.perm in 1:nrTRP){ perm.WTPS[, i.perm] <- sample(1:n) } WTPS.p[j] <- WTPSp(data.proj, group.label, group.label0, n, n.i, l, perm.WTPS = perm.WTPS, nrTRP) if(permutationTRP == FALSE){ anova.p[j] <- 1-pf(anova.statistic.quick(data.proj, group.label), l-1, n-l) ATS.simple.p[j] <- ATS.simple(data.proj, group.label)[2] }else{ anova.s <- anova.statistic.quick(data.proj, group.label) ATS.simple.s <- ATS.simple(data.proj, group.label)[1] anova.perm <- numeric(nrTRP) ATS.simple.perm <- numeric(nrTRP) for(i.perm in 1:nrTRP){ anova.perm[i.perm] <- anova.statistic.quick(data.proj, sample(group.label)) ATS.simple.perm[i.perm] <- ATS.simple(data.proj, sample(group.label))[1] } anova.p[j] <- mean(anova.perm >= anova.s) ATS.simple.p[j] <- mean(ATS.simple.perm >= ATS.simple.s) } } iik <- iik + 1 all.data.proj[[iik]] <- ik.data.proj pvalues.anova[iik] <- min(ik*anova.p[order(anova.p)]/1:ik) pvalues.ATS.simple[iik] <- min(ik*ATS.simple.p[order(ATS.simple.p)]/1:ik) pvalues.WTPS[iik] <- min(ik*WTPS.p[order(WTPS.p)]/1:ik) } if(parallel.method == "parallel.method1"){ rs <- foreach(j = 1:ik, .combine = rbind) %dopar% { bm.p <- cumsum(rnorm(p, mean = 0, sd = 1))/sqrt(p) bm.p <- bm.p/modulo(bm.p) ik.data.proj[, j] <- t(x) %*% as.matrix(bm.p) data.proj <- ik.data.proj[, j] perm.WTPS <- matrix(0, nrow = n, ncol = nrTRP) for(i.perm in 1:nrTRP){ perm.WTPS[, i.perm] <- sample(1:n) } WTPS.p <- WTPSp(data.proj, group.label, group.label0, n, n.i, l, perm.WTPS = perm.WTPS, nrTRP) if(permutationTRP == FALSE){ c(1-pf(anova.statistic.quick(data.proj, group.label), l-1, n-l), ATS.simple(data.proj, group.label)[2], WTPS.p, data.proj) }else{ anova.s <- anova.statistic.quick(data.proj, group.label) ATS.simple.s <- ATS.simple(data.proj, group.label)[1] anova.perm <- numeric(nrTRP) ATS.simple.perm <- numeric(nrTRP) for(i.perm in 1:nrTRP){ anova.perm[i.perm] <- anova.statistic.quick(data.proj, sample(group.label)) ATS.simple.perm[i.perm] <- ATS.simple(data.proj, sample(group.label))[1] } c(mean(anova.perm >= anova.s), mean(ATS.simple.perm >= ATS.simple.s), WTPS.p, data.proj) } } if(ik == 1) rs <- matrix(rs, nrow = 1, ncol = n+3) iik <- iik + 1 if(ik == 1){ all.data.proj[[iik]] <- matrix(rs[, 4:(n+3)], ncol = 1) }else{ all.data.proj[[iik]] <- t(rs[, 4:(n+3)]) } pvalues.anova[iik] <- min(ik*(rs[, 1])[order(rs[, 1])]/1:ik) pvalues.ATS.simple[iik] <- min(ik*(rs[, 2])[order(rs[, 2])]/1:ik) pvalues.WTPS[iik] <- min(ik*(rs[, 3])[order(rs[, 3])]/1:ik) } } } }else{ ik <- max(k) ik.data.proj <- matrix(0, nrow = n, ncol = ik) if (projection == "GAUSS") { z <- matrix(rnorm(p * ik), nrow = ik, ncol = p) modu <- apply(z, 1, modulo) z <- z/modu if(parallel.method == "parallel.method0"){ anova.p <- numeric(ik) ATS.simple.p <- numeric(ik) WTPS.p <- numeric(ik) for(j in 1:ik){ ik.data.proj[, j] <- t(x) %*% z[j,] data.proj <- ik.data.proj[, j] perm.WTPS <- matrix(0, nrow = n, ncol = nrTRP) for(i.perm in 1:nrTRP){ perm.WTPS[, i.perm] <- sample(1:n) } WTPS.p[j] <- WTPSp(data.proj, group.label, group.label0, n, n.i, l, perm.WTPS = perm.WTPS, nrTRP) if(permutationTRP == FALSE){ anova.p[j] <- 1-pf(anova.statistic.quick(data.proj, group.label), l-1, n-l) ATS.simple.p[j] <- ATS.simple(data.proj, group.label)[2] }else{ anova.s <- anova.statistic.quick(data.proj, group.label) ATS.simple.s <- ATS.simple(data.proj, group.label)[1] anova.perm <- numeric(nrTRP) ATS.simple.perm <- numeric(nrTRP) for(i.perm in 1:nrTRP){ anova.perm[i.perm] <- anova.statistic.quick(data.proj, sample(group.label)) ATS.simple.perm[i.perm] <- ATS.simple(data.proj, sample(group.label))[1] } anova.p[j] <- mean(anova.perm >= anova.s) ATS.simple.p[j] <- mean(ATS.simple.perm >= ATS.simple.s) } } all.data.proj <- ik.data.proj iik <- 0 for (ik in k) { iik <- iik + 1 pvalues.anova[iik] <- min(ik * anova.p[1:ik][order(anova.p[1:ik])] / 1:ik) pvalues.ATS.simple[iik] <- min(ik * ATS.simple.p[1:ik][order(ATS.simple.p[1:ik])] / 1:ik) pvalues.WTPS[iik] <- min(ik * WTPS.p[1:ik][order(WTPS.p[1:ik])] / 1:ik) } } if(parallel.method == "parallel.method1"){ rs <- foreach(j = 1:ik, .combine = rbind) %dopar% { ik.data.proj[, j] <- t(x) %*% z[j,] data.proj <- ik.data.proj[, j] perm.WTPS <- matrix(0, nrow = n, ncol = nrTRP) for(i.perm in 1:nrTRP){ perm.WTPS[, i.perm] <- sample(1:n) } WTPS.p <- WTPSp(data.proj, group.label, group.label0, n, n.i, l, perm.WTPS = perm.WTPS, nrTRP) if(permutationTRP == FALSE){ c(1-pf(anova.statistic.quick(data.proj, group.label), l-1, n-l), ATS.simple(data.proj, group.label)[2], WTPS.p, data.proj) }else{ anova.s <- anova.statistic.quick(data.proj, group.label) ATS.simple.s <- ATS.simple(data.proj, group.label)[1] anova.perm <- numeric(nrTRP) ATS.simple.perm <- numeric(nrTRP) for(i.perm in 1:nrTRP){ anova.perm[i.perm] <- anova.statistic.quick(data.proj, sample(group.label)) ATS.simple.perm[i.perm] <- ATS.simple(data.proj, sample(group.label))[1] } c(mean(anova.perm >= anova.s), mean(ATS.simple.perm >= ATS.simple.s), WTPS.p, data.proj) } } if (ik == 1) rs <- matrix(rs, nrow = 1, ncol = n+3) if (ik == 1) { all.data.proj <- matrix(rs[, 4:(n+3)], ncol = 1) } else { all.data.proj <- t(rs[, 4:(n+3)]) } iik <- 0 for (ik in k) { iik <- iik + 1 pvalues.anova[iik] <- min(ik * (rs[1:ik, 1])[order(rs[1:ik, 1])] / 1:ik) pvalues.ATS.simple[iik] <- min(ik * (rs[1:ik, 2])[order(rs[1:ik, 2])] / 1:ik) pvalues.WTPS[iik] <- min(ik * (rs[1:ik, 3])[order(rs[1:ik, 3])] / 1:ik) } } } else { if(parallel.method == "parallel.method0"){ anova.p <- numeric(ik) ATS.simple.p <- numeric(ik) WTPS.p <- numeric(ik) for(j in 1:ik){ bm.p <- cumsum(rnorm(p, mean = 0, sd = 1))/sqrt(p) bm.p <- bm.p/modulo(bm.p) ik.data.proj[, j] <- t(x) %*% as.matrix(bm.p) data.proj <- ik.data.proj[, j] perm.WTPS <- matrix(0, nrow = n, ncol = nrTRP) for(i.perm in 1:nrTRP){ perm.WTPS[, i.perm] <- sample(1:n) } WTPS.p[j] <- WTPSp(data.proj, group.label, group.label0, n, n.i, l, perm.WTPS = perm.WTPS, nrTRP) if(permutationTRP == FALSE){ anova.p[j] <- 1-pf(anova.statistic.quick(data.proj, group.label), l-1, n-l) ATS.simple.p[j] <- ATS.simple(data.proj, group.label)[2] }else{ anova.s <- anova.statistic.quick(data.proj, group.label) ATS.simple.s <- ATS.simple(data.proj, group.label)[1] anova.perm <- numeric(nrTRP) ATS.simple.perm <- numeric(nrTRP) for(i.perm in 1:nrTRP){ anova.perm[i.perm] <- anova.statistic.quick(data.proj, sample(group.label)) ATS.simple.perm[i.perm] <- ATS.simple(data.proj, sample(group.label))[1] } anova.p[j] <- mean(anova.perm >= anova.s) ATS.simple.p[j] <- mean(ATS.simple.perm >= ATS.simple.s) } } all.data.proj <- ik.data.proj iik <- 0 for (ik in k) { iik <- iik + 1 pvalues.anova[iik] <- min(ik * anova.p[1:ik][order(anova.p[1:ik])] / 1:ik) pvalues.ATS.simple[iik] <- min(ik * ATS.simple.p[1:ik][order(ATS.simple.p[1:ik])] / 1:ik) pvalues.WTPS[iik] <- min(ik * WTPS.p[1:ik][order(WTPS.p[1:ik])] / 1:ik) } } if(parallel.method == "parallel.method1"){ rs <- foreach(j = 1:ik, .combine = rbind) %dopar% { bm.p <- cumsum(rnorm(p, mean = 0, sd = 1))/sqrt(p) bm.p <- bm.p/modulo(bm.p) ik.data.proj[, j] <- t(x) %*% as.matrix(bm.p) data.proj <- ik.data.proj[, j] perm.WTPS <- matrix(0, nrow = n, ncol = nrTRP) for(i.perm in 1:nrTRP){ perm.WTPS[, i.perm] <- sample(1:n) } WTPS.p <- WTPSp(data.proj, group.label, group.label0, n, n.i, l, perm.WTPS = perm.WTPS, nrTRP) if(permutationTRP == FALSE){ c(1-pf(anova.statistic.quick(data.proj, group.label), l-1, n-l), ATS.simple(data.proj, group.label)[2], WTPS.p, data.proj) }else{ anova.s <- anova.statistic.quick(data.proj, group.label) ATS.simple.s <- ATS.simple(data.proj, group.label)[1] anova.perm <- numeric(nrTRP) ATS.simple.perm <- numeric(nrTRP) for(i.perm in 1:nrTRP){ anova.perm[i.perm] <- anova.statistic.quick(data.proj, sample(group.label)) ATS.simple.perm[i.perm] <- ATS.simple(data.proj, sample(group.label))[1] } c(mean(anova.perm >= anova.s), mean(ATS.simple.perm >= ATS.simple.s), WTPS.p, data.proj) } } if (ik == 1) rs <- matrix(rs, nrow = 1, ncol = n+3) if (ik == 1) { all.data.proj <- matrix(rs[, 4:(n+3)], ncol = 1) } else { all.data.proj <- t(rs[, 4:(n+3)]) } iik <- 0 for (ik in k) { iik <- iik + 1 pvalues.anova[iik] <- min(ik * (rs[1:ik, 1])[order(rs[1:ik, 1])] / 1:ik) pvalues.ATS.simple[iik] <- min(ik * (rs[1:ik, 2])[order(rs[1:ik, 2])] / 1:ik) pvalues.WTPS[iik] <- min(ik * (rs[1:ik, 3])[order(rs[1:ik, 3])] / 1:ik) } } } } resultTRP <- list(pvalues.anova = pvalues.anova, pvalues.ATS = pvalues.ATS.simple, pvalues.WTPS = pvalues.WTPS, data.projections = all.data.proj, k = k, projection = projection, permutation = permutationTRP, B.TRP = nrTRP, independent.projection.tests = independent.projection.tests) } if(any(c("FP", "CH", "CS", "L2b", "Fb", "Fmaxb", "TRP") %in% test)){ if(parallel.method == "parallel.method1"){ parallel::stopCluster(cl) } } list.results = list() for(ii in test){ if(ii == "FP"){ list.results[[which(test == ii)]] = resultFP names(list.results)[which(test == ii)] = "FP" } if(ii == "CH"){ list.results[[which(test == ii)]] = resultCH names(list.results)[which(test == ii)] = "CH" } if(ii == "CS"){ list.results[[which(test == ii)]] = resultCS names(list.results)[which(test == ii)] = "CS" } if(ii == "L2N"){ list.results[[which(test == ii)]] = resultL2N names(list.results)[which(test == ii)] = "L2N" } if(ii == "L2B"){ list.results[[which(test == ii)]] = resultL2B names(list.results)[which(test == ii)] = "L2B" } if(ii == "L2b"){ list.results[[which(test == ii)]] = resultL2b names(list.results)[which(test == ii)] = "L2b" } if(ii == "FN"){ list.results[[which(test == ii)]] = resultFN names(list.results)[which(test == ii)] = "FN" } if(ii == "FB"){ list.results[[which(test == ii)]] = resultFB names(list.results)[which(test == ii)] = "FB" } if(ii == "Fb"){ list.results[[which(test == ii)]] = resultFb names(list.results)[which(test == ii)] = "Fb" } if(ii == "GPF"){ list.results[[which(test == ii)]] = resultGPF names(list.results)[which(test == ii)] = "GPF" } if(ii == "Fmaxb"){ list.results[[which(test == ii)]] = resultFmaxb names(list.results)[which(test == ii)] = "Fmaxb" } if(ii == "TRP"){ list.results[[which(test == ii)]] = resultTRP names(list.results)[which(test == ii)] = "TRP" } } list.results$data = x list.results$group.label = group.label list.results$parallel = parallel list.results$nslaves = nslaves class(list.results) = "fanovatests" return(list.results) }
linearCase <- function(x, y, trt, propen, wgt, intercept) { p <- 1L:{ncol(x)+1L} n <- length(y) trtOpts <- sort(unique(trt)) trtOpts <- trtOpts[-1L] k <- length(trtOpts) x1 <- cbind(1.0,x) * wgt y <- y * wgt xpro <- NULL for( i in 1L:k ) { xpro <- cbind(xpro, x1 * {{trt == trtOpts[i]} - propen[,i+1L]}) } if( intercept ) { fit <- stats::lm(y ~ x + xpro, data = data.frame(x,xpro,y))$coef gamma <- fit[p] beta <- fit[-p] } else { fit <- stats::lm(y ~ -1 + x + xpro, data = data.frame(x,xpro,y))$coef gamma <- 0.0 beta <- fit } if( any(is.na(fit)) ) { stop("NAs encountered in fit of baseline mean function.", call. = FALSE) } AL <- adaptiveLasso(x = x, y = y, gamma = gamma, beta = beta, propen = propen, trt = trt, wgt = wgt) return(AL) }
.tuneLearnFullFits <- function(lsig, form, fam, qu, err, ctrl, data, argGam, gausFit, varHat, initM){ n <- nrow(data) nt <- length(lsig) mainObj <- do.call("gam", c(list("formula" = form, "family" = quote(elf(qu = qu, co = NA, theta = NA, link = ctrl$link)), "data" = quote(data), "fit" = FALSE), argGam)) argGam <- argGam[ names(argGam) != "sp" ] repar <- if( is.list(form) ){ Sl.setup( mainObj ) } else { .prepBootObj(obj = mainObj, eps = NULL, control = argGam$control)[ c("UrS", "Mp", "U1") ] } tmp <- pen.edf( gausFit ) if( length(tmp) ) { edfStore <- list( ) } else { edfStore <- NULL } store <- vector("list", nt) for( ii in 1:nt ) { mainObj$family$putCo( err * sqrt(2*pi*varHat) / (2*log(2)) ) mainObj$family$putTheta( lsig[ii] ) convProb <- FALSE withCallingHandlers({ fit <- do.call("gam", c(list("G" = quote(mainObj), "in.out" = initM[["in.out"]], "start" = initM[["start"]]), argGam)) }, warning = function(w) { if (length(grep("Fitting terminated with step failure", conditionMessage(w))) || length(grep("Iteration limit reached without full convergence", conditionMessage(w)))) { message( paste("log(sigma) = ", round(lsig[ii], 3), " : outer Newton did not converge fully.", sep = "") ) convProb <<- TRUE invokeRestart("muffleWarning") } }) if( !is.null(edfStore) ) { edfStore[[ii]] <- c(lsig[ii], pen.edf(fit)) } if( ii == 1 ){ pMat <- pMatFull <- predict.gam(fit, type = "lpmatrix") lpi <- attr(pMat, "lpi") if( !is.null(lpi) ){ pMat <- pMat[ , lpi[[1]]] attr(pMat, "lpi") <- lpi } } sdev <- NULL if(ctrl$loss %in% c("cal", "calFast") && ctrl$vtype == "m"){ Vp <- fit$Vp if( !is.null(lpi) ){ Vp <- fit$Vp[lpi[[1]], lpi[[1]]] } sdev <- sqrt(rowSums((pMat %*% Vp) * pMat)) } initM <- list("start" = coef(fit), "in.out" = list("sp" = fit$sp, "scale" = 1)) if( ctrl$loss == "calFast" ){ if( ii == 1 ){ EXXT <- crossprod(pMatFull, pMatFull) / n EXEXT <- tcrossprod( colMeans(pMatFull), colMeans(pMatFull) ) } Vbias <- .biasedCov(fit = fit, X = pMatFull, EXXT = EXXT, EXEXT = EXEXT, lpi = lpi) store[[ii]] <- list("loss" = .sandwichLoss(mFit = fit, X = pMat, XFull = pMatFull, sdev = sdev, repar = repar, alpha = Vbias$alpha, VSim = Vbias$V), "convProb" = convProb) } else { store[[ii]] <- list("sp" = fit$sp, "fit" = fit$fitted, "co" = fit$family$getCo(), "init" = initM$start, "sdev" = sdev, "weights" = fit$working.weights, "res" = fit$residuals, "convProb" = convProb) } } if( !is.null(edfStore) ){ edfStore <- do.call("rbind", edfStore) colnames(edfStore) <- c("lsig", names( pen.edf(fit) )) } return( list("store" = store, "edfStore" = edfStore, "pMat" = if(ctrl$loss != "calFast") { pMat } else { NULL } ) ) }
daysum <- function(var, infile, outfile, nc34 = 4, overwrite = FALSE, verbose = FALSE, nc = NULL) { dayx_wrapper(4, var, infile, outfile, nc34, overwrite, verbose = verbose, nc = nc) }
timestamp <- Sys.time() library(caret) library(plyr) library(recipes) library(dplyr) model <- "leapSeq" library(caret) library(plyr) library(recipes) library(dplyr) set.seed(1) training <- SLC14_1(30) testing <- SLC14_1(100) trainX <- training[, -ncol(training)] trainY <- training$y rec_reg <- recipe(y ~ ., data = training) %>% step_center(all_predictors()) %>% step_scale(all_predictors()) testX <- trainX[, -ncol(training)] testY <- trainX$y rctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all") rctrl2 <- trainControl(method = "LOOCV") rctrl3 <- trainControl(method = "none") rctrlR <- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random") set.seed(849) test_reg_cv_model <- train(trainX, trainY, method = "leapSeq", trControl = rctrl1, preProc = c("center", "scale")) test_reg_pred <- predict(test_reg_cv_model, testX) set.seed(849) test_reg_cv_form <- train(y ~ ., data = training, method = "leapSeq", trControl = rctrl1, preProc = c("center", "scale")) test_reg_pred_form <- predict(test_reg_cv_form, testX) set.seed(849) test_reg_rand <- train(trainX, trainY, method = "leapSeq", trControl = rctrlR, tuneLength = 4) set.seed(849) test_reg_loo_model <- train(trainX, trainY, method = "leapSeq", trControl = rctrl2, preProc = c("center", "scale")) set.seed(849) test_reg_none_model <- train(trainX, trainY, method = "leapSeq", trControl = rctrl3, tuneLength = 1, preProc = c("center", "scale")) test_reg_none_pred <- predict(test_reg_none_model, testX) set.seed(849) test_reg_rec <- train(x = rec_reg, data = training, method = "leapSeq", trControl = rctrl1) if( !isTRUE( all.equal(test_reg_cv_model$results, test_reg_rec$results)) ) stop("CV weights not giving the same results") test_reg_imp_rec <- varImp(test_reg_rec) test_reg_pred_rec <- predict(test_reg_rec, testing[, -ncol(testing)]) tests <- grep("test_", ls(), fixed = TRUE, value = TRUE) sInfo <- sessionInfo() timestamp_end <- Sys.time() save(list = c(tests, "sInfo", "timestamp", "timestamp_end"), file = file.path(getwd(), paste(model, ".RData", sep = ""))) if(!interactive()) q("no")
get_global_graph_attr_info <- function(graph) { 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 (nrow(graph$global_attrs) == 0) { global_graph_attrs_tbl <- dplyr::tibble( attr = character(0), value = character(0), attr_type = character(0) ) } else if (nrow(graph$global_attrs) > 0) { global_graph_attrs_tbl <- dplyr::as_tibble(graph$global_attrs) } global_graph_attrs_tbl }
find_outliers <- function(.data = NULL, var = NULL, by = NULL, plots = FALSE, coef = 1.5, verbose = TRUE, plot_theme = theme_metan()) { if (!missing(by)){ if(length(as.list(substitute(by))[-1L]) != 0){ stop("Only one grouping variable can be used in the argument 'by'.\nUse 'group_by()' to pass '.data' grouped by more than one variable.", call. = FALSE) } .data <- group_by(.data, {{by}}) } if(is_grouped_df(.data)){ results <- .data %>% doo(find_outliers, var = {{var}}, plots = plots, coef = coef, verbose = verbose, plot_theme = plot_theme) %>% as.data.frame() names(results)[[which(names(results) == "data")]] <- "outliers" return(results) } if(has_class(.data, c("numeric", "integer"))){ var_name <- as.numeric(.data) dd <- data.frame(.data) } else { var_name <- .data %>% dplyr::select({{var}}) %>% unlist() %>% as.numeric() dd <- data.frame(.data %>% select({{var}})) } tot <- sum(!is.na(var_name)) na1 <- sum(is.na(var_name)) m1 <- mean(var_name, na.rm = TRUE) m11 <- (sd(var_name, na.rm = TRUE)/m1) * 100 outlier <- boxplot.stats(var_name, coef = coef)$out names_out <- paste(which(dd[, 1] %in% outlier), sep = " ") if (length(outlier) >= 1) { mo <- mean(outlier) maxo <- max(outlier) mino <- min(outlier) names_out_max <- paste(which(dd[, 1] == maxo)) names_out_min <- paste(which(dd[, 1] == mino)) } var_name2 <- ifelse(var_name %in% outlier, NA, var_name) names <- rownames(var_name2) na2 <- sum(is.na(var_name2)) if ((na2 - na1) > 0) { if(verbose == TRUE){ cat("Trait:", colnames(dd), "\n") cat("Number of possible outliers:", na2 - na1, "\n") cat("Line(s):", names_out, "\n") cat("Proportion: ", round((na2 - na1)/sum(!is.na(var_name2)) * 100, 1), "%\n", sep = "") cat("Mean of the outliers:", round(mo, 3), "\n") cat("Maximum of the outliers:", round(maxo, 3), " | Line", names_out_max, "\n") cat("Minimum of the outliers:", round(mino, 3), " | Line", names_out_min, "\n") m2 <- mean(var_name2, na.rm = TRUE) m22 <- (sd(var_name2, na.rm = TRUE)/m2) * 100 cat("With outliers: mean = ", round(m1, 3), " | CV = ", round(m11, 3), "%", sep = "", "\n") cat("Without outliers: mean = ", round(m2, 3), " | CV = ", round(m22, 3), "%", sep = "", "\n\n") } } if (any(plots == TRUE)) { df_out <- data.frame(with = var_name, without = var_name2) nbins <- round(1 + 3.322 * log(nrow(df_out)), 0) with_box <- ggplot(df_out, aes(x = "Outlier", y = with)) + stat_boxplot(geom = "errorbar", width=0.2, size = 0.2, na.rm = TRUE)+ geom_boxplot(outlier.color = "black", outlier.shape = 21, outlier.size = 2.5, outlier.fill = "red", color = "black", width = .5, size = 0.2, na.rm = TRUE)+ plot_theme %+replace% theme(axis.text.x = element_text(color = "white"), panel.grid.major.x = element_blank(), axis.ticks.x = element_blank())+ labs(y = "Observed value", x = "") without_box <- ggplot(df_out, aes(x = "Outlier", y = without)) + stat_boxplot(geom = "errorbar", width=0.2, size = 0.2, na.rm = TRUE)+ geom_boxplot(outlier.color = "black", outlier.shape = 21, outlier.size = 2.5, outlier.fill = "red", color = "black", width = .5, size = 0.2, na.rm = TRUE)+ plot_theme %+replace% theme(axis.text.x = element_text(color = "white"), panel.grid.major.x = element_blank(), axis.ticks.x = element_blank())+ labs(y = "Observed value", x = "") with_hist <- ggplot(df_out, aes(x = with))+ geom_histogram(position="identity", color = "black", fill = "gray", na.rm = TRUE, size = 0.2, bins = nbins)+ scale_y_continuous(expand = expansion(mult = c(0, .1)))+ plot_theme + labs(x = "Observed value", y = "Count") without_hist <- ggplot(df_out, aes(x = without))+ geom_histogram(position="identity", color = "black", fill = "gray", na.rm = TRUE, size = 0.2, bins = nbins)+ scale_y_continuous(expand = expansion(mult = c(0, .1)))+ plot_theme + labs(x = "Observed value", y = "Count") p1 <- wrap_plots(with_box + labs(title = "With outliers"), with_hist, nrow = 1) p2 <- wrap_plots(without_box + labs(title = "Without outliers"), without_hist, nrow = 1) plot(p1 / p2) } if ((na2 - na1) == 0) { if(verbose == TRUE){ cat("No possible outlier identified. \n\n") } } outlier <- ifelse(((na2 - na1) == 0), 0, na2 - na1) invisible(outlier) }
classVariable_Generic <- R6Class( classname = "variable_Generic", public = list( allDrawnVariables = NA, allLikelihoodVars = NA, allObserved = NA, attributeProfile = NA, constraintMatrix = NA, completeCases = NA, covMat = NA, defaultSimulatedParameters = list(), distributionSpecs = list(), formula = NA, formulaRHS = NA, hyperparameters = list(), imputeList = NA, incompleteCases = NA, initializeAlpha = NA, initialParameterValues = list(), isLatent = NA, isLatentJoint = NA, isPredictor = NA, likelihoodPTR = NA, meanIdentification = NA, missing = NA, nCategories = NA, nConstraints = NA, nImpute = NA, nMissing = NA, nObserved = NA, nParam = NA, nSubVariables = NA, modeledN = NA, modeledObs = NA, observed = NA, paramNames = NA, parameters = list(), predictedBy = NA, predicts = NA, predNames = NA, predTypes = NA, priorAlpha = NA, routines = list(), subVariableNames = NA, variableName = NA, variableNumber = NA, varianceIdentification = NA, underlyingVariables = NA, initialize = function(){ }, initializeParameters = function(){ }, initializeUnits = function(){ }, KLI = function(){ }, likelihood = function(){ }, loadPointers = function(){ self$likelihoodPTR = bernoulliLikelihoodPtr(self$distributionSpecs$distribution) }, predictedValues = function(){ }, prepareData = function(){ }, provideParameterTypesAndLocations = function(){ }, provideParameterValues = function(){ }, random = function(){ }, sampleParameters = function(){ }, sampleUnits = function(){ }, setParameterValues = function(){ }, simulateParameters = function(){ }, simulateUnits = function(){ } ) )
cano2M <- function(nVar, dMax, poly) { pMax <- length(poly) if (pMax != d2pMax(nVar, dMax)) stop('Polynomial function size incompatible with formulation poLabs(nVar, dMax).') Kmod <- matrix(0, ncol = nVar, nrow = pMax) Kmod[, nVar] <- poly for (i in 1:(nVar - 1)) { ireg <- d2pMax(nVar - i - 1, dMax) + 1 Kmod[ireg, i] <- 1 } Kmod }
gdina_proc_check_admissible_rules <- function(rule) { admiss.rules <- c("GDINA", "ACDM", "DINA", "DINO", "GDINA1", "GDINA2", "RRUM", "SISM" ) i1 <- which( ! ( rule %in% admiss.rules ) ) if ( length(i1) > 0 ){ cat("The following rules are not implemented in gdina: ") cat( paste( unique( rule[i1] ), collapse=" " ), "\n" ) stop("Change your argument 'rule'") } }
k9_get_events <- function(event_id = NULL, start = NULL, end = NULL, priority = NULL, sources = NULL, tags = NULL, .split_request = TRUE) { if(!is.null(event_id)) { if(is.numeric(event_id)) { warning('Consider specifying event_id by character, as they might be too big for integer') } result <- k9_request(verb = "GET", path = sprintf("/api/v1/events/%s", event_id)) } else { period <- to_epochperiod(start, end) if(!is.null(priority) && !priority %in% c('low', 'normal')) { stop("priority can be eighter NULL, 'low', or 'normal'.") } if(!is.null(sources)) { sources <- paste(sources, collapse = ",") } if(!is.null(tags) && is.list(tags)) { tags <- paste(names(tags), tags, sep = ":", collapse = ",") } result <- purrr::map2_df( .x = dplyr::lag(period)[-1], .y = period[-1], .f = k9_get_events_one, sources = sources, tags = tags ) } result } k9_get_events_one <- function(start, end, priority = NULL, sources = NULL, tags = NULL) { result <- k9_request(verb = "GET", path = "/api/v1/events", query = list( start = start, end = end, priority = priority, sources = sources, tags = tags )) result }
NULL ecrpublic_batch_check_layer_availability <- function(registryId = NULL, repositoryName, layerDigests) { op <- new_operation( name = "BatchCheckLayerAvailability", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$batch_check_layer_availability_input(registryId = registryId, repositoryName = repositoryName, layerDigests = layerDigests) output <- .ecrpublic$batch_check_layer_availability_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$batch_check_layer_availability <- ecrpublic_batch_check_layer_availability ecrpublic_batch_delete_image <- function(registryId = NULL, repositoryName, imageIds) { op <- new_operation( name = "BatchDeleteImage", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$batch_delete_image_input(registryId = registryId, repositoryName = repositoryName, imageIds = imageIds) output <- .ecrpublic$batch_delete_image_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$batch_delete_image <- ecrpublic_batch_delete_image ecrpublic_complete_layer_upload <- function(registryId = NULL, repositoryName, uploadId, layerDigests) { op <- new_operation( name = "CompleteLayerUpload", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$complete_layer_upload_input(registryId = registryId, repositoryName = repositoryName, uploadId = uploadId, layerDigests = layerDigests) output <- .ecrpublic$complete_layer_upload_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$complete_layer_upload <- ecrpublic_complete_layer_upload ecrpublic_create_repository <- function(repositoryName, catalogData = NULL) { op <- new_operation( name = "CreateRepository", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$create_repository_input(repositoryName = repositoryName, catalogData = catalogData) output <- .ecrpublic$create_repository_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$create_repository <- ecrpublic_create_repository ecrpublic_delete_repository <- function(registryId = NULL, repositoryName, force = NULL) { op <- new_operation( name = "DeleteRepository", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$delete_repository_input(registryId = registryId, repositoryName = repositoryName, force = force) output <- .ecrpublic$delete_repository_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$delete_repository <- ecrpublic_delete_repository ecrpublic_delete_repository_policy <- function(registryId = NULL, repositoryName) { op <- new_operation( name = "DeleteRepositoryPolicy", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$delete_repository_policy_input(registryId = registryId, repositoryName = repositoryName) output <- .ecrpublic$delete_repository_policy_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$delete_repository_policy <- ecrpublic_delete_repository_policy ecrpublic_describe_image_tags <- function(registryId = NULL, repositoryName, nextToken = NULL, maxResults = NULL) { op <- new_operation( name = "DescribeImageTags", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$describe_image_tags_input(registryId = registryId, repositoryName = repositoryName, nextToken = nextToken, maxResults = maxResults) output <- .ecrpublic$describe_image_tags_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$describe_image_tags <- ecrpublic_describe_image_tags ecrpublic_describe_images <- function(registryId = NULL, repositoryName, imageIds = NULL, nextToken = NULL, maxResults = NULL) { op <- new_operation( name = "DescribeImages", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$describe_images_input(registryId = registryId, repositoryName = repositoryName, imageIds = imageIds, nextToken = nextToken, maxResults = maxResults) output <- .ecrpublic$describe_images_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$describe_images <- ecrpublic_describe_images ecrpublic_describe_registries <- function(nextToken = NULL, maxResults = NULL) { op <- new_operation( name = "DescribeRegistries", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$describe_registries_input(nextToken = nextToken, maxResults = maxResults) output <- .ecrpublic$describe_registries_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$describe_registries <- ecrpublic_describe_registries ecrpublic_describe_repositories <- function(registryId = NULL, repositoryNames = NULL, nextToken = NULL, maxResults = NULL) { op <- new_operation( name = "DescribeRepositories", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$describe_repositories_input(registryId = registryId, repositoryNames = repositoryNames, nextToken = nextToken, maxResults = maxResults) output <- .ecrpublic$describe_repositories_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$describe_repositories <- ecrpublic_describe_repositories ecrpublic_get_authorization_token <- function() { op <- new_operation( name = "GetAuthorizationToken", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$get_authorization_token_input() output <- .ecrpublic$get_authorization_token_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$get_authorization_token <- ecrpublic_get_authorization_token ecrpublic_get_registry_catalog_data <- function() { op <- new_operation( name = "GetRegistryCatalogData", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$get_registry_catalog_data_input() output <- .ecrpublic$get_registry_catalog_data_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$get_registry_catalog_data <- ecrpublic_get_registry_catalog_data ecrpublic_get_repository_catalog_data <- function(registryId = NULL, repositoryName) { op <- new_operation( name = "GetRepositoryCatalogData", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$get_repository_catalog_data_input(registryId = registryId, repositoryName = repositoryName) output <- .ecrpublic$get_repository_catalog_data_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$get_repository_catalog_data <- ecrpublic_get_repository_catalog_data ecrpublic_get_repository_policy <- function(registryId = NULL, repositoryName) { op <- new_operation( name = "GetRepositoryPolicy", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$get_repository_policy_input(registryId = registryId, repositoryName = repositoryName) output <- .ecrpublic$get_repository_policy_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$get_repository_policy <- ecrpublic_get_repository_policy ecrpublic_initiate_layer_upload <- function(registryId = NULL, repositoryName) { op <- new_operation( name = "InitiateLayerUpload", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$initiate_layer_upload_input(registryId = registryId, repositoryName = repositoryName) output <- .ecrpublic$initiate_layer_upload_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$initiate_layer_upload <- ecrpublic_initiate_layer_upload ecrpublic_put_image <- function(registryId = NULL, repositoryName, imageManifest, imageManifestMediaType = NULL, imageTag = NULL, imageDigest = NULL) { op <- new_operation( name = "PutImage", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$put_image_input(registryId = registryId, repositoryName = repositoryName, imageManifest = imageManifest, imageManifestMediaType = imageManifestMediaType, imageTag = imageTag, imageDigest = imageDigest) output <- .ecrpublic$put_image_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$put_image <- ecrpublic_put_image ecrpublic_put_registry_catalog_data <- function(displayName = NULL) { op <- new_operation( name = "PutRegistryCatalogData", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$put_registry_catalog_data_input(displayName = displayName) output <- .ecrpublic$put_registry_catalog_data_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$put_registry_catalog_data <- ecrpublic_put_registry_catalog_data ecrpublic_put_repository_catalog_data <- function(registryId = NULL, repositoryName, catalogData) { op <- new_operation( name = "PutRepositoryCatalogData", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$put_repository_catalog_data_input(registryId = registryId, repositoryName = repositoryName, catalogData = catalogData) output <- .ecrpublic$put_repository_catalog_data_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$put_repository_catalog_data <- ecrpublic_put_repository_catalog_data ecrpublic_set_repository_policy <- function(registryId = NULL, repositoryName, policyText, force = NULL) { op <- new_operation( name = "SetRepositoryPolicy", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$set_repository_policy_input(registryId = registryId, repositoryName = repositoryName, policyText = policyText, force = force) output <- .ecrpublic$set_repository_policy_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$set_repository_policy <- ecrpublic_set_repository_policy ecrpublic_upload_layer_part <- function(registryId = NULL, repositoryName, uploadId, partFirstByte, partLastByte, layerPartBlob) { op <- new_operation( name = "UploadLayerPart", http_method = "POST", http_path = "/", paginator = list() ) input <- .ecrpublic$upload_layer_part_input(registryId = registryId, repositoryName = repositoryName, uploadId = uploadId, partFirstByte = partFirstByte, partLastByte = partLastByte, layerPartBlob = layerPartBlob) output <- .ecrpublic$upload_layer_part_output() config <- get_config() svc <- .ecrpublic$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .ecrpublic$operations$upload_layer_part <- ecrpublic_upload_layer_part
NULL sql_translation.Snowflake <- function(con) { sql_variant( sql_translator( .parent = base_odbc_scalar, log10 = function(x) sql_expr(log(10, !!x)) ), base_agg, base_win ) } simulate_snowflake <- function() simulate_dbi("Snowflake") sql_table_analyze.Snowflake <- function(con, table, ...) {}
library(mpe) Sigma <- matrix(c(1, 0.8, 0.8, 1), nrow = 2) power.known.var(K = 2, delta = c(0.25, 0.4), Sigma = Sigma, sig.level = 0.025, power = 0.8) power.known.var(K = 2, delta = c(0.25, 0.4), SD = c(1,1), rho = 0.8, sig.level = 0.025, power = 0.8) power.known.var(K = 2, n = 252, delta = c(0.25,0.4), Sigma=Sigma, sig.level = 0.025) power.known.var(K = 2, n = 252, delta = c(0.25, 0.4), SD = c(1,1), rho = 0.8, sig.level = 0.025) delta <- c(0.25, 0.5) Sigma <- matrix(c(1, 0.75, 0.75, 1), ncol = 2) n <- 50 X <- rmvnorm(n=n, mean = delta, sigma = Sigma) Y <- rmvnorm(n=n, mean = rep(0, length(delta)), sigma = Sigma) mpe.z.test(X = X, Y = Y, Sigma = Sigma) Sigma <- matrix(c(1, 0.5, 0.5, 1), nrow = 2) power.known.var(K = 2, delta = c(0.5, 0.4), Sigma = Sigma, sig.level = 0.025, power = 0.8) Sigma <- matrix(c(1, 0.5, 0.5, 1), nrow = 2) power.unknown.var(K = 2, delta = c(0.5, 0.4), Sigma = Sigma, sig.level = 0.025, power = 0.8, min.n = 105, max.n = 120) Sigma <- matrix(c(1, 0.5, 0.5, 1), nrow = 2) power.unknown.var(K = 2, delta = c(0.5, 0.4), rho = 0.5, SD = c(1,1), sig.level = 0.025, power = 0.8, min.n = 105, max.n = 120) power.unknown.var(K = 2, n = 107, delta = c(0.5,0.4), Sigma = matrix(c(1, 0.5,0.5, 1), nrow=2), sig.level = 0.025) delta <- c(0.5, 0.4) Sigma <- matrix(c(1, 0.5, 0.5, 1), ncol = 2) n <- 106 X <- rmvnorm(n=n, mean = delta, sigma = Sigma) Y <- rmvnorm(n=n, mean = rep(0, length(delta)), sigma = Sigma) mpe.t.test(X = X, Y = Y) atleast.one.endpoint(K = 2, delta = c(0.20,0.30), Sigma = matrix(c(1, 0.3, 0.3, 1), nrow = 2), power = 0.8, sig.level = 0.025) atleast.one.endpoint(K = 2, delta = c(0.20, 0.30), SD = c(1,1), rho = 0.3, power = 0.8) atleast.one.endpoint(K = 2, n = 147, delta = c(0.20,0.30), Sigma = matrix(c(1, 0.3, 0.3, 1), nrow = 2)) power.known.var(K = 2,delta = c(0.47, 0.48), Sigma = matrix(c(1, 0.0, 0.0, 1), nrow = 2), sig.level = 0.025, power = 0.8) power.known.var(K= 2,delta = c(0.47, 0.48), Sigma = matrix(c(1, 0.3, 0.3, 1), nrow = 2), sig.level = 0.025, power = 0.8) power.known.var(K = 2,delta = c(0.47, 0.48), Sigma = matrix(c(1, 0.5, 0.5, 1), nrow = 2), sig.level = 0.025, power = 0.8) power.known.var(K = 2, delta = c(0.47, 0.48), Sigma = matrix(c(1, 0.8, 0.8, 1), nrow = 2), sig.level = 0.025, power = 0.8) power.known.var(K = 3, delta = c(0.36, 0.30, 0.26), Sigma = matrix(c(1, 0.3, 0.3, 0.3, 1, 0.3, 0.3, 0.3, 1), nrow = 3), sig.level = 0.025, power = 0.8) power.unknown.var(K = 3, delta = c(0.36, 0.30, 0.26), Sigma = matrix(c(1, 0.3, 0.3, 0.3, 1, 0.3, 0.3, 0.3, 1), nrow = 3), sig.level = 0.025, power = 0.8, min.n = 268, max.n = 300) atleast.one.endpoint(K= 2, delta = c(0.47, 0.48), Sigma = matrix(c(1, 0.0, 0.0, 1), nrow = 2), power = 0.8) atleast.one.endpoint(K= 2, delta = c(0.47, 0.48), Sigma = matrix(c(1, 0.3, 0.3, 1), nrow = 2), power = 0.8) atleast.one.endpoint(K= 2, delta = c(0.47, 0.48), Sigma = matrix(c(1, 0.5, 0.5, 1), nrow = 2), power = 0.8) atleast.one.endpoint(K= 2, delta = c(0.47, 0.48), Sigma = matrix(c(1, 0.8, 0.8, 1), nrow = 2), power = 0.8)
sysreqs_collect <- function(prj = NULL) { prj <- safe_get_prj(prj) stopifnot(!is.null(prj)) params <- prj$load_params() pkg_loginfo("Detecting repositories (for R %s)...", params$r_ver) repo_infos <- get_all_repo_infos(params) log_repo_infos(repo_infos) avail_vers <- resolve_prj_deps(repo_infos, params) pkg_loginfo("Detected %s dependencies. Processing...", length(vers.get_names(avail_vers))) tmp_dir <- tempfile() dir.create(tmp_dir, recursive = TRUE) on.exit({ unlink(tmp_dir, recursive = TRUE, force = TRUE) }, add = TRUE) result <- list() dloaded <- pkg_download(avail_vers$avails, dest_dir = tmp_dir) for (r in seq_len(nrow(dloaded))) { dl <- dloaded[r, ] dcf <- get_pkg_desc(dl$Package, dl$Path) if (!is.null(dcf$SystemRequirements)) { result[[dl$Package]] <- gsub("\n", " ", dcf$SystemRequirements) } } prj_packages <- build_project_pkgslist(params$pkgs_path) if (length(prj_packages) > 0) { pkg_loginfo("Processing project packages...") for (pkg in names(prj_packages)) { dcf <- get_pkg_desc(pkg, file.path(params$pkgs_path, prj_packages[[pkg]])) if (!is.null(dcf$SystemRequirements)) { result[[pkg]] <- gsub("\n", " ", dcf$SystemRequirements) } } } pkg_loginfo("Done.") return(result) } sysreqs_check <- function(prj = NULL) { sysreqs <- sysreqs_collect(prj) if (length(sysreqs) == 0) { pkg_loginfo("No system requirements detected to check.") return(invisible()) } recipe <- build_sysreqs_check_recipe() recipe <- sysreqs_recipe_collect_all(recipe, sysreqs) result <- perform(recipe) assert(length(result$notools) + length(result$nolibs) == 0, sprintf("Some system requirements are not satisfied: %s", paste(c(result$notools, result$nolibs), collapse = ", "))) pkg_loginfo("All system requirements satisfied.") } sysreqs_install <- function(prj = NULL) { sysreqs <- sysreqs_collect(prj) if (length(sysreqs) == 0) { pkg_loginfo("No system requirements detected to install.") return(invisible()) } params <- safe_get_prj(prj)$load_params() recipe <- build_sysreqs_install_recipe(params$prj_path) recipe <- sysreqs_recipe_collect_all(recipe, sysreqs) perform(recipe) } sysreqs_script <- function(prj = NULL) { sysreqs <- sysreqs_collect(prj) if (length(sysreqs) == 0) { pkg_loginfo("No system requirements detected to install.") return(invisible()) } params <- safe_get_prj(prj)$load_params() recipe <- build_sysreqs_script_recipe(params$prj_path) recipe <- sysreqs_recipe_collect_all(recipe, sysreqs) script <- perform(recipe) pkg_loginfo("Building script created at %s.", script) return(invisible(script)) }
which.column<-function(a,b){ if (!is.matrix(b)){ b=matrix(b,1,2) } id1=is.element(b[,1],a[1]) id2=is.element(b[,2],a[2]) id=which(id1*id2==1) return(id) }
validate_bundleDBI <- function(emuDBhandle, session, bundle){ DBconfig = load_DBconfig(emuDBhandle) dbLevelDefs = list_levelDefinitions(emuDBhandle) levelNames <- DBI::dbGetQuery(emuDBhandle$connection, paste0("SELECT DISTINCT level ", "FROM items ", "WHERE db_uuid = '", emuDBhandle$UUID, "' ", " AND session = '", session, "' ", " AND bundle ='", bundle, "'"))$level levelDefNames = sapply(DBconfig$levelDefinitions, function(l) l$name) delta1 = setdiff(levelNames, levelDefNames) delta2 = setdiff(levelDefNames, levelNames) if(length(delta1) != 0 || length(delta2) != 0){ if(length(delta1) != 0){ return(list(type = 'ERROR', message = paste('Following levels where found that do not ", "match any levelDefinition:', paste(delta1), ';', 'in bundle:', bundle))) }else{ warning("No items for levelDefinition where found for level:'", paste(delta2), "';", "in bundle:'", bundle , "'") } } bundleLevels <- DBI::dbGetQuery(emuDBhandle$connection, paste0("SELECT DISTINCT ", " level AS name, ", " type ", "FROM items ", "WHERE db_uuid = '", emuDBhandle$UUID, "' ", " AND session = '", session, "' ", " AND bundle ='", bundle, "' ")) joinedLevelDefs = bundleLevels %>% dplyr::left_join(dbLevelDefs, by = "name") %>% dplyr::select(.data$name, DBconfigType = .data$type.x, bundleType = .data$type.y) if(!all(joinedLevelDefs$DBconfigType == joinedLevelDefs$bundleType)){ return(list(type = 'ERROR', message = paste0('There are level types that differ from those defined:\n', paste(utils::capture.output(print(joinedLevelDefs)), collapse = "\n")))) } tmp <- DBI::dbGetQuery(emuDBhandle$connection, paste0("SELECT DISTINCT * ", "FROM items ", "WHERE session = '", session,"' ", " AND bundle ='", bundle, "' ", " AND type = 'SEGMENT'")) return(list(type = 'SUCCESS', message = '')) }
drop_na_columns <- function(data) { data %>% select(which(colMeans(is.na(.)) < 1)) %>% suppressMessages() %>% suppressWarnings() } get_class_df <- function(data) { class_data <- data %>% future_map(class) class_df <- seq_along(class_data) %>% future_map_dfr(function(x) { tibble(nameColumn = names(data)[[x]], typeColumn = class_data[[x]] %>% .[length(.)]) }) return(class_df) } tidy_column_formats <- function(data, drop_na_columns = TRUE) { data <- data %>% mutate_if(is_character, funs(ifelse(. == "N/A", NA, .))) %>% mutate_if(is_character, funs(ifelse(. == "", NA, .))) data <- data %>% mutate_at(data %>% select(dplyr::matches("^idCRD")) %>% names(), funs(. %>% as.numeric())) %>% mutate_at(data %>% select( dplyr::matches( "^name[A-Z]|^details[A-Z]|^description[A-Z]|^city[A-Z]|^state[A-Z]|^country[A-Z]|^count[A-Z]|^street[A-Z]|^address[A-Z]" ) ) %>% select(-dplyr::matches("nameElement")) %>% names(), funs(. %>% str_to_upper())) %>% mutate_at( data %>% select(dplyr::matches("^amount")) %>% names(), funs(. %>% as.numeric() %>% formattable::currency(digits = 0)) ) %>% mutate_at(data %>% select(dplyr::matches("^is|^has")) %>% names(), funs(. %>% as.logical())) %>% mutate_at( data %>% select(dplyr::matches("latitude|longitude")) %>% names(), funs(. %>% as.numeric() %>% formattable::digits(digits = 5)) ) %>% mutate_at( data %>% select(dplyr::matches("^price[A-Z]|pershare")) %>% select(-dplyr::matches("priceNotation")) %>% names(), funs(. %>% formattable::currency(digits = 3)) ) %>% mutate_at( data %>% select(dplyr::matches( "^count[A-Z]|^number[A-Z]|^year[A-Z]" )) %>% select(-dplyr::matches("country|county")) %>% names(), funs(. %>% formattable::comma(digits = 0)) ) %>% mutate_at( data %>% select(dplyr::matches( "codeInterestAccrualMethod|codeOriginalInterestRateType|codeLienPositionSecuritization|codePaymentType|codePaymentFrequency|codeServicingAdvanceMethod|codePropertyStatus" )) %>% names(), funs(. %>% as.integer()) ) %>% mutate_at(data %>% select(dplyr::matches("^ratio|^multiple|^priceNotation|^value")) %>% names(), funs(. %>% formattable::comma(digits = 3))) %>% mutate_at(data %>% select(dplyr::matches("^pct|^percent")) %>% names(), funs(. %>% formattable::percent(digits = 3))) %>% mutate_at( data %>% select(dplyr::matches("^amountFact")) %>% names(), funs(. %>% as.numeric() %>% formattable::currency(digits = 3)) ) %>% suppressWarnings() has_dates <- data %>% select(dplyr::matches("^date")) %>% ncol() > 0 if (has_dates) { data %>% select(dplyr::matches("^date")) %>% future_map(class) } if (drop_na_columns ) { data <- data %>% drop_na_columns() } return(data) } tidy_column_relations <- function(data, column_keys = c('idCIK', 'nameEntity'), bind_to_original_df = FALSE, clean_column_formats = TRUE) { class_df <- data %>% get_class_df() df_lists <- class_df %>% filter(typeColumn %in% c('list', 'date.frame')) has_lists <- df_lists %>% nrow() > 0 columns_matching <- names(data)[!names(data) %>% substr(nchar(.), nchar(.)) %>% readr::parse_number() %>% is.na() %>% suppressWarnings()] %>% suppressWarnings() %>% suppressMessages() %>% suppressWarnings() if ('dataAllFilings' %in% names(data)) { data <- data %>% unnest() %>% tidy_column_formats() return(data) } if ('dataAssetXBRL' %in% names(data)) { data <- data %>% unnest() %>% tidy_column_formats() return(data) } if (has_lists == F & columns_matching %>% length() == 0) { return(data) } data <- data %>% mutate(idRow = 1:n()) %>% select(idRow, everything()) df <- tibble() if (columns_matching %>% length() > 0) { match <- columns_matching %>% str_replace_all('[0-9]', '') %>% unique() %>% paste0(collapse = '|') df_match <- data %>% select(idRow, one_of(column_keys), dplyr::matches(match)) has_dates <- names(df_match) %>% str_count("date") %>% sum() > 0 if (has_dates) { df_match <- df_match %>% mutate_at(df_match %>% select(dplyr::matches("^date")) %>% names(), funs(. %>% as.character())) } key_cols <- df_match %>% select(c(idRow, one_of(column_keys))) %>% names() valuecol <- 'value' gathercols <- df_match %>% select(-c(idRow, one_of(column_keys))) %>% names() df_match <- df_match %>% gather_('item', 'value', gathercols, na.rm = T) %>% mutate( countItem = item %>% readr::parse_number(), countItem = ifelse(countItem %>% is.na(), 0, countItem) + 1, item = item %>% str_replace_all('[0-9]', '') ) %>% suppressWarnings() %>% suppressMessages() df <- df %>% bind_rows(df_match) } if (has_lists) { df_list <- 1:nrow(df_lists) %>% future_map_dfr(function(x) { column <- df_lists$nameColumn[x] if (column == 'dataInsiderCompaniesOwned') { is_insider <- TRUE } else { is_insider <- FALSE } df <- data %>% select(idRow, one_of(c(column_keys, column))) col_length_df <- 1:nrow(df) %>% future_map_dfr(function(x) { value <- df[[column]][[x]] if (value %>% purrr::is_null()) { return(tibble(idRow = x)) } columns_matching <- names(value)[!names(value) %>% substr(nchar(.), nchar(.)) %>% readr::parse_number() %>% is.na() %>% suppressWarnings()] %>% suppressWarnings() %>% suppressMessages() %>% suppressWarnings() if (column == "dataAllFilings") { return(tibble(idRow = x, countCols = value %>% ncol())) } if (columns_matching %>% length() == 0) { return(tibble(idRow = x)) } tibble(idRow = x, countCols = value %>% ncol()) }) if (col_length_df %>% ncol() == 1) { return(tibble()) } df <- df %>% left_join(col_length_df) %>% filter(!countCols %>% is.na()) %>% select(-countCols) %>% suppressWarnings() %>% suppressMessages() df <- df %>% unnest() has_dates <- names(df) %>% str_count("date") %>% sum() > 0 if (has_dates) { df <- df %>% mutate_at(df %>% select(dplyr::matches("^date")) %>% names(), funs(. %>% as.character())) } gathercols <- df %>% select(-c(idRow, one_of(column_keys))) %>% names() df <- df %>% gather_('item', 'value', gathercols, na.rm = T) %>% mutate( countItem = item %>% readr::parse_number(), countItem = ifelse(countItem %>% is.na(), 0, countItem) + 1, item = item %>% str_replace_all('[0-9]', ''), value = value %>% as.character() ) %>% suppressWarnings() %>% suppressMessages() if (is_insider) { df <- df %>% mutate(item = item %>% paste0('Insider')) } return(df) }) %>% arrange(idRow) %>% distinct() df <- df %>% bind_rows(df_list) } has_data <- df %>% nrow() > 0 if (!has_data) { return(data %>% select(-dplyr::matches("idRow"))) } if (has_data) { df <- df %>% arrange(idRow) %>% distinct() col_order <- c(df %>% select(-c(item, value)) %>% names(), df$item) df <- df %>% spread(item, value) %>% select(one_of(col_order)) %>% suppressWarnings() has_dates <- data %>% select(dplyr::matches("^date")) %>% ncol() > 0 if (has_dates) { df <- df %>% mutate_at(df %>% select(dplyr::matches("^date[A-Z]")) %>% names(), funs(. %>% lubridate::ymd())) %>% mutate_at(df %>% select(dplyr::matches("^datetime[A-Z]")) %>% names(), funs(. %>% lubridate::ymd_hm())) } if (clean_column_formats) { df <- df %>% tidy_column_formats() } if ('nameFormType' %in% names(df)) { df <- df %>% filter(!nameFormType %>% is.na()) } if (bind_to_original_df) { if (has_lists) { if (columns_matching %>% length() > 0) { ignore_cols <- c(columns_matching, df_lists$nameColumn) %>% paste0(collapse = '|') } else { ignore_cols <- c(df_lists$nameColumn) %>% paste0(collapse = '|') } } if (!has_lists) { ignore_cols <- columns_matching %>% paste0(collapse = '|') } data <- data %>% select(-dplyr::matches(ignore_cols)) %>% left_join(df %>% nest(-idRow, .key = dataResolved)) %>% suppressMessages() return(data) } if (!bind_to_original_df) { return(df) } } }
asymcp<-function(d,p_1,i,z_i){ if(!(methods::is(d,"asymdesign")|methods::is(d,"asymprob"))) stop("asymcp must be called with class of either asymdesign or asymprob.") p_0=d$p_0 i=round(i) if((min(p_1)<=p_0)|(max(p_1)>=1)) stop('Please input p_1 that lies between p_0 and 1 (not including p_0 and 1).') if((i>=K)|(i<1)) stop('i is less than 1 or more than K-1.') if(abs(z_i)>=100) stop('invalid interim statistic: too large or too small.') K=d$K-i n.I=(d$n.I)[i:(i+K)] lowerbounds=(d$lowerbounds)[(i+1):(i+K)] cp=matrix(0,1+length(p_1),1) infor=n.I/p_0/(1-p_0) lowerbounds1=lowerbounds*sqrt(infor[-1])-z_i*sqrt(infor[1]) sigma=matrix(0,K,K) for(j1 in 1:K){ for(j2 in 1:K){ sigma[j1,j2]=infor[(min(j1,j2)+1)] } } sigma=sigma-infor[1] cp[1,]=mvtnorm::pmvnorm(lower=lowerbounds1,upper=rep(Inf,K),mean=rep(0,K),sigma=sigma)[1] for(s in 1:length(p_1)){ p1=p_1[s] infor=n.I/p1/(1-p1) lowerbounds1=lowerbounds*sqrt(infor[-1])-z_i*sqrt(infor[1]) sigma=matrix(0,K,K) for(j1 in 1:K){ for(j2 in 1:K){ sigma[j1,j2]=infor[(min(j1,j2)+1)] } } sigma=sigma-infor[1] mean1=(p1-p_0)*(infor[-1]-infor[1]) cp[(s+1),]=mvtnorm::pmvnorm(lower=lowerbounds1,upper=rep(Inf,K),mean=mean1,sigma=sigma)[1] } cp=cbind(c(p_0,p_1),cp) colnames(cp)=c('p','cp') return(list(K=d$K,n.I=d$n.I,u_K=d$u_K,lowerbounds=d$lowerbounds,i=i,z_i=z_i,cp=cp,p_1=p_1,p_0=p_0)) }
panel.cor <- function(x, y, digits = 2, cex.cor) { usr <- par("usr"); on.exit(par(usr)) par(usr = c(0, 1, 0, 1)) r <- cor(x, y,use="na.or.complete") txt <- format(c(r, 0.123456789), digits = digits)[1] if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt) text(0.5, 0.5, txt, cex = cex.cor * abs(r)) }
test_that("mutation models are validated", { alleles = 1:3 afr = c(.2,.3,.5) rate = 0.1 M = mutationModel("prop", alleles=alleles, afreq=afr, rate=rate) expect_silent(validateMutationModel(M)) }) test_that("male and female models are equal by default", { alleles = 1:3 afr = c(.2,.3,.5) rate = 0.1 m = mutationMatrix("prop", alleles=alleles, afreq=afr, rate=rate) M = mutationModel("prop", alleles=alleles, afreq=afr, rate=rate) expect_identical(M$female, m) expect_identical(M$male, m) }) test_that("stepwise mutation model splits correctly in male/female", { alleles = c(1, 1.5, 2,3) M = mutationModel("step", alleles = alleles, rate = list(male=0, female=0.1), rate2 = list(male=0.2, female=0), range = list(male=2, female=3)) matM = mutationMatrix("step", alleles = alleles, rate = 0, rate2 = 0.2, range = 2) matF = mutationMatrix("step", alleles = alleles, rate = 0.1, rate2 = 0, range = 3) expect_identical(M, mutationModel(list(male=matM, female=matF))) })
proposePoints = function(opt.state) { opt.problem = getOptStateOptProblem(opt.state) control = getOptProblemControl(opt.problem) if (control$n.objectives == 1L) { if (is.null(control$multipoint.method)) { res = proposePointsByInfillOptimization(opt.state) } else { res = switch(control$multipoint.method, "cb" = proposePointsParallelCB(opt.state), "cl" = proposePointsConstantLiar(opt.state), "moimbo" = proposePointsMOIMBO(opt.state) ) } } else { res = switch(control$multiobj.method, "parego" = proposePointsParEGO(opt.state), "mspot" = proposePointsMSPOT(opt.state), "dib" = proposePointsDIB(opt.state) ) } if (control$interleave.random.points > 0L) res = joinProposedPoints(list(res, proposePointsRandom(opt.state))) if (!is.matrix(res$crit.vals)) res$crit.vals = matrix(res$crit.vals, ncol = 1L) if (control$filter.proposed.points) res = filterProposedPoints(res, opt.state) res }
r.med.sub <- function(x.sub, x, weight.sub, weight, k){ n <- length(x) if(is.null(weight)){ weight <- rep(1, n) weight.sub <- rep(1, length(x.sub)) } rhow <- k*weighted.median(x, weight) gap <- sum(sapply(1:length(x.sub), function(i){ max(x.sub[i] - rhow, 0)*weight.sub[i]}))/sum(weight.sub) return(gap) }
InferenceA <- function(listA,niter,burnin){ Amean=matrix(0,nrow=4,ncol=4) for(i in burnin:niter){ temp=listA[[i]] Amean=Amean+temp } Amean=Amean/(niter-burnin) return(Amean) }
.charpolynom.matrix <- function(x) { if (ncol(x) != nrow(x)) { stop("Square matrix is expected") } if (ncol(x) == 1) { return(x[1, 1] + polynom::polynomial(c(0, -1))) } s <- nrow(x) d <- polyMatrix(cbind(matrix(0, s, s), diag(-1, s, s)), s, s, 1) return(det(x + d)) } .char.inc.degree <- function (cp) { return(cbind(0, cp)) } .char.add <- function(f, s) { if (ncol(f) > ncol(s)) { return(.char.add(s, f)) } s[,seq_len(ncol(f))] <- s[,seq_len(ncol(f))] + f return(s) } .char.step <- function (x, l) { if(is.matrix(l) && nrow(l) == 1) { l <- l[1, 1] } if(!is.matrix(l)) { x <- polyMatrix(x, 1, 1) if (l == 0) { return(x) } else { xx <- polyMatrix(matrix(c(0, -1), 1, 2), 1, 2) return(.char.add(x, xx)) } } stopifnot(nrow(x) == ncol(x) && nrow(l) == ncol(l) && nrow(x) == nrow(l)) stopifnot(nrow(x) != 1) res <- polyMatrix(0, 1, 1) for(c in seq_len(ncol(x))) { xx <- x[-1, -c] ll <- l[-1, -c] rr <- .char.step(xx, ll) if (c %% 2 == 0 ) { rr <- -rr } res <- .char.add(res, rr * x[1, c]) if (l[1, c] == 1) { res <- .char.add(res, -.char.inc.degree(rr)) } } return(res) } .charpolynom.polyMatrix <- function (x) { if (ncol(x) != nrow(x)) { stop("Square matrix is expected") } return(polyMatrixCharClass(coef=.char.step(x, diag(1, nrow(x), ncol(x))))) } setGeneric("charpolynom", function(x) { stop("Matrix object is expected") }) setMethod("charpolynom", signature(x="matrix"), .charpolynom.matrix) setMethod("charpolynom", signature(x=P), function (x) { return(charpolynom(polyMatrix(x))) }) setMethod("charpolynom", signature(x=PM), .charpolynom.polyMatrix)
context("sprinkle_round") x <- dust(head(mtcars)) test_that( "Correctly reassigns the appropriate elements of round columns in the table part", { expect_equal( sprinkle_round(x, cols = 2, round = 3)[["body"]][["round"]], rep(c("", 3, ""), times = c(6, 6, 6*9)) ) } ) test_that( "Succeeds when called on a dust_list object", { expect_silent( dplyr::group_by(mtcars, am, vs) %>% dust(ungroup = FALSE) %>% sprinkle_round(round = 2) ) } ) test_that( "Cast an error if x is not a dust object", { expect_error(sprinkle_round(mtcars)) } ) test_that( "Cast an error if round is not a numeric(1)", { expect_error(sprinkle_round(x, round = "3")) } ) test_that( "Cast an error if round is not a numeric(1)", { expect_error(sprinkle_round(x, round = c(2, 3))) } ) test_that( "Casts an error if part is not one of body, head, foot, or interfoot", { expect_error( sprinkle_round(x, round = 20, part = "not a part") ) } ) test_that( "Casts an error if fixed is not logical(1)", { expect_error(sprinkle_round(x, round = 20, fixed = "FALSE")) } ) test_that( "Casts an error if fixed is not logical(1)", { expect_error(sprinkle_round(x, round = 20, fixed = c(TRUE, FALSE))) } ) test_that( "Casts an error if recycle is not one of none, rows, or cols", { expect_error(sprinkle_round(x, recycle = "not an option")) } ) test_that( "Casts an error if recycle = 'none' and round does not have length 1.", { expect_error(sprinkle_round(x, round = 1:2, recycle = "none")) } ) test_that( "Passes when recycle != 'none' and round does has length > 1.", { expect_silent(sprinkle_round(x, round = 1:3, recycle = "rows")) } )
lpc.control <- function (iter =100, cross=TRUE, boundary = 0.005, convergence.at =0.00001, mult=NULL, ms.h=NULL, ms.sub=30, pruning.thresh=0.0, rho0=0.4) { if (boundary!=0 && boundary < convergence.at) { warning("The boundary correction will not have any effect if its threshold is set to a smaller value than the convergence criterion.") } if (iter <= 9) { warning("Please choose iter=10 at least. The default value iter=100 has been used instead.") iter <- 100 } if (pruning.thresh<0) { warning("This should be a non-negative number. The default 0 has been used instead.") pruning.thresh<-0 } if (rho0<0) { warning("This should be a non-negative number. The default 0.4 has been used instead.") rho0<-0.4 } if (!is.logical(cross)){ warning("cross needs to be a Boolean. The default FALSE has been used instead.") } if (!is.null(mult)){ if (mult<1){ mult <-1 warning("mult needs to be a positive integer. The value mult=1 has been used instead.") } cat("Number of starting points manually enforced to be", mult, ".", "\n") } if ((ms.sub<0) || (ms.sub >100)){ ms.sub<- 30 warning("ms.sub needs to be a percentage between 0 and 100. The default choice 30 has been used instead.") } list(iter = iter, cross=cross, boundary = boundary, convergence.at = convergence.at, mult=mult, ms.h=ms.h, ms.sub=ms.sub, pruning.thresh=pruning.thresh, rho0=rho0) }
EBImoran <- function (z, listw, nn, S0, zero.policy = NULL, subtract_mean_in_numerator=TRUE) { if (is.null(zero.policy)) zero.policy <- get("zeroPolicy", envir = .spdepOptions) stopifnot(is.logical(zero.policy)) stopifnot(is.vector(z)) zm <- mean(z) zz <- sum((z - zm)^2) if (subtract_mean_in_numerator) z <- z - zm lz <- lag.listw(listw, z, zero.policy = zero.policy) EBI <- (nn/S0) * (sum(z * lz)/zz) res <- EBI res } EBImoran.mc <- function (n, x, listw, nsim, zero.policy = NULL, alternative = "greater", spChk = NULL, return_boot=FALSE, subtract_mean_in_numerator=TRUE) { message("The default for subtract_mean_in_numerator set TRUE from February 2016") if (is.null(zero.policy)) zero.policy <- get("zeroPolicy", envir = .spdepOptions) stopifnot(is.logical(zero.policy)) alternative <- match.arg(alternative, c("greater", "less")) if (!inherits(listw, "listw")) stop(paste(deparse(substitute(listw)), "is not a listw object")) if (missing(nsim)) stop("nsim must be given") m <- length(listw$neighbours) if (m != length(x)) stop("objects of different length") if (m != length(n)) stop("objects of different length") if (is.null(spChk)) spChk <- get.spChkOption() if (spChk && !chkIDs(x, listw)) stop("Check of data and weights ID integrity failed") if (spChk && !chkIDs(n, listw)) stop("Check of data and weights ID integrity failed") gamres <- suppressWarnings(nsim > gamma(m + 1)) if (gamres) stop("nsim too large for this number of observations") if (nsim < 1) stop ("nsim too small") S0 <- Szero(listw) EB <- EBest(n, x) p <- EB$raw b <- attr(EB, "parameters")$b a <- attr(EB, "parameters")$a v <- a + (b/x) v[v < 0] <- b/x z <- (p - b)/sqrt(v) if (return_boot) { EBI_boot <- function(var, i, ...) { var <- var[i] return(EBImoran(z=var, ...)) } cores <- get.coresOption() if (is.null(cores)) { parallel <- "no" } else { parallel <- ifelse (get.mcOption(), "multicore", "snow") } ncpus <- ifelse(is.null(cores), 1L, cores) cl <- NULL if (parallel == "snow") { cl <- get.ClusterOption() if (is.null(cl)) { parallel <- "no" warning("no cluster in ClusterOption, parallel set to no") } } res <- boot(z, statistic=EBI_boot, R=nsim, sim="permutation", listw=listw, nn=m, S0=S0, zero.policy=zero.policy, subtract_mean_in_numerator=subtract_mean_in_numerator, parallel=parallel, ncpus=ncpus, cl=cl) return(res) } res <- numeric(length = nsim + 1) for (i in 1:nsim) res[i] <- EBImoran(sample(z), listw, m, S0, zero.policy, subtract_mean_in_numerator=subtract_mean_in_numerator) res[nsim + 1] <- EBImoran(z, listw, m, S0, zero.policy, subtract_mean_in_numerator=subtract_mean_in_numerator) rankres <- rank(res) zrank <- rankres[length(res)] diff <- nsim - zrank diff <- ifelse(diff > 0, diff, 0) if (alternative == "less") pval <- punif((diff + 1)/(nsim + 1), lower.tail=FALSE) else if (alternative == "greater") pval <- punif((diff + 1)/(nsim + 1)) if (!is.finite(pval) || pval < 0 || pval > 1) warning("Out-of-range p-value: reconsider test arguments") statistic <- res[nsim + 1] names(statistic) <- "statistic" parameter <- zrank names(parameter) <- "observed rank" method <- "Monte-Carlo simulation of Empirical Bayes Index" if (subtract_mean_in_numerator) method <- paste(method, "(mean subtracted)") data.name <- paste("cases: ", deparse(substitute(n)), ", risk population: ", deparse(substitute(x)), "\nweights: ", deparse(substitute(listw)), "\nnumber of simulations + 1: ", nsim + 1, "\n", sep = "") lres <- list(statistic = statistic, parameter = parameter, p.value = pval, alternative = alternative, method = method, data.name = data.name, res = res, z = z) class(lres) <- c("htest", "mc.sim") lres } probmap <- function(n, x, row.names=NULL, alternative="less") { alternative <- match.arg(alternative, c("greater", "less")) if (!is.numeric(x)) stop(paste(deparse(substitute(x)), "is not a numeric vector")) if (!is.numeric(n)) stop(paste(deparse(substitute(n)), "is not a numeric vector")) if (any(is.na(x))) stop("NA in at risk population") if (any(is.na(n))) stop("NA in cases") if (any(x < 0)) stop("negative risk population") if (any(n < 0)) stop("negative number of cases") p <- n/x nsum <- sum(n) xsum <- sum(x) b <- nsum/xsum expCount <- x*b relRisk <- 100*(n/expCount) if (alternative == "less") { pmap <- ppois(n, expCount) } else { pmap <- 1 - ppois(n-1, expCount) } if (is.null(row.names)) res <- data.frame(raw=p, expCount=expCount, relRisk=relRisk, pmap=pmap) else res <- data.frame(raw=p, expCount=expCount, relRisk=relRisk, pmap=pmap, row.names=row.names) res } EBest <- function(n, x, family="poisson") { if (!is.numeric(x)) stop(paste(deparse(substitute(x)), "is not a numeric vector")) if (!is.numeric(n)) stop(paste(deparse(substitute(n)), "is not a numeric vector")) if (any(is.na(x))) stop("NA in at risk population") if (any(is.na(n))) stop("NA in cases") if (any(x < .Machine$double.eps)) stop("non-positive risk population") if (any(n < 0)) stop("negative number of cases") if (length(x) != length(n)) stop("vectors of different length") m <- length(n) p <- n/x nsum <- sum(n) xsum <- sum(x) b <- nsum/xsum s2 <- sum(x * (((p - b)^2)/xsum)) if (family == "poisson") { a <- s2 - (b/(xsum/m)) if (a < 0) a <- 0 est <- b + (a*(p - b)) / (a + (b/x)) res <- data.frame(raw=p, estmm=est) attr(res, "family") <- family attr(res, "parameters") <- list(a=a, b=b) } else if (family == "binomial") { rho <- (x*s2 - (x/mean(x))*(b*(1-b))) / ((x-1)*s2 + ((mean(x)-x) /mean(x))*(b*(1-b))) est <- rho*p + (1-rho)*b res <- data.frame(raw = p, estmm = est) attr(res, "family") <- family attr(res, "parameters") <- list(a=s2, b=b) } else stop("family unknown") res } EBlocal <- function(ri, ni, nb, zero.policy = NULL, spChk = NULL, geoda = FALSE) { if (is.null(zero.policy)) zero.policy <- get("zeroPolicy", envir = .spdepOptions) stopifnot(is.logical(zero.policy)) if (!inherits(nb, "nb")) stop(paste(deparse(substitute(nb)), "is not an nb object")) lnb <- length(nb) if (lnb < 1) stop("zero length neighbour list") if (lnb != length(ri)) stop("objects of different length") if (lnb != length(ni)) stop("objects of different length") if (is.null(spChk)) spChk <- get.spChkOption() if (spChk && !chkIDs(ni, nb)) stop("Check of data and neighbour ID integrity failed") if (spChk && !chkIDs(ri, nb)) stop("Check of data and neighbour ID integrity failed") if (!is.numeric(ni)) stop(paste(deparse(substitute(ni)), "is not a numeric vector")) if (!is.numeric(ri)) stop(paste(deparse(substitute(ri)), "is not a numeric vector")) if (any(is.na(ni))) stop("NA in at risk population") if (any(ni == 0)) stop("zero in at risk population") if (any(is.na(ri))) stop("NA in cases") if (any(ni < 0)) stop("negative risk population") if (any(ri < 0)) stop("negative number of cases") lw <- nb2listw(include.self(nb), style="B", zero.policy=zero.policy) xi <- ri/ni r.i <- lag.listw(lw, ri, zero.policy = zero.policy) n.i <- lag.listw(lw, ni, zero.policy = zero.policy) nbar.i <- lag.listw(nb2listw(include.self(nb), style="W", zero.policy=zero.policy), ni, zero.policy = zero.policy) m.i <- r.i/n.i if (geoda) { work <- vector(mode="list", length=lnb) cnb <- card(lw$neighbours) for (i in 1:lnb) { work[[i]] <- rep(m.i[i], cnb[i]) work[[i]] <- xi[lw$neighbours[[i]]] - work[[i]] work[[i]] <- work[[i]]^2 work[[i]] <- ni[lw$neighbours[[i]]] * work[[i]] } C.i <- sapply(work, sum) } else { C.i <- lag.listw(lw, (ni * (xi - m.i)^2), zero.policy = zero.policy) } a.i <- (C.i/n.i) - (m.i/nbar.i) a.i[a.i < 0] <- 0 est <- m.i + (xi - m.i) * (a.i / (a.i + (m.i/ni))) res <- data.frame(raw=xi, est=est) attr(res, "parameters") <- list(a=a.i, m=m.i) res }
test_that("Validate GetElements using legacy credentials", { skip_on_cran() SCAuth(Sys.getenv("USER", ""), Sys.getenv("SECRET", "")) elem <- GetElements("zwitchdev", report.type='warehouse') expect_is(elem, "data.frame") })
library(testthat) `%is%` <- expect_equal `%throws%` <- expect_error context("caller examples") test_that("Example 1", { where <- "0" x <- y <- z <- NULL e <- function() { where <- "e" x <<- environment() f <- function() { where <- "f" y <<- environment() g <- function() { where <- "g" z <<- environment() caller()$where %is% "f" } g() } f() } e() }) test_that("foo", { where <- "0" x <- y <- z <- NULL e <- function() { where <- "e" x <<- environment() f <- function() { where <- "f" y <<- environment() g <- function() { where <- "g" z <<- environment() } g() } f() } e() h <- function() { eval(quote(caller()), y)$where %throws% "e" } h() }) test_that("caller from a lazy argument in a closed environment", { where <- "0" e <- function() { where <- "e" f <- function() { where <- "f" g <- function(g) { where <- "g" function(f) g } g(caller()) } f() } e()()$where %throws% "e" })
make.tree.musse <- function(pars, max.taxa=Inf, max.t=Inf, x0, single.lineage=TRUE) { k <- (sqrt(1 + 4*length(pars))-1)/2 if ( !isTRUE(all.equal(k, as.integer(k))) ) stop("Invalid parameter length: must be k(k+1) long") check.pars.musse(pars, k) if ( x0 < 1 || x0 > k ) stop("x0 must be an integer in [1,k]") pars <- cbind(matrix(pars[seq_len(2*k)], k, 2), matrix(pars[(2*k+1):(k*(k+1))], k, k-1, TRUE)) to <- matrix(unlist(lapply(1:k, function(i) (1:k)[-i])), k, k-1, TRUE) r.i <- rowSums(pars) extinct <- FALSE split <- FALSE parent <- 0 n.i <- rep(0, k) len <- 0 t <- 0 hist <- list() if ( single.lineage ) { states <- x0 n.taxa <- lineages <- n.i[x0] <- 1 start <- 0 } else { stop("Nope.") } while ( n.taxa <= max.taxa && n.taxa > 0 ) { r.n <- r.i * n.i r.tot <- sum(r.n) dt <- rexp(1, r.tot) t <- t + dt if ( t > max.t ) { dt <- dt - (t - max.t) len[lineages] <- len[lineages] + dt t <- max.t break } len[lineages] <- len[lineages] + dt state <- sample(k, 1, FALSE, r.n/r.tot) j <- sample(n.i[state], 1) lineage <- lineages[states[lineages] == state][j] type <- sample(k+1, 1, FALSE, pars[state,]) if ( type == 1 ) { if ( n.taxa == max.taxa ) break new.i <- length(extinct) + 1:2 split[lineage] <- TRUE extinct[new.i] <- split[new.i] <- FALSE states[new.i] <- state parent[new.i] <- lineage start[new.i] <- t len[new.i] <- 0 n.i[state] <- n.i[state] + 1 n.taxa <- n.taxa + 1 lineages <- which(!split & !extinct) } else if ( type == 2 ) { extinct[lineage] <- TRUE lineages <- which(!split & !extinct) n.i[state] <- n.i[state] - 1 n.taxa <- n.taxa - 1 } else { states[lineage] <- state.new <- to[state,type - 2] n.i[c(state.new, state)] <- n.i[c(state.new, state)] + c(1,-1) hist[[length(hist)+1]] <- c(lineage, t, state, state.new) } } info <- data.frame(idx=seq_along(extinct), len=len, parent=parent, start=start, state=states, extinct=extinct, split=split) hist <- as.data.frame(do.call(rbind, hist)) if ( nrow(hist) == 0 ) hist <- as.data.frame(matrix(NA, 0, 4)) names(hist) <- c("idx", "t", "from", "to") hist$x0 <- info$start[match(hist$idx, info$idx)] hist$tc <- hist$t - hist$x0 attr(info, "t") <- t attr(info, "hist") <- hist info } tree.musse <- function(pars, max.taxa=Inf, max.t=Inf, include.extinct=FALSE, x0=NA) { k <- (sqrt(1 + 4*length(pars))-1)/2 if ( !isTRUE(all.equal(k, as.integer(k))) ) stop("Invalid parameter length: must be k(k+1) long") if ( length(x0) != 1 || is.na(x0) || x0 < 1 || x0 > k ) stop("Invalid root state") info <- make.tree.musse(pars, max.taxa, max.t, x0) phy <- me.to.ape.bisse(info[-1,], info$state[1]) if ( include.extinct || is.null(phy) ) phy else prune(phy) } tree.musse.multitrait <- function(pars, n.trait, depth, max.taxa=Inf, max.t=Inf, include.extinct=FALSE, x0=NA) { tr <- musse.multitrait.translate(n.trait, depth) np <- ncol(tr) if ( !(all(is.finite(x0)) && length(x0) == n.trait) ) stop(sprintf("x0 must be a vector of length %d"), n.trait) if ( !all(x0 %in% c(0, 1)) ) stop("All x0 must be in [0,1]") if ( length(pars) != ncol(tr) ) stop(sprintf("Expected %d parameters:\n\t%s", ncol(tr), paste(colnames(tr), collapse=", "))) pars2 <- drop(tr %*% pars) code <- paste(x0, collapse="") types <- do.call(expand.grid, rep(list(0:1), n.trait)) key <- apply(types, 1, paste, collapse="") x02 <- match(code, key) tree <- tree.musse(pars2, max.taxa, max.t, include.extinct, x02) tree$tip.state <- types[tree$tip.state,,drop=FALSE] rownames(tree$tip.state) <- tree$tip.label colnames(tree$tip.state) <- LETTERS[seq_len(n.trait)] tree }
two.stage.model.outputs<-function (B1,catchability,obs,g) { ai<-data.frame(c(obs$year), c(rep(0,length(obs$year))),c(rep(0,length(obs$year))),c(rep(0,length(obs$year))),c(rep(0,length(obs$year)))) colnames(ai)<-c("year","bts","cgfs","uk","fr") for (i in 1:length(obs[,1])) { ai$bts[i]<-exp(catchability[1])*B1[i] ai$cgfs[i]<-exp(catchability[2])*B1[i]*exp(-g/4) ai$uk[i]<-0.5*exp(catchability[3])*(B1[i]*exp(-g/4)+(B1[i]*exp(-g/2)-obs$L.Q341[i])*exp(-g/4)) ai$fr[i]<-0.5*exp(catchability[4])*(B1[i] + (B1[i]*exp(-g/2) - obs$L.Q3412[i])*exp(-g/2)) } sigma.bts<-sqrt(mean(log(obs$bts/ai$bts)^2)) sigma.cgfs<-sqrt(mean(log(obs$cgfs/ai$cgfs)^2)) sigma.lpue.uk<-sqrt(mean(log(obs$lpue.uk/ai$uk)^2)) sigma.lpue.fr<-sqrt(mean(log(obs$lpue.fr/ai$fr)^2)) residus.mlh<-data.frame( c(obs$year[1]:obs$year[length(obs$year)]), (length(obs$bts)*log(sigma.bts)+1/(2*sigma.bts^2)*sum(log(obs$bts/ai$bts)^2)), (length(obs$cgfs)*log(sigma.cgfs)+1/(2*sigma.cgfs^2)*sum(log(obs$cgfs/ai$cgfs)^2)), (length(obs$lpue.uk)*log(sigma.lpue.uk)+1/(2*sigma.lpue.uk^2)*sum(log(obs$lpue.uk/ai$uk)^2)), (length(obs$lpue.fr)*log(sigma.lpue.fr)+1/(2*sigma.lpue.fr^2)*sum(log(obs$lpue.fr/ai$fr)^2)) ) colnames(residus.mlh)<-c("year","res.bts","res.cgfs","lpue.uk","lpue.fr") residus.ssr<-data.frame( c(obs$year[1]:obs$year[length(obs$year)]), (log(obs$bts/ai$bts))^2, (log(obs$cgfs/ai$cgfs))^2, (log(obs$lpue.uk/ai$uk))^2, (log(obs$lpue.fr/ai$fr))^2 ) colnames(residus.ssr)<-c("year","res.bts","res.cgfs","lpue.uk","lpue.fr") residus.raw<-data.frame( c(obs$year[1]:obs$year[length(obs$year)]), (obs$bts-ai$bts), (obs$cgfs-ai$cgfs), (obs$lpue.uk-ai$uk), (obs$lpue.fr-ai$fr) ) colnames(residus.raw)<-c("year","bts","cgfs","uk","fr") residuals.st<-data.frame( c(obs$year[1]:obs$year[length(obs$year)]), (residus.raw$bts-mean(residus.raw$bts))/sd(residus.raw$bts), (residus.raw$cgfs-mean(residus.raw$cgfs))/sd(residus.raw$cgfs), (residus.raw$uk-mean(residus.raw$uk))/sd(residus.raw$uk), (residus.raw$fr-mean(residus.raw$fr))/sd(residus.raw$fr)) colnames(residuals.st)<-c("year","bts","cgfs","lpue.uk","lpue.fr") sum.residus<-sum(residus.ssr[,2:5]) biomass<-data.frame( c(obs$year[1]:obs$year[length(obs$year)]), B1, B1*exp(-g/2), obs$L.Q3412, (obs$L.Q3412)/(B1*exp(-g/2)), (B1*exp(-g/2)-obs$L.Q3412)*exp(-g/2) ) colnames(biomass)<-c("year","B1","B.jan","landings","exp.rate","B2") resultat<-list( obs, sum.residus, residus.ssr, residus.mlh, residus.raw, residuals.st, ai, biomass ) names(resultat)<-c("observed", "sum.residuals", "residuals.ssr", "residuals.mlh", "residuals.raw", "residuals.st", "predicted.ai", "biomass") return(resultat) } two.stage.model.fit<-function(to.fit, obs.fit, g.fit) { resultat.fit<-two.stage.model.outputs(B1=to.fit[1:length(obs.fit$year)], catchability=to.fit[(length(obs.fit$year)+1):(length(obs.fit$year)+4)] ,obs=obs.fit, g=g.fit) return(resultat.fit$sum.residuals) } delta.glm<-function(input.data) { input.data$year<-as.factor(input.data$year) input.data$fishing.season<-as.factor(input.data$fishing.season) input.data$rectangle<-as.factor(input.data$rectangle) input.data$power.class<-as.factor(input.data$power.class) input.data$factor.month<-"00" input.data[input.data$month==1,]$factor.month<-"01" input.data[input.data$month==2,]$factor.month<-"02" input.data[input.data$month==3,]$factor.month<-"03" input.data[input.data$month==4,]$factor.month<-"04" input.data[input.data$month==5,]$factor.month<-"05" input.data[input.data$month==6,]$factor.month<-"06" input.data[input.data$month==7,]$factor.month<-"07" input.data[input.data$month==8,]$factor.month<-"08" input.data[input.data$month==9,]$factor.month<-"09" input.data[input.data$month==10,]$factor.month<-"10" input.data[input.data$month==11,]$factor.month<-"11" input.data[input.data$month==12,]$factor.month<-"12" input.data<-data.frame(input.data$year, input.data$fishing.season, input.data$factor.month, input.data$rectangle, input.data$power.class, input.data$lpue) colnames(input.data)<-c("year", "fishing.season", "month", "rectangle", "power.class", "lpue") input.data$presence<-1 input.data[input.data$lpue==0,]$presence<-0 binomial.glm<-glm(presence ~ fishing.season + month + rectangle + power.class, family="binomial", data=input.data) binomial.summary<-summary(binomial.glm) binomial.residuals<-residuals(binomial.glm) binomial.fit<-fitted(binomial.glm) positive.input.data<-input.data[input.data$lpue>0,] gaussian.glm<-glm(log(lpue) ~ fishing.season + month + rectangle + power.class, family="gaussian", data=positive.input.data) gaussian.summary<-summary(gaussian.glm) gaussian.residuals<-residuals(gaussian.glm) gaussian.fit<-fitted(gaussian.glm) positive.input.data<-input.data[input.data$lpue>0,] positive.input.data$year<-as.factor(as.character(positive.input.data$year)) positive.input.data$fishing.season<-as.factor(as.character(positive.input.data$fishing.season)) positive.input.data$month<-as.factor(as.character(positive.input.data$month)) positive.input.data$rectangle<-as.factor(as.character(positive.input.data$rectangle)) positive.input.data$power.class<-as.factor(as.character(positive.input.data$power.class)) l.fishing.season<-length(levels(as.factor(positive.input.data$fishing.season))) l.month<-length(levels(as.factor(positive.input.data$month))) l.rectangle<-length(levels(as.factor(positive.input.data$rectangle))) l.power.class<-length(levels(as.factor(positive.input.data$power.class))) l.total<-l.fishing.season*l.month*l.rectangle*l.power.class predicted.lpue <- matrix(NA,nrow=l.total,ncol=4) predicted.lpue[,4] <- rep(levels(positive.input.data$power.class),(l.total/l.power.class)) for(k in 1:l.fishing.season){ for(j in 1:l.rectangle){ for(m in 1:l.month){ start.fishing.season <- k*l.rectangle*l.month*l.power.class - l.rectangle*l.month*l.power.class end.fishing.season <- k*l.rectangle*l.month*l.power.class start.rectangle <- start.fishing.season + j*l.month*l.power.class - l.month*l.power.class end.rectangle <- start.fishing.season + j*l.month*l.power.class start.month <- start.rectangle + m*l.power.class - l.power.class+1 end.month <- start.rectangle + m*l.power.class predicted.lpue[start.month:end.month,3] <- rep(levels(positive.input.data$month)[m], l.power.class) } predicted.lpue[(start.rectangle+1):end.rectangle,2] <- rep(levels(positive.input.data$rectangle)[j], l.month*l.power.class) } predicted.lpue[(start.fishing.season+1):end.fishing.season,1] <- rep(levels(positive.input.data$fishing.season)[k], l.rectangle * l.month* l.power.class) } predicted.lpue<-as.data.frame(predicted.lpue) colnames(predicted.lpue)<-c("fishing.season", "rectangle", "month", "power.class") binomial.glm.prediction <- predict.glm(binomial.glm, predicted.lpue[,1:4], type="r", se.fit=T) gaussian.glm.prediction <- predict.glm(gaussian.glm, predicted.lpue[,1:4], type="r", se.fit=T) binomial.glm.prediction.fit<-binomial.glm.prediction$fit gaussian.glm.prediction.fit<-gaussian.glm.prediction$fit gaussian.glm.prediction.var<-(gaussian.glm.prediction$se.fit)^2 gaussian.prediction<-exp(gaussian.glm.prediction.fit+gaussian.glm.prediction.var/2) predicted.lpue$st.lpue<-binomial.glm.prediction.fit*gaussian.prediction delta.outputs<-list( binomial.glm, binomial.summary, binomial.residuals, binomial.fit, gaussian.glm, gaussian.summary, gaussian.residuals, gaussian.fit, predicted.lpue ) names(delta.outputs)<-c("binomial.glm", "binomial.summary", "binomial.residuals", "binomial.fit", "gaussian.glm", "gaussian.summary", "gaussian.residuals", "gaussian.fit", "predicted.lpue" ) return(delta.outputs) }
prey.cluster <- function(prey.fa, method="complete", dist.meas=2) { mult.rep <- function(x.vec) { no.zero <- sum(x.vec == 0) x.vec[x.vec == 0] <- 1e-05 x.vec[x.vec > 0] <- (1 - no.zero * 1e-05) * x.vec[x.vec > 0] return(x.vec) } prey.fa[,-1] <- prey.fa[,-1]/apply(prey.fa[,-1],1,sum) sort.preytype <- order(prey.fa[,1]) prey.fa <- prey.fa[sort.preytype,] prey.fa[,-1] <- t(apply(prey.fa[,-1],1,mult.rep)) prey.means <- MEANmeth(prey.fa) I <- nrow(prey.means) dist.mat <- matrix(rep(NA,I*I),nrow=I) if (dist.meas==1) { my.ylab <- "KL Distance" for (i in 2:I) { for (j in 1:(i-1)) { dist.mat[i,j] <- KL.dist(as.vector(prey.means[i,]),as.vector(prey.means[j,])) } } } else if (dist.meas==2) { my.ylab <- "Aitchison Distance" for (i in 2:I) { for (j in 1:(i-1)) { dist.mat[i,j] <- AIT.dist(as.vector(prey.means[i,]),as.vector(prey.means[j,])) } } } else { my.ylab <- "CS Distance" for (i in 2:I) { for (j in 1:(i-1)) { dist.mat[i,j] <- chisq.dist(as.vector(prey.means[i,]),as.vector(prey.means[j,]),1) } } } plot(stats::hclust(stats::as.dist(dist.mat),method=method),labels=rownames(prey.means),xlab="", ylab=my.ylab, sub=NA) }
plotts.dwt.wge=function (x,n.levels=4,type='S8') { n=length(x) dwtd=rep(0,n.levels) if (n/2^n.levels != trunc(n/2^n.levels)) stop("Sample size is not divisible by 2^n.levels") if (2^n.levels > n) stop("wavelet transform exceeds sample size in dwt") numrows <- n.levels+2 numcols <- 1 timelab <- 'Lag' valuelab <- '' fig.width <- 5 fig.height <- 4 cex.labs <- c(1,1,1) par(mfrow=c(numrows,numcols),mar=c(3.5,2.5,.5,1)) dj=c('d1','d2','d3','d4','d5','d6','d7','d8','d9','d10','d11','d12','d13','d14') sj=c('s1','s2','s3','s4','s5','s6','s7','s8','s9','s10','s11','s12','s13','s14') tt=1:n if(n < 200) {plot(tt,x,type='o',xaxt='n',yaxt='n',cex=1,pch=16,cex.lab=.75,cex.axis=.75,lwd=.75,xlab='',ylab='',axes=F,xlim=c(0,n))} if(n >= 200) {plot(tt,x,type='l',xaxt='n',yaxt='n',cex=1,pch=16,cex.lab=.75,cex.axis=.75,lwd=.75,xlab='',ylab='',axes=F,xlim=c(0,n))} mtext(side=c(2),text='Data',cex=c(1)) if(type=='haar'){typewf='haar'} if(type=='S8'){typewf='la8'} if(type=='D4'){typewf='d4'} if(type=='D6'){typewf='d6'} if(type=='D8'){typewf='d8'} x.dwt <- waveslim::dwt(x, n.levels, wf = typewf, boundary = "periodic") x<-c(0,n) y<-c(0,0) ymin=0 ymax=0 nlp1=n.levels+1 for (j in 1:nlp1){ ymin=min(ymin,x.dwt[[j]]) ymax=max(ymax,x.dwt[[j]]) } for (j in 1:n.levels) {nj<-tt/2^j end=n/2^j k<-1:end td<-k*2^j-.5*2^j+.5 plot(td,x.dwt[[j]],type='h',yaxt='n',cex=0.6,pch=15,cex.lab=2,cex.axis=2,lwd=1,xlab='',ylab='',axes=F,ylim=c(ymin,ymax),xlim=c(0,n)) lines(x,y) mtext(side=c(2),text=dj[j],cex=c(1.)) } plot(td,x.dwt[[n.levels+1]],type='h',yaxt='n',cex=0.6,pch=15,cex.lab=2,cex.axis=2,lwd=1,xlab='',ylab='',axes=F,ylim=c(ymin,ymax),xlim=c(0,n)) lines(x,y) axis(side=1,cex.axis=1.5,mgp=c(3,1,0),tcl=-.3);mtext(side=c(2),text=sj[n.levels],cex=c(1.)) mtext(side=1,text='Time', cex=1.1,line=2) if(attr(x.dwt,'wavelet') =='la8'){attr(x.dwt,'wavelet')='S8'} if(attr(x.dwt,'wavelet') =='d4'){attr(x.dwt,'wavelet')='D4'} if(attr(x.dwt,'wavelet') =='d6'){attr(x.dwt,'wavelet')='D6'} if(attr(x.dwt,'wavelet') =='d8'){attr(x.dwt,'wavelet')='D8'} return(x.dwt) }
test_that("R6 pyclasses respect convert=FALSE", { d <- py_eval("{}", FALSE) r_cls <- R6Class( "r_class", public = list( a_method = function(x = NULL) { expect_same_pyobj(x, d) x$update(list("foo" = NULL)) } )) py_cls <- r_to_py(r_cls, convert = FALSE) py_inst <- py_cls() py_inst$a_method(d) expect_identical(py_to_r(d), list("foo" = NULL)) }) test_that("R6 pyclasses respect convert=TRUE", { d <- py_eval("{}", FALSE) r_cls <- R6Class( "r_class", public = list( a_method = function(x = NULL) { expect_type(x, "list") x[["foo"]] <- "bar" x } )) py_cls <- r_to_py(r_cls, convert = TRUE) py_inst <- py_cls() ret <- py_inst$a_method(d) expect_identical(ret, list(foo = "bar")) expect_identical(py_to_r(d), py_eval("{}")) }) test_that("%py_class% can be lazy about initing python", { res <- callr::r(function() { library(keras) options("topLevelEnvironment" = environment()) MyClass %py_class% { initialize <- function(x) { print("Hi from MyClass$initialize()!") self$x <- x } my_method <- function() { self$x } } if (reticulate:::is_python_initialized()) stop() MyClass2(MyClass) %py_class% { "This will be a __doc__ string for MyClass2" initialize <- function(...) { "This will be the __doc__ string for the MyClass2.__init__() method" print("Hi from MyClass2$initialize()!") super$initialize(...) } } if (reticulate:::is_python_initialized()) stop() my_class_instance2 <- MyClass2(42) my_class_instance2$my_method() }) expect_equal(res, 42) }) test_that("%py_class% initialize", { NaiveSequential %py_class% { initialize <- function(layers) self$layers <- layers } x <- NaiveSequential(list(1, "2", 3)) expect_identical(x$layers, list(1, "2", 3)) })
bucher_moduleUI <- function(id) { ns <- NS(id) tabPanel("Bucher method", h4("Adjusted Indirect Comparisons (Bucher method)"), fluidRow( column(6, fluidRow( column(4, numericInput(ns("buch_AC_est"), "A vs C", NA)), column(4, numericInput(ns("buch_AC_lo"), "95%CI LL", NA)), column(4, numericInput(ns("buch_AC_hi"), "95%CI UL", NA)) ), fluidRow( column(4, numericInput(ns("buch_BC_est"), "B vs C", NA)), column(4, numericInput(ns("buch_BC_lo"), "95%CI LL", NA)), column(4, numericInput(ns("buch_BC_hi"), "95%CI UL", NA)) ), radioButtons(ns("buch_type"), "What kind of effect measure is this?", choices = list( "Relative Risk / Odds Ratio / Other exponentiated measure" = "exp", "logRR / logOR / Other absolute measure" = "abs" ), width="100%") ), column(6, verbatimTextOutput(ns("buch_output"))) ) ) } bucher_module <- function(input, output, session) { output$buch_output <- renderPrint({ eff <- as.numeric(c(input$buch_AC_est, input$buch_AC_lo, input$buch_AC_hi, input$buch_BC_est, input$buch_BC_lo, input$buch_BC_hi)) if (sum(is.na(eff))==0) { if (input$buch_type=="exp" & sum(eff<0, na.rm=TRUE)>0) return(cat(" ")) if (input$buch_type=="exp") eff <- log(eff) eff <- matrix(eff, nrow=2, byrow=TRUE) colnames(eff) <- c("est", "lo", "hi"); rownames(eff) <- c("AC", "BC") pool.eff <- diff(eff[c("BC","AC"), "est"]) pool.sd <- sqrt( (abs(diff(eff["AC", c("lo","hi")]))/(2*qnorm(0.975)))^2 + (abs(diff(eff["BC", c("lo","hi")]))/(2*qnorm(0.975)))^2) symm.ac <- abs(abs(diff(eff["AC", c("est","hi")]))/abs(diff(eff["AC", c("lo","est")]))-1)<0.05 symm.bc <- abs(abs(diff(eff["BC", c("est","hi")]))/abs(diff(eff["BC", c("lo","est")]))-1)<0.05 output <- c( if (input$buch_type=="exp") "Exponentiated measure - converting to log:\n" else "", sprintf("Point estimate, A vs C: %.3f", eff["AC", "est"]), sprintf("Standard error, A vs C: %.3f", abs(diff(eff["AC", c("lo","hi")]))/(2*qnorm(0.975))), sprintf("\nPoint estimate, B vs C: %.3f", eff["BC", "est"]), sprintf("Standard error, B vs C: %.3f", abs(diff(eff["BC", c("lo","hi")]))/(2*qnorm(0.975))), sprintf("\nPoint estimate, A vs B: %.3f", pool.eff), sprintf("Standard error, A vs B: %.3f", pool.sd), sprintf("95%% Confidence Interval, A vs B: %.3f \u2014 %.3f", pool.eff-qnorm(0.975)*pool.sd, pool.eff+qnorm(0.975)*pool.sd), (if (input$buch_type=="exp") paste( "\nExponentiating:", sprintf("Point estimate, A vs B: %.2f", exp(pool.eff)), sprintf("95%% Confidence Interval, A vs B: %.2f \u2014 %.2f", exp(pool.eff-qnorm(0.975)*pool.sd), exp(pool.eff+qnorm(0.975)*pool.sd) ), sep="\n") else ""), "") if (!symm.ac) output <- c(output, "WARNING: The 95% CI for A vs C does not look symmetric.", " Are the values you entered correct?") if (!symm.bc) output <- c(output, "WARNING: The 95% CI for B vs C does not look symmetric.", " Are the values you entered correct?") return(cat(paste(output, collapse="\n"))) } else return(cat("No (appropriate) input data provided.")) }) }
context("canvasXpress Web Charts - Contour") test_that("cXcontour1", { check_ui_test(cXcontour1()) }) test_that("cXcontour2", { check_ui_test(cXcontour2()) }) test_that("cXcontour3", { check_ui_test(cXcontour3()) }) test_that("cXcontour4", { check_ui_test(cXcontour4()) }) test_that("cXcontour5", { check_ui_test(cXcontour5()) }) test_that("cXcontour6", { check_ui_test(cXcontour6()) })
knitr::opts_chunk$set(echo = TRUE, fig.height=4, fig.width=4) library("ivreg") data("Kmenta", package = "ivreg") Kmenta deq <- ivreg(Q ~ P + D | D + F + A, data=Kmenta) summary(deq) seq <- ivreg(Q ~ P + F + A | D + F + A, data=Kmenta) summary(seq) par(mfrow=c(2, 2)) plot(deq) library("car") qqPlot(deq) influencePlot(deq) Kmenta1 <- Kmenta Kmenta1[20, "Q"] <- 95 deq1 <- update(deq, data=Kmenta1) compareCoefs(deq, deq1) qqPlot(deq1) outlierTest(deq1) influencePlot(deq1) avPlots(deq1) deq1.20 <- update(deq1, subset = -20) compareCoefs(deq, deq1, deq1.20) H <- cbind(hatvalues(deq1), hatvalues(deq1, type="both"), hatvalues(deq1, type="maximum")) colnames(H) <- c("stage2", "geom.mean", "maximum") head(H) scatterplotMatrix(H, smooth=FALSE) cbind(dfbeta(deq1)[20, ], coef(deq1) - coef(deq1.20)) c(influence(deq1)$sigma[20], sigma(deq1.20)) crPlots(deq, smooth=list(span=1)) ceresPlots(deq, smooth=list(span=1)) library("effects") plot(predictorEffects(deq, residuals=TRUE), partial.residuals=list(span=1)) deq2 <- update(deq, . ~ I((P - 85)^4/10^5) + D) crPlots(deq2, smooth=list(span=1)) plot(predictorEffects(deq2, residuals=TRUE), partial.residuals=list(span=1)) plot(fitted(deq), rstudent(deq)) abline(h=0) spreadLevelPlot(deq, smooth=list(span=1)) with(Kmenta, plot(Q, Q^-2.5)) abline(lm(Q^-2.5 ~ Q, data=Kmenta)) ncvTest(deq) ncvTest(deq, var = ~ P + D) summary(deq, vcov=sandwich::sandwich) SEs <- round(cbind(sqrt(diag(sandwich::sandwich(deq))), sqrt(diag(vcov(deq)))), 4) colnames(SEs) <- c("sandwich", "conventional") SEs Kmenta2 <- Kmenta[, c("D", "F", "A")] set.seed(492365) Kmenta2 <- within(Kmenta2, { EQ <- 75.25 + 0.1125*D + 0.1250*F + 0.225*A EP <- 85.00 + 0.7500*D - 0.5000*F - 0.900*A d1 <- rnorm(20) d2 <- rnorm(20) v1 <- 2*d1 v2 <- -0.5*v1 + d2 w <- 3*(EQ - min(EQ) + 0.1)/(max(EQ) - min(EQ)) v1 <- v1*w Q <- EQ + v1 P <- EP + v2 }) with(Kmenta2, plot(EQ, v1)) deq2 <- update(deq, data=Kmenta2) summary(deq2) spreadLevelPlot(deq2) ncvTest(deq2) SEs2 <- round(cbind(sqrt(diag(sandwich::sandwich(deq2))), sqrt(diag(vcov(deq2)))), 4) colnames(SEs2) <- c("sandwich", "conventional") SEs2 set.seed <- 869255 b.deq2 <- Boot(deq2) summary(deq2, vcov.=vcov(b.deq2)) confint(b.deq2) deqw <- update(deq, data=Kmenta2, weights=1/w) summary(deqw) ncvTest(deqw) plot(fitted(deqw), rstudent(deqw)) outlierTest(deqw) sqrt(vif(deq)) mcPlots(deq) deq.mm <- update(deq1, method = "MM") summary(deq.mm) compareCoefs(deq, deq1, deq1.20, deq.mm) weights(deq.mm, type = "robustness") influencePlot(deq.mm)
test_that <- function(desc, code) { if (exists(".testthat_db", envir=.GlobalEnv)) { db <- get(".testthat_db", envir=.GlobalEnv) dbxDelete(db, "events") } testthat::test_that(desc, code) }
pfco <- function(xdata, cont, test, log2.opt=0, trim.opt=0.25) { n <- nrow(xdata); idnames <- rownames(xdata); xcol <- colnames(xdata); n.xcol <- length(xcol); idx1 <- xcol %in% cont; m1 <- sum(idx1); idx2 <- xcol %in% test; m2 <- sum(idx2); rankmat <- calcSRmat(xdata, cont, test, log2.opt, trim.opt); rmat.sr <- rankmat$rmat.sr; FC <- rankmat$FC; FC2 <- rankmat$FC2; moyV <- rankmat$moyV; stdV <- rankmat$stdV; m2c <- rankmat$m2c; smat <- (t(rmat.sr) %*% rmat.sr)/n; smat.eig <- eigen(smat); v <- smat.eig$vectors[,1:2]; if (v[1,1] < 0) v <- -v; u1 <- mean(v[,1])*rmat.sr %*% v[,1]; u2 <- mean(v[,2])*rmat.sr %*% v[,2]; u1b <- u1 + u2; moy <- mean(u1b) std <- sqrt((n-1)/n)*sd(u1b) f.value <- pnorm(u1b, mean = moy, sd = std) em <- 0.5; p.value <- tprobaCalc(moyV, stdV, n, m2c-1, em); comp <- sqrt(smat.eig$values); comp.w <- comp / sum(comp); comp.wcum <- cumsum(comp.w); list(idnames=idnames, FC=FC, FC2=FC2, ri=u1b, f.value=f.value, p.value=p.value, comp=comp, comp.w=comp.w, comp.wcum=comp.wcum); }
if (interactive()) savehistory(); library("aroma.affymetrix"); log <- Verbose(threshold=-10, timestamp=TRUE); naVersion <- "31"; user <- "HB"; datestamp <- "20101007"; chipType <- "Mapping250K_Nsp"; footer <- list( createdOn = format(Sys.time(), "%Y%m%d %H:%M:%S", usetz=TRUE), createdBy = list( fullname = "Henrik Bengtsson", email = sprintf("%s@%s", "henrik.bengtsson", "aroma-project.org") ), srcFiles = list() ); if (!exists("cdf")) { cdf <- AffymetrixCdfFile$byChipType(chipType); rm(csv); } print(cdf); if (!exists("csv")) { tags <- sprintf(".na%s", naVersion); pathname <- AffymetrixNetAffxCsvFile$findByChipType(chipType, tags=tags); if (isFile(pathname)) { csv <- AffymetrixNetAffxCsvFile(pathname); } rm(tags); } print(csv); tags <- sprintf("na%s,%s%s", naVersion, user, datestamp); ugp <- NULL; tryCatch({ ugp <- AromaUgpFile$byChipType(getChipType(cdf), tags=tags); }, error = function(ex) {}) if (is.null(ugp)) { ugp <- AromaUgpFile$allocateFromCdf(cdf, tags=tags); } print(ugp); units <- importFrom(ugp, csv, verbose=log); str(units); if (!exists("srcFileTags", mode="list")) { srcFileTags <- list(); srcFiles <- list(cdf, csv); for (kk in seq_along(srcFiles)) { srcFile <- srcFiles[[kk]]; tags <- list( filename=getFilename(srcFile), filesize=getFileSize(srcFile), checksum=getChecksum(srcFile) ); srcFileTags[[kk]] <- tags; } print(srcFileTags); } footer <- readFooter(ugp); footer$createdOn <- format(Sys.time(), "%Y%m%d %H:%M:%S", usetz=TRUE); footer$createdBy = list( fullname = "Henrik Bengtsson", email = sprintf("%s@%s", "henrik.bengtsson", "aroma-project.org") ); names(srcFileTags) <- sprintf("srcFile%d", seq_along(srcFileTags)); footer$srcFiles <- srcFileTags; writeFooter(ugp, footer); print(ugp); print(summary(ugp)); print(table(ugp[,1]))
crsra_membershares <- function( all_tables, groupby = c("roles", "country", "language", "gender", "empstatus", "education", "stustatus"), remove_missing = TRUE) { partner_user_id = attributes(all_tables)$partner_user_id all_tables = crsra_import_as_course(all_tables) groupby = match.arg(groupby) coursenames = names(all_tables) varname = switch(groupby, "roles" = "course_membership_role", "country" = "country_cd", "language" = "profile_language_cd", "gender" = "reported_or_inferred_gender", "empstatus" = "employment_status", "education" = "educational_attainment", "stustatus" = "student_status") y = Total = NULL rm(list = c("y", "Total")) membershares <- function(x, z) { temp <- z %>% dplyr::left_join(x, by = partner_user_id, `copy`=TRUE) temp$y = temp[[varname]] if (remove_missing) { temp = temp %>% dplyr::filter(!is.na(y)) } temp = temp %>% dplyr::group_by(y) %>% dplyr::summarise(Total = n()) %>% dplyr::mutate(Share = round(Total/sum(Total), 2)) %>% dplyr::arrange(desc(Total)) temp } mems = lapply(all_tables, function(x) x$course_memberships) users = lapply(all_tables, function(x) x$users) membertable <- purrr::map2( mems, users, membershares) names(membertable) <- coursenames return(membertable) }
flux.odae <- function(dat, var.par, min.allowed = 3, max.nrmse = 0.1, rl = NULL){ if(is.null(rl) & !exists("rl", dat)){ rl <- 0 warning("No range limit defined. Has been set to 0.") } if(!is.numeric(rl)){ rl <- dat[,rl]} if(exists("rl", dat)){rl <- dat$rl} vp <- function(dat, sel){ if(is.character(sel)){out <- dat[,sel]} else{out <- rep(sel, nrow(dat))} return(out) } dat <- lapply(var.par, function(x) vp(dat, x)) stv <- match(c("ghg", "time", "gc.qual", "area", "volume"), names(dat)) handthrough <- names(which(sapply(var.par[-stv], is.character))) hdt.fac.sel <- sapply(dat[handthrough], is.numeric) fac.out <- c(CH4 = "methane",CO22 = "carbon dioxide") fac.out <- c(fac.out, sapply(dat[handthrough][!hdt.fac.sel], function(x) as.character(x[1]))) hdt <- c(dat[c("area", "volume")], dat[handthrough][hdt.fac.sel]) dat.out <- round(sapply(hdt, mean), 3) dat <- sapply(dat[c("ghg", "time", "gc.qual", "area", "volume", "t.air", "p.air")], function(x) x[]) dat <- data.frame(dat) dat <- dat[order(dat$time),] vers <- unlist(lapply(c(min.allowed:nrow(dat)), function(x) combn(c(1:nrow(dat)), x, simplify=FALSE)), recursive=FALSE) vers <- lapply(vers, "sort") sel <- unlist(lapply(vers, function(x) length(unique(dat[x,2])))) vers <- vers[sel >= min.allowed] vers.n <- sapply(vers, "length") vers.lm <- lapply(vers, function(x) lm(ghg ~ time, data=dat[x,])) nrmse <- unlist(lapply(vers.lm, function(x) sqrt(sum(residuals(x)^2)/summary(x)$df[2])/diff(range(x$model[1], na.rm=TRUE)))) ranks <- order(vers.n, 1-nrmse, decreasing=TRUE) m2t <- ranks[nrmse[ranks] <= max.nrmse][1] if(is.na(m2t)){ m2t <- order(nrmse)[1] } lm4flux <- vers.lm[[m2t]] row.select <- vers[[m2t]] names(dat)[1] <- var.par$ghg dat$rl <- rl res <- list(lm4flux = lm4flux, row.select = row.select, orig.dat = dat, dat.out = dat.out, fac.out = fac.out) return(res) }
"irt.fa" <- function(x,nfactors=1,correct=TRUE,plot=TRUE,n.obs=NULL,rotate="oblimin",fm="minres",sort=FALSE,...) { cl <- match.call() if (is.matrix(x) | is.data.frame(x)) { if(is.null(n.obs)) n.obs <- dim(x)[1] nvar <- ncol(x) vname <- colnames(x) x <- as.matrix(x) if(!is.numeric(x)) {message("Converted non-numeric matrix input to numeric. \n Are you sure you wanted to do this?\n Please check your data") x <- matrix(as.numeric(x),ncol=nvar)} colnames(x) <- vname tx <- table(as.matrix(x)) if(dim(tx)[1] ==2) {tet <- tetrachoric(x,correct=correct) typ = "tet"} else {tet <- polychoric(x) typ = "poly"} r <- tet$rho tau <- tet$tau} else {if (!is.null(x$rho)) { r <- x$rho tau <- x$tau if(is.null(n.obs)) {n.obs <- x$n.obs} typ <- class(x)[2] if (typ == "irt.fa") typ <- "tet" } else {stop("x must be a data.frame or matrix or the result from tetra or polychoric")} } t <- fa(r,nfactors=nfactors,n.obs=n.obs,rotate=rotate,fm=fm,...) if(sort) {t <- fa.sort(t) if(typ !="tet" ) {tau <- tau[t$order,] } else {tau <- tau[t$order] } } nf <- dim(t$loadings)[2] diffi <- list() for (i in 1:nf) {diffi[[i]] <- tau/sqrt(1-t$loadings[,i]^2) } discrim <- t$loadings/sqrt(1-t$loadings^2) if(any(is.nan(discrim))) { for (i in 1:nf) { bad <- which(is.nan(discrim[,i])) if(length( bad) > 0) { warning("A discrimination with a NaN value was replaced with the maximum discrimination for factor ", i, " and item(s) ",bad, "\nexamine the factor analysis object (fa) to identify the Heywood case. \nThe item informations are probably suspect as well for this factor. \nYou might try a different factor extraction technique. ") discrim[is.nan(discrim[,i]),i] <- max(discrim[,i],na.rm=TRUE) diffi[[i]][bad,] <- tau[bad,] } }} class(diffi) <- NULL class(discrim) <- NULL tl <- t$loadings class(tl) <- NULL irt <- list(difficulty=diffi,discrimination=discrim) nlevels <- dim(diffi[[1]])[2] result <- list(irt=irt,fa = t,rho=r,tau=tau,n.obs=n.obs,Call=cl) switch(typ, tet = { class(result) <- c("psych","irt.fa")}, tetra ={class(result) <- c("psych","irt.fa")}, poly = {class(result) <- c("psych","irt.poly")}, irt.poly = {class(result) <- c("psych","irt.poly")}) if(plot) {pr <- plot(result) result$plot <- pr} return(result) } "fa2irt" <- function(f,rho,plot=TRUE,n.obs=NULL) { cl <- match.call() tau <- rho$tau if(!is.null(f$order)) {if (!is.null(ncol(tau))) { tau <- tau[f$order,] } else {tau <- tau[f$order] }} r <- rho$rho nf <- ncol(f$loadings) diffi <- list() for (i in 1:nf) {diffi[[i]] <- tau/sqrt(1-f$loadings[,i]^2) } discrim <- f$loadings/sqrt(1-f$loadings^2) if(any(is.nan(discrim))) {bad <- which(is.nan(discrim),arr.ind=TRUE) if(length(bad) > 0) { warning("An discrimination with a NaN value was replaced with the maximum discrimination for item(s) ",bad, "\nexamine the factor analysis object (fa) to identify the problem") } for (i in 1:nf) { discrimin[is.nan(discrim[,i])] <- max(discrimin[,i],na.rm=TRUE) }} irt <- list(difficulty=diffi,discrimination=discrim) result <- list(irt=irt,fa = f,rho=r,tau=tau,n.obs=n.obs,Call=cl) if(inherits(rho[2],"poly" )) {class(result) <- c("psych","irt.poly") } else {class(result) <- c("psych","irt.fa")} if(plot) {pr <- plot(result) result$plot <- pr} return(result) }
library(ggplot2) library(knitr) opts_chunk$set(comment=NA, fig.width=7.2) library(ggseas) ap_df <- tsdf(AirPassengers) head(ap_df) ggplot(ap_df, aes(x = x, y = y)) + geom_line(colour = "grey75") ggplot(ap_df, aes(x = x, y = y)) + stat_index(index.ref = 1:10) ggplot(ap_df, aes(x = x, y = y)) + stat_index(index.ref = 120, index.basis = 1000) ggplot(ap_df, aes(x = x, y = y)) + geom_line(colour = "grey75") + stat_rollapplyr(width = 12, align = "center") + labs(x = "", y = "Number of US Air Passengers\n(rolling average and original)") ggplot(ap_df, aes(x = x, y = y)) + geom_line(colour = "grey75") + stat_rollapplyr(width = 12, align = "center", geom = "point", size = 0.5, colour = "steelblue") + labs(x = "", y = "Number of US Air Passengers\n(rolling average and original)") ggplot(ap_df, aes(x = x, y = y)) + geom_line(colour = "grey50") + stat_seas(colour = "blue") + stat_stl(s.window = 7, colour = "red") ggplot(ldeaths_df, aes(x = YearMon, y = deaths, colour = sex)) + geom_point() + facet_wrap(~sex) + stat_seas() + ggtitle("Seasonally adjusted lung deaths in the UK") ggsdc(ap_df, aes(x = x, y = y), method = "seas") + geom_line() serv <- subset(nzbop, Account == "Current account" & Category %in% c("Services; Exports total", "Services; Imports total")) ggsdc(serv, aes(x = TimePeriod, y = Value, colour = Category), method = "stl", s.window = 7, frequency = 4, facet.titles = c("The original series", "The underlying trend", "Regular seasonal patterns", "All the randomness left")) + geom_line()
fabia.overlap <- function(resFAB,ind.ref,type="loadings",thresZ=0.5,thresL=NULL){ bicResult <- extractBic(resFAB,thresZ=thresZ,thresL=thresL) ind.bc.load <- bicResult$numn[,1] ind.bc.factor <- bicResult$numn[,2] overlap.BC <- c(1:length(ind.bc.load)) n.overlap.ref <- c(1:length(ind.bc.load)) n.overlap.query <- c(1:length(ind.bc.load)) if(type=="loadings"){ ind.total <- c(1:dim(resFAB@L)[1]) ind.query <- ind.total[-ind.ref] for(i.bc in 1:length(ind.bc.load)){ ind.bc.load.i <- ind.bc.load[[i.bc]] nref.temp <- length(intersect(ind.ref,ind.bc.load.i)) nquery.temp <- length(intersect(ind.query,ind.bc.load.i)) if((length(intersect(ind.ref,ind.bc.load.i))>=1) & (length(intersect(ind.query,ind.bc.load.i))>=1)){ overlap.BC[i.bc] <- i.bc n.overlap.ref[i.bc] <- nref.temp n.overlap.query[i.bc] <- nquery.temp } } } if(type=="factors"){ ind.total <- c(1:dim(resFAB@Z)[2]) ind.query <- ind.total[-ind.ref] for(i.bc in 1:length(ind.bc.factor)){ ind.bc.factor.i <- ind.bc.factor[[i.bc]] nref.temp <- length(intersect(ind.ref,ind.bc.factor.i)) nquery.temp <- length(intersect(ind.query,ind.bc.factor.i)) if((length(intersect(ind.ref,ind.bc.factor.i))>=1) & (length(intersect(ind.query,ind.bc.factor.i))>=1)){ overlap.BC[i.bc] <- i.bc n.overlap.ref[i.bc] <- nref.temp n.overlap.query[i.bc] <- nquery.temp } } } out <- data.frame(Bicluster=overlap.BC,Number.Ref=n.overlap.ref,Number.Query=n.overlap.query) return(out) } getWeightedDat <- function(Mat1,Mat2,scale.unit=TRUE){ if(scale.unit){ Mat1 <- stdize(Mat1,center=TRUE,scale=TRUE) Mat2 <- stdize(Mat2,center=TRUE,scale=TRUE) resPCA1 <- PCA(Mat1,graph=FALSE) resPCA2 <- PCA(Mat2,graph=FALSE) } else{ resPCA1 <- PCA(Mat1,scale.unit=FALSE,graph=FALSE) resPCA2 <- PCA(Mat2,scale.unit=FALSE,graph=FALSE) } getWeight1 <- resPCA1$eig[1,1] getWeight2 <- resPCA2$eig[1,1] Mat1.w <- Mat1*(1/sqrt(getWeight1)) Mat2.w <- Mat2*(1/sqrt(getWeight2)) dat <- list() dat[[1]] <- data.matrix(cbind(Mat1.w, Mat2.w)) dat[[2]] <- 1/sqrt(getWeight1) dat[[3]] <- 1/sqrt(getWeight2) dat[[4]] <- resPCA1 dat[[5]] <- resPCA2 names(dat) <- c("weightedData", "weight1","weight2", "resPCA1", "resPCA2") return(dat) }
pep2prot = function(pep.Expr.Data, rollup.map){ protIDs = unique(rollup.map) prot.Expr.Data = matrix(,nrow = length(protIDs),ncol = dim(pep.Expr.Data)[2]) for (i in 1:length(protIDs)){ temp = protIDs[i] pepSet = pep.Expr.Data[which(rollup.map==temp),] if (length(which(rollup.map==temp))==1){ prot.Expr.Data[i,] = pepSet } else{ prot.Expr.Data[i,] = apply(pepSet,2,median,na.rm = T) } } return(prot.Expr.Data) }
claim_notification <- function( frequency_vector, claim_size_list, rfun, paramfun, ...) { if (!missing(rfun) & missing(paramfun)) { paramfun <- function(claim_size, occurrence_period, ...) { c(claim_size = claim_size, occurrence_period = occurrence_period, ...) } paramfun_filled <- TRUE } else { paramfun_filled <- FALSE } if (missing(rfun)) { rfun <- stats::rweibull if (missing(paramfun)) { paramfun <- function(claim_size, occurrence_period, ...) { mean <- min(3, max(1, 2-(log(claim_size/(0.50 * .pkgenv$ref_claim)))/3))/4 / .pkgenv$time_unit cv <- 0.70 shape <- get_Weibull_parameters(mean, cv)[1, ] scale <- get_Weibull_parameters(mean, cv)[2, ] c(shape = shape, scale = scale) } } } I <- length(frequency_vector) no_claims <- sum(frequency_vector) params <- mapply(paramfun, claim_size = unlist(claim_size_list, use.names = FALSE), occurrence_period = rep(1:I, times = frequency_vector), ...) if (!is.null(names(params))) { params_split <- split(unname(params), names(params)) } else if (length(params)) { params_split <- asplit(params, 1) } else { params_split <- params } args <- as.list(params_split) keep_names <- c(intersect(names(args), names(formals(rfun)))) keep_formals <- c(list(n = no_claims), args[keep_names]) if (paramfun_filled) { tt <- try(notidel_vect <- do.call(rfun, keep_formals), TRUE) if (methods::is(tt, "try-error")) { stop("need to specify 'paramfun' for the sampling distribution") } } else { notidel_vect <- do.call(rfun, keep_formals) } notidel <- to_SynthETIC(notidel_vect, frequency_vector) notidel }
expInstantiate <- function(e, parameters = NULL, removeUnary=TRUE) { if (!is.experiment(e)) stop(.callErrorMessage("wrongParameterError", "e", "experiment")) if (!is.null(parameters) & !is.character(parameters)) stop(.callErrorMessage("wrongParameterError", "parameters", "character or character array")) if(is.null(parameters)) parameters = e$parameters else{ for (var in parameters) { if (!(var %in% e$parameters)) stop(.callErrorMessage("variableNotPresentError", var)) } } e1 <- e e1$parameters <- e1$parameters[!(e1$parameters %in% parameters)] auxParameters <- parameters if (removeUnary) { for (var in auxParameters) { col <- e1$data[[var]] if (length(unique(col)) == 1) { e1$data <- e1$data[,-which(colnames(e1$data)==var)] parameters <- parameters[-which(parameters==var)] } } } e1$data[[e1$method]] <- interaction(e1$data[,c(e1$method,parameters),drop=FALSE], sep = ",", drop=TRUE) e1$data <- e1$data[,!(colnames(e1$data) %in% parameters),drop=FALSE] e1$historic <- c(e1$historic, list(paste("Methods has been instanciated with the parameters: ", toString(auxParameters), sep=""))) config = c() for (p in auxParameters) config <- c(config, paste0(p, ' [', paste0(levels(e$data[[p]]), collapse = ","), '] (instantiated)')) e1$configuration = config e1 }