code
stringlengths
1
13.8M
.runThisTest <- Sys.getenv("RunAllRcppTests") == "yes" if (.runThisTest) { context("Make_models") testthat::test_that( desc = "Print and summary functions", code = { model <- make_model("X -> Y") out <- capture.output(CausalQueries:::print.causal_model(model)) expect_true(any(grepl("\\$X", out)) & any(grepl("\\$Y", out))) out <- class(CausalQueries:::summary.causal_model(model)) expect_equal(out[1], "summary.causal_model") expect_equal(out[2], "data.frame") model <- make_model("X -> Y") %>% set_confound(list("X <-> Y")) out <- capture.output(CausalQueries:::print.summary.causal_model(model)) expect_true(any(grepl("Parameter matrix.+", out))) model <- make_model("X->Y") %>% set_restrictions(statement = c("X[] == 0")) out <- capture.output(CausalQueries:::print.summary.causal_model(model)) expect_true(any(grepl("Restrictions.+", out))) expect_error(make_model("X -> S <- Y; S <-> Z")) } ) }
library(satellite) path <- system.file("extdata", package = "satellite") files <- list.files(path, pattern = glob2rx("LC08*.TIF"), full.names = TRUE) sat <- satellite(files) sat <- convSC2Rad(sat) sat <- convSC2Ref(sat) sat <- convRad2BT(sat)
renderTreeMap <- function(div_id, data, name = "Main", leafDepth = 2, theme = "default", show.tools = TRUE, running_in_shiny = TRUE){ theme_placeholder <- .theme_placeholder(theme) .check_logical(c('show.tools', 'running_in_shiny')) if(((class(leafDepth) %in% c('integer', 'numeric')) == FALSE)){ stop("Argument 'leafDepth' must be integer.") } if(leafDepth <=0 ){ stop("Argument 'leafDepth' must be bigger than 0.") } js_statement <- paste0("var " , div_id, " = echarts.init(document.getElementById('", div_id, "')", theme_placeholder, ");", "option_", div_id, " = {tooltip : {trigger:'item', formatter: '{b}: {c}'}, ", ifelse(show.tools, "toolbox:{feature:{mark:{show:true}, restore:{show: true}, saveAsImage:{}}}, ", ""), "series :[", "{name:'", name, "',", "type:'treemap',", "leafDepth:", leafDepth, ",", " itemStyle:{normal: {label: {show: true,formatter: '{b}'},borderWidth: 1},emphasis: {label: {show: true}}},", "data:", data, "", "}]", "};", div_id, ".setOption(option_", div_id, ");", "window.addEventListener('resize', function(){", div_id, ".resize()", "});") to_eval <- paste0("output$", div_id ," <- renderUI({tags$script(\"", js_statement, "\")})") if(running_in_shiny == TRUE){ eval(parse(text = to_eval), envir = parent.frame()) } else { cat(to_eval) } }
check_dependencies <- function() { CreatePackageReport(pkg_name = "photosynthesis") }
make_parameters <- function(model, parameters = NULL, param_type = NULL, warning = TRUE, normalize = TRUE, ...) { if (!is.null(parameters) && (length(parameters) == length(get_parameters(model)))) return(clean_param_vector(model, parameters)) if (!is.null(param_type)) if (!(param_type %in% c("flat", "prior_mean", "posterior_mean", "prior_draw", "posterior_draw", "define"))) { stop("param_type should be one of `flat`, `prior_mean`, `posterior_mean`, `prior_draw`, `posterior_draw`, or `define`") } par_args = list(...) par_args_provided <- sum(names(par_args) %in% c("distribution", "parameters", "node", "label", "statement", "confound", "nodal_type", "param_set", "param_names")) if (par_args_provided > 0 & is.null(param_type)) param_type <- "define" if (is.null(param_type)) param_type <- "prior_mean" if (param_type == "define") { param_value <- make_par_values_multiple(model, y = get_parameters(model), x = parameters, normalize = normalize, ...) } if (param_type == "flat") { param_value <- make_priors(model, distribution = "uniform") } if (param_type == "prior_mean") { param_value <- get_priors(model) } if (param_type == "prior_draw") { param_value <- make_prior_distribution(model, 1) } if (param_type == "posterior_mean") { if (is.null(model$posterior)) stop("Posterior distribution required") param_value <- apply(model$posterior_distribution, 2, mean) } if (param_type == "posterior_draw") { if (is.null(model$posterior)) stop("Posterior distribution required") df <- model$posterior_distribution param_value <- df[sample(nrow(df), 1), ] } clean_param_vector(model, param_value) } set_parameters <- function(model, parameters = NULL, param_type = NULL, warning = FALSE, ...) { if (length(parameters) != length(get_parameters(model))) { if(!is.null(parameters)) parameters <- make_parameters(model, parameters = parameters, param_type = "define", ...) if(is.null(parameters)) parameters <- make_parameters(model, param_type = param_type, ...) } model$parameters_df$param_value <- parameters model$parameters_df <- clean_params(model$parameters_df, warning = warning) model } get_parameters <- function(model, param_type = NULL) { if (is.null(param_type)) { x <- model$parameters_df$param_value names(x) <- model$parameters_df$param_names } if (!is.null(param_type)) x <- make_parameters(model, param_type = param_type) x }
zbayes <- setRefClass("Zelig-bayes", contains = "Zelig") zbayes$methods( initialize = function() { callSuper() .self$packageauthors <- "Andrew D. Martin, Kevin M. Quinn, and Jong Hee Park" .self$modelauthors <- "Ben Goodrich, and Ying Lu" } ) zbayes$methods( zelig = function(formula, burnin = 1000, mcmc = 10000, verbose = 0, ..., data, by = NULL, bootstrap = FALSE) { if(!identical(bootstrap,FALSE)){ stop("Error: The bootstrap is not available for Markov chain Monte Carlo (MCMC) models.") } .self$zelig.call <- match.call(expand.dots = TRUE) .self$model.call <- .self$zelig.call if (missing(verbose)) verbose <- round((mcmc + burnin) / 10) .self$model.call$verbose <- verbose .self$num <- mcmc callSuper(formula = formula, data = data, ..., by = by, bootstrap = FALSE) } ) zbayes$methods( param = function(z.out) { return(z.out) } ) zbayes$methods( get_coef = function() { "Get estimated model coefficients" return(.self$zelig.out$z.out[[1]]) } ) zbayes$methods( geweke.diag = function() { diag <- lapply(.self$zelig.out$z.out, coda::geweke.diag) if(length(diag)==1){ diag<-diag[[1]] } if(!citation("coda") %in% .self$refs){ .self$refs<-c(.self$refs,citation("coda")) } ref1<-bibentry( bibtype="InCollection", title = "Evaluating the accuracy of sampling-based approaches to calculating posterior moments.", booktitle = "Bayesian Statistics 4", author = person("John", "Geweke"), year = 1992, publisher = "Clarendon Press", address = "Oxford, UK", editor = c(person("JM", "Bernado"), person("JO", "Berger"), person("AP", "Dawid"), person("AFM", "Smith")) ) .self$refs<-c(.self$refs,ref1) return(diag) } ) zbayes$methods( heidel.diag = function() { diag <- lapply(.self$zelig.out$z.out, coda::heidel.diag) if(length(diag)==1){ diag<-diag[[1]] } if(!citation("coda") %in% .self$refs){ .self$refs<-c(.self$refs,citation("coda")) } ref1<-bibentry( bibtype="Article", title = "Simulation run length control in the presence of an initial transient.", author = c(person("P", "Heidelberger"), person("PD", "Welch")), journal = "Operations Research", volume = 31, year = 1983, pages = "1109--44") .self$refs<-c(.self$refs,ref1) return(diag) } ) zbayes$methods( raftery.diag = function() { diag <- lapply(.self$zelig.out$z.out, coda::raftery.diag) if(length(diag)==1){ diag<-diag[[1]] } if(!citation("coda") %in% .self$refs){ .self$refs<-c(.self$refs,citation("coda")) } ref1<-bibentry( bibtype="Article", title = "One long run with diagnostics: Implementation strategies for Markov chain Monte Carlo.", author = c(person("Adrian E", "Raftery"), person("Steven M", "Lewis")), journal = "Statistical Science", volume = 31, year = 1992, pages = "1109--44") ref2<-bibentry( bibtype="InCollection", title = "The number of iterations, convergence diagnostics and generic Metropolis algorithms.", booktitle = "Practical Markov Chain Monte Carlo", author = c(person("Adrian E", "Raftery"), person("Steven M", "Lewis")), year = 1995, publisher = "Chapman and Hall", address = "London, UK", editor = c(person("WR", "Gilks"), person("DJ", "Spiegelhalter"), person("S", "Richardson")) ) .self$refs<-c(.self$refs,ref1,ref2) return(diag) } )
source_DropboxData <-function() { stop('Unfortunately, source_DropboxData is no longer supported due to changes in the Dropbox API.', call. = FALSE) }
set.seed(123) n.seq <- 250 p <- 5 K <- 2 mix.prop <- c(0.3, 0.7) TP <- array(rep(NA, p * p * K), c(p, p, K)) TP[,,1] <- matrix(c(0.20, 0.10, 0.15, 0.15, 0.40, 0.10, 0.10, 0.20, 0.20, 0.40, 0.15, 0.10, 0.20, 0.20, 0.35, 0.15, 0.10, 0.20, 0.20, 0.35, 0.30, 0.30, 0.10, 0.10, 0.20), byrow = TRUE, ncol = p) TP[,,2] <- matrix(c(0.15, 0.35, 0.20, 0.20, 0.10, 0.40, 0.10, 0.20, 0.20, 0.10, 0.25, 0.20, 0.15, 0.15, 0.25, 0.25, 0.20, 0.15, 0.15, 0.25, 0.10, 0.20, 0.20, 0.20, 0.30), byrow = TRUE, ncol = p) A <- click.sim(n = n.seq, int = c(10, 50), alpha = mix.prop, gamma = TP) C <- click.read(A$S) N2 <- click.EM(X = C$X, K = 2); N2$BIC M2 <- click.EM(X = C$X, y = C$y, K = 2); M2$BIC F2 <- click.forward(X = C$X, K = 2); F2$BIC B2 <- click.backward(X = C$X, K = 2); B2$BIC
miivs <- function(model){ pt <- lavaan::lavaanify( model, auto = TRUE, meanstructure = TRUE ) bad.ops <- c("==", "~*~","<~") if (length(pt$lhs[pt$op %in% bad.ops & pt$user != 2]) > 0) { stop(paste("miivs: MIIVsem does not currently support", "the following operators:", paste0(bad.ops,collapse = ", "),".")) } pt$mlabel <- pt$label condNum <- !(pt$op == "=~" & !duplicated(pt$lhs)) & (!is.na(pt$ustart) & pt$free == 0) if (length(pt$ustart[condNum]) > 0){ pt[condNum,]$mlabel <- pt[condNum,]$ustart } tmpMarkers <- pt[pt$op == "=~",]$rhs[ which(!duplicated(pt[pt$op == "=~",]$lhs)) ] if (length(tmpMarkers) > 0){ for(i in 1:length(tmpMarkers)){ if(length(pt[pt$op == "=~" & pt$rhs == tmpMarkers[i],"lhs"]) > 1){ stop(paste("miivs: scaling indicators with a factor complexity", "greater than 1 are not currently supported.")) } if(length(pt[pt$op == "~" & pt$lhs == tmpMarkers[i],"lhs"]) > 0){ stop(paste("miivs: scaling indicators cannot be depdendent", "variables in regression equations.")) } } pt[pt$op == "=~" & pt$rhs %in% tmpMarkers,]$mlabel <- NA } pt$mlabel[pt$mlabel == ""] <- NA latVars <- unique(pt$lhs[pt$op == "=~"]) obsVars <- setdiff( unique(c(pt$lhs[pt$op != "=="],pt$rhs[pt$op != "==" & pt$op != "~1"])), latVars ) endVars <- unique(c(pt$rhs[pt$op == "=~"], pt$lhs[pt$op == "~"])) errVars <- paste("e.",endVars,sep="") exoVars <- c( setdiff( unique(c(pt$rhs[pt$op!="=="], pt$lhs[pt$op!="=="])), endVars ), errVars) exoVarsObs <- intersect(exoVars, obsVars) if(length(exoVarsObs) > 0){ pt[pt$rhs %in% exoVarsObs & pt$op == "~~" & pt$lhs == pt$rhs,"exo"] <- 1 } allVars <- c(endVars,exoVars) n <- length(exoVars) m <- length(endVars) s <- m + n gamma <- matrix(0, m, n, dimnames = list(endVars, exoVars)) beta <- matrix(0, m, m, dimnames = list(endVars, endVars)) Phi <- matrix(0, n, n, dimnames = list(exoVars, exoVars)) paramValues <- ifelse( pt$free == 0 & is.na(pt$mlabel), pt$ustart, NA ) for(i in which(pt$op == "=~" & pt$lhs %in% exoVars)){ gamma[pt$rhs[i],pt$lhs[i]] <- paramValues[i] } for(i in which(pt$op == "~" & pt$rhs %in% exoVars)){ gamma[pt$lhs[i],pt$rhs[i]] <- paramValues[i] } gamma[,(n-m+1):n] <- diag(m) for(i in which(pt$op == "=~" & ! pt$lhs %in% exoVars)){ beta[pt$rhs[i],pt$lhs[i]] <- paramValues[i] } for(i in which(pt$op == "~" & ! pt$rhs %in% exoVars)){ beta[pt$lhs[i],pt$rhs[i]] <- paramValues[i] } lhs <- ifelse( pt$lhs %in% endVars, paste("e.",pt$lhs,sep=""), pt$lhs ) rhs <- ifelse( pt$rhs %in% endVars, paste("e.",pt$rhs,sep=""), pt$rhs ) for(i in which(pt$op == "~~")){ Phi[lhs[i],rhs[i]] <- Phi[rhs[i],lhs[i]] <- paramValues[i] } Beta <- matrix(0,s,s, dimnames = list(allVars, allVars)) Gamma <- matrix(0,s,n, dimnames = list(allVars, exoVars)) I <- diag(nrow(Beta)) Gamma[1:m,] <- gamma Gamma[(m+1):s,] <- diag(n) Beta[1:m,1:m]<-beta `%naproduct%` <- function(x, y) { as.matrix( Matrix::Matrix(x, sparse = T) %*% Matrix::Matrix(y, sparse = T) ) } BetaI <- I-Beta BetaI[is.na(BetaI)] <- 0 BetaI <- solve(BetaI) BetaNA <- I-(is.na(Beta) | Beta != 0) trySolve <- function(mat){ "matrix" %in% class(try(solve(mat),silent=T)) } if (trySolve(BetaNA)){ BetaNA <- solve(BetaNA) } else { nz <- length(BetaNA[BetaNA==-1]) BetaNA[BetaNA==-1] <- stats::runif(nz) BetaNA <- solve(BetaNA) } BetaI[BetaNA != 0 & BetaI == 0] <- NA Sigma <- BetaI %naproduct% Gamma %naproduct% Phi %naproduct% t(Gamma) %naproduct% t(BetaI) gamBeta <- cbind(gamma,beta) eqns <- list() for(dv in unique(rownames(gamBeta)[which(apply(is.na(gamBeta),1,any))])){ eq <- list() vars <- c(dv,colnames(gamBeta)[c(which(gamBeta[dv,]!=0), which(is.na(gamBeta[dv,])))]) eq$EQnum <- NA eq$EQmod <- NA eq$DVobs <- NA eq$IVobs <- NA eq$DVlat <- dv eq$IVlat <- setdiff(vars[-1], errVars) compositeDisturbance <- paste("e.",vars[1],sep="") markers <- NULL for(var in vars){ if(var %in% latVars){ marker <- rownames(gamBeta)[which(gamBeta[,var]==1)[1]] compositeDisturbance <- c( compositeDisturbance,paste("e.",marker,sep="") ) while(marker %in% latVars){ eq$EQmod <- "measurement" marker <- rownames(gamBeta)[which(gamBeta[,marker]==1)[1]] compositeDisturbance <- c( compositeDisturbance, paste("e.",marker,sep="") ) } markers <- c(markers, marker) vars[vars == var] <- marker } } eq$DVobs <- vars[1] eq$IVobs <- setdiff(vars[-1], errVars) eq$CDist <- compositeDisturbance eq$MIIVs <- NA eq$markers <- eq$markers eqns <- c(eqns,list(eq)) } for (j in 1:length(eqns)){ eqns[[j]]$EQnum <- j Sigma_e <- Sigma[,eqns[[j]]$CDist, drop = FALSE] e <- apply(Sigma_e == 0 & ! is.na(Sigma_e),1,all) Sigma_i <- Sigma[,eqns[[j]]$markers, drop = FALSE] i <- apply(Sigma_i != 0 | is.na(Sigma_i),1,all) eqns[[j]]$MIIVs <- names(which((e&i)[obsVars])) eqns[[j]]$EQmod <- if (eqns[[j]]$DVlat %in% pt$rhs[pt$op =="=~"] ){ "measurement" } else { "regression" } } eqns <- lapply(eqns,function(eq){eq$markers <- NULL; eq}) lhsi <- c(pt$rhs[pt$op == "=~" & duplicated(pt$lhs)], pt$lhs[pt$op == "~"]) rhsi <- c(pt$lhs[pt$op == "=~" & duplicated(pt$lhs)], pt$rhs[pt$op == "~"]) labi <- c(pt$mlabel[pt$op == "=~" & duplicated(pt$lhs)], pt$mlabel[pt$op == "~"]) for ( j in 1:length(eqns)){ td <- eqns[[j]]$DVlat ti <- eqns[[j]]$IVlat eqns[[j]]$Label <- labi[which(lhsi %in% td)][ match(ti, rhsi[which(lhsi %in% td)]) ] } res <- list( eqns = eqns, pt = pt, matrices = list( Sigma = Sigma, Beta = Beta, BetaI = BetaI, Gamma = Gamma, Phi = Phi ) ) class(res) <- "miivs" res }
penalties.BTLLasso <- function(Y, X = NULL, Z1 = NULL, Z2 = NULL, get.design = get.design, control = ctrl.BTLLasso()) { n <- Y$n m <- Y$m k <- Y$k q <- Y$q object.names <- Y$object.names penalize.X <- control$penalize.X penalize.Z1.diffs <- control$penalize.Z1.diffs penalize.Z1.absolute <- control$penalize.Z1.absolute penalize.Z2 <- control$penalize.Z2 penalize.intercepts <- control$penalize.intercepts include.intercepts <- control$include.intercepts order.effect <- control$order.effect object.order.effect <- control$object.order.effect penalize.order.effect.diffs <- control$penalize.order.effect.diffs penalize.order.effect.absolute <- control$penalize.order.effect.absolute if(!is.logical(penalize.X)){ if(all(penalize.X %in% get.design$vars.X)){ which.pen.X <- rep(FALSE,get.design$p.X) which.pen.X[which(get.design$vars.X %in% penalize.X)] <- TRUE penalize.X <- TRUE }else{ stop("The argument penalize.X must either be logical or a character vector containing variable names of X which should be penalized!") } }else{ which.pen.X <- rep(TRUE,get.design$p.X) } if(!is.logical(penalize.Z1.absolute)){ if(all(penalize.Z1.absolute %in% get.design$vars.Z1)){ which.pen.Z1.absolute <- rep(FALSE,get.design$p.Z1) which.pen.Z1.absolute[which(get.design$vars.Z1 %in% penalize.Z1.absolute)] <- TRUE penalize.Z1.absolute <- TRUE }else{ stop("The argument penalize.Z1.absolute must either be logical or a character vector containing variable names of Z1 which should be penalized with respect to absolute values!") } }else{ which.pen.Z1.absolute <- rep(TRUE,get.design$p.Z1) } if(!is.logical(penalize.Z1.diffs)){ if(all(penalize.Z1.diffs %in% get.design$vars.Z1)){ which.pen.Z1.diffs <- rep(FALSE,get.design$p.Z1) which.pen.Z1.diffs[which(get.design$vars.Z1 %in% penalize.Z1.diffs)] <- TRUE penalize.Z1.diffs <- TRUE }else{ stop("The argument penalize.Z1.diffs must either be logical or a character vector containing variable names of Z1 which should be penalized with respect to absolute differences!") } }else{ which.pen.Z1.diffs <- rep(TRUE,get.design$p.Z1) } if(!is.logical(penalize.Z2)){ if(all(penalize.Z2 %in% get.design$vars.Z2)){ which.pen.Z2 <- rep(FALSE,get.design$p.Z2) which.pen.Z2[which(get.design$vars.Z2 %in% penalize.Z2)] <- TRUE penalize.Z2 <- TRUE }else{ stop("The argument penalize.Z2 must either be logical or a character vector containing variable names of Z2 which should be penalized!") } }else{ which.pen.Z2 <- rep(TRUE,get.design$p.Z2) } n.intercepts <- 0 par.names.intercepts <- c() if (include.intercepts) { n.intercepts <- m - 1 par.names.intercepts <- object.names[1:(m - 1)] } n.order <- 0 if (order.effect) { n.order <- 1 } if (object.order.effect) { n.order <- m } numpen.intercepts <- numpen.X <- numpen.Z1 <- numpen.Z2 <- numpen.order <- 0 p.X <- p.Z1 <- p.Z2 <- 0 if (include.intercepts & penalize.intercepts) { acoefs.intercepts <- diag(m - 1) help.pen <- matrix(0, ncol = choose(m - 1, 2), nrow = m - 1) combis <- combn(m - 1, 2) for (ff in 1:ncol(combis)) { help.pen[combis[1, ff], ff] <- 1 help.pen[combis[2, ff], ff] <- -1 } acoefs.intercepts <- cbind(acoefs.intercepts, help.pen) numpen.intercepts <- ncol(acoefs.intercepts) } if (!is.null(X)) { p.X <- ncol(X) if (penalize.X) { acoefs.X <- diag(x = as.numeric(rep(which.pen.X,each=m-1)), p.X * (m - 1)) help.pen <- help.pen2 <- matrix(0, ncol = choose(m - 1, 2), nrow = m - 1) combis <- combn(m - 1, 2) for (ff in 1:ncol(combis)) { help.pen[combis[1, ff], ff] <- 1 help.pen[combis[2, ff], ff] <- -1 } for (pp in 1:p.X) { m.above <- matrix(rep(matrix(0, ncol = choose(m - 1, 2), nrow = m - 1), pp - 1), ncol = choose(m - 1, 2)) m.below <- matrix(rep(matrix(0, ncol = choose(m - 1, 2), nrow = m - 1), p.X - pp), ncol = choose(m - 1, 2)) if(which.pen.X[pp]){ acoefs.X <- cbind(acoefs.X, rbind(m.above, help.pen, m.below)) }else{ acoefs.X <- cbind(acoefs.X, rbind(m.above, help.pen2, m.below)) } } acoefs.X <- acoefs.X[,colSums(abs(acoefs.X))>0, drop = FALSE] numpen.X <- ncol(acoefs.X) } } if (!is.null(Z1)) { p.Z1 <- ncol(Z1)/m if (penalize.Z1.diffs | penalize.Z1.absolute) { acoefs.Z1 <- c() if (penalize.Z1.absolute) { acoefs.Z1 <- diag(x = as.numeric(rep(which.pen.Z1.absolute,each=m)), p.Z1 * m) } if (penalize.Z1.diffs) { help.pen <- help.pen2 <- matrix(0, ncol = choose(m, 2), nrow = m) combis <- combn(m, 2) for (ff in 1:ncol(combis)) { help.pen[combis[1, ff], ff] <- 1 help.pen[combis[2, ff], ff] <- -1 } for (pp in 1:p.Z1) { m.above <- matrix(rep(matrix(0, ncol = choose(m, 2), nrow = m), pp - 1), ncol = choose(m, 2)) m.below <- matrix(rep(matrix(0, ncol = choose(m, 2), nrow = m), p.Z1 - pp), ncol = choose(m, 2)) if(which.pen.Z1.diffs[pp]){ acoefs.Z1 <- cbind(acoefs.Z1, rbind(m.above, help.pen, m.below)) }else{ acoefs.Z1 <- cbind(acoefs.Z1, rbind(m.above, help.pen2, m.below)) } } } acoefs.Z1 <- acoefs.Z1[,colSums(abs(acoefs.Z1))>0, drop = FALSE] numpen.Z1 <- ncol(acoefs.Z1) } } if (!is.null(Z2)) { p.Z2 <- ncol(Z2)/m if (penalize.Z2) { acoefs.Z2 <- diag(x = as.numeric(which.pen.Z2), p.Z2) acoefs.Z2 <- acoefs.Z2[,colSums(abs(acoefs.Z2))>0, drop = FALSE] numpen.Z2 <- ncol(acoefs.Z2) } } if (order.effect & penalize.order.effect.absolute) { acoefs.order <- matrix(1, ncol = 1, nrow = 1) numpen.order <- 1 } if (object.order.effect & (penalize.order.effect.diffs | penalize.order.effect.absolute)) { acoefs.order <- c() if (penalize.order.effect.absolute) { acoefs.order <- diag(m) } if (penalize.order.effect.diffs) { help.pen <- matrix(0, ncol = choose(m, 2), nrow = m) combis <- combn(m, 2) for (ff in 1:ncol(combis)) { help.pen[combis[1, ff], ff] <- 1 help.pen[combis[2, ff], ff] <- -1 } acoefs.order <- cbind(acoefs.order, help.pen) } numpen.order <- ncol(acoefs.order) } numpen <- numpen.intercepts + numpen.X + numpen.Z1 + numpen.Z2 + numpen.order acoefs <- matrix(0, ncol = numpen, nrow = n.intercepts + p.X * (m - 1) + p.Z1 * m + p.Z2 + n.order) current.row <- 1 current.col <- 1 if (n.order > 0) { if (numpen.order > 0) { acoefs[current.row:(current.row + n.order - 1), current.col:(current.col + numpen.order - 1)] <- acoefs.order } current.row <- current.row + n.order current.col <- current.col + numpen.order } if (include.intercepts) { if (penalize.intercepts) { acoefs[current.row:(current.row + m - 2), current.col:(current.col + numpen.intercepts - 1)] <- acoefs.intercepts } current.row <- current.row + m - 1 current.col <- current.col + numpen.intercepts } if (!is.null(X)) { if (penalize.X) { acoefs[current.row:(current.row + p.X * (m - 1) - 1), current.col:(current.col + numpen.X - 1)] <- acoefs.X } current.row <- current.row + p.X * (m - 1) current.col <- current.col + numpen.X } if (!is.null(Z1)) { if (penalize.Z1.diffs | penalize.Z1.absolute) { acoefs[current.row:(current.row + p.Z1 * m - 1), current.col:(current.col + numpen.Z1 - 1)] <- acoefs.Z1 } current.row <- current.row + p.Z1 * m current.col <- current.col + numpen.Z1 } if (!is.null(Z2)) { if (penalize.Z2) { acoefs[current.row:(current.row + p.Z2 - 1), current.col:(current.col + numpen.Z2 - 1)] <- acoefs.Z2 } current.row <- current.row + p.Z2 current.col <- current.col + numpen.Z2 } acoefs <- rbind(matrix(0, nrow = floor(q/2), ncol = ncol(acoefs)), acoefs) RET <- list(acoefs = acoefs, numpen.intercepts = numpen.intercepts, numpen.X = numpen.X, numpen.Z1 = numpen.Z1, numpen.Z2 = numpen.Z2, numpen.order = numpen.order, n.order = n.order, p.X = p.X, p.Z1 = p.Z1, p.Z2 = p.Z2, weight.penalties = control$weight.penalties) return(RET) }
.trim <- function(x) gsub("^\\s+|\\s+$", "", x) .safe_deparse <- function(string) { paste0(sapply(deparse(string, width.cutoff = 500), .trim, simplify = TRUE), collapse = "") } .select_rows <- function(data, variable, value) { data[which(data[[variable]] == value), ] } .select_nums <- function(x) { x[unlist(lapply(x, is.numeric))] } .get_direction <- function(direction) { if (length(direction) > 1) warning("Using first 'direction' value.") if (is.numeric(direction[1])) { return(sign(direction[1])) } Value <- c( "left" = -1, "right" = 1, "two-sided" = 0, "twosided" = 0, "one-sided" = 1, "onesided" = 1, "<" = -1, ">" = 1, "=" = 0, "==" = 0, "-1" = -1, "0" = 0, "1" = 1, "+1" = 1 ) direction <- Value[tolower(direction[1])] if (is.na(direction)) { stop("Unrecognized 'direction' argument.") } direction } .prepare_output <- function(temp, cleaned_parameters, is_stan_mv = FALSE, is_brms_mv = FALSE) { if (isTRUE(is_stan_mv)) { temp$Response <- gsub("(b\\[)*(.*)\\|(.*)", "\\2", temp$Parameter) for (i in unique(temp$Response)) { temp$Parameter <- gsub(sprintf("%s|", i), "", temp$Parameter, fixed = TRUE) } merge_by <- c("Parameter", "Effects", "Component", "Response") remove_cols <- c("Group", "Cleaned_Parameter", "Function", ".roworder") } else if (isTRUE(is_brms_mv)) { temp$Response <- gsub("(.*)_(.*)_(.*)", "\\2", temp$Parameter) merge_by <- c("Parameter", "Effects", "Component", "Response") remove_cols <- c("Group", "Cleaned_Parameter", "Function", ".roworder") } else { merge_by <- c("Parameter", "Effects", "Component") remove_cols <- c("Group", "Cleaned_Parameter", "Response", "Function", ".roworder") } merge_by <- intersect(merge_by, colnames(temp)) temp$.roworder <- 1:nrow(temp) out <- merge(x = temp, y = cleaned_parameters, by = merge_by, all.x = TRUE) if ((isTRUE(is_stan_mv) || isTRUE(is_brms_mv)) && all(is.na(out$Effects)) && all(is.na(out$Component))) { out$Effects <- cleaned_parameters$Effects[1:nrow(out)] out$Component <- cleaned_parameters$Component[1:nrow(out)] } if (all(is.na(out$Effects)) || all(is.na(out$Component))) { out <- out[!duplicated(out$.roworder), ] } else { out <- out[!is.na(out$Effects) & !is.na(out$Component) & !duplicated(out$.roworder), ] } attr(out, "Cleaned_Parameter") <- out$Cleaned_Parameter[order(out$.roworder)] datawizard::data_remove(out[order(out$.roworder), ], remove_cols) } .merge_and_sort <- function(x, y, by, all) { if (is.null(ncol(y))) { return(x) } x$.rowid <- 1:nrow(x) x <- merge(x, y, by = by, all = all) datawizard::data_remove(x[order(x$.rowid), ], ".rowid") } .group_vars <- function(x) { grps <- attr(x, "groups", exact = TRUE) if (is.null(grps)) { attr(x, "vars", exact = TRUE) } else { setdiff(colnames(grps), ".rows") } } .is_baysian_emmeans <- function(x) { if (inherits(x, "emm_list")) { x <- x[[1]] } post.beta <- methods::slot(x, "post.beta") !(all(dim(post.beta) == 1) && is.na(post.beta)) } .add_clean_parameters_attribute <- function(params, model) { cp <- tryCatch( { insight::clean_parameters(model) }, error = function(e) { NULL } ) attr(params, "clean_parameters") <- cp params } .n_unique <- function(x, na.rm = TRUE) { if (is.null(x)) { return(0) } if (isTRUE(na.rm)) x <- stats::na.omit(x) length(unique(x)) }
fluidPage(theme = 'zoo.css', fluidRow( tags$b("If you identify any problem in iSTATS or need some help, please contact us at: [email protected]" ), br(), tags$b("Or in github page" ), tags$a(href="https://github.com/vitor-mendes-iq/iSTATS/issues", "Click here!") ) )
function.Minimax <- function(data, marker, status, tag.healthy = 0, direction = c("<", ">"), control = control.cutpoints(), pop.prev, ci.fit = FALSE, conf.level = 0.95, measures.acc){ direction <- match.arg(direction) if (is.logical(control$maxSp) == FALSE) { stop("'maxSp' must be a logical-type argument.", call. = FALSE) } FN <-(1-measures.acc$Se[,1])*length(data[data[,status] != tag.healthy, marker]) FP <-(1-measures.acc$Sp[,1])*length(data[data[,status] == tag.healthy, marker]) M <- vector() for(i in 1:length(measures.acc$cutoffs)) { if (FN[i] > FP[i]) { M[i] <- FN[i] } else { M[i] <- FP[i] } } cMinimax <- measures.acc$cutoffs[which(round(M,10) == round(min(M,na.rm=TRUE),10))] if (length(cMinimax)> 1) { if(control$maxSp == TRUE) { Spnew <- obtain.optimal.measures(cMinimax, measures.acc)$Sp cutpointsSpnew <- cMinimax[which(round(Spnew[,1],10) == round(max(Spnew[,1],na.rm=TRUE),10))] if (length(cutpointsSpnew)> 1) { Senew <- obtain.optimal.measures(cutpointsSpnew, measures.acc)$Se cMinimax <- cutpointsSpnew[which(round(Senew[,1],10) == round(max(Senew[,1],na.rm=TRUE),10))] } if (length(cutpointsSpnew)== 1) { cMinimax <- cutpointsSpnew } } if(control$maxSp == FALSE) { Senew <- obtain.optimal.measures(cMinimax, measures.acc)$Se cutpointsSenew <- cMinimax[which(round(Senew[,1],10) == round(max(Senew[,1],na.rm=TRUE),10))] if (length(cutpointsSenew)> 1) { Spnew <- obtain.optimal.measures(cutpointsSenew, measures.acc)$Sp cMinimax <- cutpointsSenew[which(round(Spnew[,1],10) == round(max(Spnew[,1],na.rm=TRUE),10))] } if (length(cutpointsSenew)== 1) { cMinimax <- cutpointsSenew } } } optimal.M <- min(M,na.rm=TRUE) optimal.cutoff <- obtain.optimal.measures(cMinimax, measures.acc) res <- list(measures.acc = measures.acc, optimal.cutoff = optimal.cutoff, criterion = M, optimal.criterion = optimal.M) res }
context("ECOS suite Tests")
context( 'na.true') test_that( "na.true", { v <- c(T,NA,F) na.true(v) ->.; expect_equal( ., c(T,T,F) ) na.false(v) ->.; expect_equal( ., c(T,F,F) ) v <- c( 'a',NA_character_,'c' ) na.true(v) ->.; expect_equal(., c('a','TRUE','c') ) na.false(v) ->.; expect_equal(., c('a','FALSE','c') ) v <- c(1,NA_integer_,3) na.true(v) ->.; expect_equal(., c(1,1,3)) na.false(v) ->.; expect_equal(., c(1,0,3) ) })
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(caret) library(FSinR) data(iris) evaluator <- wrapperEvaluator("knn") searcher <- searchAlgorithm('sequentialForwardSelection') results <- featureSelection(iris, 'Species', searcher, evaluator) results$bestFeatures results$bestValue evaluator <- filterEvaluator('MDLC') searcher <- searchAlgorithm('sequentialForwardSelection') results <- featureSelection(iris, 'Species', searcher, evaluator) results$bestFeatures results$bestValue filter_evaluator <- filterEvaluator("IEConsistency") wrapper_evaluator <- wrapperEvaluator("lvq") resultFilter <- filter_evaluator(iris, 'Species', c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")) resultFilter resultWrapper <- wrapper_evaluator(iris, 'Species', c("Petal.Length", "Petal.Width")) resultWrapper library(caret) library(FSinR) data(mtcars) evaluator <- filterEvaluator('determinationCoefficient') directSearcher <- directSearchAlgorithm('selectKBest', list(k=3)) results <- directFeatureSelection(mtcars, 'mpg', directSearcher, evaluator) results$bestFeatures results$featuresSelected results$valuePerFeature library(caret) library(FSinR) data(mtcars) evaluator_1 <- filterEvaluator('determinationCoefficient') evaluator_2 <- filterEvaluator('ReliefFeatureSetMeasure') hybridSearcher <- hybridSearchAlgorithm('LCC') results <- hybridFeatureSelection(mtcars, 'mpg', hybridSearcher, evaluator_1, evaluator_2) results$bestFeatures results$bestValue
parse_event_content <- function(event, config) { if (!is.null(config$deserialiser)) { return(config$deserialiser(event$event_content)) } UseMethod("parse_event_content") } parse_event_content.default <- function(event, ...) { parse_json_or_empty(event$event_content) }
.geoR.env <- new.env() "variofit" <- function (vario, ini.cov.pars, cov.model, fix.nugget = FALSE, nugget = 0, fix.kappa = TRUE, kappa = 0.5, simul.number = NULL, max.dist = vario$max.dist, weights, minimisation.function, limits = pars.limits(), messages, ...) { call.fc <- match.call() if(missing(messages)) messages.screen <- as.logical(ifelse(is.null(getOption("geoR.messages")), TRUE, getOption("geoR.messages"))) else messages.screen <- messages if(length(class(vario)) == 0 || all(class(vario) != "variogram")) warning("object vario should preferably be of the geoR's class \"variogram\"") if(!missing(ini.cov.pars)){ if(any(class(ini.cov.pars) == "eyefit")) cov.model <- ini.cov.pars[[1]]$cov.model if(any(class(ini.cov.pars) == "variomodel")) cov.model <- ini.cov.pars$cov.model } if(missing(cov.model)) cov.model <- "matern" cov.model <- match.arg(cov.model, choices = .geoR.cov.models) if(cov.model == "stable") cov.model <- "powered.exponential" if(cov.model == "powered.exponential") if(limits$kappa["upper"] > 2) limits$kappa["upper"] <- 2 if(missing(weights)){ if(vario$output.type == "cloud") weights <- "equal" else weights <- "npairs" } else weights <- match.arg(weights, choices = c("npairs", "equal", "cressie")) if(messages.screen){ cat(paste("variofit: covariance model used is", cov.model, "\n")) cat(paste("variofit: weights used:", weights, "\n")) } if(missing(minimisation.function)) minimisation.function <- "optim" if(any(cov.model == c("linear", "power")) & minimisation.function == "nls"){ cat("warning: minimisation function nls can not be used with given cov.model.\n changing for \"optim\".\n") minimisation.function <- "optim" } if(minimisation.function == "nls" & weights != "equal"){ warning("variofit: minimisation function nls can only be used with weights=\"equal\".\n changing for \"optim\".\n") minimisation.function <- "optim" } if (is.matrix(vario$v) & is.null(simul.number)) stop("object in vario$v is a matrix. This function works for only 1 empirical variogram at once\n") if (!is.null(simul.number)) vario$v <- vario$v[, simul.number] if(mode(max.dist) != "numeric" || length(max.dist) > 1) stop("a single numerical value must be provided in the argument max.dist") if (max.dist == vario$max.dist) XY <- list(u = vario$u, v = vario$v, n=vario$n) else XY <- list(u = vario$u[vario$u <= max.dist], v = vario$v[vario$u <= max.dist], n = vario$n[vario$u <= max.dist]) if(cov.model == "pure.nugget"){ minimisation.function <- "not used" message <- "correlation function does not require numerical minimisation" if(weights == "equal") lm.wei <- rep(1, length(XY$u)) else lm.wei <- XY$n if(cov.model == "pure.nugget"){ if(fix.nugget){ temp <- lm((XY$v-nugget) ~ 1, weights = lm.wei) cov.pars <- c(temp$coef, 0) } else{ temp <- lm(XY$v ~ 1, weights = lm.wei) nugget <- temp$coef cov.pars <- c(0,0) } } value <- sum((temp$residuals)^2) } else{ if(messages.screen) cat(paste("variofit: minimisation function used:", minimisation.function, "\n")) umax <- max(vario$u) vmax <- max(vario$v) if(missing(ini.cov.pars)){ ini.cov.pars <- as.matrix(expand.grid(c(vmax/2, 3*vmax/4, vmax), seq(0, 0.8*umax, len=6))) if(!fix.nugget) nugget <- unique(c(nugget, vmax/10, vmax/4, vmax/2)) if(!fix.kappa) kappa <- unique(c(kappa, 0.25, 0.5, 1, 1.5, 2)) if(messages.screen) warning("initial values not provided - running the default search") } else{ if(any(class(ini.cov.pars) == "eyefit")){ init <- nugget <- kappa <- NULL for(i in 1:length(ini.cov.pars)){ init <- drop(rbind(init, ini.cov.pars[[i]]$cov.pars)) nugget <- c(nugget, ini.cov.pars[[i]]$nugget) if(cov.model == "gneiting.matern") kappa <- drop(rbind(kappa, ini.cov.pars[[i]]$kappa)) else kappa <- c(kappa, ini.cov.pars[[i]]$kappa) } ini.cov.pars <- init } if(any(class(ini.cov.pars) == "variomodel")){ nugget <- ini.cov.pars$nugget kappa <- ini.cov.pars$kappa ini.cov.pars <- ini.cov.pars$cov.pars } } if(is.matrix(ini.cov.pars) | is.data.frame(ini.cov.pars)){ ini.cov.pars <- as.matrix(ini.cov.pars) if(nrow(ini.cov.pars) == 1) ini.cov.pars <- as.vector(ini.cov.pars) else{ if(ncol(ini.cov.pars) != 2) stop("\nini.cov.pars must be a matrix or data.frame with 2 components: \ninitial values for sigmasq (partial sill) and phi (range parameter)\n") } } else if(length(ini.cov.pars) > 2) stop("\nini.cov.pars must provide initial values for sigmasq and phi\n") if(is.matrix(ini.cov.pars) | (length(nugget) > 1) | (length(kappa) > 1)) { if(messages.screen) cat("variofit: searching for best initial value ...") ini.temp <- matrix(ini.cov.pars, ncol=2) grid.ini <- as.matrix(expand.grid(sigmasq=unique(ini.temp[,1]), phi=unique(ini.temp[,2]), tausq=unique(nugget), kappa=unique(kappa))) v.loss <- function(parms, u, v, n, cov.model, weights){ sigmasq <- parms[1] phi <- parms[2] if(cov.model == "power") phi <- 2 * exp(phi)/(1+exp(phi)) tausq <- parms[3] kappa <- parms[4] if(cov.model == "power") v.mod <- tausq + cov.spatial(u, cov.pars=c(sigmasq, phi), cov.model="power", kappa=kappa) else v.mod <- (sigmasq + tausq) - cov.spatial(u, cov.pars=c(sigmasq, phi), cov.model = cov.model, kappa = kappa) if(weights == "equal") loss <- sum((v - v.mod)^2) if (weights == "npairs") loss <- sum(n * (v - v.mod)^2) if (weights == "cressie") loss <- sum((n/(v.mod^2)) * (v - v.mod)^2) return(loss) } grid.loss <- apply(grid.ini, 1, v.loss, u=XY$u, v=XY$v, n=XY$n, cov.model = cov.model, weights = weights) ini.temp <- grid.ini[which(grid.loss == min(grid.loss))[1],, drop=FALSE] if(is.R()) rownames(ini.temp) <- "initial.value" if(messages.screen){ cat(" selected values:\n") print(rbind(round(ini.temp, digits=2), status=ifelse(c(FALSE, FALSE, fix.nugget, fix.kappa), "fix", "est"))) cat(paste("loss value:", min(grid.loss), "\n")) } names(ini.temp) <- NULL ini.cov.pars <- ini.temp[1:2] nugget <- ini.temp[3] kappa <- ini.temp[4] grid.ini <- NULL } if(ini.cov.pars[1] > 2*vmax) warning("unreasonable initial value for sigmasq (too high)") if(ini.cov.pars[1] + nugget > 3*vmax) warning("unreasonable initial value for sigmasq + nugget (too high)") if(vario$output.type != "cloud"){ if(ini.cov.pars[1] + nugget < 0.3*vmax) warning("unreasonable initial value for sigmasq + nugget (too low)") } if(nugget > 2*vmax) warning("unreasonable initial value for nugget (too high)") if(ini.cov.pars[2] > 1.5*umax) warning("unreasonable initial value for phi (too high)") if(!fix.kappa){ if(cov.model == "powered.exponential") Tkappa.ini <- log(kappa/(2-kappa)) else Tkappa.ini <- log(kappa) } if (minimisation.function == "nls") { if(ini.cov.pars[2] == 0) ini.cov.pars <- max(XY$u)/10 if(kappa == 0) kappa <- 0.5 if(cov.model == "power") Tphi.ini <- log(ini.cov.pars[2]/(2-ini.cov.pars[2])) else Tphi.ini <- log(ini.cov.pars[2]) XY$cov.model <- cov.model if (fix.nugget) { XY$nugget <- as.vector(nugget) if(fix.kappa){ XY$kappa <- as.vector(kappa) res <- nls((v-nugget) ~ matrix((1-cov.spatial(u,cov.pars=c(1,exp(Tphi)), cov.model=cov.model, kappa=kappa)), ncol=1), start=list(Tphi=Tphi.ini), data=XY, algorithm="plinear", ...) } else{ if(cov.model == "powered.exponential") res <- nls((v-nugget) ~ matrix((1-cov.spatial(u,cov.pars=c(1,exp(Tphi)), cov.model=cov.model, kappa=(2*exp(Tkappa)/(1+exp(Tkappa))))), ncol=1), start=list(Tphi=Tphi.ini, Tkappa = Tkappa.ini), data=XY, algorithm="plinear", ...) else res <- nls((v-nugget) ~ matrix((1-cov.spatial(u,cov.pars=c(1,exp(Tphi)), cov.model=cov.model, kappa=exp(Tkappa))), ncol=1), start=list(Tphi=Tphi.ini, Tkappa = Tkappa.ini), data=XY, algorithm="plinear", ...) kappa <- exp(coef(res)["Tkappa"]) names(kappa) <- NULL } cov.pars <- coef(res)[c(".lin", "Tphi")] names(cov.pars) <- NULL } else{ if(fix.kappa){ XY$kappa <- kappa res <- nls(v ~ cbind(1,(1- cov.spatial(u, cov.pars=c(1,exp(Tphi)), cov.model = cov.model, kappa=kappa))), start=list(Tphi=Tphi.ini), algorithm="plinear", data=XY, ...) } else{ if(cov.model == "powered.exponential") res <- nls(v ~ cbind(1, (1-cov.spatial(u, cov.pars=c(1, exp(Tphi)), cov.model = cov.model, kappa=(2*exp(Tkappa)/(1+exp(Tkappa)))))), start=list(Tphi=Tphi.ini, Tkappa = Tkappa.ini), algorithm="plinear", data=XY, ...) else res <- nls(v ~ cbind(1, (1-cov.spatial(u, cov.pars=c(1, exp(Tphi)), cov.model = cov.model, kappa=exp(Tkappa)))), start=list(Tphi=Tphi.ini, Tkappa = Tkappa.ini), algorithm="plinear", data=XY, ...) kappa <- exp(coef(res)["Tkappa"]);names(kappa) <- NULL } nugget <- coef(res)[".lin1"];names(nugget) <- NULL cov.pars <- coef(res)[c(".lin2", "Tphi")] names(cov.pars) <- NULL } if(cov.model == "power") cov.pars[2] <- 2 * exp(cov.pars[2])/(1+exp(cov.pars[2])) else cov.pars[2] <- exp(cov.pars[2]) if(nugget < 0 | cov.pars[1] < 0){ warning("\nvariofit: negative variance parameter found using the default option \"nls\".\n Try another minimisation function and/or fix some of the parameters.\n") temp <- c(sigmasq=cov.pars[1], phi=cov.pars[2], tausq=nugget, kappa=kappa) print(rbind(round(temp, digits=4), status=ifelse(c(FALSE, FALSE, fix.nugget, fix.kappa), "fix", "est"))) return(invisible()) } value <- sum(resid(res)^2) message <- "nls does not provides convergence message" } if (minimisation.function == "nlm" | minimisation.function == "optim") { .global.list <- list(u = XY$u, v = XY$v, n=XY$n, fix.nugget = fix.nugget, nugget = nugget, fix.kappa = fix.kappa, kappa = kappa, cov.model = cov.model, m.f = minimisation.function, weights = weights) ini <- ini.cov.pars if(cov.model == "power") ini[2] <- log(ini[2]/(2-ini[2])) if(cov.model == "linear") ini <- ini[1] if(fix.nugget == FALSE) ini <- c(ini, nugget) if(!fix.kappa) ini <- c(ini, Tkappa.ini) names(ini) <- NULL if(minimisation.function == "nlm"){ result <- nlm(.loss.vario, ini, g.l = .global.list, ...) result$par <- result$estimate result$value <- result$minimum result$convergence <- result$code if(!is.null(get(".temp.theta", pos=.geoR.env))) result$par <- get(".temp.theta", pos=.geoR.env) } else{ lower.l <- sapply(limits, function(x) x[1]) upper.l <- sapply(limits, function(x) x[2]) if(fix.kappa == FALSE){ if(fix.nugget){ lower <- lower.l[c("sigmasq.lower", "phi.lower","kappa.lower")] upper <- upper.l[c("sigmasq.upper", "phi.upper","kappa.upper")] } else{ lower <- lower.l[c("sigmasq.lower", "phi.lower", "tausq.rel.lower", "kappa.lower")] upper <- upper.l[c("sigmasq.upper", "phi.upper", "tausq.rel.upper", "kappa.upper")] } } else{ if(cov.model == "power"){ if(fix.nugget){ lower <- lower.l[c("sigmasq.lower", "phi.lower")] upper <- upper.l[c("sigmasq.upper", "phi.upper")] } else{ lower <- lower.l[c("sigmasq.lower", "phi.lower", "tausq.rel.lower")] upper <- upper.l[c("sigmasq.upper", "phi.upper", "tausq.rel.upper")] } } else{ lower <- lower.l["phi.lower"] upper <- upper.l["phi.upper"] } } result <- optim(ini, .loss.vario, method = "L-BFGS-B", hessian = TRUE, lower = lower, upper = upper, g.l = .global.list, ...) } value <- result$value message <- paste(minimisation.function, "convergence code:", result$convergence) if(cov.model == "linear") result$par <- c(result$par[1],1,result$par[-1]) cov.pars <- as.vector(result$par[1:2]) if(cov.model == "power") cov.pars[2] <- 2 * exp(cov.pars[2])/(1+exp(cov.pars[2])) if(!fix.kappa){ if (fix.nugget) kappa <- result$par[3] else{ nugget <- result$par[3] kappa <- result$par[4] } if(.global.list$cov.model == "powered.exponential") kappa <- 2*(exp(kappa))/(1+exp(kappa)) else kappa <- exp(kappa) } else if(!fix.nugget) nugget <- result$par[3] } } estimation <- list(nugget = nugget, cov.pars = cov.pars, cov.model = cov.model, kappa = kappa, value = value, trend = vario$trend, beta.ols = vario$beta.ols, practicalRange = practicalRange(cov.model=cov.model, phi = cov.pars[2], kappa = kappa), max.dist = max.dist, minimisation.function = minimisation.function) estimation$weights <- weights if(weights == "equal") estimation$method <- "OLS" else estimation$method <- "WLS" estimation$fix.nugget <- fix.nugget estimation$fix.kappa <- fix.kappa estimation$lambda <- vario$lambda estimation$message <- message estimation$call <- call.fc oldClass(estimation) <- c("variomodel", "variofit") return(estimation) } ".loss.vario" <- function (theta, g.l) { if(g.l$cov.model == "linear") theta <- c(theta[1], 1, theta[-1]) if(g.l$m.f == "nlm"){ assign(".temp.theta", NULL, pos=.geoR.env) if(!g.l$fix.kappa){ if(g.l$fix.nugget){ if(g.l$cov.model == "power") theta.minimiser <- theta[1] else theta.minimiser <- theta[1:2] Tkappa <- theta[3] } else{ if(g.l$cov.model == "power") theta.minimiser <- theta[c(1:3)] else theta.minimiser <- theta[1:3] Tkappa <- theta[4] } } else theta.minimiser <- theta penalty <- 10000 * sum(0 - pmin(theta.minimiser, 0)) theta <- pmax(theta.minimiser, 0) if(!g.l$fix.kappa) theta <- c(theta.minimiser, Tkappa) if (any(theta.minimiser < 0)){ assign(".temp.theta", theta, pos=.geoR.env) } else penalty <- 0 } else penalty <- 0 if(!g.l$fix.kappa){ if (g.l$fix.nugget){ tausq <- g.l$nugget Tkappa <- theta[3] } else{ tausq <- theta[3] Tkappa <- theta[4] } if(g.l$cov.model == "powered.exponential") kappa <- 2*(exp(Tkappa))/(1+exp(Tkappa)) else kappa <- exp(Tkappa) } else{ kappa <- g.l$kappa if (g.l$fix.nugget) tausq <- g.l$nugget else tausq <- theta[3] } sigmasq <- theta[1] phi <- theta[2] if(g.l$cov.model == "power") phi <- 2 * exp(phi)/(1+exp(phi)) sill.total <- sigmasq + tausq if(any(g.l$cov.model == c("linear", "power"))) gammaU <- tausq + sigmasq * (g.l$u^phi) else gammaU <- sill.total - cov.spatial(g.l$u, cov.model = g.l$cov.model, kappa = kappa, cov.pars = c(sigmasq, phi)) if(g.l$weight == "equal") loss <- sum((g.l$v - gammaU)^2) if (g.l$weights == "npairs") loss <- sum(g.l$n * (g.l$v - gammaU)^2) if (g.l$weights == "cressie") loss <- sum((g.l$n/(gammaU^2)) * (g.l$v - gammaU)^2) if(loss > (.Machine$double.xmax^0.5) | loss == Inf | loss == -Inf | is.nan(loss)) loss <- .Machine$double.xmax^0.5 return(loss + penalty) } "print.variofit" <- function(x, digits = "default", ...) { if(is.R() & digits == "default") digits <- max(3, getOption("digits") - 3) else digits <- options()$digits if(x$fix.nugget){ est.pars <- c(sigmasq = x$cov.pars[1], phi=x$cov.pars[2]) if(x$fix.kappa == FALSE) est.pars <- c(est.pars, kappa = x$kappa) } else{ est.pars <- c(tausq = x$nugget, sigmasq = x$cov.pars[1], phi=x$cov.pars[2]) if(x$fix.kappa == FALSE) est.pars <- c(est.pars, kappa = x$kappa) } if(x$weights == "equal") cat("variofit: model parameters estimated by OLS (ordinary least squares):\n") else cat("variofit: model parameters estimated by WLS (weighted least squares):\n") cat(paste("covariance model is:", x$cov.model)) if(any(x$cov.model == c("matern", "powered.exponential", "cauchy", "gencauchy", "gneiting.matern"))) if(x$fix.kappa) cat(paste(" with fixed kappa =", x$kappa)) if(x$cov.model == "matern" & x$fix.kappa & x$kappa == 0.5) cat(" (exponential)") cat("\n") if(x$fix.nugget) cat(paste("fixed value for tausq = ", x$nugget,"\n")) cat("parameter estimates:\n") print(round(est.pars, digits=digits)) cat(paste("Practical Range with cor=0.05 for asymptotic range:", format(x$practicalRange, ...))) cat("\n") if(x$weights == "equal") cat("\nvariofit: minimised sum of squares = ") else cat("\nvariofit: minimised weighted sum of squares = ") cat(round(x$value, digits=digits)) cat("\n") return(invisible()) } "summary.variofit" <- function(object, ...) { summ.lik <- list() if(object$weights == "equal") summ.lik$pmethod <- "OLS (ordinary least squares)" else summ.lik$pmethod <- "WLS (weighted least squares)" summ.lik$cov.model <- object$cov.model summ.lik$spatial.component <- c(sigmasq = object$cov.pars[1], phi=object$cov.pars[2]) summ.lik$spatial.component.extra <- c(kappa = object$kappa) summ.lik$nugget.component <- c(tausq = object$nugget) summ.lik$fix.nugget <- object$fix.nugget summ.lik$fix.kappa <- object$fix.kappa summ.lik$practicalRange <- object$practicalRange summ.lik$sum.of.squares <- c(value = object$value) if(object$fix.nugget){ summ.lik$estimated.pars <- c(sigmasq = object$cov.pars[1], phi=object$cov.pars[2]) if(object$fix.kappa == FALSE) summ.lik$estimated.pars <- c(summ.lik$estimated.pars, kappa = object$kappa) } else{ summ.lik$estimated.pars <- c(tausq = object$nugget, sigmasq = object$cov.pars[1], phi=object$cov.pars[2]) if(object$fix.kappa == FALSE) summ.lik$estimated.pars <- c(summ.lik$estimated.pars, kappa = object$kappa) } summ.lik$weights <- object$weights summ.lik$call <- object$call oldClass(summ.lik) <- "summary.variomodel" return(summ.lik) } "print.summary.variofit" <- function(x, digits = "default", ...) { if(length(class(x)) == 0 || all(class(x) != "summary.variomodel")) stop("object is not of the class \"summary.variomodel\"") if(is.R() & digits == "default") digits <- max(3, getOption("digits") - 3) else digits <- options()$digits cat("Summary of the parameter estimation\n") cat("-----------------------------------\n") cat(paste("Estimation method:", x$pmethod, "\n")) cat("\n") cat("Parameters of the spatial component:") cat("\n") cat(paste(" correlation function:", x$cov.model)) if(x$cov.model == "matern" & x$fix.kappa & x$spatial.component.extra == 0.5) cat(" (exponential)") if(any(x$cov.model == c("matern", "powered.exponential", "cauchy", "gencauchy", "gneiting.matern"))){ if(x$fix.kappa) cat(paste("\n (fixed) extra parameter kappa = ", round(x$spatial.component.extra, digits=digits))) else cat(paste("\n (estimated) extra parameter kappa = ", round(x$spatial.component.extra, digits=digits))) } cat(paste("\n (estimated) variance parameter sigmasq (partial sill) = ", round(x$spatial.component[1], digits=digits))) cat(paste("\n (estimated) cor. fct. parameter phi (range parameter) = ", round(x$spatial.component[2], digits=digits))) cat("\n") cat("\n") cat("Parameter of the error component:") if(x$fix.nugget) cat(paste("\n (fixed) nugget =", round(x$nugget.component, digits = digits))) else cat(paste("\n (estimated) nugget = ", round(x$nugget.component, digits=digits))) cat("\n") cat("\n") cat("Practical Range with cor=0.05 for asymptotic range:", format(x$practicalRange, ...)) cat("\n") cat("\n") names(x$sum.of.squares) <- NULL if(x$weights == "equal") cat("Minimised sum of squares: ") else cat("Minimised weighted sum of squares: ") cat(round(x$sum.of.squares, digits=digits)) cat("\n") cat("\n") cat("Call:") cat("\n") print(x$call) cat("\n") invisible(x) } "variog.model.env" <- function(geodata, coords = geodata$coords, obj.variog, model.pars, nsim = 99, save.sim = FALSE, messages) { call.fc <- match.call() obj.variog$v <- NULL if(missing(messages)) messages.screen <- as.logical(ifelse(is.null(getOption("geoR.messages")), TRUE, getOption("geoR.messages"))) else messages.screen <- messages if(any(class(model.pars) == "eyefit")){ if(length(model.pars) == 1L) model.pars <- model.pars[[1]] else stop(paste("variog.model.env: more than one variograma model in the object", deparse(substitute(model.pars)), "\n specify which i_th model in the list to be used using [[i]]")) } if(!is.null(model.pars$beta)) beta <- model.pars$beta else beta <- 0 if(!is.null(model.pars$cov.model)) cov.model <- model.pars$cov.model else cov.model <- "exponential" if(!is.null(model.pars$kappa)) kappa <- model.pars$kappa else kappa <- 0.5 if(!is.null(model.pars$nugget)) nugget <- model.pars$nugget else nugget <- 0 cov.pars <- model.pars$cov.pars if(!is.null(obj.variog$estimator.type)) estimator.type <- obj.variog$estimator.type else estimator.type <- "classical" if (obj.variog$output.type != "bin") stop("envelops can be computed only for binned variogram") if (messages.screen) cat(paste("variog.env: generating", nsim, "simulations (with ", obj.variog$n.data, "points each) using the function grf\n")) simula <- grf(obj.variog$n.data, grid = as.matrix(coords), cov.model = cov.model, cov.pars = cov.pars, nugget = nugget, kappa = kappa, nsim = nsim, messages = FALSE) if(messages.screen) cat("variog.env: adding the mean or trend\n") x.mat <- unclass(trend.spatial(trend=obj.variog$trend, geodata = geodata)) if(ncol(x.mat) != length(beta)) stop("incompatible sizes of trend matrix and beta parameter vector. Check whether the trend specification are the same in the objects passed to the arguments \"obj.vario\" and \"model.pars\"") simula$data <- as.vector(x.mat %*% beta) + simula$data if (messages.screen) cat(paste("variog.env: computing the empirical variogram for the", nsim, "simulations\n")) nbins <- length(obj.variog$bins.lim) - 1 bin.f <- function(sim){ cbin <- vbin <- sdbin <- rep(0, nbins) temp <- .C("binit", as.integer(obj.variog$n.data), as.double(as.vector(coords[,1])), as.double(as.vector(coords[,2])), as.double(as.vector(sim)), as.integer(nbins), as.double(as.vector(obj.variog$bins.lim)), as.integer(estimator.type == "modulus"), as.double(max(obj.variog$u)), as.double(cbin), vbin = as.double(vbin), as.integer(FALSE), as.double(sdbin), PACKAGE = "geoR")$vbin return(temp) } simula.bins <- apply(simula$data, 2, bin.f) simula.bins <- simula.bins[obj.variog$ind.bin,] if(exists(".IND.geoR.variog.model.env")) return(simula.bins) if(save.sim == FALSE) simula$data <- NULL if (messages.screen) cat("variog.env: computing the envelops\n") limits <- apply(simula.bins, 1, range) res.env <- list(u = obj.variog$u, v.lower = limits[1, ], v.upper = limits[2,]) if(save.sim) res.env$simulated.data <- simula$data res.env$call <- call.fc oldClass(res.env) <- "variogram.envelope" return(res.env) } "boot.variofit" <- function(geodata, coords = geodata$coords, obj.variog, model.pars, nsim = 99, trace = FALSE, messages) { call.fc <- match.call() if(missing(messages)) messages.screen <- as.logical(ifelse(is.null(getOption("geoR.messages")), TRUE, getOption("geoR.messages"))) else messages.screen <- messages if(messages.screen) cat("Computing empirical variograms for simulations\n") geoR.env <- new.env() assign(".IND.geoR.variog.model.env", TRUE, pos=geoR.env) environment(variog.model.env) <- geoR.env vmat <- variog.model.env(geodata=geodata, coords=coords, obj.variog=obj.variog, model.pars=model.pars, nsim=nsim, messages = FALSE) if(messages.screen){ cat("Fitting models (variofit) for the simulated variograms\n") cat("be patient - this can take a while to run\n") } geoR.count <- new.env() assign(".geoR.count", 1, envir=geoR.count) .vf <- function(v){ obj.variog$v <- v pars <- summary(variofit(obj.variog, messages=FALSE))$estimated.pars if(trace){ cat(paste("simulation", get(".geoR.count", envir=geoR.count), "out of", nsim, "\n")) print(pars) assign(".geoR.count", get(".geoR.count", envir=geoR.count)+1, envir=geoR.count) } return(pars) } res <- as.data.frame(t(apply(vmat, 2, .vf))) class(res) <- "boot.variofit" return(res) }
expected <- eval(parse(text="\"list\"")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(x = structure(1L, .Label = \"1.3\", class = \"factor\")), .Names = \"x\", row.names = c(NA, -1L), class = \"data.frame\"))")); .Internal(typeof(argv[[1]])); }, o=expected);
filter_trace_length <- function(eventlog, interval, percentage, reverse,...) { UseMethod("filter_trace_length") } filter_trace_length.eventlog <- function(eventlog, interval = NULL, percentage = NULL, reverse = FALSE, ...) { percentage <- deprecated_perc(percentage, ...) interval[1] <- deprecated_lower_thr(interval[1], ...) interval[2] <- deprecated_upper_thr(interval[2], ...) if(!is.null(interval) && (length(interval) != 2 || !is.numeric(interval) || any(interval < 0, na.rm = T) || all(is.na(interval)) )) { stop("Interval should be a positive numeric vector of length 2. One of the elements can be NA to create open intervals.") } if(!is.null(percentage) && (!is.numeric(percentage) || !between(percentage,0,1) )) { stop("Percentage should be a numeric value between 0 and 1.") } if(is.null(interval) & is.null(percentage)) stop("At least an interval or a percentage must be provided.") else if((!is.null(interval)) & !is.null(percentage)) stop("Cannot filter on both interval and percentage simultaneously.") else if(!is.null(percentage)) filter_trace_length_percentile(eventlog, percentage = percentage, reverse = reverse) else filter_trace_length_threshold(eventlog, lower_threshold = interval[1], upper_threshold = interval[2], reverse = reverse) } filter_trace_length.grouped_eventlog <- function(eventlog, interval = NULL, percentage = NULL, reverse = FALSE, ...) { grouped_filter(eventlog, filter_trace_length, interval, percentage, reverse, ...) } ifilter_trace_length <- function(eventlog) { ui <- miniPage( gadgetTitleBar("Filter on Trace Length"), miniContentPanel( fillCol( fillRow( radioButtons("filter_type", "Filter type:", choices = c("Interval" = "int", "Use percentile cutoff" = "percentile")), radioButtons("reverse", "Reverse filter: ", choices = c("Yes","No"), selected = "No") ), uiOutput("filter_ui") ) ) ) server <- function(input, output, session){ output$filter_ui <- renderUI({ if(input$filter_type == "int") { sliderInput("interval_slider", "Process time interval", min = min(eventlog %>% group_by_case %>% summarize(n = n_distinct(!!activity_instance_id_(eventlog))) %>% pull(n)), max = max(eventlog %>% group_by_case %>% summarize(n = n_distinct(!!activity_instance_id_(eventlog))) %>% pull(n)), value = c(-Inf,Inf), step = 1) } else if(input$filter_type == "percentile") { sliderInput("percentile_slider", "Percentile cut off:", min = 0, max = 100, value = 80) } }) observeEvent(input$done, { if(input$filter_type == "int") filtered_log <- filter_trace_length(eventlog, interval = input$interval_slider, reverse = ifelse(input$reverse == "Yes", T, F)) else if(input$filter_type == "percentile") { filtered_log <- filter_trace_length(eventlog, percentage = input$percentile_slider/100, reverse = ifelse(input$reverse == "Yes", T, F)) } stopApp(filtered_log) }) } runGadget(ui, server, viewer = dialogViewer("Filter Trace Length", height = 400)) }
mean( ~NumLaughs, data = resample(Laughter)) mean( ~NumLaughs, data = resample(Laughter)) mean( ~NumLaughs, data = resample(Laughter))
genbivunif.t<-function(N=10000, rho, print.cor=TRUE) { tol<-.Machine$double.eps^0.5 if(N<=0 | abs(N - round(N)) > tol) { stop("N must be a positive integer.") } if(rho<=-1 | rho>=1) { stop("rho can take values between -1 and 1.") } t<-polyroot(c(6*rho,-7,0,1))[1] t<-Re(t)[abs(Im(t)) < 1e-6] x<-runif(N) v2<-runif(N) u<-rbeta(n=N, shape1=1-t, shape2=1+t) y<-ifelse(v2<0.5, abs(u-x), 1-abs(1-u-x)) e.rho<-round(cor(x,y), 6) if(print.cor==TRUE) { print(paste("Specified rho is ", round(rho, 6), " and empirical rho is ", e.rho, ".", sep="")) } return(list(unif.dat=data.frame(x,y), specified.rho=round(rho,6), empirical.rho=e.rho)) }
netHTML3arrows <- function(nodeLogic=NULL, wd=NULL, names=NULL, concerto="C5"){ if(is.null(nodeLogic)){ warnings("Please insert nodeLogic.") } if(is.null(wd)){ message("HTML file is saved in default working directory.") } if(concerto != "C4" && concerto !="C5") stop("Please use select either C4 or C5 for the concerto argument.") if(is.null(wd)){ wd = getwd() } htmlfile = file.path(paste0(wd, "/maze.html")) cat("\n<html><head>",file=htmlfile) if(concerto=="C5"){ button<- cssC5() }else{ button<- cssC4() } cat("\n<html><head>",file=htmlfile) cat(button, append=TRUE, file=htmlfile) cat("\n</head>", append=TRUE, file = htmlfile) cat("\n<br>", append=TRUE, file = htmlfile) cat("\n<p align=\"center\" style=\"font-family:lucida sans unicode,lucida grande,sans-serif;font-size:20px;\"><span style=\"color: white;\">Level {{level}} out of {{t_question}}.</span></p>",append=TRUE, file = htmlfile) cat("\n<body>", append = TRUE, file = htmlfile) cat("\n<p align=\"center\" style=\"font-family:lucida sans unicode,lucida grande,sans-serif;font-size:14px;\"><font color=\"white\">To solve the puzzle, travel on every path. You can return to the same country but you can only use each path once. </font></p> ", append=TRUE, file=htmlfile) cat("\n<p align=\"center\" style=\"font-family:lucida sans unicode,lucida grande,sans-serif;font-size:14px;\"><font color=\"white\">You can only go in one direction for those paths with an arrow. </font></p>", append=TRUE, file=htmlfile) cat("\n<p align=\"center\" style=\"font-family:lucida sans unicode,lucida grande,sans-serif;font-size:14px;\"><font color=\"white\">Click on any country to begin.</font></p>", append=TRUE, file=htmlfile) o <- suppressWarnings(logicMap(nodeLogic ,base.colour=3, start.colour=9,end.colour= 9,names=names,newValue=9,default.colour=FALSE, no.label=FALSE)) o coordinates <- layout_with_dh(o) coordinates.1 <- layout.norm(coordinates) png(filename="map.png", height=1000, width=1000) plot.igraph(o, layout=layout_with_dh, vertex.shape='square', vertex.size=10, vertex.label.cex=0.5) coord. <- cbind(grconvertX(coordinates.1[, 1], "user", "device"), cbind(grconvertY(coordinates.1[, 2], "user", "device"))) coord.1 <- apply(coord., 1:2, function(x) x/1.8) dev.off() cat("\n<div align=center>", append = TRUE, file=htmlfile) cat("<div class=box>", append=TRUE, file=htmlfile) cat("\n<div style= 'position:relative;width:auto; height:auto;margin:0 auto' id = 'graphContainer'>", append=TRUE, file=htmlfile) n.name <- unlist(V(o)$name) buttons = "" for (j in 1:nrow(coord.)){ buttons <- paste0(buttons,"\n<div onClick='nodeClick(this)' id = '", j,"'", " class = 'myButton' style = 'z-index:1; left:",(coord.1[j,1]),"px;top:",(coord.1[j,2]),"px'>",n.name[j],"</div>") } cat(buttons, append=TRUE, file=htmlfile) buttons ed<- ends(o, E(o), names=FALSE) start.index <- ed[,1] start.coord <- ncol(coord.) start.coord start.node.coord <- matrix(NA, nrow = length(start.index), ncol = start.coord) for(i in 1:length(start.index)){ start.node.coord[i,]<- coord.[start.index[i],] } start.node.coord.1 <- apply(start.node.coord,1:2, function(x) x/1.8) end.index<- ed[,2] end.coord <- ncol(coord.) end.node.coord <- matrix(NA, nrow = length(end.index), ncol= end.coord) for(i in 1:length(end.index)){ end.node.coord[i,] <- coord.[end.index[i],] } end.node.coord.1 <- apply(end.node.coord,1:2, function(x) x/1.8) ed (x <- nrow(end.node.coord.1)) rowNumber <- sample(x, size=3, replace=FALSE) uniDirection = c(2,2) revDirection = 3 direction <- rep(1,times=nrow(end.node.coord.1)) direction[rowNumber] = c(uniDirection,revDirection) direction direction<- cbind(direction) direction arrowDirect <- cbind.data.frame(ed,direction) arrowDirect arrowDirect connections = "" for (i in 1:nrow(ed)){ if(arrowDirect$direction[i]==3){ connections <- paste0(connections," <defs> <marker id=\"arrow",i,"\" markerWidth=\"100\" markerHeight=\"50\" refx=\"40\" refy=\"6\" orient=\"auto\"> <path id=\"colourArrow",i,"\"d=\"M2,1 L2,10 L10,6 L2,2\" style=\"fill:blue\" /> </marker> </defs> <path id=",paste0('"',ed[i,1],'_',ed[i,2],'"'), " d=","\"M",end.node.coord.1[i,1],' ',end.node.coord.1[i,2],' L',start.node.coord.1[i,1],' ',start.node.coord.1[i,2],"\" style=\"stroke:black; stroke-width: 3.25px; fill: none ;marker-end: url( </path> ") }else if(arrowDirect$direction[i]==2){ connections <- paste0(connections," <defs> <marker id=\"arrow",i,"\" markerWidth=\"100\" markerHeight=\"50\" refx=\"40\" refy=\"6\" orient=\"auto\"> <path id=\"colourArrow",i,"\" d=\"M2,1 L2,10 L10,6 L2,2\" style=\"fill:blue\" /> </marker> </defs> <path id=",paste0('"',ed[i,1],'_',ed[i,2],'"'), " d=","\"M",start.node.coord.1[i,1],' ',start.node.coord.1[i,2],' L',end.node.coord.1[i,1],' ',end.node.coord.1[i,2],"\" style=\"stroke:black; stroke-width: 3.25px; fill: none ;marker-end: url( </path> ") }else{ connections <- paste0(connections," <path id=",paste0('"',ed[i,1],'_',ed[i,2],'"'), " d=","\"M",start.node.coord.1[i,1],' ',start.node.coord.1[i,2],' L',end.node.coord.1[i,1],' ',end.node.coord.1[i,2],"\" style=\"stroke:black; stroke-width: 3.25px; fill: none ;\" > </path> ") } } connections start.node <- ed[,1] start.node<- cbind(start.node) end.node<- ed[,2] end.node <- cbind(end.node) travelled = 0 cat("\n<div>", append = TRUE, file=htmlfile) cat("\n <svg height=\"610\" width=\"600\">", append=TRUE, file=htmlfile) cat(connections, append=TRUE, file=htmlfile) cat("\n </svg>", append=TRUE, file=htmlfile) cat("\n</div>", append = TRUE, file=htmlfile) cat("\n</div>", append = TRUE, file=htmlfile) cat("\n</div>", append = TRUE, file=htmlfile) cat("\n</div>", append = TRUE, file=htmlfile) cat("\n<div id=\"hidden\">&nbsp;</div>", append=TRUE, file=htmlfile) cat("\n<div id=\"hidden2\">&nbsp;</div>", append=TRUE, file=htmlfile) cat("\n<input name=\"next\" style=\"display: none;\" type=\"Submit\" value=\"next\" />",append=TRUE, file=htmlfile) cat("\n</div>", append = TRUE, file=htmlfile) cat("\n<p style =\"width:150px; text-align: center; height:20px; background-color: edge.list <- "\n var edgeArray=[" for (i in 1:length(start.node)){ if (i != 1) { edge.list <- paste0(edge.list,",[",start.node[i,1],",",end.node[i,1],",", travelled[],",",direction[i,1], "]") } else { edge.list <- paste0(edge.list,"[",start.node[i,1],",",end.node[i,1],",", travelled[],",",direction[i,1],"]") } } edge.list <- paste0(edge.list,"];") edge.list cat("\n<script>", append = TRUE, file = htmlfile) cat(edge.list, append=TRUE, file=htmlfile) javaScript <- javaScript3Arrows(arrowDirect, rowNumber) cat(javaScript, append=TRUE, file=htmlfile) cat("\n</script>", append = TRUE, file = htmlfile) cat("\n</body>", append = TRUE, file = htmlfile) cat("\n</html>", append = TRUE, file = htmlfile) message("Check to make sure that maze is solvable. If not, set a different seed.") }
winch_available <- function() { if (grepl("/valgrind/|/vgpreload_", Sys.getenv("LD_PRELOAD"))) { return(FALSE) } default_method != 0L }
"low_level_fusion" = function(datasets){ sample.names = colnames(datasets[[1]]$data) for (i in 2:length(datasets)){ sample.names = intersect(sample.names, colnames(datasets[[i]]$data)) } subsets = list() for (i in 1:length(datasets)){ if (!is.null(datasets[[i]]$metadata)) r.factors = TRUE else r.factors = FALSE subsets[[i]] = subset_samples(datasets[[i]], samples = sample.names, rebuild.factors = r.factors) } ds.fused = fusion_merge(subsets) ds.fused } "fusion_merge" = function(datasets){ ds.fused = datasets[[1]] ds.fused$description = paste("Data integration from types: ", datasets[[1]]$type, sep = "") for (i in 2:length(datasets)){ ds.fused$data = rbind(ds.fused$data, datasets[[i]]$data) ds.fused$description = paste(ds.fused$description, datasets[[i]]$type, sep = ",") } ds.fused$metadata = datasets[[1]]$metadata ds.fused$type = "integrated-data" ds.fused }
mean.fts <- function (x, method = c("coordinate", "FM", "mode", "RP", "RPD", "radius"), na.rm = TRUE, alpha, beta, weight, ...) { if (class(x)[1] == "fts"|class(x)[1] == "fds"|class(x)[1] == "sfts"){ method = match.arg(method) if (method == "coordinate"){ loc <- rowMeans(x$y, na.rm = na.rm) } if (method == "FM"){ loc <- depth.FM(x)$mtrim } if (method == "mode"){ loc <- depth.mode(x)$mtrim } if (method == "RP"){ loc <- depth.RP(x)$mtrim } if (method == "RPD"){ loc <- depth.RPD(x)$mtrim } if (method == "radius"){ loc <- depth.radius(x, alpha, beta, weight)$mtrim } if (class(x)[1] == "fds"){ warning("Object is not a functional time series.") } return(list(x = x$x, y = loc)) } else { stop("Not a functional object.") } }
hdfeppml_int <- function(y, x, fes, tol = 1e-8, hdfetol = 1e-4, colcheck = TRUE, mu = NULL, saveX = TRUE, init_z = NULL, verbose = FALSE, maxiter = 1000, cluster = NULL, vcv = TRUE) { x <- data.matrix(x) n <- length(y) crit <- 1 iter <- 0 old_deviance <- 0 include_x <- 1:ncol(x) b <- matrix(NA, nrow = ncol(x), ncol = 1) xnames <- colnames(x) if (colcheck == TRUE){ if (verbose == TRUE) { print("checking collinearity") } include_x <- collinearity_check(y, x, fes, 1e-6) x <- x[, include_x] } if (verbose == TRUE) { print("beginning estimation") } while (crit>tol & iter<maxiter) { iter <- iter + 1 if (verbose == TRUE) { print(iter) } if (iter == 1) { if (is.null(mu)) mu <- (y + mean(y))/2 z <- (y-mu)/mu + log(mu) eta <- log(mu) last_z <- z if (is.null(init_z)) { reg_z <- matrix(z) } else { reg_z <- init_z } reg_x <- x } else { last_z <- z z <- (y-mu)/mu + log(mu) reg_z <- matrix(z - last_z + z_resid) reg_x <- x_resid } if (verbose == TRUE) { print("within transformation step") } z_resid <- collapse::fhdwithin(reg_z, fes, w = mu) x_resid <- collapse::fhdwithin(reg_x, fes, w = mu) if (verbose == TRUE) { print("obtaining coefficients") } reg <- fastolsCpp(sqrt(mu) * x_resid, sqrt(mu) * z_resid) b[include_x] <- reg reg <- list("coefficients" = b) if (verbose == TRUE) { print(iter) } if (length(include_x) == 1) { reg$residuals <- z_resid - x_resid * b[include_x] } else { reg$residuals <- z_resid - x_resid %*% b[include_x] } mu <- as.numeric(exp(z - reg$residuals)) if (verbose == TRUE) { print("info on residuals") print(max(reg$residuals)) print(min(reg$residuals)) print("info on means") print(max(mu)) print(min(mu)) print("info on coefficients") print(max(b[include_x])) print(min(b[include_x])) } if (verbose == TRUE) { print("calculating deviance") } temp <- -(y * log(y/mu) - (y-mu)) temp[which(y == 0)] <- -mu[which(y == 0)] deviance <- -2 * sum(temp) / n if (deviance < 0) deviance = 0 delta_deviance <- old_deviance - deviance if (!is.na(delta_deviance) & (deviance < 0.1 * delta_deviance)) { delta_deviance <- deviance } if (verbose == TRUE) { print("checking critical value") } denom_crit = max(c(min(c(deviance, old_deviance)), 0.1)) crit = abs(delta_deviance) / denom_crit if (verbose == TRUE) { print(deviance) print(crit) } old_deviance <- deviance } temp <- -(y * log(y / mu) - (y - mu)) temp[which(y == 0)] <- 0 if (verbose == TRUE) { print("converged") } k <- ncol(matrix(x)) n <- length(y) reg$mu <- mu reg$deviance <- -2 * sum(temp) / n reg$bic <- deviance + k * log(n) / n rownames(reg$coefficients) <- xnames if (saveX == TRUE) { reg[["x_resid"]] <- x_resid reg[["z_resid"]] <- z_resid } if (vcv) { if(!is.null(cluster)) { nclusters <- nlevels(droplevels(cluster, exclude = if(anyNA(levels(cluster))) NULL else NA)) het_matrix <- (1 / nclusters) * cluster_matrix((y - mu) / sum(sqrt(mu)), cluster, x_resid) W <- (1/nclusters) * (t(mu*x_resid) %*% x_resid) / sum(sqrt(mu)) R <- try(chol(W), silent = FALSE) V <- (1/nclusters) * chol2inv(R) %*% het_matrix %*% chol2inv(R) V <- nclusters / (nclusters - 1) * V } else { e = y - mu het_matrix = (1/n) * t(x_resid*e) %*% (x_resid*e) W = (1/n) * (t(mu*x_resid) %*% x_resid) R = try(chol(W), silent = TRUE) V = (1/n) * chol2inv(R) %*% het_matrix %*% chol2inv(R) V = (n / (n - 1)) * V } } reg[["se"]] <- sqrt(diag(V)) return(reg) }
gearyc.stat<-function(data, applyto="SMR", ...) { n<-length(data$Observed) if(applyto != "SMR") { Z<- data$Observed - data$Expected } else { Z<- data$Observed/data$Expected Z[!is.finite(Z)]<-0 } return(spdep::geary(x=Z, ...)$C) }
overview <- function(.data) { n_row <- dim(.data)[1] n_col <- dim(.data)[2] size <- object.size(.data) complete <- complete.cases(.data) duplicated <- which(duplicated(.data)) na_row <- apply(.data, 1, function(x) any(is.na(x))) na_col <- apply(.data, 2, function(x) sum(is.na(x))) info_class <- get_class(.data) division_metric <- c("size", "size", "size", "size", "duplicated", "missing", "missing", "missing", "missing", "data type", "data type", "data type", "data type", "data type", "data type", "data type") name_metric <- c("observations", "variables", "values", "memory size", "duplicate observation", "complete observation", "missing observation", "missing variables", "missing values", "numerics", "integers", "factors/ordered", "characters", "Dates", "POSIXcts", "others") result <- data.frame( division = division_metric, metrics = name_metric, value = c(n_row, n_col, n_row * n_col, size, length(duplicated), sum(complete), sum(na_row >= 1), sum(na_col >= 1), sum(na_col), sum(info_class$class == "numeric"), sum(info_class$class == "integer"), sum(info_class$class %in% c("factor", "ordered")), sum(info_class$class == "character"), sum(info_class$class == "Date"), sum(info_class$class == "POSIXct"), sum(!info_class$class %in% c("numeric", "integer", "factor", "ordered", "character", "Date", "POSIXct")) ), stringsAsFactors = FALSE ) attr(result, "duplicated") <- duplicated attr(result, "na_col") <- na_col attr(result, "info_class") <- info_class class(result) <- append("overview", class(result)) result } summary.overview <- function(object, html = FALSE, ...) { nms <- c("Number of observations", "Number of variables", "Number of values", "Size of located memory(bytes)", "Number of duplicated observations", "Number of completed observations", "Number of observations with NA", "Number of variables with NA", "Number of NA", "Number of numeric variables", "Number of integer variables", "Number of factors variables", "Number of character variables", "Number of Date variables", "Number of POSIXct variables", "Number of other variables") nms <- format(nms) line_break <- function(html = FALSE) { if (!html) { cat("\n") } else { cat("<br>") } } vls <- format(object$value, big.mark = ",") N <- object$value[1] n_dup <- object$value[5] n_na <- object$value[7] p_dup <- paste0("(", round(n_dup / N * 100, 2), "%)") p_na <- paste0("(", round(n_na / N * 100, 2), "%)") vls[5] <- paste(vls[5], p_dup) vls[7] <- paste(vls[7], p_na) if (!html) { cat_rule( left = "Data Scale", right = "", width = 60 ) } else { cat_rule( left = "Data Scale", right = "", width = 60 ) %>% paste("<br>") %>% cat() } info_scale <- paste0(nms[1:4], " : ", vls[1:4]) if (html) { info_scale <- paste(info_scale, "<br>") } cat_bullet(info_scale) line_break() if (!html) { cat_rule( left = "Duplicated Data", right = "", width = 60 ) } else { cat_rule( left = "Duplicated Data", right = "", width = 60 ) %>% paste("<br>") %>% cat() } duplicated <- paste0(nms[5], " : ", vls[5]) if (html) { duplicated <- paste(duplicated, "<br>") } cat_bullet(duplicated) line_break() if (!html) { cat_rule( left = "Missing Data", right = "", width = 60 ) } else { cat_rule( left = "Missing Data", right = "", width = 60 ) %>% paste("<br>") %>% cat() } info_missing <- paste0(nms[6:9], " : ", vls[6:9]) if (html) { info_missing <- paste(info_missing, "<br>") } cat_bullet(info_missing) line_break() if (!html) { cat_rule( left = "Data Type", right = "", width = 60 ) } else { cat_rule( left = "Data Type", right = "", width = 60 ) %>% paste("<br>") %>% cat() } info_type <- paste0(nms[10:16], " : ", vls[10:16]) if (html) { info_type <- paste(info_type, "<br>") } cat_bullet(info_type) line_break() if (!html) { cat_rule( left = "Individual variables", right = "", width = 60 ) } else { cat_rule( left = "Individual variables", right = "", width = 60 ) %>% paste("<br>") %>% cat() } info_class <- attr(object, "info_class") names(info_class) <- c("Variables", "Data Type") if (!html) { print(info_class) } else { info_class %>% knitr::kable(format = "html")%>% kableExtra::kable_styling(full_width = FALSE, font_size = 15, position = "left") } } plot.overview <- function(x, order_type = c("none", "name", "type"), typographic = TRUE, base_family = NULL, ...) { info_class <- attr(x, "info_class") na_col <- attr(x, "na_col") raw <- data.frame(info_class, cnt = x[1, "value"], n_missing = na_col) raw <- raw %>% mutate(variable = factor(variable, levels = variable)) order_type <- match.arg(order_type) if (order_type == "name") { raw <- raw %>% mutate(variable = as.character(variable)) } else if (order_type == "type") { odr <- raw %>% mutate(variable = as.character(variable)) %>% arrange(class, variable) %>% select(variable) %>% pull() raw <- raw %>% mutate(variable = factor(variable, levels = odr)) } p <- raw %>% ggplot() + geom_bar(aes(x = variable, y = cnt, fill = class), stat = "identity") + geom_point(aes(x = variable, y = n_missing, color = "Missing")) + geom_line(aes(x = variable, y = n_missing), group = 1) + scale_color_manual("Missing", values = 1, guide = guide_legend(order = 1), labels = c("")) + guides(fill = guide_legend(title = "Data Type", order = 1), color = guide_legend(order = 2)) + ylab("Count") + xlab("Variables") + theme_grey(base_family = base_family) + theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1)) if (typographic) { p <- p + theme_typographic(base_family) + theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1)) } p }
fRegress.stderr <- function (y, y2cMap, SigmaE, returnMatrix = FALSE, ...) { yfdobj <- y$yfdobj xfdlist <- y$xfdlist betalist <- y$betalist betaestlist <- y$betaestlist yhatfdobj <- y$yhatfdobj Cmat <- y$Cmat Dmat <- y$Dmat Cmatinv <- y$Cmatinv wt <- y$wt df <- y$df betastderrlist <- y$betastderrlist YhatStderr <- y$YhatStderr Bvar <- y$Bvar c2bMap <- y$c2bMap p <- length(xfdlist) ncoef <- 0 for (j in 1:p) { betaParfdj <- betalist[[j]] ncoefj <- betaParfdj$fd$basis$nbasis ncoef <- ncoef + ncoefj } if (inherits(yfdobj, "fdPar") || inherits(yfdobj, "fd")) { if (inherits(yfdobj, "fdPar")) yfdobj <- yfdobj$fd N <- dim(yfdobj$coefs)[2] ybasisobj <- yfdobj$basis rangeval <- ybasisobj$rangeval ynbasis <- ybasisobj$nbasis ninteg <- max(501, 10 * ynbasis + 1) tinteg <- seq(rangeval[1], rangeval[2], len = ninteg) deltat <- tinteg[2] - tinteg[1] ybasismat <- eval.basis(tinteg, ybasisobj, 0, returnMatrix) basisprodmat <- matrix(0, ncoef, ynbasis * N) mj2 <- 0 for (j in 1:p) { betafdParj <- betalist[[j]] betabasisj <- betafdParj$fd$basis ncoefj <- betabasisj$nbasis bbasismatj <- eval.basis(tinteg, betabasisj, 0, returnMatrix) xfdj <- xfdlist[[j]] tempj <- eval.fd(tinteg, xfdj, 0, returnMatrix) mj1 <- mj2 + 1 mj2 <- mj2 + ncoefj indexj <- mj1:mj2 mk2 <- 0 for (k in 1:ynbasis) { mk1 <- mk2 + 1 mk2 <- mk2 + N indexk <- mk1:mk2 tempk <- bbasismatj * ybasismat[, k] basisprodmat[indexj, indexk] <- deltat * crossprod(tempk, tempj) } } y2cdim <- dim(y2cMap) if (y2cdim[1] != ynbasis || y2cdim[2] != dim(SigmaE)[1]) stop("Dimensions of Y2CMAP not correct.") Varc <- y2cMap %*% SigmaE %*% t(y2cMap) CVar <- kronecker(Varc, diag(rep(1, N))) C2BMap <- Cmatinv %*% basisprodmat Bvar <- C2BMap %*% CVar %*% t(C2BMap) nplot <- max(51, 10 * ynbasis + 1) tplot <- seq(rangeval[1], rangeval[2], len = nplot) betastderrlist <- vector("list", p) PsiMatlist <- vector("list", p) mj2 <- 0 for (j in 1:p) { betafdParj <- betalist[[j]] betabasisj <- betafdParj$fd$basis ncoefj <- betabasisj$nbasis mj1 <- mj2 + 1 mj2 <- mj2 + ncoefj indexj <- mj1:mj2 bbasismat <- eval.basis(tplot, betabasisj, 0, returnMatrix) PsiMatlist <- bbasismat bvarj <- Bvar[indexj, indexj] bstderrj <- sqrt(diag(bbasismat %*% bvarj %*% t(bbasismat))) bstderrfdj <- smooth.basis(tplot, bstderrj, betabasisj)$fd betastderrlist[[j]] <- bstderrfdj } YhatStderr <- matrix(0, nplot, N) B2YhatList <- vector("list", p) for (iplot in 1:nplot) { YhatVari <- matrix(0, N, N) tval <- tplot[iplot] for (j in 1:p) { Zmat <- eval.fd(tval, xfdlist[[j]]) betabasisj <- betalist[[j]]$fd$basis PsiMatj <- eval.basis(tval, betabasisj) B2YhatMapij <- t(Zmat) %*% PsiMatj B2YhatList[[j]] <- B2YhatMapij } m2j <- 0 for (j in 1:p) { m1j <- m2j + 1 m2j <- m2j + betalist[[j]]$fd$basis$nbasis B2YhatMapij <- B2YhatList[[j]] m2k <- 0 for (k in 1:p) { m1k <- m2k + 1 m2k <- m2k + betalist[[k]]$fd$basis$nbasis B2YhatMapik <- B2YhatList[[k]] YhatVari <- YhatVari + B2YhatMapij %*% Bvar[m1j:m2j,m1k:m2k] %*% t(B2YhatMapik) } } YhatStderr[iplot, ] <- matrix(sqrt(diag(YhatVari)), 1, N) } } else { ymat <- as.matrix(yfdobj) N <- dim(ymat)[1] Zmat <- NULL for (j in 1:p) { xfdj <- xfdlist[[j]] if (inherits(xfdj, "fd")) { xcoef <- xfdj$coefs xbasis <- xfdj$basis betafdParj <- betalist[[j]] bbasis <- betafdParj$fd$basis Jpsithetaj <- inprod(xbasis, bbasis) Zmat <- cbind(Zmat, t(xcoef) %*% Jpsithetaj) } else if (inherits(xfdj, "numeric")) { Zmatj <- xfdj Zmat <- cbind(Zmat, Zmatj) } } c2bMap <- Cmatinv %*% t(Zmat) y2bmap <- c2bMap Bvar <- y2bmap %*% as.matrix(SigmaE) %*% t(y2bmap) betastderrlist <- vector("list", p) mj2 <- 0 for (j in 1:p) { betafdParj <- betalist[[j]] betabasisj <- betafdParj$fd$basis ncoefj <- betabasisj$nbasis mj1 <- mj2 + 1 mj2 <- mj2 + ncoefj indexj <- mj1:mj2 bvarj <- Bvar[indexj, indexj] xfdj <- xfdlist[[j]] if (inherits(xfdj, "fd")) { betarng <- betabasisj$rangeval ninteg <- max(c(501, 10 * ncoefj + 1)) tinteg <- seq(betarng[1], betarng[2], len = ninteg) bbasismat <- eval.basis(tinteg, betabasisj, 0, returnMatrix) bstderrj <- sqrt(diag(bbasismat %*% bvarj %*% t(bbasismat))) bstderrfdj <- smooth.basis(tinteg, bstderrj, betabasisj)$fd } else { bsterrj <- sqrt(diag(bvarj)) onebasis <- create.constant.basis(betabasisj$rangeval) bstderrfdj <- fd(t(bstderrj), onebasis) } betastderrlist[[j]] <- bstderrfdj } B2YhatList <- vector("list", p) YhatVari <- matrix(0, N, N) for (j in 1:p) { betabasisj <- betalist[[j]]$fd$basis Xfdj <- xfdlist[[j]] B2YhatMapij <- inprod(Xfdj, betabasisj) B2YhatList[[j]] <- B2YhatMapij } m2j <- 0 for (j in 1:p) { m1j <- m2j + 1 m2j <- m2j + betalist[[j]]$fd$basis$nbasis B2YhatMapij <- B2YhatList[[j]] m2k <- 0 for (k in 1:p) { m1k <- m2k + 1 m2k <- m2k + betalist[[k]]$fd$basis$nbasis B2YhatMapik <- B2YhatList[[k]] YhatVari <- YhatVari + B2YhatMapij %*% Bvar[m1j:m2j, m1k:m2k] %*% t(B2YhatMapik) } } YhatStderr <- matrix(sqrt(diag(YhatVari)), N, 1) } fRegressList <- list(yfdobj = y$yfdobj, xfdlist = y$xfdlist, betalist = y$betalist, betaestlist = y$betaestlist, yhatfdobj = y$yhatfdobj, Cmat = y$Cmat, Dmat = y$Dmat, Cmatinv = y$Cmatinv, wt = y$wt, df = y$df, y2cMap = y2cMap, SigmaE = SigmaE, betastderrlist = betastderrlist, YhatStderr = YhatStderr, Bvar = Bvar, c2bMap = c2bMap) class(fRegressList) = "fRegress" return(fRegressList) }
ReplaceDimList <- function(dimList, replaceList, total = "Total") { for (i in seq_along(replaceList)) { if (is.character(replaceList[[i]])) replaceList[[i]] <- Hrc2DimList(replaceList[[i]], total = total) else replaceList[[i]] <- FixDimListNames(replaceList[[i]]) } names1 <- make.names(names(dimList), unique = TRUE) names2 <- make.names(names(replaceList), unique = TRUE) matchNames <- match(names1, names2) dimList[!is.na(matchNames)] <- replaceList[matchNames[!is.na(matchNames)]] dimList } FixDimListNames <- function(x) { if (!any(!(c("levels", "codes") %in% names(x)))) return(x) a <- unique(c(pmatch(c("lev", "cod", "nam"), names(x)), 1:2)) a <- a[!is.na(a)][1:2] names(x)[a] <- c("levels", "codes") x }
get_NOAA_stations_nearXY <- function(lat, lng, apitoken, bbox = 1) { if(!requireNamespace("httr")) stop("package `httr` is required") coord <- data.frame(lat = lat, lng = lng) coordinates(coord) <- ~ lng + lat bdim <- bbox / 2 ext_string <- sprintf("%s,%s,%s,%s", lat - bdim, lng - bdim, lat + bdim, lng + bdim) r <- httr::GET(url = sprintf( "https://www.ncdc.noaa.gov/cdo-web/api/v2/stations?extent=%s&limit=1000", ext_string ), httr::add_headers(token = apitoken)) r.content <- httr::content(r, as = "text", encoding = "UTF-8") d <- jsonlite::fromJSON(r.content) if(nrow(d$results) == 1000) message("maximum record limit reached (n = 1000) -- try a smaller bounding box (bbox) value to return fewer stations") return(d$results) } .get_NOAA_GHCND_by_stationyear <- function(stationid, year, datatypeid, apitoken) { if(!requireNamespace("httr")) stop("package `httr` is required") startdate <- sprintf("%s-01-01", year) enddate <- sprintf("%s-12-31", year) message(sprintf('Downloading NOAA GHCND data for %s over interval %s to %s...', stationid, startdate, enddate)) datatypeids <- sprintf("&datatypeid=%s", datatypeid) datatypeid.url <- paste0(datatypeids, collapse="&") r <- httr::GET(url = paste0(sprintf( "https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND&stationid=%s&startdate=%s&enddate=%s&limit=1000", stationid, startdate, enddate), datatypeid.url), httr::add_headers(token = apitoken)) r.content <- httr::content(r, as = "text", encoding = "UTF-8") d <- jsonlite::fromJSON(r.content) if (length(d$results) == 0) { message("empty result set") return(NULL) } if (nrow(d$results) == 1000) message("maximum record limit reached (n = 1000)") return(d$results) } get_NOAA_GHCND <- function(stations, years, datatypeids, apitoken) { do.call('rbind', lapply(stations, function(s) do.call('rbind', lapply(years, function(y) do.call('rbind', lapply(datatypeids, function(d) .get_NOAA_GHCND_by_stationyear(s, y, d, apitoken))))))) }
detectCores <- function(...) { parallel::detectCores(...) } setLogFile <- function(con=stdout()) { if ("connection" %in% class(con) ) assign('LOGFILE', con) } setPPMbounds <- function(proton=c(-0.5,11), carbon=c(0,200)) { assign('PPM_MIN', proton[1]) assign('PPM_MAX', proton[2]) assign('PPM_MIN_13C', carbon[1]) assign('PPM_MAX_13C', carbon[2]) } doProcessing <- function (path, cmdfile, samplefile=NULL, bucketfile=NULL, ncpu=1 ) { if( ! file.exists(path)) stop(paste0("ERROR: ",path," does NOT exist\n"), call.=FALSE) if( ! file.exists(cmdfile)) stop(paste0("ERROR: ",cmdfile," does NOT exist\n"), call.=FALSE) if( ! is.null(samplefile) && ! file.exists(samplefile)) stop(paste0("ERROR: ",samplefile," does NOT exist\n"), call.=FALSE) if( ! is.null(bucketfile) && ! file.exists(bucketfile)) stop(paste0("ERROR: ",bucketfile," does NOT exist\n"), call.=FALSE) if ( checkMacroCmdFile(cmdfile) == 0 ) stop(paste0("ERROR: ",cmdfile," seems to include errors\n"), call.=FALSE) trim <- function (x) gsub("^\\s+|\\s+$", "", x) Write.LOG(LOGFILE, "Rnmr1D: --- READING and CONVERTING ---\n", mode="at") procParams <- Spec1rProcpar procParams$VENDOR <- "bruker" procParams$INPUT_SIGNAL <- "1r" procParams$READ_RAW_ONLY <- TRUE CMDTEXT <- gsub("\t", "", readLines(cmdfile)) if ( length(grep(" procpar <- unlist(strsplit(gsub(" Write.LOG(LOGFILE, paste0( "Rnmr1D: ", paste(procpar,collapse=", "), "\n")) parnames <- NULL; parvals <- NULL for (param in procpar ) { parnames <- c( parnames, unlist(strsplit(param,"="))[1] ); parvals <- c( parvals, unlist(strsplit(param,"="))[2] ); } names(parvals) <- parnames; procpar <- data.frame(t(parvals), stringsAsFactors=FALSE) if (! is.null(procpar$Vendor)) procParams$VENDOR <- tolower(trim(procpar$Vendor)) if (! is.null(procpar$Type)) procParams$INPUT_SIGNAL <- trim(procpar$Type) if (! is.null(procpar$LB)) procParams$LB <- as.numeric(procpar$LB) if (! is.null(procpar$GB)) procParams$GB <- as.numeric(procpar$GB) if (! is.null(procpar$ZNEG)) procParams$RABOT <- ifelse( procpar$ZNEG=="TRUE", TRUE, FALSE) if (! is.null(procpar$TSP)) procParams$TSP <- ifelse( procpar$TSP=="TRUE", TRUE, FALSE) if (! is.null(procpar$O1RATIO)) procParams$O1RATIO <- as.numeric(procpar$O1RATIO) if (! is.null(procpar$ZF)) procParams$ZEROFILLING <- as.numeric(procpar$ZF) if (! is.null(procpar$USRPHC) && procpar$USRPHC=="TRUE") { procParams$OPTPHC0 <- procParams$OPTPHC1 <- FALSE if (! is.null(procpar$PHC0)) procParams$phc0 <- as.numeric(procpar$PHC0) if (! is.null(procpar$PHC1)) procParams$phc1 <- as.numeric(procpar$PHC1) } else { if (! is.null(procpar$PHC0)) procParams$OPTPHC0 <- ifelse( procpar$PHC0=="TRUE", TRUE, FALSE) if (! is.null(procpar$PHC1)) procParams$OPTPHC1 <- ifelse( procpar$PHC1=="TRUE", TRUE, FALSE) if (! is.null(procpar$CRIT1)) procParams$CRITSTEP1 <- as.numeric(procpar$CRIT1) } if (procParams$INPUT_SIGNAL=='fid') procParams$READ_RAW_ONLY <- FALSE } Write.LOG(LOGFILE, "Rnmr1D: Generate the 'samples' & 'factors' files from the list of raw spectra\n") metadata <- NULL samples <- NULL if (!is.null(samplefile) && file.exists(samplefile)) samples <- utils::read.table(samplefile, sep="\t", header=T,stringsAsFactors=FALSE) metadata <- generateMetadata(path, procParams, samples) if (is.null(metadata)) { msg <- "Something failed when attempting to generate the metadata files" stop(paste0(msg,"\n"), call.=FALSE) } gc() LIST <- metadata$rawids Write.LOG(LOGFILE, paste0("Rnmr1D: -- Nb Spectra = ",dim(LIST)[1]," -- Nb Cores = ",ncpu,"\n")) specObj <- NULL tryCatch({ cl <- parallel::makeCluster(ncpu) doParallel::registerDoParallel(cl) Sys.sleep(1) x <- 0 specList <- foreach::foreach(x=1:(dim(LIST)[1]), .combine=cbind) %dopar% { ACQDIR <- LIST[x,1] NAMEDIR <- ifelse( procParams$VENDOR=='bruker', basename(dirname(ACQDIR)), basename(ACQDIR) ) PDATA_DIR <- ifelse( procParams$VENDOR=='rs2d', 'Proc', 'pdata' ) procParams$LOGFILE <- LOGFILE procParams$PDATA_DIR <- file.path(PDATA_DIR,LIST[x,3]) spec <- Spec1rDoProc(Input=ACQDIR,param=procParams) if (procParams$INPUT_SIGNAL=='1r') Sys.sleep(0.3) Write.LOG(stderr(),".") if (dim(LIST)[1]>1) { list( x, spec ) } else { spec } } Write.LOG(LOGFILE,"\n") gc() parallel::stopCluster(cl) if (dim(LIST)[1]>1) { L <- simplify2array(sapply( order(simplify2array(specList[1,])), function(x) { specList[2,x] } ) ) specList <- L } Write.LOG(LOGFILE, "Rnmr1D: Generate the final matrix of spectra...\n") M <- NULL N <- dim(LIST)[1] vpmin<-0; vpmax<-0 for(i in 1:N) { if (N>1) { spec <- specList[,i]; } else { spec <- specList; } if (spec$acq$NUC == "13C") { PPM_MIN <- PPM_MIN_13C; PPM_MAX <- PPM_MAX_13C; } P <- spec$ppm>PPM_MIN & spec$ppm<=PPM_MAX V <- spec$int[P] vppm <- spec$ppm[P] if (PPM_MIN<spec$pmin) { nbzeros <- round((spec$pmin - PPM_MIN)/spec$dppm) vpmin <- vpmin + spec$pmin - nbzeros*spec$dppm V <- c( rep(0,nbzeros), V ) } else { vpmin <- vpmin + vppm[1] } if (PPM_MAX>spec$pmax) { nbzeros <- round((PPM_MAX - spec$pmax)/spec$dppm) vpmax <- vpmax + spec$pmax + nbzeros*spec$dppm V <- c( V, rep(0,nbzeros) ) } else { vpmax <- vpmax + vppm[length(vppm)] } M <- rbind(M, rev(V)) } cur_dir <- getwd() specMat <- NULL specMat$int <- M specMat$ppm_max <- (vpmax/N); specMat$ppm_min <- (vpmin/N); specMat$nspec <- dim(M)[1] specMat$size <- dim(M)[2] specMat$dppm <- (specMat$ppm_max - specMat$ppm_min)/(specMat$size - 1) specMat$ppm <- rev(seq(from=specMat$ppm_min, to=specMat$ppm_max, by=specMat$dppm)) specMat$buckets_zones <- NULL specMat$namesASintMax <- FALSE specMat$fWriteSpec <- FALSE specObj <- metadata specObj$specMat <- specMat samples <- metadata$samples IDS <- cbind(basename(dirname(as.vector(LIST[,1]))), LIST[, c(2:3)]) if (N>1) { PARS <- t(sapply( c(1:N), function(x) { c( specList[,x]$acq$PULSE, specList[,x]$acq$NUC, specList[,x]$acq$SOLVENT, specList[,x]$acq$GRPDLY, specList[,x]$proc$phc0, specList[,x]$proc$phc1, specList[,x]$acq$SFO1, specList[,x]$proc$SI, specList[,x]$acq$SW, specList[,x]$acq$SWH, specList[,x]$acq$RELAXDELAY, specList[,x]$acq$O1 ) })) specObj$nuc <- specList[,1]$acq$NUC } else { PARS <- t( c( spec$acq$PULSE, spec$acq$NUC, spec$acq$SOLVENT, spec$acq$GRPDLY, spec$proc$phc0, spec$proc$phc1, spec$acq$SFO1, spec$proc$SI, specList$acq$SW, spec$acq$SWH, spec$acq$RELAXDELAY, spec$acq$O1) ) specObj$nuc <- spec$acq$NUC } LABELS <- c("PULSE", "NUC", "SOLVENT", "GRPDLY", "PHC0","PHC1","SF","SI","SW", "SWH","RELAXDELAY","O1" ) if (regexpr('BRUKER', toupper(specList[,1]$acq$INSTRUMENT))>0) { if (N>1) { PARS <- cbind( IDS[,c(2:3)], PARS ) } else { PARS <- c( IDS[1,c(2:3)], PARS ) } LABELS <- c("EXPNO", "PROCNO", LABELS) } if (regexpr('RS2D', toupper(specList[,1]$acq$INSTRUMENT))>0) { if (N>1) { PARS <- cbind( IDS[,3], PARS ) } else { PARS <- c( IDS[1,3], PARS ) } LABELS <- c("PROCNO", LABELS) } if (N>1) { PARS <- cbind( samples[,1], samples[,2], PARS ) } else { PARS <- c( samples[1, 1], samples[1, 2], PARS ) } colnames(PARS) <- c("Spectrum", "Samplecode", LABELS ) specObj$infos <- PARS specObj$origin <- paste(procParams$VENDOR, procParams$INPUT_SIGNAL) Write.LOG(LOGFILE,"Rnmr1D: ------------------------------------\n") Write.LOG(LOGFILE,"Rnmr1D: Process the Macro-commands file\n") Write.LOG(LOGFILE,"Rnmr1D: ------------------------------------\n") Write.LOG(LOGFILE,"Rnmr1D: \n") specMat <- doProcCmd(specObj, CMDTEXT, ncpu=ncpu, debug=TRUE) if (specMat$fWriteSpec) specObj$specMat <- specMat gc() if( ! is.null(bucketfile) && file.exists(bucketfile)) { Write.LOG(LOGFILE, "Rnmr1D: ------------------------------------\n") Write.LOG(LOGFILE, "Rnmr1D: Process the file of buckets\n") Write.LOG(LOGFILE, "Rnmr1D: ------------------------------------\n") Write.LOG(LOGFILE, "Rnmr1D: \n") buckets_infile <- utils::read.table(bucketfile, header=T, sep="\t",stringsAsFactors=FALSE) if ( sum(c('min','max') %in% colnames(buckets_infile)) == 2 ) { buckets <- cbind( buckets_infile$max, buckets_infile$min ) specObj$specMat$buckets_zones <- buckets Write.LOG(LOGFILE, paste0("Rnmr1D: NB Buckets = ",dim(buckets)[1],"\n")) Write.LOG(LOGFILE, "Rnmr1D: \n") } else { Write.LOG(LOGFILE,"ERROR: the file of bucket's areas does not contain the 2 mandatory columns having 'min' and 'max' in its header line\n") } } specObj$specMat$fWriteSpec <- NULL specObj$specMat$LOGMSG <- NULL }, error=function(e) { cat(paste0("ERROR: ",e)) }) return(specObj) }
calc.deviance <- function(obs, pred, weights = rep(1,length(obs)), family="binomial", calc.mean = TRUE) { if (length(obs) != length(pred)) { stop("observations and predictions must be of equal length") } y_i <- obs u_i <- pred family = tolower(family) if (family == "binomial" | family == "bernoulli") { deviance.contribs <- (y_i * log(u_i)) + ((1-y_i) * log(1 - u_i)) deviance <- -2 * sum(deviance.contribs * weights) } else if (family == "poisson") { deviance.contribs <- ifelse(y_i == 0, 0, (y_i * log(y_i/u_i))) - (y_i - u_i) deviance <- 2 * sum(deviance.contribs * weights) } else if (family == "laplace") { deviance <- sum(abs(y_i - u_i)) } else if (family == "gaussian") { deviance <- sum((y_i - u_i) * (y_i - u_i)) } else { stop('unknown family, should be one of: "binomial", "bernoulli", "poisson", "laplace", "gaussian"') } if (calc.mean) deviance <- deviance/length(obs) return(deviance) }
rm(list = ls()) library("highcharter") suppressPackageStartupMessages(library("dplyr")) options(highcharter.theme = hc_theme_smpl()) data(diamonds, package = "ggplot2") series <- diamonds %>% sample_n(500) %>% group_by(name = cut) %>% do(data = list_parse2(data.frame(x = .$price, y = .$carat))) %>% list_parse() str(series, max.level = 2) head(series[[1]]$data, 3) highchart() %>% hc_chart(type = "scatter") %>% hc_add_series_list(series) dat <- data.frame(id = c(1,2,3,4,5,6), grp = c("A","A","B","B","C","C"), value = c(10,13,9,15,11,16)) dat highchart() %>% hc_chart(type = "line") %>% hc_add_series_df_tidy(data = dat, group = grp, values = value)
get_graphab_raster_codes <- function(proj_name, mode = "all", proj_path = NULL){ if(!is.null(proj_path)){ chg <- 1 wd1 <- getwd() setwd(dir = proj_path) } else { chg <- 0 proj_path <- getwd() } if(!inherits(proj_name, "character")){ if(chg == 1){setwd(dir = wd1)} stop("'proj_name' must be a character string") } else if (!(paste0(proj_name, ".xml") %in% list.files(path = paste0("./", proj_name)))){ if(chg == 1){setwd(dir = wd1)} stop("The project you refer to does not exist. Please use graphab_project() before.") } proj_end_path <- paste0(proj_name, "/", proj_name, ".xml") if(!inherits(mode, "character")){ if(chg == 1){setwd(dir = wd1)} stop("'mode' must be a character string.") } else if (!(mode %in% c("all", "habitat"))){ if(chg == 1){setwd(dir = wd1)} stop("'mode' must be equal to 'all' or 'habitat'.") } xml <- tempfile(pattern = ".txt") file.copy(from = proj_end_path, to = xml) file_data <- utils::read.table(xml) na_code <- file_data[which(stringr::str_sub(file_data[, 1], 1, 8) == "<noData>"), 1] na_code <- stringr::str_sub(na_code, 9, -10) if(na_code == "NaN"){ na_pres <- FALSE } else { na_pres <- TRUE if(stringr::str_sub(na_code, -2, -1) == ".0"){ na_code <- stringr::str_sub(na_code, 1, -3) } } if(mode == "all"){ first_code <- min(which(file_data[, 1] == "<codes>")) + 1 last_code <- min(which(file_data[, 1] == "</codes>")) - 1 vec_codes <- file_data[first_code:last_code, 1] } else if(mode == "habitat"){ first_code <- which(file_data[, 1] == "<patchCodes>")+1 vec_codes <- file_data[first_code, 1] } vec_codes <- unlist(lapply(vec_codes, FUN = function(x){stringr::str_sub(x, 6, -7)})) if(na_pres){ if(na_code %in% vec_codes){ vec_codes <- vec_codes[-which(vec_codes == na_code)] message(paste0("No data value is equal to ", na_code)) } } if(chg == 1){ setwd(dir = wd1) } vec_codes <- as.numeric(vec_codes) return(vec_codes) }
read.bnd <- function(file, sorted=FALSE) { data.raw <- scan(file, what = list("", ""), sep = ",", quote = "") oldOptions <- options(warn = -1) on.exit(options(oldOptions)) data.numeric <- lapply(data.raw, as.numeric) options(oldOptions) unquote <- function(string) { return(gsub(pattern="\"", replacement="", x=string)) } whereIsIn <- which(data.raw[[1]] == "is.in") surroundingNames <- unquote(data.raw[[2]][whereIsIn]) whereRegionNames <- setdiff(which(is.na(data.numeric[[1]])), whereIsIn) nPolygons <- length(whereRegionNames) cat("Note: map consists of", nPolygons, "polygons\n") belongingRegions <- unquote(data.raw[[1]][whereRegionNames]) regions <- unique(belongingRegions) cat("Note: map consists of", length(regions), "regions\n") polyLengths <- data.numeric[[2]][whereRegionNames] enclosedPolygonsInds <- findInterval(x=whereIsIn, vec=whereRegionNames) surrounding <- replicate(n=nPolygons, expr=character()) for(i in seq_along(enclosedPolygonsInds)) { surrounding[[enclosedPolygonsInds[i]]] <- surroundingNames[i] } data.numeric <- cbind(data.numeric[[1]], data.numeric[[2]]) data.numeric <- na.omit(data.numeric) cat("Reading map ...") map <- vector(mode="list", length=nPolygons) names(map) <- belongingRegions startInds <- cumsum(c(1, polyLengths)) for(k in seq_along(map)) { map[[k]] <- data.numeric[startInds[k]:(startInds[k+1] - 1), ] if(sum(map[[k]][1,] == map[[k]][polyLengths[k],]) != 2) warning(paste("Note: First and last point of polygon ",k," (region ",names(map)[k],") are not identical", sep=""), call. = FALSE) } cat(" finished\n") rm(data.numeric) if(sorted){ numericNames <- as.numeric(names(map)) newOrder <- if(any(is.na(numericNames))) { cat("Note: regions sorted by name\n") order(names(map)) } else { cat("Note: regions sorted by number\n") order(numericNames) } map <- map[newOrder] surrounding <- surrounding[newOrder] } minima <- sapply(map, function(x){apply(x,2,min)}) maxima <- sapply(map, function(x){apply(x,2,max)}) minimum <- apply(minima,1,min) maximum <- apply(maxima,1,max) x.range <- maximum[1] - minimum[1] y.range <- maximum[2] - minimum[2] rval <- structure(map, class = "bnd", surrounding = surrounding, regions = regions) attr(rval, "asp") <- (y.range / x.range) / cos((mean(c(maximum[2] - minimum[2])) * pi) / 180) rval }
ddirichlet<-function(x,alpha) { dirichlet1 <- function(x, alpha) { logD <- sum(lgamma(alpha)) - lgamma(sum(alpha)) s<-sum((alpha-1)*log(x)) exp(sum(s)-logD) } if(!is.matrix(x)) if(is.data.frame(x)) x <- as.matrix(x) else x <- t(x) if(!is.matrix(alpha)) alpha <- matrix( alpha, ncol=length(alpha), nrow=nrow(x), byrow=TRUE) if( any(dim(x) != dim(alpha)) ) stop("Mismatch between dimensions of 'x' and 'alpha'.") pd <- vector(length=nrow(x)) for(i in 1:nrow(x)) pd[i] <- dirichlet1(x[i,],alpha[i,]) pd[ apply( x, 1, function(z) any( z <0 | z > 1)) ] <- 0 pd[ apply( x, 1, function(z) all.equal(sum( z ),1) !=TRUE) ] <- 0 pd } rdirichlet<-function(n,alpha) { l<-length(alpha); x<-matrix(rgamma(l*n,alpha),ncol=l,byrow=TRUE); sm<-x%*%rep(1,l); x/as.vector(sm); } rdirichlet2 <- function(alpha, n) { return(rdirichlet(n, alpha)) } odirichlet <- function(a, n = 0, ...) { if (class(a) != "ovariable") stop("a is not an ovariable!\n") if (n == 0) n <- openv$N if ("Iter" %in% colnames(a@output)) n <- 1 out <- oapply(a, FUN = rdirichlet2, n = n, use_aggregate = FALSE, ...) if (!"Iter" %in% colnames(a@output)) { levels(out@output$Var2) <- 1:n colnames(out@output)[colnames(out@output) == "Var2"] <- "Iter" } out@output <- out@output[!grepl("^Var", colnames(out@output))] out@marginal <- colnames(out@output) %in% c(colnames(a@output)[a@marginal], "Iter") return(out) }
setupDASIMTest <- function(packages = c(), env = parent.frame()) { setupDSLiteServer(packages, c("DASIM1", "DASIM2", "DASIM3"), "logindata.dslite.dasim", "DSLite", "dslite.server", env) }
test_performance <- function(..., reference = 1) { UseMethod("test_performance") } test_performance.default <- function(..., reference = 1, include_formula = FALSE) { objects <- insight::ellipsis_info(..., only_models = TRUE) names(objects) <- match.call(expand.dots = FALSE)$`...` .test_performance_checks(objects) if (inherits(objects, c("ListNestedRegressions", "ListNonNestedRegressions", "ListLavaan"))) { test_performance(objects, reference = reference, include_formula = include_formula) } else { stop("The models cannot be compared for some reason :/") } } test_performance.ListNestedRegressions <- function(objects, reference = 1, include_formula = FALSE, ...) { out <- .test_performance_init(objects, include_formula = include_formula, ...) tryCatch( { rez <- test_bf(objects, reference = "sequential") if (!is.null(rez)) { rez$Model <- NULL out <- cbind(out, rez) } }, error = function(e) { } ) tryCatch( { rez <- test_vuong(objects) rez$Model <- NULL out <- merge(out, rez, sort = FALSE) }, error = function(e) { } ) attr(out, "is_nested") <- attributes(objects)$is_nested attr(out, "reference") <- if (attributes(objects)$is_nested_increasing) "increasing" else "decreasing" class(out) <- c("test_performance", class(out)) out } test_performance.ListNonNestedRegressions <- function(objects, reference = 1, include_formula = FALSE, ...) { out <- .test_performance_init(objects, include_formula = include_formula, ...) tryCatch( { rez <- test_bf(objects, reference = reference) if (!is.null(rez)) { rez$Model <- NULL out <- cbind(out, rez) } }, error = function(e) { } ) tryCatch( { rez <- test_vuong(objects, reference = reference) rez$Model <- NULL out <- merge(out, rez, sort = FALSE) }, error = function(e) { } ) attr(out, "is_nested") <- attributes(objects)$is_nested attr(out, "reference") <- reference class(out) <- c("test_performance", class(out)) out } format.test_performance <- function(x, digits = 2, ...) { out <- insight::format_table(x, digits = digits, ...) if (isTRUE(attributes(x)$is_nested)) { footer <- paste0( "Models were detected as nested and are compared in sequential order.\n" ) } else { footer <- paste0( "Each model is compared to ", x$Name[attributes(x)$reference], ".\n" ) } attr(out, "table_footer") <- footer out } print.test_performance <- function(x, digits = 2, ...) { out <- insight::export_table(format(x, digits = digits, ...), ...) cat(out) } print_md.test_performance <- function(x, digits = 2, ...) { insight::export_table(format(x, digits = digits, ...), format = "markdown", ...) } print_html.test_performance <- function(x, digits = 2, ...) { insight::export_table(format(x, digits = digits, ...), format = "html", ...) } display.test_performance <- function(object, format = "markdown", digits = 2, ...) { if (format == "markdown") { print_md(x = object, digits = digits, ...) } else { print_html(x = object, digits = digits, ...) } } .test_performance_init <- function(objects, include_formula = FALSE) { names <- insight::model_name(objects, include_formula = include_formula) out <- data.frame( Name = names(objects), Model = names, stringsAsFactors = FALSE ) row.names(out) <- NULL out } .test_performance_checks <- function(objects, multiple = TRUE, same_response = TRUE) { if (multiple && insight::is_model(objects)) { stop("At least two models are required to test them.", call. = FALSE) } if (same_response && !inherits(objects, "ListLavaan") && attributes(objects)$same_response == FALSE) { stop(insight::format_message("The models' dependent variables don't have the same data, which is a prerequisite to compare them. Probably the proportion of missing data differs between models."), call. = FALSE) } already_warned <- FALSE for (i in objects) { if (!already_warned) { check_formula <- insight::formula_ok(i) } if (check_formula) { already_warned <- TRUE } } objects }
InflectWorkflow<-function(Rsq,NumSD,Temperature,Rep,SourcePath,OutputPath){ OutputPath_Curves=paste(OutputPath,"Curves",sep="/") OutputPath_SigCurves=paste(OutputPath,"SigCurves",sep="/") FileCondition<-paste(paste("Condition",Rep),"xlsx",sep=".") FileControl<-paste(paste("Control",Rep),"xlsx",sep=".") NumberTemperatures<-as.numeric(NROW(Temperature)) ConditionData <- as.data.frame(read_excel(file.path(paste(SourcePath,FileCondition,sep="/")))) ControlData <- as.data.frame(read_excel(file.path(paste(SourcePath,FileControl,sep="/")))) Data_Control <- ControlData[,c(2:(1+NumberTemperatures))] Data_Condition <- ConditionData[,c(2:(1+NumberTemperatures))] Protein_Control <- ControlData[c(1)] Protein_Condition <- ConditionData[c(1)] Data_Control_Norm<-Data_Control[,1:ncol(Data_Control)]/Data_Control[,1] Data_Condition_Norm<- Data_Condition[,1:ncol(Data_Condition)]/Data_Condition[,1] All_Control_Norm<-data.frame(Protein_Control,Data_Control_Norm) All_Condition_Norm<-data.frame(Protein_Condition,Data_Condition_Norm) All_Control_Norm_Omit<-na.omit(All_Control_Norm) All_Condition_Norm_Omit<-na.omit(All_Condition_Norm) Proteins_Control_Norm_Omit<-All_Control_Norm_Omit[1] Proteins_Condition_Norm_Omit<-All_Condition_Norm_Omit[1] Data_Control_Norm_Omit<-((All_Control_Norm_Omit[2:(1+NumberTemperatures)])) Data_Condition_Norm_Omit<-(All_Condition_Norm_Omit[2:(1+NumberTemperatures)]) write_xlsx(Data_Control_Norm_Omit,paste(OutputPath,"NormalizedControlResults.xlsx",sep="/")) write_xlsx(Data_Condition_Norm_Omit,paste(OutputPath,"NormalizedConditionResults.xlsx",sep="/")) Data_Control_Norm_Omit_Median<-apply(Data_Control_Norm_Omit, 2, FUN=median) Data_Condition_Norm_Omit_Median<-apply(Data_Condition_Norm_Omit, 2, FUN=median) ControlMedian<-Data_Control_Norm_Omit_Median[1:NumberTemperatures] ConditionMedian<-Data_Condition_Norm_Omit_Median[1:NumberTemperatures] Proteins_Control_Norm_Omit<-All_Control_Norm_Omit[c(1)] Proteins_Condition_Norm_Omit<-All_Condition_Norm_Omit[c(1)] ControlNormBothCorrect<-FPLFit_Correction(ControlMedian,Data_Control_Norm_Omit,"Control",Temperature) ConditionNormBothCorrect<-FPLFit_Correction(ConditionMedian,Data_Condition_Norm_Omit,"Condition",Temperature) Data_Norm_Omit<-Data_Control_Norm_Omit NormBothCorrect<-ControlNormBothCorrect DataParametersControl<-FPLFit(Data_Control_Norm_Omit,ControlNormBothCorrect,"Control",Temperature,NumberTemperatures) DataParametersCondition<-FPLFit(Data_Condition_Norm_Omit,ConditionNormBothCorrect,"Condition",Temperature,NumberTemperatures) DataParametersControlResults <- data.frame(Proteins_Control_Norm_Omit, DataParametersControl, ControlNormBothCorrect) DataParametersConditionResults <- data.frame(Proteins_Condition_Norm_Omit, DataParametersCondition, ConditionNormBothCorrect) DataParametersResultsAll <-merge(DataParametersControlResults,DataParametersConditionResults,by="Accession") significance_condition <- DataParametersResultsAll[c(6)] >= Rsq & DataParametersResultsAll[c(NumberTemperatures+11)] >= Rsq SignificantAll<- DataParametersResultsAll[significance_condition, c(1:NCOL(DataParametersResultsAll))] ProteinsFilter<- DataParametersResultsAll[significance_condition, c(1)] DeltaTmControlMinusCondition<-SignificantAll[,3]-SignificantAll[,8+NumberTemperatures] DeltaTmDataSet<-data.table(SignificantAll,DeltaTmControlMinusCondition) DeltaTmSort<-DeltaTmDataSet[order(-DeltaTmControlMinusCondition)] Observation <- 1:NROW(ProteinsFilter) DataParametersAnalysisResults <- data.frame(Observation,DeltaTmSort) Observation <- as.numeric(DataParametersAnalysisResults[,1]) DeltTm <- DataParametersAnalysisResults[,NCOL(DataParametersAnalysisResults)] TmData <- data.table(Observation, DeltTm) SDH<-mean(DeltTm)+NumSD*sd(DeltTm) SDL<-mean(DeltTm)-NumSD*sd(DeltTm) significance_condition <- DataParametersAnalysisResults[c(NCOL(DataParametersAnalysisResults))] >= SDH | DataParametersAnalysisResults[c(NCOL(DataParametersAnalysisResults))] <= SDL SignificantAll_SD<- DataParametersAnalysisResults[significance_condition, c(1:NCOL(DataParametersAnalysisResults))] write_xlsx(DataParametersResultsAll,paste(OutputPath,"Results.xlsx",sep="/")) write_xlsx(SignificantAll_SD,paste(OutputPath,"SignificantResults.xlsx",sep="/")) n <- 1 repeat{ pdf(paste(OutputPath_Curves,paste(DataParametersAnalysisResults[n,2],"pdf",sep="."),sep="/")) plot(x = Temperature, y = DataParametersAnalysisResults[n,c(8:(NumberTemperatures+7))],pch = 2, frame = TRUE,xlab = "Temperature (C)", ylab = "Normalized Abundance",col = "blue",axes=FALSE,ylim=c(0,1.5),xlim=c(20,100),main=DataParametersAnalysisResults[n,2]) Temperaturevals<-seq(min(Temperature), max(Temperature), by=1) lines(Temperaturevals ,(DataParametersAnalysisResults[n,c(5)]+((DataParametersAnalysisResults[n,c(6)]-DataParametersAnalysisResults[n,c(5)])/(1+exp(-DataParametersAnalysisResults[n,c(3)]*(Temperaturevals-DataParametersAnalysisResults[n,c(4)]))))),col="blue") points(Temperature, DataParametersAnalysisResults[n,c((13+NumberTemperatures):(12+(2*NumberTemperatures)))], col="red", pch=8,lty=1) lines(Temperaturevals<-seq(min(Temperature), max(Temperature), by=1),(DataParametersAnalysisResults[n,c(NumberTemperatures+10)]+((DataParametersAnalysisResults[n,c(NumberTemperatures+11)]-DataParametersAnalysisResults[n,c(NumberTemperatures+10)])/(1+exp(-DataParametersAnalysisResults[n,c(NumberTemperatures+8)]*(Temperaturevals-DataParametersAnalysisResults[n,c(NumberTemperatures+9)]))))),lty=2,col="red") axis(side=1, at=seq(20,100,by=5)) axis(side=2, at=seq(0,1.5, by=.1)) legend(60,1.3,legend=c("Control","Condition"), col=c("blue","red"),pch=c(2,8),lty=c(1,2)) plottable=matrix(data=NA,nrow=3,ncol=2) colnames(plottable)<-c("Condition","Temperature") plottable[1,1]<-"Control Tm" plottable[2,1]<-"Condition Tm" plottable[3,1]<-"Delta Tm" plottable[1,2]<-round(DataParametersAnalysisResults[n,c(4)],2) plottable[2,2]<-round(DataParametersAnalysisResults[n,c(NumberTemperatures+9)],2) plottable[3,2]<-round((DataParametersAnalysisResults[n,c(4)])-(DataParametersAnalysisResults[n,c(NumberTemperatures+9)]),2) addtable2plot(60,0.8,plottable,hlines=TRUE,vlines=TRUE,bty="o",bg="gray") dev.off() n=n+1 if (n > NROW(DataParametersAnalysisResults)){ break } } n <- 1 repeat{ pdf(paste(OutputPath_SigCurves,paste(SignificantAll_SD[n,2],"pdf",sep="."),sep="/")) plot(x = Temperature, y = SignificantAll_SD[n,c(8:(NumberTemperatures+7))],pch = 2, frame = TRUE,xlab = "Temperature (C)", ylab = "Normalized Abundance",col = "blue",axes=FALSE,ylim=c(0,1.5),xlim=c(20,100),main=SignificantAll_SD[n,2]) Temperaturevals<-seq(min(Temperature), max(Temperature), by=1) lines(Temperaturevals ,(SignificantAll_SD[n,c(5)]+((SignificantAll_SD[n,c(6)]-SignificantAll_SD[n,c(5)])/(1+exp(-SignificantAll_SD[n,c(3)]*(Temperaturevals-SignificantAll_SD[n,c(4)]))))),col="blue") points(Temperature, SignificantAll_SD[n,c((13+NumberTemperatures):(12+(2*NumberTemperatures)))], col="red", pch=8,lty=1) lines(Temperaturevals<-seq(min(Temperature), max(Temperature), by=1),(SignificantAll_SD[n,c(NumberTemperatures+10)]+((SignificantAll_SD[n,c(NumberTemperatures+11)]-SignificantAll_SD[n,c(NumberTemperatures+10)])/(1+exp(-SignificantAll_SD[n,c(NumberTemperatures+8)]*(Temperaturevals-SignificantAll_SD[n,c(NumberTemperatures+9)]))))),lty=2,col="red") axis(side=1, at=seq(20,100,by=5)) axis(side=2, at=seq(0,1.5, by=.1)) legend(65,1.3,legend=c("Control","Condition"), col=c("blue","red"),pch=c(2,8),lty=c(1,2)) plottable=matrix(data=NA,nrow=3,ncol=2) colnames(plottable)<-c("Condition","Temperature") plottable[1,1]<-"Control Tm" plottable[2,1]<-"Condition Tm" plottable[3,1]<-"Delta Tm" plottable[1,2]<-round(SignificantAll_SD[n,c(4)],2) plottable[2,2]<-round(SignificantAll_SD[n,c(NumberTemperatures+9)],2) plottable[3,2]<-round((SignificantAll_SD[n,c(4)])-(SignificantAll_SD[n,c(NumberTemperatures+9)]),2) addtable2plot(65,0.8,plottable,hlines=TRUE,vlines=TRUE,bty="o",bg="gray") dev.off() n=n+1 if (n > NROW(SignificantAll_SD)){ break } } WaterfallPlot <- ggplot(DataParametersAnalysisResults[c(1,NCOL(DataParametersAnalysisResults))], aes(x = Observation,y = DeltTm)) + geom_point(size=3) + labs(x = "Rank of Melting Point Difference Control and Condition", y = "Delta Tm (C)") + ylim(c(1.1*min(DataParametersAnalysisResults$DeltaTmControlMinusCondition),1.1*max(DataParametersAnalysisResults$DeltaTmControlMinusCondition))) + theme_minimal() + theme(legend.position="none") +theme_set(theme_gray(base_size = 15))+ geom_hline(yintercept = SDH, linetype = "dashed", color = "orange") + geom_hline(yintercept=SDL, linetype = "dashed", color = "orange") plot(WaterfallPlot) ggsave(filename = "WaterfallPlot.pdf", path = OutputPath_Curves, plot = WaterfallPlot, device = "pdf", width = 10, height = 10, units = "in", useDingbats = FALSE) }
test_that("estat_0003411172", { skip_on_cran() estat_set_apikey(keyring::key_get("estat-api")) estat_set("limit_downloads", 1e1) census_2015 <- estat("https://www.e-stat.go.jp/dbview?sid=0003411172") expect_s3_class(census_2015, "estat") census_2015 <- census_2015 %>% estat_activate("\u8868\u7ae0\u9805\u76ee") %>% filter(name == "\u4eba\u53e3") %>% select() %>% estat_activate("\u5168\u56fd", "region") %>% select(code, name) %>% estat_activate("\u6642\u9593\u8ef8", "year") %>% select(name) census_2015 <- estat_download(census_2015, "pop") expect_s3_class(census_2015, "tbl_df") expect_setequal(names(census_2015), c("region_code", "region_name", "year", "pop")) expect_equal(vctrs::vec_size(census_2015), 78L) }) test_that("estat_0003183561", { skip_on_cran() estat_set_apikey(keyring::key_get("estat-api")) worker_city_2015 <- estat("0003183561") expect_s3_class(worker_city_2015, "estat") worker_city_2015 <- worker_city_2015 %>% estat_activate("\u8868\u7ae0\u9805\u76ee") %>% filter(name == "15\u6b73\u4ee5\u4e0a\u5c31\u696d\u8005\u6570") %>% select() %>% estat_activate("\u7523\u696d\u5206\u985e", "industry") %>% filter(stringr::str_detect(name, "^[AB]")) %>% select(name) %>% estat_activate("\u5e74\u9f62") %>% filter(name == "\u7dcf\u6570\uff08\u5e74\u9f62\uff09") %>% select() %>% estat_activate("\u7537\u5973|\u6027\u5225", "sex") %>% filter(name != "\u7dcf\u6570\uff08\u7537\u5973\u5225\uff09") %>% select(name) %>% estat_activate("\u5f93\u696d\u5730") %>% filter(name == "\u5317\u6d77\u9053") %>% select() %>% estat_activate("\u5e74\u6b21") %>% select() %>% estat_download("worker") expect_s3_class(worker_city_2015, "tbl_df") expect_setequal(names(worker_city_2015), c("industry", "sex", "worker")) expect_equal(vctrs::vec_size(worker_city_2015), 4L) })
harmonize_geo_code <- function (dat) { . <- change <- geo <- code13 <- code16 <- nuts_level <- NULL country_code <- n <- values <- time <- name <- resolution <- NULL dat <- mutate_if ( dat, is.factor, as.character) nuts_correspondence <- regional_changes_2016 <- eu_countries <- NULL utils::data("nuts_correspondence", package = "eurostat", envir = environment()) utils::data("regional_changes_2016", package = "eurostat", envir = environment()) utils::data("eu_countries", package = "eurostat", envir = environment()) regions_in_correspondence <- unique(c(nuts_correspondence$code13, nuts_correspondence$code16)) regions_in_correspondence <- sort(regions_in_correspondence [!is.na(regions_in_correspondence)]) unchanged_regions <- regional_changes_2016 %>% filter ( change == 'unchanged' ) regional_changes_by_2016 <- nuts_correspondence %>% mutate ( geo = code16 ) %>% filter ( !is.na(code16) ) %>% select ( -geo ) %>% distinct ( code13, code16, name, nuts_level, change, resolution) regional_changes_by_2013 <- nuts_correspondence %>% mutate ( geo = code13 ) %>% filter ( !is.na(code13) ) %>% select ( -geo ) %>% distinct ( code13, code16, name, nuts_level, change, resolution) all_regional_changes <- regional_changes_by_2016 %>% full_join ( regional_changes_by_2013, by = c("code13", "code16", "name", "nuts_level", "change", "resolution")) duplicates <- all_regional_changes %>% add_count ( code13, code16 ) %>% filter ( n > 1 ) if ( nrow(duplicates) > 0 ) { stop ("There are duplicates in the correspondence table.") } all_regions_full_metadata <- unchanged_regions %>% mutate ( resolution = NA_character_ ) %>% rbind ( all_regional_changes ) nuts_2013_codes <- unique (all_regions_full_metadata$code13) nuts_2016_codes <- unique (all_regions_full_metadata$code16) nuts_2013_codes <- nuts_2013_codes[!is.na(nuts_2013_codes)] nuts_2016_codes <- nuts_2016_codes[!is.na(nuts_2016_codes)] tmp_by_code16 <- dat %>% mutate ( geo = as.character(geo)) %>% filter ( geo %in% all_regions_full_metadata$code16 ) %>% left_join ( all_regions_full_metadata %>% dplyr::rename ( geo = code16 ), by = "geo") %>% mutate ( code16 = geo ) %>% mutate ( nuts_2016 = geo %in% nuts_2016_codes ) %>% mutate ( nuts_2013 = geo %in% nuts_2013_codes ) tmp_by_code13 <- dat %>% mutate ( geo = as.character(geo)) %>% filter ( geo %in% all_regions_full_metadata$code13 ) %>% left_join ( all_regions_full_metadata %>% dplyr::rename ( geo = code13 ), by = "geo") %>% mutate ( code13 = geo ) %>% mutate ( nuts_2016 = geo %in% nuts_2016_codes, nuts_2013 = geo %in% nuts_2013_codes) message ( "In this data frame ", nrow(tmp_by_code16), " observations are coded with the current NUTS2016\ngeo labels and ", nrow ( tmp_by_code13), " observations/rows have NUTS2013 historical labels.") tmp_s <- tmp_by_code16 %>% semi_join ( tmp_by_code13, by = names ( tmp_by_code13)) if (! all(tmp_s$nuts_2013 & tmp_s$nuts_2016)) { stop ("Wrong selection of unchanged regions.") } tmp_s2 <- tmp_by_code13 %>% semi_join ( tmp_by_code16, by = names (tmp_by_code16)) tmp_a1 <- tmp_by_code16 %>% anti_join ( tmp_by_code13, by = names(tmp_by_code13) ) if ( any(tmp_a1$nuts_2013) ) { stop ("Wrong selection of NUTS2013-only regions.") } tmp_a2 <- tmp_by_code13 %>% anti_join ( tmp_by_code16, by = names(tmp_by_code13) ) if ( any(tmp_a2$nuts_2016) ) { stop ("Wrong selection of NUTS2013-only regions.") } tmp2 <- rbind ( tmp_s, tmp_a1, tmp_a2 ) not_found_geo <- unique(dat$geo[! dat$geo %in% tmp2$geo ]) not_eu_regions <- not_found_geo[! substr(not_found_geo,1,2) %in% eu_countries$code] not_found_eu_regions <- not_found_geo[ substr(not_found_geo,1,2) %in% eu_countries$code] if ( length(not_found_eu_regions)>0 ) { if ( any( not_found_eu_regions %in% c("SI02", "SI01", "EL1", "EL2", "UKI1", "UK2"))) { message ( "Some or all of these regions use codes earlier than NUTS2013 definition.") } if ( any(grepl("XX", not_found_eu_regions ))) { message ( "Some or all of these regions use data that cannot be connected to a regional unit.") } tmp_not_found <- dat %>% filter ( geo %in% not_found_eu_regions ) %>% mutate ( nuts_level = nchar(geo)-2, name = NA_character_, code13 = NA_character_, code16 = NA_character_, nuts_2016 = FALSE, nuts_2013 = FALSE) %>% mutate ( code13 = case_when ( geo == "EL1" ~ "EL5", geo == "EL2" ~ "EL6", geo == "SI01" ~ "SI03", geo == "SI02" ~ "SI04", geo %in% c("UKI1", "UKI2") ~ NA_character_, substr(geo,3,4) == "XX" ~ geo, TRUE ~ NA_character_ )) %>% mutate ( code16 = case_when ( geo == "EL1" ~ "EL5", geo == "EL2" ~ "EL6", geo == "SI01" ~ "SI03", geo == "SI02" ~ "SI04", geo %in% c("UKI1", "UKI2") ~ NA_character_, substr(geo,3,4) == "XX" ~ geo, TRUE ~ NA_character_) ) %>% mutate ( name = dplyr::case_when ( geo == "SI01" ~ "Vzhodna Slovenija", geo == "SI02" ~ "Zahodna Slovenija", geo == "EL1" ~ "Voreia Ellada", geo == "EL2" ~ "Kentriki Ellada", geo %in% c("UKI1", "UKI2") ~ NA_character_, substr(geo,3,4) == "XX" ~ "data not related to any territorial unit", TRUE ~ NA_character_)) %>% mutate ( change = dplyr::case_when ( geo %in% c("UKI1", "UKI2") ~ "split in 2013 (NUTS2010 coding)", geo %in% c("EL1", "EL2") ~ "boundary shift in 2013 (NUTS2010 coding)", geo %in% c("SI01", "SI02") ~ "boundary shift in 2013 (NUTS2010 coding)", substr(geo,3,4) == "XX" ~ "data not related to any territorial unit", TRUE ~ NA_character_ )) %>% mutate ( resolution = "You should control these changes and see how they affect your data.") still_not_found_vector <- tmp_not_found %>% filter ( is.na(code16)) %>% select (geo) %>% unlist () %>% unique() if ( length(still_not_found_vector)>0) { warning ( "The following geo labels were not found in the correspondence table:", paste(still_not_found_vector, collapse = ", "), ".") } tmp2 <- rbind ( tmp2, tmp_not_found ) } tmp_not_eu <- dat %>% filter ( geo %in% not_eu_regions ) %>% mutate ( nuts_level = nchar(geo)-2, change = "not in EU - not controlled", resolution = "check with national authorities", name = NA_character_, code13 = NA_character_, code16 = NA_character_, nuts_2016 = FALSE, nuts_2013 = FALSE) tmp3 <- rbind ( tmp2, tmp_not_eu ) if ( length(dat$geo [! dat$geo %in% tmp3$geo ])>0 ) { unique ( dat$geo [! dat$geo %in% tmp3$geo ]) message (tmp3 %>% anti_join (dat)) message (dat %>% anti_join (tmp3)) stop ("Not all original rows were checked.") } utils::data(eu_countries, package ="eurostat", envir = environment()) eu_country_vector <- unique ( substr(eu_countries$code, 1, 2) ) if ( any(tmp3$change == 'not in EU - not controlled') ) { not_EU_country_vector <- tmp3 %>% filter ( change == 'not in EU - not controlled' ) %>% select ( geo ) not_eu_observations <- nrow (not_EU_country_vector) not_EU_country_vector <- not_EU_country_vector %>% unlist() %>% substr(., 1,2) %>% sort () %>% unique () message ( "Not checking for regional label consistency in non-EU countries.\n", "In this data frame not controlled countries: ", paste (not_EU_country_vector, collapse = ", "), " \n", "with altogether ", not_eu_observations, " observations/rows.") } tmp_left <- tmp3 %>% select ( geo, time, values, code13, code16, name ) tmp_right <- tmp3 %>% select ( -geo, -code13, -code16, -time, -values, -name ) cbind ( tmp_left, tmp_right) }
best_subset_classifier <- function(model, data.train, model.family, model.optimizer, n.iter, verbose = c(TRUE, FALSE)) { if (isTRUE(verbose == TRUE)) { if (model.optimizer == 'bobyqa'){ out <- lme4::glmer(formula = model, data = data.train, family = model.family, lme4::glmerControl( optimizer = model.optimizer, optCtrl = list(maxfun = n.iter))) } else if (model.optimizer == 'nloptwrap') { out <- lme4::glmer(formula = model, data = data.train, family = model.family, lme4::glmerControl( calc.derivs = FALSE, optimizer = model.optimizer, optCtrl = list( method = "NLOPT_LN_NELDERMEAD", starttests = TRUE, kkt = TRUE))) } } else { if (model.optimizer == 'bobyqa') { out <- suppressMessages(suppressWarnings( lme4::glmer(formula = model, data = data.train, family = model.family, lme4::glmerControl(optimizer = model.optimizer, optCtrl = list(maxfun = n.iter))) )) } else if (model.optimizer == 'nloptwrap') { out <- suppressMessages(suppressWarnings( lme4::glmer(formula = model, data = data.train, family = model.family, lme4::glmerControl( calc.derivs = FALSE, optimizer = model.optimizer, optCtrl = list( method = "NLOPT_LN_NELDERMEAD", starttests = TRUE, kkt = TRUE))) )) } } return(out) }
exchangeSPsurv <- function(duration, immune, Y0, LY, S, data, N, burn, thin, w = c(1, 1, 1), m = 10, ini.beta = 0, ini.gamma = 0, ini.W = 0, ini.V= 0, form = c('Weibull', 'exponential', 'loglog'), prop.varV, prop.varW, id_WV = unique(data[,S])) { dis <- match.arg(form) model <- 'frailtySPsurv' r <- formcall(duration = duration, immune = immune, data = data, Y0 = Y0, LY = LY, S = S, N = N, burn = burn, thin = thin, w = w, m = m, ini.beta = ini.beta, ini.gamma = ini.gamma, ini.W = ini.W, ini.V = ini.V, form = dis, prop.varV = prop.varV, prop.varW = prop.varW, model = model) if(form == 'loglog'){ results <- mcmcfrailtySPlog(Y = r$Y, Y0 = r$Y0, C = r$C, LY = r$LY, X = r$X, Z = r$Z, S = r$S, N = r$N, burn = r$burn, thin = r$thin, w = r$w, m = r$m, ini.beta = r$ini.beta, ini.gamma = r$ini.gamma, ini.W = r$ini.W, ini.V = r$ini.V, form = r$form, prop.varV = r$prop.varV, prop.varW = r$prop.varW, id_WV = id_WV) } else { results <- mcmcfrailtySP(Y = r$Y, Y0 = r$Y0, C = r$C, LY = r$LY, X = r$X, Z = r$Z, S = r$S, N = r$N, burn = r$burn, thin = r$thin, w = r$w, m = r$m, ini.beta = r$ini.beta, ini.gamma = r$ini.gamma, ini.W = r$ini.W, ini.V = r$ini.V, form = r$form, prop.varV = r$prop.varV, prop.varW = r$prop.varW, id_WV = id_WV) } results$call <- match.call() class(results) <- c(model) results } summary.frailtySPsurv <- function(object, parameter = character(), ...){ summary(coda::mcmc(object[[parameter]]), ...) } print.frailtySPsurv <- function(x, ...){ cat('Call:\n') print(x$call) cat('\n') x2 <- summary(x, parameter = 'betas') cat("\n", "Iterations = ", x2$start, ":", x2$end, "\n", sep = "") cat("Thinning interval =", x2$thin, "\n") cat("Number of chains =", x2$nchain, "\n") cat("Sample size per chain =", (x2$end - x2$start)/x2$thin + 1, "\n") cat("\nEmpirical mean and standard deviation for each variable,") cat("\nplus standard error of the mean:\n\n") cat('\n') cat('Duration equation: \n') print(summary(x, parameter = 'betas')$statistics) cat('\n') cat('Immune equation: \n') print(summary(x, parameter = 'gammas')$statistics) cat('\n') } plot.frailtySPsurv <- function(x, parameter = character(), ...){ plot((coda::mcmc(x[[parameter]])), ...) }
"emae_series"
print.MisfittingPersons <- function(x, ...) { cat("\n") cat("Percentage of Misfitting Persons:", round(x$PersonMisfit,4), "%","\n") cat("\n") }
pairSE<-function(daten, m=NULL, nsample=30, size=0.50, seed="no", pot=TRUE, zerocor=TRUE, verbose=TRUE, ...){ N<-dim(daten)[1] k<-dim(daten)[2] if(mode(size)=="character") {if(size=="jack"){nsize<-N-1 ; nsample=N } } if(mode(size)=="numeric") {if(size >= 1 | size <= 0 ) stop("size should have values between 0 and 1") ;nsize<-round(N*size)} if(mode(seed)=="numeric") {set.seed(seed)} ergli<-vector("list", length=nsample) for (i in 1:nsample){ sx<-daten[sample(1:dim(daten)[1],nsize),] if(verbose==TRUE){cat("sample ", i , "of",nsample, "with size n =",nsize,"\n")} ergli[[i]]<-pair(sx, m=m, pot=pot,zerocor=zerocor) } dim(ergli[[1]]$threshold)[1] -> nvar dim(ergli[[1]]$threshold)[2] -> nthr ergli_sig <- t(sapply(ergli,function(x){x$sigma})) SE_sig<-apply(ergli_sig, 2, sd,na.rm=TRUE) ergli_thr <- t(sapply(ergli,function(x){x$threshold})) SE_thr <- matrix((apply(ergli_thr, 2, sd,na.rm=TRUE)),nrow=nvar,ncol=nthr,byrow=F) rownames(SE_thr) <- names(SE_sig) colnames(SE_thr) <- paste("threshold",1:nthr,sep=".") SE <- SE_thr SEsigma <- SE_sig parametererg <- pair(daten, m=m, pot=pot,zerocor=zerocor) parametererg_1 <- parametererg$threshold erg<-list(threshold=parametererg_1, sigma=parametererg$sigma, SE=SE, SEsigma=SEsigma) class(erg) <- c("pairSE","list") return(erg) }
print.TransModel <- function(x,...){ cat("Call:\n") print(x$call) if(x$p==0){ cat("No covariates/ null model.","\n") } if(x$p>0){ cat("\nCoefficients:\n") print(x$coefficients) cat("\nCovariance Matrix:\n") print(x$vcov) } class(x)<-"TransModel" }
get_some_data <- function(config, outfile) { if (config_bad(config)) { stop("Bad config") } if (!can_write(outfile)) { stop("Can't write outfile") } if (!can_open_network_connection(config)) { stop("Can't access network") } data <- parse_something_from_network() if(!makes_sense(data)) { return(FALSE) } data <- beautify(data) write_it(data, outfile) TRUE }
BDATBIOMASSE <- function(BDATArtNr, D1, H1 = 0, D2 = 0, H2 = 0, H) { df <- data.frame( spp = BDATArtNr, D1 = D1, H1 = H1, D2 = D2, H2 = H2, H = H ) res <- getBiomass(tree = df, mapping = NULL) return(res) }
plot.indicators<-function(x, type="sqrtIV", maxline=TRUE, ...) { A = x$A B = x$B sqrtIV=x$sqrtIV order = rowSums(x$C) if(is.data.frame(A)) { if(type=="IV") val = sqrtIV[,1]^2 else if(type=="sqrtIV") val = sqrtIV[,1] else if(type=="A") val = A[,1] else if(type=="B") val = B[,1] else if(type=="LA") val = A[,2] else if(type=="UA") val = A[,3] else if(type=="LB") val = B[,2] else if(type=="UB") val = B[,3] else if(type=="LsqrtIV") val = sqrtIV[,2] else if(type=="UsqrtIV") val = sqrtIV[,3] } else { if(type=="IV") val = sqrtIV^2 else if(type=="sqrtIV") val = sqrtIV else if(type=="A") val = A else if(type=="B") val = B } plot(order,val, type="n", axes=FALSE, xlab="Order", ylab=type,...) points(order,val, pch=1, cex=0.5) axis(1, at = order, labels=order) axis(2) if(maxline) lines(1:max(order),tapply(val,order,max), col="gray") }
knitr::opts_chunk$set(echo = TRUE) knitr::opts_knit$set(root.dir = '.') library(magrittr) knitr::include_graphics("NBL_data_files.png", dpi = 10) knitr::include_graphics("download_from_cart.png", dpi = 10)
get_na_counts <- function(x, grouping_cols = NULL, exclude_cols=NULL){ UseMethod("get_na_counts") } get_na_counts.data.frame <- function(x, grouping_cols = NULL, exclude_cols = NULL){ if(! is.null(grouping_cols)){ check_column_existence(x, grouping_cols, unique_name = "to group by") x <- x %>% dplyr::group_by(!!!dplyr::syms(grouping_cols)) } if(! is.null(exclude_cols)){ check_column_existence(x, exclude_cols,unique_name = "to exclude") x <- x %>% dplyr::select(-all_of(exclude_cols)) } x %>% dplyr::summarise(dplyr::across(dplyr::everything(), ~sum(is.na(.)))) }
ULS_Gauss <- function(prep){ fit_per_group <- (prep$nPerGroup+1)/(prep$nTotal) * sapply(prep$groupModels, do.call, what=ULS_Gauss_pergroup) sum(fit_per_group) } ULS_Gauss_pergroup <- function(means,S,tau,mu,sigma,WLS.W,estimator,thresholds, meanstructure = TRUE, corinput = FALSE,...){ if (estimator == "DWLS"){ WLS.W <- Diagonal(x = diag(WLS.W)) } if (missing(tau) || all(is.na(as.matrix(tau)))){ if (meanstructure){ obs <- as.vector(means) imp <- as.vector(mu) } else { obs <- numeric(0) imp <- numeric(0) } } else { obs <- numeric(0) imp <- numeric(0) for (i in seq_along(thresholds)){ if (!is.na(means[i])){ obs <- c(obs, means[i]) imp <- c(imp, mu[i]) } else { obs <- c(obs, thresholds[[i]]) imp <- c(imp, tau[seq_len(length(thresholds[[i]])),i]) } } } if (corinput){ obs <- c(obs, Vech(S, diag = FALSE)) imp <- c(imp, Vech(sigma, diag = FALSE)) } else { obs <- c(obs, Vech(S)) imp <- c(imp, Vech(sigma)) } as.numeric(t(obs - imp) %*% WLS.W %*% (obs - imp)) }
ahistory <- function(artifact = NULL, md5hash = NULL, repoDir = aoptions('repoDir'), format = "regular", alink = FALSE, ...) { if (!is.null(artifact)) md5hash <- adigest(artifact) if (is.null(md5hash)) stop("Either artifact or md5hash has to be set") stopifnot(length(format) == 1 & format %in% c("regular", "kable")) elements <- strsplit(md5hash, "/")[[1]] if (length(elements) >= 3){ md5hash <- tail(elements,1) subdir <- ifelse(length(elements) > 3, paste(elements[3:(length(elements)-1)], collapse="/"), "/") RemoteRepoCheck( repo = elements[2], user = elements[1], branch = "master", subdir = subdir, repoType = aoptions("repoType")) remoteHook <- getRemoteHook(repo = elements[2], user = elements[1], branch = "master", subdir = subdir) Temp <- downloadDB( remoteHook ) on.exit( unlink( Temp, recursive = TRUE, force = TRUE)) repoDir <- Temp } res_names <- c() res_md5 <- md5hash ind <- 1 while (!is.null(md5hash) && length(md5hash)>0) { tags <- getTagsLocal(md5hash, tag = "", repoDir=repoDir) tmp <- grep(tags, pattern="^RHS:", value = TRUE) if (length(tmp) > 0) { res_names[ind] <- substr(tmp[1],5,nchar(tmp[1])) } else { tmp <- grep(tags, pattern="^name:", value = TRUE) if (length(tmp) > 0) { res_names[ind] <- substr(tmp[1],6,nchar(tmp[1])) } else { df <- data.frame(md5hash = res_md5, call = rep("", length(res_md5)), stringsAsFactors = FALSE) if (format == "kable") { class(df) = c("ahistoryKable", "data.frame") if (alink) { df$md5hash <- paste0("[", df$md5hash, "]", sapply(df$md5hash, alink, ...) %>% as.vector() %>% strsplit(split = "]") %>% lapply(`[[`, 2) ) } } else { class(df) = c("ahistory", "data.frame") } return(df) } } md5hash <- grep(tags, pattern="^LHS:", value = TRUE) if (length(md5hash) > 0) { md5hash <- substr(md5hash[1],5,nchar(md5hash[1])) res_md5[ind+1] <- md5hash } ind <- ind + 1 } if (length(res_md5) != length(res_names)) { res_md5[max(length(res_md5), length(res_names))+1] = "" res_names[max(length(res_md5), length(res_names))+1] = "" } df <- data.frame(md5hash = res_md5, call = res_names, stringsAsFactors = FALSE) if (format == "kable") { class(df) = c("ahistoryKable", "data.frame") if (alink) { df$md5hash <- paste0("[", df$md5hash, "]", sapply(df$md5hash, alink, ...) %>% as.vector() %>% strsplit(split = "]") %>% lapply(`[[`, 2) ) } } else { class(df) = c("ahistory", "data.frame") } df } print.ahistory <- function(x, ...) { x[,2] <- paste0(x[,2], sapply(max(nchar(x[,2])) + 1 - nchar(x[,2]), function(j) paste(rep(" ", j), collapse=""))) for (i in nrow(x):1) { if (i < nrow(x)) cat("-> ") else cat(" ") cat(x[i,2], " [", x[i,1], "]\n", sep = "") } } print.ahistoryKable <- function(x, ...){ if (!requireNamespace("knitr", quietly = TRUE)) { stop("knitr package required for archivist:::print.ahistoryKable function") } cat(knitr::kable(x[nrow(x):1, 2:1], ...), sep="\n") }
select.spls <- function(model){ res.select <- list() for (h in 1:model$ncomp){ set.ind.zero <- which(model$loadings$X[,h]!=0) names(set.ind.zero) <- model$names$X[set.ind.zero] res.select[[h]] <- set.ind.zero } select.x <- res.select ind.total.x <- sort(unique(unlist(select.x))) names(ind.total.x) <- model$names$X[ind.total.x] res.select <- list() for (h in 1:model$ncomp){ set.ind.zero <- which(model$loadings$Y[,h]!=0) names(set.ind.zero) <- model$names$Y[set.ind.zero] res.select[[h]] <- set.ind.zero } select.y <- res.select ind.total.y <- sort(unique(unlist(select.y))) names(ind.total.y) <- model$names$Y[ind.total.y] return(list(select.X=select.x,select.Y=select.y,select.X.total=ind.total.x,select.Y.total=ind.total.y)) }
lsem_bootstrap_inference <- function(parameters_boot, est, repl_factor=NULL) { R <- ncol(parameters_boot) est_boot <- rowMeans(parameters_boot, na.rm=TRUE) if (is.null(repl_factor)){ repl_factor <- 1/(R-1) } se_boot <- sqrt( rowSums( ( parameters_boot - est_boot )^2 ) * repl_factor ) bias_boot <- (est_boot - est)*repl_factor*(R-1) est_bc <- est - bias_boot res <- list(mean_boot=est_boot, se_boot=se_boot, est_bc=est_bc, bias_boot=bias_boot, est=est) return(res) }
if (getRversion() >= "2.15.1") { utils::globalVariables(c( "regionId", "i.family", "wd", "wd.x", "wd.y", "taxo", ".EACHI", "meanWDsp", "nIndsp", "sdWDsp", "meanWD", "meanWDgn", "nInd", "nIndgn", "sdWD", "sdWDgn", "levelWD", "meanWDfm", "nIndfm", "sdWDfm", "meanWDst", "nIndst", "sdWDst" )) } getWoodDensity <- function(genus, species, stand = NULL, family = NULL, region = "World", addWoodDensityData = NULL, verbose = TRUE) { if (length(genus) != length(species)) { stop("Your data (genus and species) do not have the same length") } if (!is.null(family) && (length(genus) != length(family))) { stop("Your family vector and your genus/species vectors do not have the same length") if (any(colSums(table(family, genus) > 0, na.rm = TRUE) >= 2)) { stop("Some genera are in two or more families") } } if (!is.null(stand) && (length(genus) != length(stand))) { stop("Your stand vector and your genus/species vectors do not have the same length") } if (!is.null(addWoodDensityData)) { if (!(all(names(addWoodDensityData) %in% c("genus", "species", "wd", "family")) && length(names(addWoodDensityData)) %in% c(3, 4))) { stop('The additional wood density database should be organized in a dataframe with three (or four) columns: "genus","species","wd", and the column "family" is optional') } } wdData <- setDT(copy(BIOMASS::wdData)) sd_10 <- setDT(copy(BIOMASS::sd_10)) sd_tot <- sd(wdData$wd) Region <- tolower(region) if ((Region != "world") && any(is.na(chmatch(Region, tolower(wdData$regionId))))) { stop("One of the region you entered is not recognized in the global wood density database") } subWdData <- wdData if (!("world" %in% Region)) { subWdData <- wdData[tolower(regionId) %chin% Region] } if (nrow(subWdData) < 1000 && is.null(addWoodDensityData)) { warning( "DRYAD data only stored ", nrow(subWdData), " wood density values in your region of interest. ", 'You could provide additional wood densities (parameter addWoodDensityData) or widen your region (region="World")' ) } if (!is.null(addWoodDensityData)) { setDT(addWoodDensityData) if (!("family" %in% names(addWoodDensityData))) { genusFamily <- setDT(copy(BIOMASS::genusFamily)) addWoodDensityData[genusFamily, on = "genus", family := i.family] } addWoodDensityData <- addWoodDensityData[!is.na(wd), ] subWdData <- merge(subWdData, addWoodDensityData, by = c("family", "genus", "species"), all = TRUE) subWdData[!is.na(regionId), wd := wd.x][is.na(regionId), wd := wd.y][, ":="(wd.x = NULL, wd.y = NULL)] } if (verbose) { message("The reference dataset contains ", nrow(subWdData), " wood density values") } inputData <- data.table(genus = as.character(genus), species = as.character(species)) if (!is.null(family)) { inputData[, family := as.character(family)] } else { if (!exists("genusFamily", inherits = FALSE)) { genusFamily <- setDT(copy(BIOMASS::genusFamily)) } inputData[genusFamily, on = "genus", family := i.family] } if (!is.null(stand)) { inputData[, stand := as.character(stand)] } taxa <- unique(inputData, by = c("family", "genus", "species")) if (verbose) { message("Your taxonomic table contains ", nrow(taxa), " taxa") } coalesce <- function(x, y) { if (length(y) == 1) { y <- rep(y, length(x)) } where <- is.na(x) x[where] <- y[where] x } meanWdData <- subWdData[(family %in% taxa$family | genus %in% taxa$genus | species %in% taxa$species), ] if (nrow(meanWdData) == 0) { stop("Our database have not any of your family, genus and species") } inputData[, ":="(meanWD = NA_real_, nInd = NA_integer_, sdWD = NA_real_, levelWD = NA_character_)] if (!((!is.null(family) && nrow(merge(inputData, meanWdData[, .N, by = .(family)], c("family"))) != 0) || nrow(merge(inputData, meanWdData[, .N, by = .(family, genus)], c("family", "genus"))) != 0 || nrow(merge(inputData, meanWdData[, .N, by = .(family, genus, species)], c("family", "genus", "species"))) != 0)) { stop("There is no exact match among the family, genus and species, try with 'addWoodDensity' or inform the 'family' or increase the 'region'") } sdSP <- sd_10[taxo == "species", sd] meanSP <- meanWdData[, by = c("family", "genus", "species"), .( meanWDsp = mean(wd), nIndsp = .N, sdWDsp = sdSP ) ] inputData[meanSP, on = c("family", "genus", "species"), by = .EACHI, `:=`( meanWD = meanWDsp, nInd = nIndsp, sdWD = sdWDsp, levelWD = "species" ) ] sdGN <- sd_10[taxo == "genus", sd] meanGN <- meanSP[, by = c("family", "genus"), .( meanWDgn = mean(meanWDsp), nIndgn = .N, sdWDgn = sdGN ) ] inputData[meanGN, on = c("family", "genus"), by = .EACHI, `:=`( meanWD = coalesce(meanWD, meanWDgn), nInd = coalesce(nInd, nIndgn), sdWD = coalesce(sdWD, sdWDgn), levelWD = coalesce(levelWD, "genus") ) ] if (!is.null(family)) { sdFM <- sd_10[taxo == "family", sd] meanFM <- meanGN[, by = family, .( meanWDfm = mean(meanWDgn), nIndfm = .N, sdWDfm = sdFM ) ] inputData[meanFM, on = "family", by = .EACHI, `:=`( meanWD = coalesce(meanWD, meanWDfm), nInd = coalesce(nInd, nIndfm), sdWD = coalesce(sdWD, sdWDfm), levelWD = coalesce(levelWD, "family") ) ] } if (!is.null(stand)) { meanST <- inputData[!is.na(meanWD), by = stand, .( meanWDst = mean(meanWD), nIndst = .N, sdWDst = sd(meanWD) ) ] inputData[is.na(meanWD), levelWD := stand] inputData[meanST, on = "stand", by = .EACHI, `:=`( meanWD = coalesce(meanWD, meanWDst), nInd = coalesce(nInd, nIndst), sdWD = coalesce(sdWD, sdWDst) ) ] } meanDS <- inputData[ !is.na(meanWD), .( meanWDds = mean(meanWD), nIndds = .N, sdWDds = sd(meanWD) ) ] inputData[ is.na(meanWD), `:=`( meanWD = meanDS$meanWDds, nInd = meanDS$nIndds, sdWD = meanDS$sdWDds, levelWD = "dataset" ) ] inputData[is.na(sdWD) | sdWD==0, sdWD:=sd_tot] result <- setDF(inputData[, .(family, genus, species, meanWD, sdWD, levelWD, nInd)]) return(result) }
timeIntegratedBranchRate <- function(t1, t2, p1, p2){ tol <- 0.00001; res <- vector(mode = 'numeric', length = length(t1)); zero <- which(abs(p2) < tol); p1s <- p1[zero]; t1s <- t1[zero]; t2s <- t2[zero]; res[zero] <- p1s * (t2s - t1s); nonzero <- which(p2 < -tol); p1s <- p1[nonzero]; p2s <- p2[nonzero]; t1s <- t1[nonzero]; t2s <- t2[nonzero]; res[nonzero] <- (p1s/p2s)*(exp(p2s*t2s) - exp(p2s*t1s)); nonzero <- which(p2 > tol); p1s <- p1[nonzero]; p2s <- p2[nonzero]; t1s <- t1[nonzero]; t2s <- t2[nonzero]; res[nonzero] <- (p1s/p2s)*(2*p2s*(t2s-t1s) + exp(-p2s*t2s) - exp(-p2s*t1s)); return(res); }
subset.mppData <- function(x, mk.list = NULL, gen.list = NULL, ...) { check_mppData(mppData = x) if(is.null(mk.list) && is.null(gen.list)){ stop("You must specify either mk.list or gen.list.") } if (!is.null(mk.list)){ if (!(is.character(mk.list) || is.logical(mk.list) || is.numeric(mk.list))) { stop("mk.list must be a character, logical or numeric vector.") } if(is.logical(mk.list)){ if(length(mk.list) != dim(x$map)[1]) stop("The mk.list does not have the same length as the map") } if (is.logical(mk.list) || is.numeric(mk.list)) { mk.list <- x$map[mk.list, 1] } } if (!is.null(gen.list)){ if (!(is.character(gen.list) || is.logical(gen.list) || is.numeric(gen.list))) { stop("gen.list must be a character, logical or numeric vector.") } if(is.logical(gen.list)){ if(length(gen.list) != length(x$geno.id)) stop("gen.list does not have the same length as the genotypes list") } if (is.logical(gen.list) || is.numeric(gen.list)) { gen.list <- x$geno.id[gen.list] geno.ind <- x$geno.id %in% gen.list } else if(is.character(gen.list)) { geno.ind <- x$geno.id %in% gen.list } } if(!is.null(mk.list)){ x$geno.IBS <- x$geno.IBS[, x$map[, 1] %in% mk.list, drop = FALSE] for (i in 1:length(x$geno.IBD$geno)) { chr.mk.names <- attr(x$geno.IBD$geno[[i]]$prob, "dimnames")[[2]] indicator <- chr.mk.names %in% mk.list x$geno.IBD$geno[[i]]$prob <- x$geno.IBD$geno[[i]]$prob[, indicator, ] } x$allele.ref <- x$allele.ref[, x$map[, 1] %in% mk.list, drop = FALSE] x$geno.par <- x$geno.par[(x$geno.par[, 1] %in% mk.list), , drop = FALSE] if(!is.null(x$par.clu)){ x$par.clu <- x$par.clu[rownames(x$par.clu) %in% mk.list, , drop = FALSE] } x$map <- x$map[(x$map[, 1] %in% mk.list), , drop = FALSE] chr.ind <- factor(x = x$map[, 2], levels = unique(x$map[, 2])) x$map[, 3] <- sequence(table(chr.ind)) } if(!is.null(gen.list)){ x$geno.IBS <- x$geno.IBS[geno.ind, ] for (i in 1:length(x$geno.IBD$geno)) { x$geno.IBD$geno[[i]]$prob <- x$geno.IBD$geno[[i]]$prob[geno.ind, , ] } x$pheno <- x$pheno[geno.ind, , drop = FALSE] x$geno.id <- x$geno.id[geno.ind] ped.temp <- as.matrix(x$ped.mat) ped.mat.found <- ped.temp[ped.temp[, 1] == "founder", , drop = FALSE] ped.mat.off <- ped.temp[ped.temp[, 1] == "offspring", , drop = FALSE] ped.mat.off <- ped.mat.off[geno.ind, , drop = FALSE] found.sub <- unique(c(ped.mat.off[, 3], ped.mat.off[, 4])) ped.mat.found <- ped.mat.found[ped.mat.found[, 2] %in% found.sub, , drop = FALSE] pedigree.new <- rbind(ped.mat.found, ped.mat.off) x$ped.mat <- data.frame(pedigree.new, stringsAsFactors = FALSE) x$cross.ind <- x$cross.ind[geno.ind] } list.cr <- unique(x$cross.ind) ppc <- x$par.per.cross ppc <- ppc[ppc[, 1] %in% list.cr, , drop = FALSE] x$parents <- union(ppc[, 2], ppc[, 3]) x$n.cr <- length(list.cr) x$n.par <- length(x$parents) x$par.per.cross <- ppc new_par <- c("mk.names", "chr", "pos.ind", "pos.cM", x$parents) x$geno.par <- x$geno.par[, colnames(x$geno.par) %in% new_par , drop = FALSE] if(!is.null(x$par.clu)){ par.clu <- x$par.clu par.clu <- par.clu[, x$parents] par.clu <- parent_clusterCheck(par.clu = par.clu)[[1]] x$par.clu <- par.clu } class(x) <- c("mppData", "list") return(x) }
aw <- function(object, ...) UseMethod("aw") aw.mkinfit <- function(object, ...) { oo <- list(...) data_object <- object$data[c("time", "variable", "observed")] for (i in seq_along(oo)) { if (!inherits(oo[[i]], "mkinfit")) stop("Please supply only mkinfit objects") data_other_object <- oo[[i]]$data[c("time", "variable", "observed")] if (!identical(data_object, data_other_object)) { stop("It seems that the mkinfit objects have not all been fitted to the same data") } } all_objects <- list(object, ...) AIC_all <- sapply(all_objects, AIC) delta_i <- AIC_all - min(AIC_all) denom <- sum(exp(-delta_i/2)) w_i <- exp(-delta_i/2) / denom return(w_i) } aw.mmkin <- function(object, ...) { if (ncol(object) > 1) stop("Please supply an mmkin column object") do.call(aw, object) }
library(ggplot2) sortList <- function(x) { x[sort(names(x))] } print.ggplot <- custom_print.ggplot test_that("ggplot coordmap", { dat <- data.frame(xvar = c(0, 5), yvar = c(10, 20)) tmpfile <- tempfile("test-shiny", fileext = ".png") on.exit(unlink(tmpfile)) p <- ggplot(dat, aes(xvar, yvar)) + geom_point() + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0)) png(tmpfile, width = 500, height = 500) m <- getGgplotCoordmap(print(p), 500, 500, 72) dev.off() expect_equal(m$dims, list(width = 500, height = 500)) expect_equal(m$panels[[1]]$mapping, list(x = "xvar", y = "yvar")) expect_equal( sortList(m$panels[[1]]$domain), sortList(list(left=0, right=5, bottom=10, top=20)) ) expect_equal( sortList(m$panels[[1]]$log), sortList(list(x=NULL, y=NULL)) ) expect_identical(m$panels[[1]]$panel_vars, list(a=1)[0]) expect_true(m$panels[[1]]$range$left > 20 && m$panels[[1]]$range$left < 70) expect_true(m$panels[[1]]$range$right > 480 && m$panels[[1]]$range$right < 499) expect_true(m$panels[[1]]$range$bottom > 450 && m$panels[[1]]$range$bottom < 490) expect_true(m$panels[[1]]$range$top > 1 && m$panels[[1]]$range$top < 20) p <- ggplot(dat, aes(xvar)) + geom_point(aes(y=yvar)) png(tmpfile) m <- getGgplotCoordmap(print(p), 500, 500, 72) dev.off() expect_equal(sortList(m$panels[[1]]$mapping), list(x = "xvar", y = "yvar")) p <- ggplot(dat, aes(xvar/2)) + geom_histogram(binwidth=1) png(tmpfile) m <- getGgplotCoordmap(print(p), 500, 500, 72) dev.off() expect_equal(sortList(m$panels[[1]]$mapping), list(x = "xvar/2", y = NULL)) }) test_that("ggplot coordmap with facet_wrap", { dat <- data.frame(xvar = c(0, 5, 10), yvar = c(10, 20, 30), g = c("a", "b", "c")) tmpfile <- tempfile("test-shiny", fileext = ".png") on.exit(unlink(tmpfile)) p <- ggplot(dat, aes(xvar, yvar)) + geom_point() + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0)) + facet_wrap(~ g, ncol = 2) png(tmpfile) m <- getGgplotCoordmap(print(p), 500, 400, 72) dev.off() expect_equal(length(m$panels), 3) expect_equal(m$panels[[1]]$panel, 1) expect_equal(m$panels[[1]]$row, 1) expect_equal(m$panels[[1]]$col, 1) expect_equal(m$panels[[2]]$panel, 2) expect_equal(m$panels[[2]]$row, 1) expect_equal(m$panels[[2]]$col, 2) expect_equal(m$panels[[3]]$panel, 3) expect_equal(m$panels[[3]]$row, 2) expect_equal(m$panels[[3]]$col, 1) expect_equal(m$panels[[1]]$mapping, list(x = "xvar", y = "yvar", panelvar1 = "g")) expect_equal(m$panels[[1]]$mapping, m$panels[[2]]$mapping) expect_equal(m$panels[[2]]$mapping, m$panels[[3]]$mapping) expect_equal( sortList(m$panels[[1]]$domain), sortList(list(left=0, right=10, bottom=10, top=30)) ) expect_equal(sortList(m$panels[[1]]$domain), sortList(m$panels[[2]]$domain)) expect_equal(sortList(m$panels[[2]]$domain), sortList(m$panels[[3]]$domain)) factor_vals <- dat$g expect_equal(m$panels[[1]]$panel_vars, list(panelvar1 = factor_vals[1])) expect_equal(m$panels[[2]]$panel_vars, list(panelvar1 = factor_vals[2])) expect_equal(m$panels[[3]]$panel_vars, list(panelvar1 = factor_vals[3])) }) test_that("ggplot coordmap with facet_grid", { dat <- data.frame(xvar = c(0, 5, 10), yvar = c(10, 20, 30), g = c("a", "b", "c")) tmpfile <- tempfile("test-shiny", fileext = ".png") on.exit(unlink(tmpfile)) p <- ggplot(dat, aes(xvar, yvar)) + geom_point() + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0)) p1 <- p + facet_grid(. ~ g) png(tmpfile) m <- getGgplotCoordmap(print(p1), 500, 400, 72) dev.off() expect_equal(length(m$panels), 3) expect_equal(m$panels[[1]]$panel, 1) expect_equal(m$panels[[1]]$row, 1) expect_equal(m$panels[[1]]$col, 1) expect_equal(m$panels[[2]]$panel, 2) expect_equal(m$panels[[2]]$row, 1) expect_equal(m$panels[[2]]$col, 2) expect_equal(m$panels[[3]]$panel, 3) expect_equal(m$panels[[3]]$row, 1) expect_equal(m$panels[[3]]$col, 3) expect_equal(m$panels[[1]]$mapping, list(x = "xvar", y = "yvar", panelvar1 = "g")) expect_equal(m$panels[[1]]$mapping, m$panels[[2]]$mapping) expect_equal(m$panels[[2]]$mapping, m$panels[[3]]$mapping) expect_equal( sortList(m$panels[[1]]$domain), sortList(list(left=0, right=10, bottom=10, top=30)) ) expect_equal(sortList(m$panels[[1]]$domain), sortList(m$panels[[2]]$domain)) expect_equal(sortList(m$panels[[2]]$domain), sortList(m$panels[[3]]$domain)) factor_vals <- dat$g expect_equal(m$panels[[1]]$panel_vars, list(panelvar1 = factor_vals[1])) expect_equal(m$panels[[2]]$panel_vars, list(panelvar1 = factor_vals[2])) expect_equal(m$panels[[3]]$panel_vars, list(panelvar1 = factor_vals[3])) p1 <- p + facet_grid(g ~ .) png(tmpfile) m <- getGgplotCoordmap(print(p1), 500, 400, 72) dev.off() expect_equal(length(m$panels), 3) expect_equal(m$panels[[1]]$panel, 1) expect_equal(m$panels[[1]]$row, 1) expect_equal(m$panels[[1]]$col, 1) expect_equal(m$panels[[2]]$panel, 2) expect_equal(m$panels[[2]]$row, 2) expect_equal(m$panels[[2]]$col, 1) expect_equal(m$panels[[3]]$panel, 3) expect_equal(m$panels[[3]]$row, 3) expect_equal(m$panels[[3]]$col, 1) expect_equal(m$panels[[1]]$mapping, list(x = "xvar", y = "yvar", panelvar1 = "g")) expect_equal(m$panels[[1]]$mapping, m$panels[[2]]$mapping) expect_equal(m$panels[[2]]$mapping, m$panels[[3]]$mapping) expect_equal( sortList(m$panels[[1]]$domain), sortList(list(left=0, right=10, bottom=10, top=30)) ) expect_equal(sortList(m$panels[[1]]$domain), sortList(m$panels[[2]]$domain)) expect_equal(sortList(m$panels[[2]]$domain), sortList(m$panels[[3]]$domain)) factor_vals <- dat$g expect_equal(m$panels[[1]]$panel_vars, list(panelvar1 = factor_vals[1])) expect_equal(m$panels[[2]]$panel_vars, list(panelvar1 = factor_vals[2])) expect_equal(m$panels[[3]]$panel_vars, list(panelvar1 = factor_vals[3])) }) test_that("ggplot coordmap with 2D facet_grid", { dat <- data.frame(xvar = c(0, 5, 10, 15), yvar = c(10, 20, 30, 40), g = c("a", "b"), h = c("i", "j")) tmpfile <- tempfile("test-shiny", fileext = ".png") on.exit(unlink(tmpfile)) p <- ggplot(dat, aes(xvar, yvar)) + geom_point() + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0)) p1 <- p + facet_grid(g ~ h) png(tmpfile) m <- getGgplotCoordmap(print(p1), 500, 400, 72) dev.off() expect_equal(length(m$panels), 4) expect_equal(m$panels[[1]]$panel, 1) expect_equal(m$panels[[1]]$row, 1) expect_equal(m$panels[[1]]$col, 1) expect_equal(m$panels[[2]]$panel, 2) expect_equal(m$panels[[2]]$row, 1) expect_equal(m$panels[[2]]$col, 2) expect_equal(m$panels[[3]]$panel, 3) expect_equal(m$panels[[3]]$row, 2) expect_equal(m$panels[[3]]$col, 1) expect_equal(m$panels[[4]]$panel, 4) expect_equal(m$panels[[4]]$row, 2) expect_equal(m$panels[[4]]$col, 2) expect_equal(m$panels[[1]]$mapping, list(x = "xvar", y = "yvar", panelvar1 = "h", panelvar2 = "g")) expect_equal(m$panels[[1]]$mapping, m$panels[[2]]$mapping) expect_equal(m$panels[[2]]$mapping, m$panels[[3]]$mapping) expect_equal(m$panels[[4]]$mapping, m$panels[[4]]$mapping) expect_equal( sortList(m$panels[[1]]$domain), sortList(list(left=0, right=15, bottom=10, top=40)) ) expect_equal(sortList(m$panels[[1]]$domain), sortList(m$panels[[2]]$domain)) expect_equal(sortList(m$panels[[2]]$domain), sortList(m$panels[[3]]$domain)) expect_equal(sortList(m$panels[[3]]$domain), sortList(m$panels[[4]]$domain)) expect_equal(m$panels[[1]]$panel_vars, list(panelvar1 = dat$h[1], panelvar2 = dat$g[1])) expect_equal(m$panels[[2]]$panel_vars, list(panelvar1 = dat$h[2], panelvar2 = dat$g[1])) expect_equal(m$panels[[3]]$panel_vars, list(panelvar1 = dat$h[1], panelvar2 = dat$g[2])) expect_equal(m$panels[[4]]$panel_vars, list(panelvar1 = dat$h[2], panelvar2 = dat$g[2])) }) test_that("ggplot coordmap with various data types", { tmpfile <- tempfile("test-shiny", fileext = ".png") on.exit(unlink(tmpfile)) dat <- expand.grid(xvar = letters[1:3], yvar = LETTERS[1:4]) p <- ggplot(dat, aes(xvar, yvar)) + geom_point() + scale_x_discrete(expand = c(0 ,0)) + scale_y_discrete(expand = c(0, 0)) png(tmpfile) m <- getGgplotCoordmap(print(p), 500, 400, 72) dev.off() expectation <- list( left = 1, right = 3, bottom = 1, top = 4, discrete_limits = list( x = letters[1:3], y = LETTERS[1:4] ) ) expect_equal( sortList(m$panels[[1]]$domain), sortList(expectation) ) dat <- data.frame( xvar = as.Date("2016-09-27") + c(0, 10), yvar = as.POSIXct("2016-09-27 09:00:00", origin = "1960-01-01", tz = "GMT") + c(3600, 0) ) p <- ggplot(dat, aes(xvar, yvar)) + geom_point() + scale_x_date(expand = c(0 ,0)) + scale_y_datetime(expand = c(0, 0)) png(tmpfile) m <- getGgplotCoordmap(print(p), 500, 400, 72) dev.off() expect_equal( sortList(m$panels[[1]]$domain), sortList(list( left = as.numeric(dat$xvar[1]), right = as.numeric(dat$xvar[2]), bottom = as.numeric(dat$yvar[2]), top = as.numeric(dat$yvar[1]) )) ) }) test_that("ggplot coordmap with various scales and coords", { tmpfile <- tempfile("test-shiny", fileext = ".png") on.exit(unlink(tmpfile)) dat <- data.frame(xvar = c(0, 5), yvar = c(10, 20)) p <- ggplot(dat, aes(xvar, yvar)) + geom_point() + scale_x_continuous(expand = c(0 ,0)) + scale_y_reverse(expand = c(0, 0)) png(tmpfile) m <- getGgplotCoordmap(print(p), 500, 400, 72) dev.off() expect_equal( sortList(m$panels[[1]]$domain), sortList(list(left=0, right=5, bottom=20, top=10)) ) p <- ggplot(dat, aes(xvar, yvar)) + geom_point() + scale_x_continuous(expand = c(0 ,0)) + scale_y_continuous(expand = c(0 ,0)) + coord_flip() png(tmpfile) m <- getGgplotCoordmap(print(p), 500, 400, 72) dev.off() expect_equal(m$panels[[1]]$mapping, list(x = "yvar", y = "xvar")) expect_equal( sortList(m$panels[[1]]$domain), sortList(list(left=10, right=20, bottom=0, top=5)) ) dat <- data.frame(xvar = c(10^-1, 10^3), yvar = c(2^-2, 2^4)) p <- ggplot(dat, aes(xvar, yvar)) + geom_point() + scale_x_log10(expand = c(0 ,0)) + scale_y_continuous(expand = c(0, 0)) + coord_trans(y = "log2") png(tmpfile) m <- getGgplotCoordmap(print(p), 500, 400, 72) dev.off() expect_equal( sortList(m$panels[[1]]$log), sortList(list(x=10, y=2)) ) expect_equal( sortList(m$panels[[1]]$domain), sortList(list(left=-1, right=3, bottom=-2, top=4)) ) }) test_that("ggplot coordmap maintains discrete limits", { tmpfile <- tempfile("test-shiny", fileext = ".png") on.exit(unlink(tmpfile)) p <- ggplot(mpg) + geom_point(aes(fl, cty), alpha = 0.2) + facet_wrap(~drv, scales = "free_x") png(tmpfile) m <- getGgplotCoordmap(print(p), 500, 400, 72) dev.off() expect_length(m$panels, 3) expect_equal( m$panels[[1]]$domain$discrete_limits, list(x = c("d", "e", "p", "r")) ) expect_equal( m$panels[[2]]$domain$discrete_limits, list(x = c("c", "d", "e", "p", "r")) ) expect_equal( m$panels[[3]]$domain$discrete_limits, list(x = c("e", "p", "r")) ) p2 <- ggplot(mpg) + geom_point(aes(cty, fl), alpha = 0.2) + facet_wrap(~drv, scales = "free_y") png(tmpfile) m2 <- getGgplotCoordmap(print(p2), 500, 400, 72) dev.off() expect_length(m2$panels, 3) expect_equal( m2$panels[[1]]$domain$discrete_limits, list(y = c("d", "e", "p", "r")) ) expect_equal( m2$panels[[2]]$domain$discrete_limits, list(y = c("c", "d", "e", "p", "r")) ) expect_equal( m2$panels[[3]]$domain$discrete_limits, list(y = c("e", "p", "r")) ) p3 <- ggplot(mpg) + geom_point(aes(fl, cty), alpha = 0.2) + scale_x_discrete(limits = c("c", "d", "e")) png(tmpfile) m3 <- getGgplotCoordmap(suppressWarnings(print(p3)), 500, 400, 72) dev.off() expect_length(m3$panels, 1) expect_equal( m3$panels[[1]]$domain$discrete_limits, list(x = c("c", "d", "e")) ) p4 <- ggplot(mpg) + geom_point(aes(cty, fl), alpha = 0.2) + scale_y_discrete(limits = c("e", "f")) png(tmpfile) m4 <- getGgplotCoordmap(suppressWarnings(print(p4)), 500, 400, 72) dev.off() expect_length(m4$panels, 1) expect_equal( m4$panels[[1]]$domain$discrete_limits, list(y = c("e", "f")) ) p5 <- ggplot(mpg) + geom_point(aes(fl, cty), alpha = 0.2) + scale_x_discrete( limits = c("e", "f"), labels = c("foo", "bar") ) png(tmpfile) m5 <- getGgplotCoordmap(suppressWarnings(print(p5)), 500, 400, 72) dev.off() expect_length(m5$panels, 1) expect_equal( m5$panels[[1]]$domain$discrete_limits, list(x = c("e", "f")) ) })
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(ruin) set.seed(1991) model <- CramerLundbergCapitalInjections( initial_capital = 0, premium_rate = 1, claim_poisson_arrival_rate = 1, claim_size_generator = rexp, claim_size_parameters = list(rate = 1), capital_injection_poisson_rate = 1, capital_injection_size_generator = rexp, capital_injection_size_parameters = list(rate = 1) ) one_path <- simulate_path(model = model, max_time_horizon = 10) one_path <- simulate_path(model = model, max_time_horizon = 10) head(one_path@path) plot_path(one_path) ruin_probability(model = model, time_horizon = 10, parallel = FALSE)
build_vignette_with_user_id_token = FALSE if (build_vignette_with_user_id_token) { knitr::opts_chunk$set(fig.width = 12, fig.height = 10, fig.align = "center", warning = FALSE, message = FALSE, eval = TRUE, echo = TRUE, cache = TRUE, cache.rebuild = TRUE) USER_ID = 'use the true user-id here' token = 'use the true token here' } if (!build_vignette_with_user_id_token) { knitr::opts_chunk$set(fig.width = 12, fig.height = 10, fig.align = "center", warning = FALSE, message = FALSE) file_heart = system.file('tests_vignette_rds', 'heart_dat.RDS', package = 'fitbitViz') file_sleep = system.file('tests_vignette_rds', 'sleep_ts.RDS', package = 'fitbitViz') file_tcx = system.file('tests_vignette_rds', 'res_tcx.RDS', package = 'fitbitViz') file_rst = system.file('tests_vignette_rds', 'raysh_rst.tif', package = 'fitbitViz') heart_dat = readRDS(file = file_heart) sleep_ts = readRDS(file = file_sleep) res_tcx = readRDS(file = file_tcx) raysh_rst = raster::raster(x = file_rst) } WEEK = 11 num_character_error = 135 weeks_2021 = fitbitViz:::split_year_in_weeks(year = 2021) date_start = lubridate::floor_date(lubridate::ymd(weeks_2021[WEEK]), unit = 'weeks') + 1 date_end = date_start + 6 sleep_time_begins = "00H 40M 0S" sleep_time_ends = "08H 00M 0S" VERBOSE = FALSE dt_heart_rate_data = data.table::rbindlist(heart_dat$heart_rate_intraday) dt_heart_rate = DT::datatable(data = dt_heart_rate_data, rownames = FALSE, extensions = 'Buttons', options = list(pageLength = 10, dom = 'Bfrtip', buttons = list(list(extend = 'csv', filename = 'heart_rate_time_series')))) dt_heart_rate hrt_rt_var = fitbitViz::heart_rate_variability_sleep_time(heart_rate_data = heart_dat, sleep_begin = sleep_time_begins, sleep_end = sleep_time_ends, ggplot_hr_var = TRUE, angle_x_axis = 25) dt_heart_rate_var = DT::datatable(data = hrt_rt_var$hr_var_data, rownames = FALSE, extensions = 'Buttons', options = list(pageLength = 10, dom = 'Bfrtip', buttons = list(list(extend = 'csv', filename = 'heart_rate_variability')))) dt_heart_rate_var dt_sleep_heatmap = DT::datatable(data = sleep_ts$heatmap_data, rownames = FALSE, extensions = 'Buttons', options = list(pageLength = 10, dom = 'Bfrtip', buttons = list(list(extend = 'csv', filename = 'sleep_heat_map')))) dt_sleep_heatmap res_lft = fitbitViz::leafGL_point_coords(dat_gps_tcx = res_tcx, color_points_column = 'AltitudeMeters', provider = leaflet::providers$Esri.WorldImagery, option_viewer = rstudioapi::viewer, CRS = 4326) res_lft dt_gps_tcx = DT::datatable(data = res_tcx, rownames = FALSE, extensions = 'Buttons', class = 'white-space: nowrap', options = list(pageLength = 10, dom = 'Bfrtip', buttons = list(list(extend = 'csv', filename = 'GPS_TCX_data')))) dt_gps_tcx sf_rst_ext = fitbitViz::extend_AOI_buffer(dat_gps_tcx = res_tcx, buffer_in_meters = 1000, CRS = 4326, verbose = VERBOSE) linestring_dat = fitbitViz::gps_lat_lon_to_LINESTRING(dat_gps_tcx = res_tcx, CRS = 4326, time_split_asc_desc = NULL, verbose = VERBOSE) idx_3m = c(which.min(res_tcx$AltitudeMeters), as.integer(length(res_tcx$AltitudeMeters) / 2), which.max(res_tcx$AltitudeMeters)) cols_3m = c('latitude', 'longitude', 'AltitudeMeters') dat_3m = res_tcx[idx_3m, ..cols_3m]
localUploadUI <- function(id){ ns <- NS(id) box(width = 4, title = h2("Upload Local Files"), solidHeader = T, status = "success", fileInput( inputId = ns("file"), label = "Upload Local Files", accept = NULL, multiple = TRUE, placeholder = "Drag and drop files here" ), DT::DTOutput(ns("dtfiles")), verbatimTextOutput(ns("test")), hr(), textInput( ns("new_local_filename"), label = "Set Destination Directory (for testing only)", placeholder = "Enter New Directory Name Here" ), actionButton(ns("LocalFinishButton"), label = "Finish Download"), hr(), p("Location of Downloaded Files: (Testing Only)"), verbatimTextOutput(ns("LocaldbfilesPath")) ) } localUpload <- function(input, output, session){ observe({ inFile <- input$file n <- length(inFile$name) names <- inFile$name if (is.null(inFile)) return(NULL) splits <- list() for (i in 1:n) { splits <- base::sub("/tmp/Rtmp[[:alnum:]]{6}/", "", inFile[i, "datapath"]) print(splits) filenames <- list.files(temp) oldpath <- file.path(temp, splits[i]) print(oldpath[i]) print(list.files(temp)[i]) print(file.path(temp, inFile[i, "name"])) base::file.rename(oldpath[i], file.path(temp, "local_tempdir", inFile[i, "name"])) base::unlink(dirname(oldpath[i]), recursive = TRUE) } uploaded_local <- as.data.frame(list.files(file.path(temp, "local_tempdir"))) names(uploaded_local) <- "Available Files" Shared.data$local_files <- uploaded_local }) output$dtfiles <- DT::renderDT({Shared.data$local_files}, selection = 'single', options = list(ordering = F, dom = 'tp')) observe({ Shared.data$selected_row_local <- as.character(Shared.data$local_files[input$dtfiles_rows_selected,]) }) output$test <- renderPrint({Shared.data$selected_row_local}) observeEvent(input$LocalFinishButton, { local_dirname <- gsub(" ", "_", input$new_local_filename) dir.create(file.path(PEcAn_path, local_dirname)) path_to_local_tempdir <- file.path(local_tempdir) list_of_local_files <- list.files(path_to_local_tempdir) n <- length(list_of_d1_files) for (i in 1:n){ base::file.copy(file.path(path_to_local_tempdir, list_of_local_files[i]), file.path(PEcAn_path, local_dirname, list_of_local_files[i])) } output$LocaldbfilesPath <- renderText({paste0(PEcAn_path, local_dirname)}) }) }
plot.mmsbm <- function(x, type="groups", FX=NULL, node=NULL, ...){ if(type %in% c("blockmodel", "membership", "hmm")){ if (!requireNamespace("ggplot2", quietly = TRUE)) { stop("Package \"ggplot2\" needed to produce requested plot. Please install it.", call. = FALSE) } } if(type=="groups"){ colRamp <- colorRamp(c(" g.mode <- ifelse(x$forms$directed, "directed", "undirected") adj_mat <- x$BlockModel dimnames(adj_mat) <- list(paste("G",1:nrow(adj_mat), sep=""), paste("G", 1:ncol(adj_mat), sep="")) block.G <- igraph::graph.adjacency(plogis(adj_mat), mode=g.mode, weighted=TRUE) e.weight <- (1/diff(range(igraph::E(block.G)$weight))) * (igraph::E(block.G)$weight - max(igraph::E(block.G)$weight)) + 1 e.cols <- rgb(colRamp(e.weight), maxColorValue = 255) times.arg <- if(g.mode == "directed") { x$n_blocks } else { rev(seq_len(x$n_blocks)) } v.size <- rowMeans(x$MixedMembership)*100 + 20 radian.rescale <- function(x, start=0, direction=1) { c.rotate <- function(x) (x + start) %% (2 * pi) * direction c.rotate(scales::rescale(x, c(0, 2 * pi), range(x))) } loop.rads <- radian.rescale(x=1:x$n_blocks, direction=-1, start=0) loop.rads <- rep(loop.rads, times = times.arg) igraph::plot.igraph(block.G, main = "", edge.width=4, edge.color=e.cols, edge.curved = x$forms$directed, edge.arrow.size = 0.65, edge.loop.angle = loop.rads, vertex.size=v.size, vertex.color="white", vertex.frame.color="black", vertex.label.font=2, vertex.label.cex=1, vertex.label.color="black", layout = igraph::layout_in_circle) .bar.legend(colRamp, range(igraph::E(block.G)$weight)) } if(type=="blockmodel"){ x$dyadic.data$Y <- x$Y nodes <- unique(x$monadic.data$`(nid)`) MMat <- sapply(nodes,function(y){ Dsub <- x$dyadic.data[x$dyadic.data$`(sid)`==y | x$dyadic.data$`(rid)`==y,] return(sapply(nodes, function(y){sum(Dsub$Y[Dsub$`(sid)`==y | Dsub$`(rid)`==y])})) }) diag(MMat) <- 0 clusters <- head(x, n=length(nodes)) csort <- sort(sapply(nodes, function(y){which.max(sapply(clusters, "[[", y))})) corder <- unlist(sapply(1:x$n_blocks, function(z){sort(clusters[[z]][names(csort)[csort==z]], decreasing=T)})) MMat <- MMat[names(corder), names(corder)] plot(1, 1, xlim = c(.5, length(nodes) + .5), ylim = c(.5, length(nodes) + .5), main = "", xlab = "", ylab = "", type = "n", axes = FALSE) polygon.color <- c("white", "black") for (i in 1:length(nodes)) { for (t in 1:length(nodes)) { temp <- ifelse(MMat[i,t] > 0, 2, 1) polygon(c(.5 + t - 1, .5 + t, .5 + t, .5 + t - 1), length(nodes) - c(i-.5, i-.5, i+.5, i+.5), density = NA, border = polygon.color[temp], col = polygon.color[temp]) } } par(xpd=FALSE) for(i in 1:x$n_blocks){ if(i < x$n_blocks){ abline(h=length(nodes)-length(which(csort %in% 1:i))-.5, col="red", lty=2, lwd=2) abline(v=length(which(csort %in% 1:i))+.5, col="red", lty=2, lwd=2) } } v.size <- rowMeans(x$MixedMembership) bm <- x$BlockModel bm[upper.tri(bm)] <- NA dm <- data.frame(Sender = rep(paste("Group", 1:nrow(bm)), times = x$n_blocks), Receiver = rep(paste("Group", 1:nrow(bm)), each = x$n_blocks), Val = plogis(c(bm))) dm <- dm[complete.cases(dm),] dm$Sender <- factor(dm$Sender, levels=rev(paste("Group", 1:nrow(bm)))) p <- ggplot2::ggplot(ggplot2::aes_string(y = "Sender", x = "Receiver", fill="Val"), data = dm) + ggplot2::ggtitle("Edge Formation Between Blocs") + ggplot2::theme(plot.title = ggplot2::element_text(hjust = 0.5)) + ggplot2::geom_tile(color = "white") + ggplot2::theme_bw() + ggplot2::scale_size(guide='none') + ggplot2::scale_fill_gradient2(low = " midpoint = max(dm$Val)/2, limit = c(0,max(dm$Val)), name="Edge\nProbability") print(p) } if(type=="membership"){ ifelse(is.null(node), nr <- 1:nrow(x$monadic.data), nr <- which(x$monadic.data$`(nid)`==node)) avgmems <- lapply(1:nrow(x$MixedMembership), function(y){ tapply(x$MixedMembership[y,nr], x$monadic.data[nr,"(tid)"], mean)}) avgmems <- as.data.frame(cbind(rep(unique(as.character(x$monadic.data[nr,"(tid)"])), nrow(x$MixedMembership)),unlist(avgmems), rep(1:nrow(x$MixedMembership), each=length(unique(x$monadic.data[nr,"(tid)"]))))) colnames(avgmems) <- c("Time", "Avg.Membership", "Group") avgmems$Group <- factor(avgmems$Group, levels=length(unique(avgmems$Group)):1) if(class(avgmems$Avg.Membership) != "numeric"){avgmems$Avg.Membership <- as.numeric(as.character(avgmems$Avg.Membership))} if(class(avgmems$Time) != "numeric"){avgmems$Time <- as.numeric(as.character(avgmems$Time))} return(ggplot2::ggplot() + ggplot2::geom_area(ggplot2::aes_string(y = "Avg.Membership", x = "Time", fill="Group"), data = avgmems, stat="identity", position="stack") + ggplot2::guides(fill=ggplot2::guide_legend(title="Group"))) } if(type=="effect"){ stopifnot(is.list(FX)) cov <- strsplit(names(FX)[1], " ")[[1]][5] ymax <- max(hist(FX[[5]])[["counts"]]) hist(FX[[5]], main=paste("Distribution of Marginal Effects:", strsplit(names(FX)[1], " ")[[1]][5]), xlab=paste("Effect of", cov, "on Pr(Edge Formation)")) plot(unique(x$dyadic.data[,"(tid)"]), tapply(FX[[5]], x$dyadic.data[,"(tid)"], mean), type="o", xlab="Time", ylab=paste("Effect of", cov, "on Pr(Edge Formation)"), main="Marginal Effect over Time") nodenames <- names(sort(table(x$monadic.data[,"(nid)"]), decreasing=TRUE)) nodes <- sort(FX[[3]])[names(sort(FX[[3]])) %in% nodenames] plot(1, type="n", xlab="Node-Level Estimated Effect", ylab="", xlim=c(min(nodes), max(nodes) + 0.001), ylim = c(0, length(nodes)), yaxt="n") for(i in 1:length(nodes)){ points(nodes[i],i, pch=19) text(nodes[i],i, names(nodes)[i], pos=4, cex=0.7) } } if(type=="hmm"){ hms <- as.data.frame(do.call(rbind, lapply(1:nrow(x$Kappa), function(x){ cbind(1:ncol(x$Kappa), x$Kappa[x,], x) }))) colnames(hms) <- c("Time", "Kappa", "State") hms$State <- as.factor(hms$State) return(ggplot2::ggplot() + ggplot2::geom_area(ggplot2::aes_string(y = "Kappa", x = "Time", fill="State"), data = hms, stat="identity", position="stack") + ggplot2::guides(fill=ggplot2::guide_legend(title="HMM State"))) } }
coxed.npsf.tvc <- function(cox.model, newdata=NULL, coef=NULL, b.ind=NULL) { start <- ceiling(cox.model$y[,1]) end <- ceiling(cox.model$y[,2]) failed <- cox.model$y[,3] exp.xb <- exp(predict(cox.model, type="lp")) if(!is.null(coef)){ start <- start[b.ind] end <- end[b.ind] failed <- failed[b.ind] exp.xb <- exp.xb[b.ind] } h <- as.data.frame(cbind(start, end, failed, exp.xb)) diff <- h$end - h$start h <- h[rep(1:nrow(h), diff),] h$time <- h$start + sequence(diff) h$failed <- ifelse(h$time==h$end, h$failed, 0) h <- dplyr::group_by(h, time) h <- dplyr::summarize(h, d = sum(failed), exp.xb = sum(exp.xb)) CBH <- cumsum(h$d / h$exp.xb) S.bl <- exp(-CBH) baseline.functions <- data.frame(time = h$time, cbh = CBH, survivor = S.bl) if(!is.null(newdata)) exp.xb <- exp(predict(cox.model, newdata=newdata, type="lp")) expect.duration <- sapply(exp.xb, FUN=function(x){ sum(S.bl^x) }) return(list(baseline.functions = baseline.functions, exp.dur = expect.duration)) }
gen_esize_m <- function (lineup_boot_df, k){ table_boot_df <- map(lineup_boot_df,~table(.)) map_dbl(table_boot_df, ~ esize_m(., k)) }
.resno2str <- function(res, sep=c("+", "-")) { res <- res[!is.na(res)] if(!length(res)>0){ return(NULL) } else { res1 <- bounds(res) res2 <- paste(res1[,"start"], res1[,"end"], sep=sep[2]) inds <- res1[,"start"] == res1[,"end"] res2[inds] <- res1[inds, "start"] res3 <- paste(res2, collapse=sep[1]) return(res3) } } pymol <- function(...) UseMethod("pymol") pymol.pdbs <- function(pdbs, col=NULL, as="ribbon", file=NULL, type="script", exefile = "pymol", user.vec=NULL, ...) { allowed <- c("session", "script", "launch") if(!type %in% allowed) { stop(paste("input argument 'type' must be either of:", paste(allowed, collapse=", "))) } allowed <- c("ribbon", "cartoon", "lines", "putty") if(!as %in% allowed) { stop(paste("input argument 'as' must be either of:", paste(allowed, collapse=", "))) } if(!is.null(col) & !inherits(col, "core")) { if(length(col) == 1) { allowed <- c("index", "index2", "rmsf", "gaps", "user") if(!col %in% allowed) { stop(paste("input argument 'col' must be either of:", paste(allowed, collapse=", "))) } } else { if(!is.numeric(col)) { stop("col must be a numeric vector with length equal to the number of structures in the input pdbs object") } if(length(col) != length(pdbs$id)) { stop("col must be a vector with length equal to the number of structures in input pdbs") } } } if(is.null(file)) { if(type=="session") file <- "R.pse" if(type=="script") file <- "R.pml" } if(type %in% c("session", "launch")) { exefile1 <- .get.exepath(exefile) success <- .test.exefile(exefile1) if(!success) { stop(paste("Launching external program failed\n", " make sure '", exefile, "' is in your search path", sep="")) } exefile <- exefile1 } dots <- list(...) if("prefix" %in% names(dots)) { pdbs$id <- paste(dots$prefix, pdbs$id, sep="") } if("pdbext" %in% names(dots)) { pdbs$id <- paste(pdbs$id, dots$pdbext, sep="") } if(type %in% c("session", "launch")) tdir <- tempdir() else tdir <- "." pdbdir <- paste(tdir, "pymol_pdbs", sep="/") if(!file.exists(pdbdir)) dir.create(pdbdir) pmlfile <- tempfile(tmpdir=tdir, fileext=".pml") psefile <- tempfile(tmpdir=tdir, fileext=".pse") ids <- basename.pdb(pdbs$id) bf <- NULL if(as == "putty") { bf <- rmsf(pdbs$xyz) } else { if(!is.null(col)) { if(col[1] == "rmsf") { bf <- rmsf(pdbs$xyz) } if(col[1] == "index2") { bf <- 1:ncol(pdbs$ali)/ncol(pdbs$ali) } if(col[1] == "user") { if(is.null(user.vec) || !is.numeric(user.vec) || length(user.vec) != ncol(pdbs$ali)) { stop("User defined color vector must be numeric and the same dimension as pdbs") } bf <- user.vec } } } if(all(file.exists(pdbs$id))) { allatom <- TRUE files <- pdbs$id for(i in 1:length(pdbs$id)) { pdb <- read.pdb(files[i]) sele <- atom.select(pdb, "calpha") gaps <- is.gap(pdbs$xyz[i,]) pdb$xyz <- fit.xyz(pdbs$xyz[i, !gaps], pdb$xyz, fixed.inds = 1:length(pdbs$xyz[i, !gaps]), mobile.inds = sele$xyz) fn <- paste0(pdbdir, "/", ids[i], ".pdb") tmpbf <- NULL if(!is.null(bf)) { gaps <- is.gap(pdbs$ali[i,]) tmpbf <- pdb$atom$b*0 tmpbf[sele$atom] <- bf[!gaps] } write.pdb(pdb, b=tmpbf, file=fn) files[i] <- fn } } else { allatom <- FALSE files <- rep(NA, length(pdbs$id)) for(i in 1:length(pdbs$id)) { pdb <- pdbs2pdb(pdbs, inds=i)[[1]] fn <- paste0(pdbdir, "/", ids[i], ".pdb") tmpbf <- NULL if(!is.null(bf)) { gaps <- is.gap(pdbs$ali[i,]) tmpbf <- bf[!gaps] } write.pdb(pdb=pdb, b=tmpbf, file=fn) files[i] <- fn } } lines <- rep(NA, 5*length(pdbs$id)) for(i in 1:length(files)) { lines[i] <- paste("load", files[i]) } l <- i if(as == "putty") { lines[l+1] <- "cartoon putty" lines[l+2] <- "as cartoon" lines[l+3] <- "unset cartoon_smooth_loops" lines[l+4] <- "unset cartoon_flat_sheets" lines[l+5] <- "spectrum b, rainbow" lines[l+6] <- "set cartoon_putty_radius, 0.2" l <- l+6 as <- "cartoon" } if(!allatom) { if(!as %in% c("cartoon", "ribbon")) { warning("'as' set to 'ribbon' for c-alpha only structures") as <- "ribbon" } lines[l+1] <- paste0("set ", as, "_trace_atoms, 1") l <- l+1 } lines[l+1] <- paste("as", as) l <- l+1 if(!is.null(col)) { if(inherits(col, "core")) { core <- col l <- l+1 lines[l] <- "color grey50" for(j in 1:length(files)) { res <- .resno2str(pdbs$resno[j, core$atom]) if(!is.null(res)) { selname <- paste0(ids[j], "-core") lines[l+1] <- paste0("select ", selname, ", ", ids[j], " and resi ", res) lines[l+2] <- paste0("color red, ", selname) l <- l+2 } } } if(col[1] == "gaps") { l <- l+1 lines[l] <- "color grey50" gaps <- gap.inspect(pdbs$ali) for(j in 1:length(files)) { res <- .resno2str(pdbs$resno[j, gaps$t.inds]) if(!is.null(res)) { selname <- paste0(ids[j], "-gap") lines[l+1] <- paste0("select ", selname, ", ", ids[j], " and resi ", res) lines[l+2] <- paste0("color red, ", selname) l <- l+2 } } } if(length(col) > 1 & is.vector(col)) { cols <- c("grey40", "red", "green", "blue", "cyan", "purple", "yellow", "grey90", "magenta", "orange", "pink", "wheat", "deepolive", "teal", "violet", "limon", "slate", "density", "forest", "smudge", "salmon", "brown") for(j in 1:length(files)) { lines[l+1] <- paste0("color ", cols[col[j]], ", ", ids[j]) l <- l+1 } } if(col[1] == "rmsf") { l <- l+1 lines[l] <- "spectrum b, rainbow" } if(col[1] == "index") { for(i in 1:length(pdbs$id)) { l <- l+1 lines[l] <- paste("spectrum count, rainbow,", ids[i], "and name C*") } } if(col[1] == "index2") { for(i in 1:length(pdbs$id)) { l <- l+1 lines[l] <- paste("spectrum b, rainbow,", ids[i]) } } if(col[1] == "user") { for(i in 1:length(pdbs$id)) { l <- l+1 lines[l] <- paste("spectrum b, rainbow,", ids[i]) } } } lines[l+1] <- "zoom" l <- l+1 if(type == "session") { lines[l+1] <- paste("save", normalizePath(psefile, winslash='/', mustWork=FALSE)) } lines <- lines[!is.na(lines)] write.table(lines, file=pmlfile, append=FALSE, quote=FALSE, sep="\n", row.names=FALSE, col.names=FALSE) if(type %in% c("session", "launch")) { if(type == "session") args <- "-cq" else args <- "" cmd <- paste(exefile, args, pmlfile) os1 <- Sys.info()["sysname"] if (os1 == "Windows") { status <- shell(paste(shQuote(exefile), args, pmlfile)) } else { status <- system(cmd) } if(!(status %in% c(0,1))) { stop(paste("An error occurred while running command\n '", exefile, "'", sep="")) } } if(type == "session") { file.copy(psefile, file, overwrite=TRUE) unlink(pmlfile) unlink(psefile) message(paste("PyMOL session written to file", file)) invisible(file) } if(type == "script") { file.copy(pmlfile, file, overwrite=TRUE) unlink(pmlfile) message(paste("PyMOL script written to file", file)) invisible(file) } }
expected <- eval(parse(text="structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), class = \"factor\", .Label = c(\"A\", \"B\", \"C\", \"D\"))")); test(id=0, code={ argv <- eval(parse(text="list(structure(1:4, .Label = c(\"A\", \"B\", \"C\", \"D\"), class = \"factor\", .Names = c(\"a\", \"b\", \"c\", \"d\")), 2)")); .Internal(rep.int(argv[[1]], argv[[2]])); }, o=expected);
add_ceplane_setup <- function(plot_params) { do.call("plot", plot_params$setup, quote = TRUE) axis(1) axis(2) } add_ceplane_polygon <- function(plot_params) { do.call("polygon", plot_params$polygon, quote = TRUE) box() } add_ceplane_points <- function(he, plot_params) { do.call("matplot", c(list(x = he$delta_e, y = he$delta_c, add = TRUE), plot_params$points), quote = TRUE) } add_ceplane_icer <- function(he, plot_params) { do.call("text", plot_params$icer_text, quote = TRUE) do.call("points", c(list( x = colMeans(he$delta_e), y = colMeans(he$delta_c)), plot_params$icer_points), quote = TRUE) } add_ceplane_k_txt <- function(plot_params) { k_equals_txt <- paste0("k == ", format( plot_params$wtp, digits = 3, nsmall = 2, scientific = FALSE)) do.call(text, c(list(labels = parse(text = k_equals_txt)), plot_params$k_txt)) } add_ceplane_legend <- function(legend_params) { do.call(legend, legend_params) } add_axes <- function() { abline(h = 0, v = 0, col = "dark grey") }
tll <- function(l) { deprecate("purrr::transpose") if (length(l) == 0) return(list()) plyr::llply( setMissingNames(object=seq_along(l[[1]]), nm=names(l[[1]])), function (n) plyr::llply(l, function(ll) ll[[n]]) ) }
rm_proc_create_pseudoraters <- function( dat, rater, pid, reference_rater=NULL ) { dat0 <- dat rater0 <- paste0(rater) pid0 <- pid items <- colnames(dat) dat <- NULL pid <- NULL rater <- NULL I <- length(items) m0 <- as.data.frame( matrix(NA, nrow=nrow(dat0), ncol=I) ) colnames(m0) <- colnames(dat0) for (ii in 1:I){ dat_ii <- m0 dat_ii[, ii ] <- dat0[,ii] rater_ii <- paste0( rater0, "-", items[ii] ) rater <- c( paste(rater), paste(rater_ii) ) dat <- rbind( dat, dat_ii) pid <- c( pid, pid0) } if ( ! is.null(reference_rater) ){ reference_rater <- paste0(reference_rater, "-", items ) } res <- list( dat=dat, rater=rater, pid=pid, reference_rater=reference_rater) return(res) }
acontext("hjust text anchor") grad.desc <- function( FUN = function(x, y) x^2 + 2 * y^2, rg = c(-3, -3, 3, 3), init = c(-3, 3), gamma = 0.05, tol = 0.001, gr = NULL, len = 50, nmax = 50) { x <- seq(rg[1], rg[3], length = len) y <- seq(rg[2], rg[4], length = len) contour <- expand.grid(x = x, y = y) contour$z <- as.vector(outer(x, y, FUN)) nms = names(formals(FUN)) grad = if (is.null(gr)) { deriv(as.expression(body(FUN)), nms, function.arg = TRUE) } else { function(...) { res = FUN(...) attr(res, 'gradient') = matrix(gr(...), nrow = 1, ncol = 2) res } } xy <- init newxy <- xy - gamma * attr(grad(xy[1], xy[2]), 'gradient') z <- FUN(newxy[1], newxy[2]) gap <- abs(z - FUN(xy[1], xy[2])) i <- 1 while (gap > tol && i <= nmax) { xy <- rbind(xy, newxy[i, ]) newxy <- rbind(newxy, xy[i + 1, ] - gamma * attr(grad(xy[i + 1, 1], xy[i + 1, 2]), 'gradient')) z <- c(z, FUN(newxy[i + 1, 1], newxy[i + 1, 2])) gap <- abs(z[i + 1] - FUN(xy[i + 1, 1], xy[i + 1, 2])) i <- i + 1 if (i > nmax) warning('Maximum number of iterations reached!') } objective <- data.frame(iteration = 1:i, x = xy[, 1], y = xy[, 2], z = z) invisible(list(contour = contour, objective = objective)) } dat <- grad.desc() contour <- dat$contour objective <- dat$objective objective <- plyr::ldply(objective$iteration, function(i) { df <- subset(objective, iteration <= i) cbind(df, iteration2 = i) }) objective2 <- subset(objective, iteration == iteration2) grad.desc.viz <- function(hjust) { objective2$hjust <- hjust contour.plot <- ggplot() + geom_contour(data = contour, aes(x = x, y = y, z = z, colour = ..level..), size = .5) + scale_colour_continuous(name = "z value") + geom_path(data = objective, aes(x = x, y = y), showSelected = "iteration2", colour = "red", size = 1) + geom_point(data = objective, aes(x = x, y = y), showSelected = "iteration2", colour = "green", size = 2) + geom_text(data = objective2, aes(x = x, y = y - 0.2, label = round(z, 2)), showSelected = "iteration2") + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0)) + ggtitle("contour of function value") + theme_animint(width = 600, height = 600) objective.plot <- ggplot() + geom_line(data = objective2, aes(x = iteration, y = z), colour = "red") + geom_point(data = objective2, aes(x = iteration, y = z), colour = "red") + geom_tallrect(data = objective2, aes(xmin = iteration - 1 / 2, xmax = iteration + 1 / 2), clickSelects = "iteration2", alpha = .3) + geom_text(data = objective2, aes(x = iteration, y = z + 0.3, label = iteration), showSelected = "iteration2", hjust = hjust) + ggtitle("objective value vs. iteration") + theme_animint(width = 600, height = 600) viz <- list(contour = contour.plot, objective = objective.plot, time = list(variable = "iteration2", ms = 2000), title = "Demonstration of Gradient Descent Algorithm") } viz <- grad.desc.viz(hjust = 0) info <- animint2HTML(viz) test_that("unspecified hjust means text-anchor: middle (other hjust=0)", { style.value <- getStyleValue(info$html, '//g[@class="geom4_text_contour"]//text', "text-anchor") expect_match(style.value, "middle") }) test_that('geom_text(hjust=0) => <text style="text-anchor: start">', { style.value <- getStyleValue(info$html, '//g[@class="geom8_text_objective"]//text', "text-anchor") expect_match(style.value, "start") }) viz <- grad.desc.viz(hjust = 1) info <- animint2HTML(viz) test_that("unspecified hjust means text-anchor: middle (other hjust=1)", { style.value <- getStyleValue(info$html, '//g[@class="geom4_text_contour"]//text', "text-anchor") expect_match(style.value, "middle") }) test_that('geom_text(hjust=1) => <text style="text-anchor: end">', { style.value <- getStyleValue(info$html, '//g[@class="geom8_text_objective"]//text', "text-anchor") expect_match(style.value, "end") }) viz <- grad.desc.viz(hjust = 0.5) info <- animint2HTML(viz) test_that("unspecified hjust means text-anchor: middle (other hjust=0.5)", { style.value <- getStyleValue(info$html, '//g[@class="geom4_text_contour"]//text', "text-anchor") expect_match(style.value, "middle") }) test_that('geom_text(hjust=0.5) => <text style="text-anchor: middle">', { style.value <- getStyleValue(info$html, '//g[@class="geom8_text_objective"]//text', "text-anchor") expect_match(style.value, "middle") }) test_that('geom_text(hjust=other) => unsupported value error', { viz <- grad.desc.viz(hjust = 0.8) expect_error(animint2HTML(viz), "animint only supports hjust values 0, 0.5, 1") }) hjust.df <- data.frame( hjust=c(0,0.5,1), anchor=c("start", "middle", "end"), stringsAsFactors=FALSE) hjust.df$label <- paste0("hjust=",hjust.df$hjust) rownames(hjust.df) <- hjust.df$label viz <- list( text=ggplot()+ geom_text(aes(hjust, hjust, label=label, hjust=hjust), data=hjust.df) ) test_that("aes(hjust) works fine for 0, 0.5, 1", { info <- animint2HTML(viz) xpath <- '//g[@class="geom1_text_text"]//text' text.list <- getNodeSet(info$html, xpath) computed.anchor <- getStyleValue(info$html, xpath, "text-anchor") label.vec <- sapply(text.list, xmlValue) expected.anchor <- hjust.df[label.vec, "anchor"] expect_identical(computed.anchor, expected.anchor) }) hjust.df <- data.frame(hjust=c(0,0.5,1,1.5), anchor=c("start", "middle", "end", "unknown")) hjust.df$label <- paste0("hjust=",hjust.df$hjust) rownames(hjust.df) <- hjust.df$label viz <- list( text=ggplot()+ geom_text(aes(hjust, hjust, label=label, hjust=hjust), data=hjust.df) ) test_that("error if aes(hjust) not in 0, 0.5, 1", { expect_error({ info <- animint2HTML(viz) }, "animint only supports hjust values 0, 0.5, 1") }) vjust.df <- data.frame(vjust=c(0,0.5,1)) vjust.df$label <- paste0("vjust=",vjust.df$vjust) rownames(vjust.df) <- vjust.df$label viz <- list( text=ggplot()+ geom_text(aes(vjust, vjust, label=label, vjust=vjust), data=vjust.df) ) test_that("aes(vjust!=0) raises warning", { expect_warning({ animint2HTML(viz) }, "animint only supports vjust=0") }) viz <- list( text=ggplot()+ geom_text(aes(vjust, vjust, label=0, vjust=0), data=vjust.df) ) test_that("aes(vjust=0) does not raise warning", { expect_no_warning({ animint2HTML(viz) }) }) viz <- list( text=ggplot()+ geom_text(aes(vjust, vjust, label="no vjust"), data=vjust.df) ) test_that("unspecified vjust does not raise warning", { expect_no_warning({ animint2HTML(viz) NULL }) }) viz.1 <- list( text=ggplot()+ geom_text(aes(vjust, vjust, label=1), vjust=1, data=vjust.df) ) viz.0.5 <- list( text=ggplot()+ geom_text(aes(vjust, vjust, label=0), vjust=0.5, data=vjust.df) ) viz.0.7 <- list( text=ggplot()+ geom_text(aes(vjust, vjust, label=0.7), vjust=0.7, data=vjust.df) ) test_that("geom_text(vjust!=0) raises warning", { expect_warning({ animint2HTML(viz.1) }, "animint only supports vjust=0") expect_warning({ animint2HTML(viz.0.5) }, "animint only supports vjust=0") expect_warning({ animint2HTML(viz.0.7) }, "animint only supports vjust=0") }) viz <- list( text=ggplot()+ geom_text(aes(vjust, vjust, label=0), vjust=0, data=vjust.df) ) test_that("geom_text(vjust=0) does not raise warning", { expect_no_warning({ animint2HTML(viz) }) })
.runThisTest <- Sys.getenv("RunAllparametersTests") == "yes" if (.runThisTest && requiet("testthat") && requiet("parameters")) { test_that("emmeans | lm", { skip_if_not_installed("emmeans") skip_if_not_installed("boot") model <- lm(mpg ~ log(wt) + factor(cyl), data = mtcars) set.seed(7) b <- bootstrap_model(model, iterations = 1000) expect_equal(summary(emmeans::emmeans(b, ~cyl))$emmean, summary(emmeans::emmeans(model, ~cyl))$emmean, tolerance = 0.1 ) set.seed(7) b <- bootstrap_parameters(model, iterations = 1000) expect_equal(summary(emmeans::emmeans(b, ~cyl))$emmean, summary(emmeans::emmeans(model, ~cyl))$emmean, tolerance = 0.1 ) mp <- model_parameters(emmeans::emmeans(b, consec ~ cyl), verbose = FALSE) expect_equal( colnames(mp), c( "Parameter", "Median", "CI", "CI_low", "CI_high", "pd", "ROPE_CI", "ROPE_low", "ROPE_high", "ROPE_Percentage", "Component" ) ) expect_equal(nrow(mp), 5) }) test_that("emmeans | lmer", { skip_if_not_installed("emmeans") skip_if_not_installed("boot") skip_if_not_installed("lme4") model <- lme4::lmer(mpg ~ log(wt) + factor(cyl) + (1 | gear), data = mtcars) set.seed(7) b <- bootstrap_model(model, iterations = 1000) expect_equal(summary(emmeans::emmeans(b, ~cyl))$emmean, summary(emmeans::emmeans(model, ~cyl))$emmean, tolerance = 0.1 ) set.seed(7) b <- bootstrap_parameters(model, iterations = 1000) expect_equal(summary(emmeans::emmeans(b, ~cyl))$emmean, summary(emmeans::emmeans(model, ~cyl))$emmean, tolerance = 0.1 ) mp <- suppressWarnings(model_parameters(emmeans::emmeans(b, consec ~ cyl))) expect_equal( colnames(mp), c( "Parameter", "Median", "CI", "CI_low", "CI_high", "pd", "ROPE_CI", "ROPE_low", "ROPE_high", "ROPE_Percentage", "Component" ) ) expect_equal(nrow(mp), 5) }) }
CSWCapabilities <- R6Class("CSWCapabilities", inherit = OWSCapabilities, private = list( xmlElement = "Capabilities", xmlNamespacePrefix = "CSW" ), public = list( initialize = function(url, version, client = NULL, logger = NULL, ...) { owsVersion <- switch(version, "2.0.2" = "1.1", "3.0.0" = "2.0" ) private$xmlNamespacePrefix <- paste0(private$xmlNamespacePrefix,"_",gsub("\\.","_",version)) super$initialize( element = private$xmlElement, namespacePrefix = private$xmlNamespacePrefix, url, service = "CSW", owsVersion = owsVersion, serviceVersion = version, logger = logger, ...) xmlObj <- self$getRequest()$getResponse() } ) )
context("fillBins") library(testthat) library(lubridate) library(stringi) set_seed(10) pedOne <- data.frame(ego_id = c("s1", "d1", "s2", "d2", "o1", "o2", "o3", "o4"), `si re` = c(NA, NA, NA, NA, "s1", "s1", "s2", "s2"), dam_id = c(NA, NA, NA, NA, "d1", "d2", "d2", "d2"), sex = c("F", "M", "M", "F", "F", "F", "F", "M"), birth_date = mdy( paste0(sample(1:12, 8, replace = TRUE), "-", sample(1:28, 8, replace = TRUE), "-", sample(seq(0, 15, by = 3), 8, replace = TRUE) + 2000)), stringsAsFactors = FALSE, check.names = FALSE) pedOne$age <- (mdy("06/01/2018") - as.Date(pedOne$birth)) / dyears(1) test_that("fillBins adds correct number to each bin", { lower_ages <- seq(0, 20, by = 5) upper_ages <- NULL expect_equal(fillBins(pedOne, lower_ages)$males, c(0, 0, 2, 1, 0)) expect_equal(fillBins(pedOne, lower_ages)$females, c(2, 2, 0, 1, 0)) })
NOT_CRAN <- identical(tolower(Sys.getenv("NOT_CRAN")), "true") knitr::opts_chunk$set( collapse = TRUE, comment = " purl = NOT_CRAN, eval = NOT_CRAN, screenshot.force = FALSE )
context("test-ls_fun_calls") test_that("ls_fun_calls works", { fun <- ls_fun_calls(quote(library(tidycode))) expect_equal(fun, list("library")) fun <- ls_fun_calls(quote(lm(mpg ~ cyl, mtcars))) expect_equal(fun, list("lm", "~")) })
text1 <- "Really love my dog, he is the best friend anyone could ever ask for!" text2 <- "RT I want @coolguy24 to meet me for test_Tidy_df <- tibble::tribble( ~user_id, ~status_id, ~created_at, ~screen_name, ~text, ~hashtags, ~location, ~key, ~query, as.character(12344), as.character(098098), as.POSIXct("2021-04-07 01:15:33"), as.character("cool123"), text1, as.character("dog"), as.character("Phoenix AZ"), as.character("dude123 2021-04-07 01:15:33"), as.character(" as.character(987234), as.character(90898), as.POSIXct("2021-04-07 01:16:43"), as.character("sweet123"), text2, as.character("dog"), as.character("Denver CO"), as.character("sweet123 2021-04-07 01:16:43"), as.character(" ) true_Tidy_df <- tibble::tribble( ~text, ~Token, text1, as.character("love"), text1, as.character("dog"), text1, as.character("friend"), text2, as.character("coolguy24"), text2, as.character("meet"), text2, as.character("icecream") ) true <- true_Tidy_df[[2]] test <- saotd::tweet_tidy(DataFrame = test_Tidy_df) test <- test[[10]] testthat::test_that("The tweet_tidy function is working as properly", { testthat::expect_equal(test, true) testthat::expect_error(object = saotd::tweet_tidy(DataFrame = text), "The input for this function is a data frame.") })
library(lg) context("Bandwidth selection") set.seed(1) n <- 20 x <- rt(n, df = 10) result <- bw_select_cv_univariate(x) test_that("Univariate bw selection works", { expect_true(is.numeric(result$bw)) expect_equal(result$convergence, 0) }) n <- 20 x_uni <- rnorm(n) x_tri <- cbind(rnorm(n), rnorm(n), rnorm(n)) test_that("Plugin bw selection works", { expect_equal(bw_select_plugin_univariate(x = x_uni), 1.75*n^(-1/5)) expect_equal(bw_select_plugin_multivariate(x = x_tri), 1.75*n^(-1/6)) expect_equal(bw_select_plugin_univariate(n = n), 1.75*n^(-1/5)) expect_equal(bw_select_plugin_multivariate(n = n), 1.75*n^(-1/6)) expect_equal(bw_select_plugin_univariate(n = n, c = 1, a = -.5), n^(-.5)) })
context("array") test_that("array patterns work as expected", { skip_on_ci() skip_if_not_installed("vdiffr") library("vdiffr") df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2)) pattern_ggplot <- function(pattern) { ggplot(df, aes(trt, outcome)) + geom_col_pattern(aes(fill=trt), colour='black', pattern = pattern) + theme_bw() + labs(title = pattern) } expect_doppelganger("gradient", pattern_ggplot("gradient")) expect_doppelganger("magick", pattern_ggplot("magick")) skip_if_not_installed("ambient") set.seed(42) expect_doppelganger("ambient", pattern_ggplot("ambient")) }) test_that("image pattern work as expected", { skip_on_ci() skip_if_not_installed("vdiffr") library("vdiffr") logo_filename <- system.file("img", "Rlogo.png" , package="png") magpie_filename <- system.file("img", "magpie.jpg", package="ggpattern") bug_filename <- system.file("img", "bug.jpg" , package="ggpattern") df1 <- data.frame( trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2), gravity = c('South', 'North', 'West'), filltype = c('squish', 'fit' , 'expand'), scale = c(1, 2, 0.5), filename = c(logo_filename, magpie_filename, bug_filename), stringsAsFactors = FALSE ) expect_doppelganger("image_logo_none", { ggplot(df1, aes(trt, outcome)) + geom_col_pattern( aes( fill = trt, pattern_gravity = I(gravity), pattern_scale = I(scale) ), pattern = 'image', pattern_filename = logo_filename, pattern_type = 'none', colour = 'black' ) + theme_bw(15) + labs( title = "ggpattern::geom_col_pattern()", subtitle = "pattern = 'image', pattern_type = 'none'" ) + theme(legend.key.size = unit(1.5, 'cm')) + coord_fixed(ratio = 1/2) }) expect_doppelganger("image_logo_variety", { ggplot(df1, aes(trt, outcome)) + geom_col_pattern( aes( fill = trt, pattern_gravity = I(gravity), pattern_type = I(filltype) ), pattern = 'image', colour = 'black', pattern_filename = logo_filename, ) + theme_bw(15) + labs( title = "ggpattern::geom_col_pattern()", subtitle = "pattern = 'image'" ) + theme(legend.position = 'none') + coord_fixed(ratio = 1/2) }) })
PlotLOOCV <- function(name, burnin = 0.1) { opar <-par(no.readonly=TRUE) on.exit(par(opar)) inFileName <- paste0(name, '.xml') inFile <- readLines(inFileName) versionLine <- readLines(inFileName,n=1) ver <- grepl(pattern = 'version=\"1.0', x = versionLine) ver2 <- grepl(pattern = 'version=\"2.', x = versionLine) ver1 = F if (ver == T & ver2 == F) {ver1 = T} if (ver1 == T) { check <- any(grepl(pattern = 'Generated by BEAUTi v1.10.', x = inFile)) if (check == T) {stop( "Leave-one-out analysis not yet implemented for this Beast 1 version")} matchLines <- grep(pattern = "date value=", x = inFile, value = T) values <- na.omit(as.numeric (gsub("[^0-9].", "", matchLines))) taxa = length(values) for (i in 1 : taxa){ fileRep <- paste0(name, ".Taxon", i, ".log") if (file_test("-f", fileRep) == F) {stop( "Log files not found, check files and verify that follow the proper naming convention --filename.Taxon1.log")} temp1 <- read.table(fileRep, header = TRUE, sep = '\t') bn <- dim(temp1)[1] - round(dim(temp1)[1]*(burnin), 0) temp2 <- tail(temp1, bn) coltemp <- colnames(temp2[2]) col <- unlist(strsplit(colnames(temp2[2]), split = "age.")) [2] if (i == 1) {data <- cbind(temp2[, 2])} else { data <- cbind(data, temp2[, 2])} if (i == 1) {colnames = col} else { colnames = c(colnames, col)} print (paste("log of taxon", i, "processed")) } } if (ver2 == T) { linearDates=F taxa <- length(grep('taxon=', inFile)) line <- grep(pattern = 'traitname=\"date|traitname=\'date', x = inFile) linearDates <- grepl(pattern = 'value=', inFile[line]) if (linearDates == T) { dateLine <- inFile[line] step1 <- gsub('\">','',strsplit(dateLine, 'value=\"')[[1]][2]) step2 <- unlist(strsplit(step1, ",")) numberDates <- length(step2) date <- unlist(strsplit(step2, "=")) dateHap <- date[c(T, F)] dateHap <- dateHap[1: numberDates] dateValues <- date[c(F, T)] values <- (as.numeric(gsub(",$", "", dateValues))) for (i in 1 : taxa){ fileRep <- paste0(name, ".Taxon", i, ".log") temp1 <- read.table(fileRep, header = TRUE, sep = '\t') bn <- dim(temp1)[1] - round(dim(temp1)[1]*(burnin), 0) temp2 <- tail(temp1, bn) coltemp <- colnames(temp2[3]) col <- unlist(strsplit(colnames(temp2[3]), split = "height.")) [2] if (i == 1) {data <- cbind(temp2[, 3])} else { data <- cbind(data, temp2[, 3])} if (i == 1) {colnames = col} else { colnames = c(colnames, col)} print (paste("log of taxon", i, "processed")) } } if (linearDates == F) { datePositions = c() repeat { if (length(grep("value=", inFile[line])) > 0) line <- line + 1 if (length(grep("alignment", inFile[line])) > 0) break if (length(grep("=", inFile[line])) > 0) {datePositions <- c(datePositions, line)} line <- line + 1 } numberDates <- length(datePositions) dateLines <- inFile[datePositions] dateLines <- trimws(dateLines) date <- unlist(strsplit(dateLines, "=")) dateHap <- date[c(T, F)] dateHap <- dateHap[1: numberDates] values <- date[c(F, T)] values <- na.omit(as.numeric (gsub("[^\\d]+", "", values, perl = T))) for (i in 1 : taxa){ fileRep <- paste0(name, ".Taxon", i, ".log") temp1 <- read.table(fileRep, header = TRUE, sep = '\t') bn <- dim(temp1)[1] - round(dim(temp1)[1]*(burnin), 0) temp2 <- tail(temp1, bn) coltemp <- colnames(temp2[3]) col <- unlist(strsplit(colnames(temp2[3]), split = "height.")) [2] if (i == 1) {data <- cbind(temp2[, 3])} else { data <- cbind(data, temp2[, 3])} if (i == 1) {colnames = col} else { colnames = c(colnames, col)} print (paste("log of taxon", i, "processed")) } } } colnames(data) = colnames if (ver1 == T) { data = ceiling(max(values)) - data } stats = matrix('NA',3,dim(data)[2]) colnames(stats) = colnames(data) rownames(stats) = c("median", "min", "max") for (i in 1:dim(stats)[2]){ stats[1,i] = median(data[, i]) stats[2,i] = emp.hpd(data[, i], conf = 0.95)[1] stats[3,i] = emp.hpd(data[, i], conf = 0.95)[2] } write.table (stats, paste0(name, "_leave_one_out.txt")) mindata = floor(as.numeric(min(stats[2, ]))) maxdata = ceiling(as.numeric(max(stats[3, ]))) xsp <- maxdata - mindata xlim <- c(mindata - xsp * 0.35, maxdata) ylim <- c(-2*taxa, 0) fail = NULL plot(1, xlim = xlim, ylim = ylim, axes = F, xlab = "", ylab = "", type = "n", ann = F) for (i in 1 : taxa){ median = (as.numeric(stats[1, i])) min = round((as.numeric(stats[2, i])), 3) max = round((as.numeric(stats[3, i])), 3) label = substr(colnames[i], 1, 20) arrows (min, -2*i, max, -2*i, angle = 90, code = 3, length = 0.08, lwd = 1) points (median, -2*i, cex = 1, pch = 3) if (min <= values[i] & values[i] <= max) {pt = 1; col = "black"} else {pt = 20; col = "red"; fail <- append(fail, i)} points (values[i], -2*i, cex = 1, pch = pt, col = col, bg = col) text ((mindata - xsp * 0.20), -2*i, labels = label, cex = 0.5) } axis(1, at = seq(mindata, maxdata), labels = seq(mindata, maxdata), cex.axis = 0.7, lwd = 1, line = 0) LOOCV_result <- all(fail == 0) if (LOOCV_result == TRUE) { mtext("Pass!!! Age estimation for all taxa inside the expected 95% HPD", side = 3, line = 1, col = "red") } else {mtext(paste("Age estimation for taxon/taxa", paste(fail, collapse = ", "), "is/are not overlapping with expected 95% HPD"), side = 3, line = 2, col = "red"); mtext("Attention !!! check LOOCV report file", side = 3, line = 1, col = "red"); write.table (colnames[fail], row.names = fail, sep = ",", col.names = "Taxon not overlapping with estimated 95% HPD (position, name)", paste0(name, "_LOOCV_report.txt")) } pdf(paste0("Fig_LOOCV_", name, ".pdf")) plot(1, xlim = xlim, ylim = ylim, axes = F, xlab = "", ylab = "", type = "n", ann = F) for (i in 1 : taxa){ median = (as.numeric(stats[1, i])) min = round((as.numeric(stats[2, i])), 3) max = round((as.numeric(stats[3, i])), 3) label = substr(colnames[i], 1, 20) arrows (min, -2*i, max, -2*i, angle = 90, code = 3, length = 0.08, lwd = 1) points (median, -2*i, cex = 1, pch = 3) if (min <= values[i] & values[i] <= max) {pt = 1; col = "black"} else {pt = 20; col = "red"; fail} points (values[i], -2*i, cex = 1, pch = pt, col = col, bg = col) text ((mindata - xsp * 0.20), -2*i, labels = label, cex = 0.5) } axis(1, at = seq(mindata, maxdata), labels = seq(mindata, maxdata), cex.axis = 0.7, lwd = 1, line = 0) LOOCV_result <- all(fail == 0) if (LOOCV_result == TRUE) { mtext("Pass!!! Age estimation for all taxa inside the expected 95% HPD", side = 3, line = 1, col = "red") } else {mtext(paste("Age estimation for taxon/taxa", paste(fail, collapse = ", "), "is/are not overlapping with expected 95% HPD"), side = 3, line = 2, col = "red"); mtext("Attention !!! check LOOCV report file", side = 3, line = 1, col = "red") } dev.off() }
test_that( "test.has_no_duplicates.without_duplicates.returns_false", { x <- 1:10 expect_true(has_no_duplicates(x)) } ) test_that( "test.has_no_duplicates.with_1_duplicate.returns_false", { x <- rep.int(1, 2) actual <- has_no_duplicates(x) expect_false(actual) expect_equal(cause(actual), noquote("x has a duplicate at position 2.")) } ) test_that( "test.has_no_duplicates.with_multiple_duplicates.returns_false", { x <- rep.int(1, 3) actual <- has_no_duplicates(x) expect_false(actual) expect_equal(cause(actual), noquote("x has duplicates at positions 2, 3.")) } ) test_that( "test.has_duplicates.without_duplicates.returns_false", { x <- 1:10 actual <- has_duplicates(x) expect_false(actual) expect_equal(cause(actual), noquote("x has no duplicates.")) } ) test_that( "test.has_duplicates.with_duplicates.returns_false", { x <- rep.int(1, 2) expect_true(has_duplicates(x)) } )
if (capabilities("tcltk") && requireNamespace("tcltk", quietly = TRUE)) { handlers("tkprogressbar") with_progress({ y <- slow_sum(1:10) }) print(y) }
library(jsonlite) library(shiny) library(stringr) library(dplyr) library(ggplot2) library(lubridate) library(cranlogs) library(zoo) library(plotly) library(scales) library(httr) cranlogs::cran_downloads("vistime", "last-month") get_initial_release_date = function(packages) { min_date = Sys.Date() - 1 for (pkg in packages) { pkg_data = httr::GET(paste0("http://crandb.r-pkg.org/", pkg, "/all")) pkg_data = httr::content(pkg_data) initial_release = pkg_data$timeline[[1]] min_date = min(min_date, as.Date(initial_release)) } min_date } package_names = names(httr::content(httr::GET("http://crandb.r-pkg.org/-/desc"))) ui <- fluidPage( titlePanel("Package Downloads Over Time"), sidebarLayout( sidebarPanel( HTML("Enter an R package to see the "You can enter multiple packages to compare them"), selectInput("package", label = "Packages:", selected = c("timevis", "timeline", "vistime", "timelineS"), choices = package_names, multiple = TRUE), radioButtons("transformation", "Data Transformation:", c("Monthly", "Weekly", "Daily", "Cumulative")), sliderInput("mav_n", "Window for moving average", min = 1, max = 50, step = 5, value = 7), HTML("Created using the <a href='https://github.com/metacran/cranlogs'>cranlogs</a> package.", "This app is not affiliated with RStudio or CRAN.", "You can find the code for the app <a href='https://github.com/dgrtwo/cranview'>here</a>,", "or read more about it <a href='http://varianceexplained.org/r/cran-view/'>here</a>.") ), mainPanel( plotlyOutput("downloadsPlot") ) ) ) server <- function(input, output) { downloads <- reactive({ packages <- input$package cran_downloads(packages = packages, from = get_initial_release_date("vistime"), to = Sys.Date()-4) %>% as_tibble }) output$downloadsPlot <- renderPlotly({ d <- downloads() %>% group_by(package) if (input$transformation == "Cumulative") { d <- d %>% mutate_at("count", cumsum) } else if (input$transformation == "Monthly"){ d <- d %>% group_by(package, month = as.yearmon(date)) %>% summarize(date = min(date), count = sum(count)) } else if (input$transformation == "Weekly"){ d <- d %>% group_by(package, week = paste0(year(date), "-", str_pad(week(date), pad = "0", width = 2))) %>% summarize(date = min(date), count = sum(count)) } d <- d %>% group_by(package) %>% mutate(mav = rollmean(count, input$mav_n, fill = NA, align = "right")) %>% ungroup() %>% filter(!is.na(mav)) p <- plot_ly(type = "scatter") if('vistime' %in% input$package){ releases <- content(GET(paste0("http://crandb.r-pkg.org/vistime/all")))$timeline for(version in names(releases)){ p <- p %>% add_segments(x = as.POSIXct(releases[[version]]), xend = as.POSIXct(releases[[version]]), y = 0, yend = max(d$mav), color = I("grey"), showlegend = FALSE) %>% add_text(x = as.POSIXct(releases[[version]]), y = max(d$mav)*1.1, text = version, color = I("grey"), showlegend = FALSE) } } p %>% add_lines(x = ~date, y=~mav, data = d, color = ~package) %>% layout(xaxis=list(title="Date"), yaxis=list(title="Number of downloads"), title = ifelse(input$mav_n > 1, paste("Averaged over", input$mav_n, str_replace(tolower(input$transformation), "ly", "s")), "")) }) } shinyApp(ui = ui, server = server)
gen_news <- function(old_y, new_y, output_dfm, target_variable, target_period) { old_y <- data.frame(date=new_y$date) %>% left_join(old_y, by="date") data_old <- old_y data_new <- new_y is_quarterly <- function(dates, series) { tmp <- data.frame(dates, series) %>% dplyr::filter(!is.na(series)) %>% select(dates) %>% pull if (identical((sapply(tmp, function(x) substr(x, 6, 7)) %>% unique %>% sort), c("03", "06", "09", "12"))) { return (TRUE) } else { return (FALSE) } } quarterly <- c(FALSE) for (i in 2:ncol(data_new)) { quarterly <- append(quarterly, is_quarterly(data_new[,1], data_new[,i])) } monthlies <- data_old[,which(quarterly == FALSE)] quarterlies <- data_old[,which(quarterly == TRUE)] column_names <- c(colnames(data_old)[which(quarterly == FALSE)], colnames(data_old)[which(quarterly == TRUE)]) data_old <- cbind(monthlies, quarterlies) colnames(data_old) <- column_names monthlies <- data_new[,which(quarterly == FALSE)] quarterlies <- data_new[,which(quarterly == TRUE)] data_new <- cbind(monthlies, quarterlies) colnames(data_new) <- column_names t_nowcast <- which(data_new$date == target_period) add_month <- function (X) { month <- as.numeric(substr(X, 6, 7)) year <- as.numeric(substr(X, 1, 4)) if (month == 12) { return (as.Date(paste0(year+1, "-01-01"))) } else { return (as.Date(paste0(year, "-", month+1, "-01"))) } } for (i in 1:12) { data_old[nrow(data_new) + 1, "date"] <- add_month(data_old[nrow(data_old), "date"]) data_new[nrow(data_new) + 1, "date"] <- add_month(data_new[nrow(data_new), "date"]) } dates <- data_new$date data_old <- data_old[,2:ncol(data_old)] data_new <- data_new[,2:ncol(data_new)] i_series <- which(colnames(data_new) == target_variable) N <- ncol(data_new) data_rev <- cbind(data.frame(date=dates), data_new) data_rev[is.na(cbind(data.frame(date=dates), data_old))] <- NA results_old <- news_dfm(cbind(data.frame(date=dates), data_old), data_rev, output_dfm, target_variable, target_period) y_old <- results_old$y_old results_new <- news_dfm(data_rev, cbind(data.frame(date=dates), data_new), output_dfm, target_variable, target_period) y_rev <- results_new$y_old; y_new <- results_new$y_new actual <- results_new$actual; forecast <- results_new$fore; weight <- results_new$weight if (sum(is.na(forecast)) == length(forecast)) { message("No forecast was made") news_table <- NULL impact_revisions <- 0 impact_releases <- 0 } else { impact_revisions <- y_rev - y_old news <- actual - forecast impact_releases <- sweep(weight, MARGIN = 1, news, "*") news_table <- data.frame(cbind(forecast, actual, weight, impact_releases), row.names = colnames(data_old)) colnames(news_table) <- c("Forecast", "Actual", "Weight", "Impact") news_table[,"New Data"] <- as.numeric(as.logical(colSums(is.na(data_old) & !is.na(data_new)))) impact_total <- impact_revisions + colSums(impact_releases, na.rm = T) message("Nowcast Impact Decomposition") message(paste("old nowcast: ", y_old * 100, "%", sep = "")) message(paste("new nowcast: ", y_new * 100, "%", sep = "")) message(paste("Impact from data revisions: ", sprintf("%.2f", impact_revisions * 100), "%", sep = "")) message(paste("Impact from data releases: ", sprintf("%.2f", sum(news_table[, "Impact"] * 100, na.rm = TRUE)), "%", sep = "")) message(paste("Total impact: ", sprintf("%.2f", (impact_revisions + sum(news_table[, "Impact"], na.rm = TRUE)) * 100), "%", sep = "")) message("Nowcast Detail Table") message(news_table[, c("Forecast", "Actual", "Weight", "Impact")]) } return(list(target_period = target_period, target_variable = target_variable, y_old = y_old, y_new = y_new, forecast = forecast, actual = actual, weight = weight, news_table = news_table, impact_revisions = impact_revisions, impact_releases = impact_releases, impact_total = impact_total)) }
mcnp_est_nps <- function(err_target) { n <- as.numeric(readline(prompt = "How many tallies (1, 2 or 3) will you be scanning? ")) stopifnot(n %in% c(1, 2, 3)) cat("Copy and paste MCNP tally fluctuation charts. \n Then hit [enter] \n Do not include column headers.") raw_scan <- scan() mtrx <- matrix(raw_scan, ncol = 1 + 5 * n, byrow = TRUE) tfc.df <- data.frame(mtrx) rm(mtrx) latter_half <- tfc.df[-(1:floor(length(tfc.df[, 1]) / 2)), ] new_err <- seq(err_target, 0.5, length.out = 50) err_loc <- c(3, 8, 13)[1:n] tal_num <- c("first", "second", "third") counter <- 0 nps_fn <- function(err, b, m) exp((err - b) / m) for (i in err_loc) { counter <- counter + 1 cat("\n ") if (latter_half[length(latter_half[, 1]), i] <= err_target) { cat(paste0("Error target already achieved in ", tal_num[counter], " tally.")) next } lm1 <- stats::lm(latter_half[, i] ~ log(latter_half[, 1])) if (summary(lm1)$adj.r.squared < 0.8) { cat(paste0("Warning: Not a reliable trend in ", tal_num[counter], " tally. \n")) } if (lm1$coefficients[[2]] > 0) { cat(paste0( "Error trend is positive in ", tal_num[counter], " tally.\nResults will be erroneous.\n" )) } extrap_nps1 <- nps_fn(new_err, stats::coefficients(lm1)[[1]], stats::coefficients(lm1)[[2]]) cat("\n ") print(data.frame(Tally = tal_num[counter], `Estimated nps needed` = format(extrap_nps1[1], digits = 2, scientific = TRUE ), `error target` = err_target, row.names = "")) graphics::plot( x = tfc.df[, 1], y = tfc.df[, i], xlim = c(tfc.df[1, 1], max(c(extrap_nps1, tfc.df[, 1]))), ylim = c( err_target, max(tfc.df[, i]) ), xlab = "nps", ylab = "MC run uncert", log = "x", main = paste0( "rough forecast nps vs error, ", tal_num[counter], " tally" ), col = "darkblue", col.main = "darkblue", col.axis = "darkblue", col.lab = "darkblue" ) graphics::lines(extrap_nps1, new_err[1:length(extrap_nps1)], col = "firebrick1", lty = 2 ) graphics::abline(h = err_target, col = "darkgreen", lty = 2) } }
library("shiny") library("shinyWidgets") ui <- fluidPage( tags$h1("Exemple dropdown"), dropdown( tags$h3("List of Input"), shinyWidgets::pickerInput(inputId = 'xcol', label = 'X Variable', choices = names(iris)), selectInput(inputId = 'ycol', label = 'Y Variable', choices = names(iris), selected = names(iris)[[2]]), sliderInput(inputId = 'clusters', label = 'Cluster count', value = 3, min = 1, max = 9), style = "material-circle", icon = icon("cog"), status = "danger", animate = animateOptions(enter = animations$zooming_entrances$zoomInDown, exit = animations$zooming_exits$zoomOutUp, duration = 1) ), plotOutput(outputId = 'plot1') ) server <- function(input, output, session) { selectedData <- reactive({ iris[, c(input$xcol, input$ycol)] }) clusters <- reactive({ kmeans(selectedData(), input$clusters) }) output$plot1 <- renderPlot({ palette(c(" " par(mar = c(5.1, 4.1, 0, 1)) plot(selectedData(), col = clusters()$cluster, pch = 20, cex = 3) points(clusters()$centers, pch = 4, cex = 4, lwd = 4) }) } shinyApp(ui = ui, server = server)
cat("Running ranking (LambdaMart) example.\n") generate.data <- function(N) { num.queries <- floor(N/25) query <- sample(1:num.queries, N, replace=TRUE) query.level <- runif(num.queries) X1 <- query.level[query] X2 <- runif(N) X3 <- runif(N) Y <- X1 + X2 X2 <- X2 + scale(runif(num.queries))[query] SNR <- 5 sigma <- sqrt(var(Y)/SNR) Y <- Y + runif(N, 0, sigma) data.frame(Y, query=query, X1, X2, X3) } cat('Generating data\n') N=1000 data.train <- generate.data(N) cat('Fitting a model with gaussian loss function\n') train_params_gauss <- training_params(num_trees = 2000, shrinkage = 0.005, interaction_depth = 3, bag_fraction = 0.5, num_train = N, id = seq_len(nrow(data)), num_features = 3, min_num_obs_in_node = 10) gbm.gaussian <- gbmt(Y~X1+X2+X3, data=data.train, distribution=gbm_dist('Gaussian'), train_params=train_params_gauss, keep_gbm_data=TRUE, cv_folds=5, is_verbose = FALSE ) best.iter.gaussian <- gbmt_performance(gbm.gaussian, method="cv") title('Training of gaussian model') cat('Fitting a model with pairwise loss function (ranking metric: normalized discounted cumulative gain)\n') gbm.ndcg <- gbmt(Y~X1+X2+X3, data=data.train, distribution=gbm_dist( name='Pairwise', metric="ndcg", group='query'), train_params=train_params_gauss, keep_gbm_data=TRUE, cv_folds=5, is_verbose = FALSE ) best.iter.ndcg <- gbmt_performance(gbm.ndcg, method='cv') title('Training of pairwise model with ndcg metric') cat('Fit a model with pairwise loss function (ranking metric: fraction of concordant pairs)\n') gbm.conc <- gbmt(Y~X1+X2+X3, data=data.train, distribution=gbm_dist( name='Pairwise', metric="conc", group='query'), train_params = train_params_gauss, keep_gbm_data=TRUE, cv_folds=5, is_verbose = FALSE ) best.iter.conc <- gbmt_performance(gbm.conc, method='cv') title('Training of pairwise model with conc metric') par.old <- par(mfrow=c(1,3)) summary(gbm.gaussian, num_trees=best.iter.gaussian, main='gaussian') summary(gbm.ndcg, num_trees=best.iter.ndcg, main='pairwise (ndcg)') summary(gbm.conc, num_trees=best.iter.conc, main='pairwise (conc)') par(par.old) cat("Generating some new data\n") data.test <- generate.data(N) cat("Calculating predictions\n") predictions <- data.frame(random=runif(N), X2=data.test$X2, gaussian=predict(gbm.gaussian, data.test, best.iter.gaussian), pairwise.ndcg=predict(gbm.ndcg, data.test, best.iter.ndcg), pairwise.conc=predict(gbm.conc, data.test, best.iter.conc)) cat("Computing loss metrics\n") dist_1 <- gbm_dist("Gaussian") dist_2 <- gbm_dist(name='Pairwise', metric="ndcg", group_index=data.test$query, max_rank=5) dist_3 <- gbm_dist(name='Pairwise', metric="conc", group_index=data.test$query, max_rank=0) result.table <- data.frame(measure=c('random', 'X2 only', 'gaussian', 'pairwise (ndcg)', 'pairwise (conc)'), squared.loss=sapply(1:length(predictions), FUN=function(i) { loss(y=data.test$Y, predictions[[i]], w=rep(1,N), offset=rep(0, N), dist=gbm_dist(name="Gaussian")) }), ndcg5.loss=sapply(1:length(predictions), FUN=function(i) { loss(y=data.test$Y, predictions[[i]], w=rep(1,N), offset=rep(0 ,N), distribution_obj=dist_2)}), concordant.pairs.loss=sapply(1:length(predictions), FUN=function(i) { loss(y=data.test$Y, predictions[[i]], w=rep(1,N), offset=rep(0, N), distribution_obj= dist_3) }), row.names=NULL) cat('Performance measures for the different models on the test set (smaller is better):\n') print(result.table,digits=2)
plot.effpoly <- function(x, x.var=which.max(levels), main=paste(effect, "effect plot"), symbols=TRUE, lines=TRUE, axes, confint, lattice, ..., type, multiline, rug, xlab, ylab, colors, cex, lty, lwd, factor.names, show.strip.values, ci.style, band.colors, band.transparency, style, transform.x, ticks.x, xlim, ticks, ylim, rotx, roty, alternating, grid, layout, key.args, use.splines){ if (!is.logical(lines) && !is.list(lines)) lines <- list(lty=lines) lines <- applyDefaults(lines, defaults=list(lty=trellis.par.get("superpose.line")$lty, lwd=trellis.par.get("superpose.line")$lwd[1], col=NULL, splines=TRUE, multiline=FALSE), arg="lines") if (missing(multiline)) multiline <- lines$multiline if (missing(lwd)) lwd <- lines$lwd if (missing(lty)) lty <- lines$lty if (missing(use.splines)) use.splines <- lines$splines lines.col <- lines$col lines <- if (missing(lty)) lines$lty else lty if (!is.logical(symbols) && !is.list(symbols)) symbols <- list(pch=symbols) symbols <- applyDefaults(symbols, defaults= list( pch=trellis.par.get("superpose.symbol")$pch, cex=trellis.par.get("superpose.symbol")$cex[1]), arg="symbols") cex <- symbols$cex symbols <- symbols$pch if (missing(axes)) axes <- NULL axes <- applyDefaults(axes, defaults=list( x=list(rotate=0, cex=1, rug=TRUE), y=list(lab=NULL, lim=c(NA, NA), ticks=list(at=NULL, n=5), type="probability", rotate=0, cex=1), alternating=TRUE, grid=FALSE), arg="axes") x.args <- applyDefaults(axes$x, defaults=list(rotate=0, cex=1, rug=TRUE), arg="axes$x") if (missing(xlab)) { xlab.arg <- FALSE xlab <- list() } if (missing(xlim)) { xlim.arg <- FALSE xlim <- list() } if (missing(ticks.x)) { ticks.x.arg <- FALSE ticks.x <- list() } if (missing(transform.x)) { transform.x.arg <- FALSE transform.x <- list() } if (missing(rotx)) rotx <- x.args$rotate if (missing(rug)) rug <- x.args$rug cex.x <- x.args$cex x.args$rotate <- NULL x.args$rug <- NULL x.args$cex <- NULL x.pred.names <- names(x.args) if (length(x.pred.names) > 0){ for (pred.name in x.pred.names){ x.pred.args <- applyDefaults(x.args[[pred.name]], defaults=list(lab=NULL, lim=NULL, ticks=NULL, transform=NULL), arg=paste0("axes$x$", pred.name)) if (!xlab.arg) xlab[[pred.name]] <- x.pred.args$lab if (!xlim.arg) xlim[[pred.name]] <- x.pred.args$lim if (!ticks.x.arg) ticks.x[[pred.name]] <- x.pred.args$ticks if (!transform.x.arg) transform.x[[pred.name]] <- x.pred.args$transform } } if (length(xlab) == 0) xlab <- NULL if (length(xlim) == 0) xlim <- NULL if (length(ticks.x) == 0) ticks.x <- NULL if (length(transform.x) == 0) transform.x <- NULL y.args <- applyDefaults(axes$y, defaults=list(lab=NULL, lim=c(NA, NA), ticks=list(at=NULL, n=5), type="probability", style="lines", rotate=0, cex=1), arg="axes$y") if (missing(ylim)) ylim <- y.args$lim if (missing(ticks)) ticks <- y.args$ticks if (missing(type)) type <- y.args$type type <- match.arg(type, c("probability", "logit")) if (missing(ylab)) ylab <- y.args$lab if (is.null(ylab)) ylab <- paste0(x$response, " (", type, ")") if (missing(roty)) roty <- y.args$rotate cex.y <- y.args$cex if (missing(alternating)) alternating <- axes$alternating if (missing(grid)) grid <- axes$grid if (missing(style)) style <- match.arg(y.args$style, c("lines", "stacked")) if (missing(colors)) colors <- if (is.null(lines.col)){ if (style == "lines" || x$model == "multinom") trellis.par.get("superpose.line")$col else sequential_hcl(length(x$y.levels)) } else { lines.col } if (missing(confint)) confint <- NULL confint <- applyDefaults(confint, defaults=list(style=if (style == "lines" && !multiline && !is.null(x$se.prob)) "auto" else "none", alpha=0.15, col=colors), onFALSE=list(style="none", alpha=0, col="white"), arg="confint") if (missing(ci.style)) ci.style <- confint$style if (missing(band.transparency)) band.transparency <- confint$alpha if (missing(band.colors)) band.colors <- confint$col if(!is.null(ci.style)) ci.style <- match.arg(ci.style, c("auto", "bars", "lines", "bands", "none")) confint <- confint$style != "none" if (is.null(multiline)) multiline <- if (confint) FALSE else TRUE effect.llines <- llines has.se <- !is.null(x$confidence.level) if (confint && !has.se) stop("there are no confidence limits to plot") if (style == "stacked"){ if (type != "probability"){ type <- "probability" warning('type set to "probability" for stacked plot') } if (confint){ confint <- FALSE warning('confint set to FALSE for stacked plot') } ylim <- c(0, 1) } if (missing(lattice)) lattice <- NULL lattice <- applyDefaults(lattice, defaults=list( layout=NULL, strip=list(factor.names=TRUE, values=TRUE, cex=1), array=list(row=1, col=1, nrow=1, ncol=1, more=FALSE), arg="lattice" )) lattice$key.args <- applyDefaults(lattice$key.args, defaults=list( space="top", border=FALSE, fontfamily="sans", cex=.75, cex.title=1, arg="key.args" )) if (missing(layout)) layout <- lattice$layout if (missing(key.args)) key.args <- lattice$key.args strip.args <- applyDefaults(lattice$strip, defaults=list(factor.names=TRUE, values=TRUE, cex=1), arg="lattice$strip") factor.names <- strip.args$factor.names if (missing(show.strip.values)) show.strip.values <- strip.args$values cex.strip <- strip.args$cex height.strip <- max(1, cex.strip) array.args <- applyDefaults(lattice$array, defaults=list(row=1, col=1, nrow=1, ncol=1, more=FALSE), arg="lattice$array") row <- array.args$row col <- array.args$col nrow <- array.args$nrow ncol <- array.args$ncol more <- array.args$more .mod <- function(a, b) ifelse( (d <- a %% b) == 0, b, d) .modc <- function(a) .mod(a, length(colors)) .mods <- function(a) .mod(a, length(symbols)) .modl <- function(a) .mod(a, length(lines)) effect <- paste(sapply(x$variables, "[[", "name"), collapse="*") split <- c(col, row, ncol, nrow) n.predictors <- length(names(x$x)) y.lev <- x$y.lev n.y.lev <- length(y.lev) ylevel.names <- make.names(paste("prob",y.lev)) colnames(x$prob) <- colnames(x$logit) <- ylevel.names if (has.se){ colnames(x$lower.logit) <- colnames(x$upper.logit) <- colnames(x$lower.prob) <- colnames(x$upper.prob)<- ylevel.names } x.frame <-as.data.frame(x) predictors <- names(x.frame)[1:n.predictors] levels <- if (n.predictors==1) length (x.frame[,predictors]) else sapply(apply(x.frame[, predictors, drop=FALSE], 2, unique), length) if (is.character(x.var)) { which.x <- which(x.var == predictors) if (length(which.x) == 0) stop(paste("x.var = '", x.var, "' is not in the effect.", sep="")) x.var <- which.x } x.vals <- x.frame[, names(x.frame)[x.var]] response <- matrix(0, nrow=nrow(x.frame), ncol=n.y.lev) for (i in 1:length(x$y.lev)){ level <- which(colnames(x$prob)[i] == ylevel.names) response[,i] <- rep(x$y.lev[level], length(response[,i])) } prob <- as.vector(x$prob) logit <- as.vector(x$logit) response <- as.vector(response) if (has.se){ lower.prob <- as.vector(x$lower.prob) upper.prob <- as.vector(x$upper.prob) lower.logit <- as.vector(x$lower.logit) upper.logit <- as.vector(x$upper.logit) } response <- factor(response, levels=y.lev) Data <- data.frame(prob, logit) if (has.se) Data <- cbind(Data, data.frame(lower.prob, upper.prob, lower.logit, upper.logit)) Data[[x$response]] <- response for (i in 1:length(predictors)){ Data <- cbind(Data, x.frame[predictors[i]]) } levs <- levels(x$data[[predictors[x.var]]]) n.predictor.cats <- sapply(Data[, predictors[-c(x.var)], drop=FALSE], function(x) length(unique(x))) if (length(n.predictor.cats) == 0) n.predictor.cats <- 1 ci.style <- if(is.null(ci.style) || ci.style == "auto") { if(is.factor(x$data[[predictors[x.var]]])) "bars" else "bands"} else ci.style if( ci.style=="none" ) confint <- FALSE if (!confint){ if (style == "lines"){ if (!multiline){ layout <- if(is.null(layout)) c(prod(n.predictor.cats), length(levels(response)), 1) else layout if (is.factor(x$data[[predictors[x.var]]])){ range <- if (type=="probability") range(prob, na.rm=TRUE) else range(logit, na.rm=TRUE) ylim <- if (!any(is.na(ylim))) ylim else c(range[1] - .025*(range[2] - range[1]), range[2] + .025*(range[2] - range[1])) tickmarks <- make.ticks(ylim, link=I, inverse=I, at=ticks$at, n=ticks$n) levs <- levels(x$data[[predictors[x.var]]]) if (show.strip.values){ for (pred in predictors[-x.var]){ Data[[pred]] <- as.factor(Data[[pred]]) } } result <- xyplot(eval(if (type=="probability") parse(text=if (n.predictors==1) paste("prob ~ as.numeric(", predictors[x.var],") |", x$response) else paste("prob ~ as.numeric(", predictors[x.var],") |", paste(predictors[-x.var], collapse="*"), paste("*", x$response))) else parse(text=if (n.predictors==1) paste("logit ~ as.numeric(", predictors[x.var],") |", x$response) else paste("logit ~ as.numeric(", predictors[x.var],")|", paste(predictors[-x.var], collapse="*"), paste("*", x$response)))), par.strip.text=list(cex=0.8), strip=strip.custom(strip.names=c(factor.names, TRUE), sep=" = ", par.strip.text=list(cex=cex.strip), par.strip.text=list(cex=cex.strip)), panel=function(x, y, subscripts, x.vals, rug, ... ){ if (grid) ticksGrid(x=1:length(levs), y=tickmarks$at) good <- !is.na(y) effect.llines(x[good], y[good], lwd=lwd, lty=lty, type="b", pch=19, col=colors[1], cex=cex, ...) subs <- subscripts+as.numeric(rownames(Data)[1])-1 }, ylab=ylab, ylim=if (is.null(ylim)) if (type == "probability") range(prob) else range(logit) else ylim, xlab=if (is.null(xlab)) predictors[x.var] else xlab[[x.var]], main=main, x.vals=x$data[[predictors[x.var]]], rug=rug, scales=list(x=list(at=1:length(levs), labels=levs, rot=rotx, cex=cex.x), y=list(at=tickmarks$at, labels=tickmarks$labels, rot=roty, cex=cex.y), alternating=alternating), layout=layout, data=Data, ...) result$split <- split result$more <- more class(result) <- c("plot.eff", class(result)) } else { if(use.splines) effect.llines <- spline.llines range <- if (type=="probability") range(prob, na.rm=TRUE) else range(logit, na.rm=TRUE) ylim <- if (!any(is.na(ylim))) ylim else c(range[1] - .025*(range[2] - range[1]), range[2] + .025*(range[2] - range[1])) tickmarks <- make.ticks(ylim, link=I, inverse=I, at=ticks$at, n=ticks$n) nm <- predictors[x.var] x.vals <- x$data[[nm]] if (nm %in% names(ticks.x)){ at <- ticks.x[[nm]]$at n <- ticks.x[[nm]]$n } else{ at <- NULL n <- 5 } xlm <- if (nm %in% names(xlim)){ xlim[[nm]] } else range.adj(Data[nm]) tickmarks.x <- if ((nm %in% names(transform.x)) && !(is.null(transform.x))){ trans <- transform.x[[nm]]$trans make.ticks(trans(xlm), link=transform.x[[nm]]$trans, inverse=transform.x[[nm]]$inverse, at=at, n=n) } else { trans <- I make.ticks(xlm, link=I, inverse=I, at=at, n=n) } if (show.strip.values){ for (pred in predictors[-x.var]){ Data[[pred]] <- as.factor(Data[[pred]]) } } result <- xyplot(eval(if (type=="probability") parse(text=if (n.predictors==1) paste("prob ~ trans(", predictors[x.var],") |", x$response) else paste("prob ~ trans(", predictors[x.var],") |", paste(predictors[-x.var], collapse="*"), paste("*", x$response))) else parse(text=if (n.predictors==1) paste("logit ~ trans(", predictors[x.var],") |", x$response) else paste("logit ~ trans(", predictors[x.var],") |", paste(predictors[-x.var], collapse="*"), paste("*", x$response))) ), par.strip.text=list(cex=0.8), strip=strip.custom(strip.names=c(factor.names, TRUE), sep=" = ", par.strip.text=list(cex=cex.strip), par.strip.text=list(cex=cex.strip)), panel=function(x, y, subscripts, x.vals, rug, ... ){ if (grid) ticksGrid(x=tickmarks.x$at, y=tickmarks$at) if (rug) lrug(trans(x.vals)) good <- !is.na(y) effect.llines(x[good], y[good], lwd=lwd, lty=lty, col=colors[1], ...) subs <- subscripts+as.numeric(rownames(Data)[1])-1 }, ylab=ylab, xlim=suppressWarnings(trans(xlm)), ylim= if (is.null(ylim)) if (type == "probability") range(prob) else range(logit) else ylim, xlab=if (is.null(xlab)) predictors[x.var] else xlab[[x.var]], main=main, x.vals=x$data[[predictors[x.var]]], rug=rug, scales=list(y=list(at=tickmarks$at, labels=tickmarks$labels, rot=roty, cex=cex.y), x=list(at=tickmarks.x$at, labels=tickmarks.x$labels, rot=rotx, cex=cex.x), alternating=alternating), layout=layout, data=Data, ...) result$split <- split result$more <- more class(result) <- c("plot.eff", class(result)) } } else { layout <- if (is.null(layout)){ lay <- c(prod(n.predictor.cats[-(n.predictors - 1)]), prod(n.predictor.cats[(n.predictors - 1)]), 1) if (lay[1] > 1) lay else lay[c(2, 1, 3)] } else layout if (n.y.lev > min(c(length(colors), length(lines), length(symbols)))) warning('Colors, lines and symbols may have been recycled') range <- if (type=="probability") range(prob, na.rm=TRUE) else range(logit, na.rm=TRUE) ylim <- if (!any(is.na(ylim))) ylim else c(range[1] - .025*(range[2] - range[1]), range[2] + .025*(range[2] - range[1])) tickmarks <- make.ticks(ylim, link=I, inverse=I, at=ticks$at, n=ticks$n) if (is.factor(x$data[[predictors[x.var]]])){ key <- list(title=x$response, cex.title=1, border=TRUE, text=list(as.character(unique(response))), lines=list(col=colors[.modc(1:n.y.lev)], lty=lines[.modl(1:n.y.lev)], lwd=lwd), points=list(pch=symbols[.mods(1:n.y.lev)], col=colors[.modc(1:n.y.lev)]), columns = if ("x" %in% names(key.args)) 1 else find.legend.columns(length(n.y.lev), space=if("x" %in% names(key.args)) "top" else key.args$space)) for (k in names(key.args)) key[k] <- key.args[k] if (show.strip.values){ for (pred in predictors[-x.var]){ Data[[pred]] <- as.factor(Data[[pred]]) } } result <- xyplot(eval(if (type=="probability") parse(text=if (n.predictors==1) paste("prob ~ as.numeric(", predictors[x.var], ")") else paste("prob ~ as.numeric(", predictors[x.var],") | ", paste(predictors[-x.var], collapse="*"))) else parse(text=if (n.predictors==1) paste("logit ~ as.numeric(", predictors[x.var], ")") else paste("logit ~ as.numeric(", predictors[x.var],") | ", paste(predictors[-x.var], collapse="*")))), strip=strip.custom(strip.names=c(factor.names, TRUE), sep=" = ", par.strip.text=list(cex=cex.strip), par.strip.text=list(cex=cex.strip)), panel=function(x, y, subscripts, rug, z, x.vals, ...){ if (grid) ticksGrid(x=1:length(levs), y=tickmarks$at) for (i in 1:n.y.lev){ sub <- z[subscripts] == y.lev[i] good <- !is.na(y[sub]) effect.llines(x[sub][good], y[sub][good], lwd=lwd, type="b", col=colors[.modc(i)], lty=lines[.modl(i)], pch=symbols[i], cex=cex, ...) } }, ylab=ylab, ylim= if (is.null(ylim)) if (type == "probability") range(prob) else range(logit) else ylim, xlab=if (is.null(xlab)) predictors[x.var] else xlab[[x.var]], x.vals=x$data[[predictors[x.var]]], rug=rug, z=response, scales=list(x=list(at=1:length(levs), labels=levs, rot=rotx, cex=cex.x), y=list(at=tickmarks$at, labels=tickmarks$labels, rot=roty, cex=cex.y), alternating=alternating), main=main, key=key, layout=layout, data=Data, ...) result$split <- split result$more <- more class(result) <- c("plot.eff", class(result)) } else { if(use.splines) effect.llines <- spline.llines range <- if (type=="probability") range(prob, na.rm=TRUE) else range(logit, na.rm=TRUE) ylim <- if (!any(is.na(ylim))) ylim else c(range[1] - .025*(range[2] - range[1]), range[2] + .025*(range[2] - range[1])) tickmarks <- make.ticks(ylim, link=I, inverse=I, at=ticks$at, n=ticks$n) nm <- predictors[x.var] x.vals <- x$data[[nm]] if (nm %in% names(ticks.x)){ at <- ticks.x[[nm]]$at n <- ticks.x[[nm]]$n } else{ at <- NULL n <- 5 } xlm <- if (nm %in% names(xlim)){ xlim[[nm]] } else range.adj(Data[nm]) tickmarks.x <- if ((nm %in% names(transform.x)) && !(is.null(transform.x))){ trans <- transform.x[[nm]]$trans make.ticks(trans(xlm), link=transform.x[[nm]]$trans, inverse=transform.x[[nm]]$inverse, at=at, n=n) } else { trans <- I make.ticks(xlm, link=I, inverse=I, at=at, n=n) } key <- list(title=x$response, cex.title=1, border=TRUE, text=list(as.character(unique(response))), lines=list(col=colors[.modc(1:n.y.lev)], lty=lines[.modl(1:n.y.lev)], lwd=lwd), columns = if ("x" %in% names(key.args)) 1 else find.legend.columns(length(n.y.lev), space=if("x" %in% names(key.args)) "top" else key.args$space)) for (k in names(key.args)) key[k] <- key.args[k] if (show.strip.values){ for (pred in predictors[-x.var]){ Data[[pred]] <- as.factor(Data[[pred]]) } } result <- xyplot(eval(if (type=="probability") parse(text=if (n.predictors==1) paste("prob ~ trans(", predictors[x.var], ")") else paste("prob ~ trans(", predictors[x.var],") |", paste(predictors[-x.var], collapse="*"))) else parse(text=if (n.predictors==1) paste("logit ~ trans(", predictors[x.var], ")") else paste("logit ~ trans(", predictors[x.var],") | ", paste(predictors[-x.var], collapse="*")))), strip=strip.custom(strip.names=c(factor.names, TRUE), sep=" = ", par.strip.text=list(cex=cex.strip), par.strip.text=list(cex=cex.strip)), panel=function(x, y, subscripts, rug, z, x.vals, ...){ if (grid) ticksGrid(x=tickmarks.x$at, y=tickmarks$at) if (rug) lrug(trans(x.vals)) for (i in 1:n.y.lev){ sub <- z[subscripts] == y.lev[i] good <- !is.na(y[sub]) effect.llines(x[sub][good], y[sub][good], lwd=lwd, type="l", col=colors[.modc(i)], lty=lines[.modl(i)], ...) } }, ylab=ylab, xlim=suppressWarnings(trans(xlm)), ylim= if (is.null(ylim)) if (type == "probability") range(prob) else range(logit) else ylim, xlab=if (is.null(xlab)) predictors[x.var] else xlab[[x.var]], x.vals=x$data[[predictors[x.var]]], rug=rug, z=response, scales=list(x=list(at=tickmarks.x$at, labels=tickmarks.x$labels, rot=rotx, cex=cex.x), y=list(at=tickmarks$at, labels=tickmarks$labels, rot=roty, cex=cex.y), alternating=alternating), main=main, key=key, layout=layout, data=Data, ...) result$split <- split result$more <- more class(result) <- c("plot.eff", class(result)) } } } else { tickmarks <- make.ticks(c(0, 1), link=I, inverse=I, at=ticks$at, n=ticks$n) layout <- if (is.null(layout)){ lay <- c(prod(n.predictor.cats[-(n.predictors - 1)]), prod(n.predictor.cats[(n.predictors - 1)]), 1) if (lay[1] > 1) lay else lay[c(2, 1, 3)] } else layout if (n.y.lev > length(colors)) stop(paste('Not enough colors to plot', n.y.lev, 'regions')) key <- list(text=list(lab=rev(y.lev)), rectangle=list(col=rev(colors[1:n.y.lev])), columns = 1) for (k in names(key.args)) key[k] <- key.args[k] if (is.factor(x$data[[predictors[x.var]]])){ if(any(is.na(Data$prob))) stop("At least one combination of factor levels is not estimable.\n Stacked plots are misleading, change to style='lines'") result <- barchart(eval(parse(text=if (n.predictors == 1) paste("prob ~ ", predictors[x.var], sep="") else paste("prob ~ ", predictors[x.var]," | ", paste(predictors[-x.var], collapse="*")))), strip=strip.custom(strip.names=c(factor.names, TRUE), sep=" = ", par.strip.text=list(cex=cex.strip), par.strip.text=list(cex=cex.strip)), panel=function(x, y, ...){ panel.barchart(x, y, ...) if (grid) ticksGrid(x=NA, y=tickmarks$at, col="white") }, groups = response, col=colors, horizontal=FALSE, stack=TRUE, data=Data, ylim=ylim, ylab=ylab, xlab=if (is.null(xlab)) predictors[x.var] else xlab[[x.var]], scales=list(x=list(rot=rotx, at=1:length(levs), labels=levs, cex=cex.x), y=list(rot=roty, at=tickmarks$at, labels=tickmarks$labels, cex=cex.y), alternating=alternating), main=main, key=key, layout=layout) result$split <- split result$more <- more class(result) <- c("plot.eff", class(result)) } else { if(use.splines) effect.llines <- spline.llines nm <- predictors[x.var] x.vals <- x$data[[nm]] if (nm %in% names(ticks.x)){ at <- ticks.x[[nm]]$at n <- ticks.x[[nm]]$n } else{ at <- NULL n <- 5 } xlm <- if (nm %in% names(xlim)){ xlim[[nm]] } else range.adj(Data[nm]) tickmarks.x <- if ((nm %in% names(transform.x)) && !(is.null(transform.x))){ trans <- transform.x[[nm]]$trans make.ticks(trans(xlm), link=transform.x[[nm]]$trans, inverse=transform.x[[nm]]$inverse, at=at, n=n) } else { trans <- I make.ticks(xlm, link=I, inverse=I, at=at, n=n) } if (show.strip.values){ for (pred in predictors[-x.var]){ x$x[[pred]] <- as.factor(x$x[[pred]]) } } result <- densityplot(eval(parse(text=if (n.predictors == 1) paste("~ trans(", predictors[x.var], ")", sep="") else paste("~ trans(", predictors[x.var], ") | ", paste(predictors[-x.var], collapse="*")))), probs=x$prob, strip=strip.custom(strip.names=c(factor.names, TRUE), sep=" = ", par.strip.text=list(cex=cex.strip), par.strip.text=list(cex=cex.strip)), panel = function(x, subscripts, rug, x.vals, probs=probs, col=colors, ...){ fill <- function(x, y1, y2, col){ if (length(y2) == 1) y2 <- rep(y2, length(y1)) if (length(y1) == 1) y1 <- rep(y1, length(y2)) panel.polygon(c(x, rev(x)), c(y1, rev(y2)), col=col) } n <- ncol(probs) Y <- t(apply(probs[subscripts,], 1, cumsum)) fill(x, 0, Y[,1], col=col[1]) for (i in 2:n){ fill(x, Y[,i-1], Y[,i], col=col[i]) } if (rug) lrug(trans(x.vals)) if (grid) ticksGrid(x=tickmarks.x$at, y=tickmarks$at, col="white") }, rug=rug, x.vals=x$data[[predictors[x.var]]], data=x$x, xlim=suppressWarnings(trans(xlm)), ylim= c(0, 1), ylab=ylab, xlab=if (is.null(xlab)) predictors[x.var] else xlab[[x.var]], scales=list(x=list(at=tickmarks.x$at, labels=tickmarks.x$labels, rot=rotx, cex=cex.x), y=list(rot=roty, at=tickmarks$at, labels=tickmarks$labels, cex=cex.y), alternating=alternating), main=main, key=key, layout=layout, ...) result$split <- split result$more <- more class(result) <- c("plot.eff", class(result)) } } } else{ if (type == "probability"){ lower <- lower.prob upper <- upper.prob } else { lower <- lower.logit upper <- upper.logit } if (!multiline){ layout <- if(is.null(layout)) c(prod(n.predictor.cats), length(levels(response)), 1) else layout if (is.factor(x$data[[predictors[x.var]]])){ range <- range(c(lower, upper), na.rm=TRUE) ylim <- if (!any(is.na(ylim))) ylim else c(range[1] - .025*(range[2] - range[1]), range[2] + .025*(range[2] - range[1])) tickmarks <- make.ticks(ylim, link=I, inverse=I, at=ticks$at, n=ticks$n) levs <- levels(x$data[[predictors[x.var]]]) if (show.strip.values){ for (pred in predictors[-x.var]){ Data[[pred]] <- as.factor(Data[[pred]]) } } result <- xyplot(eval(if (type=="probability") parse(text=if (n.predictors==1) paste("prob ~ as.numeric(", predictors[x.var],") |", x$response) else paste("prob ~ as.numeric(", predictors[x.var],") |", paste(predictors[-x.var], collapse="*"), paste("*", x$response))) else parse(text=if (n.predictors==1) paste("logit ~ as.numeric(", predictors[x.var],") |", x$response) else paste("logit ~ as.numeric(", predictors[x.var],")|", paste(predictors[-x.var], collapse="*"), paste("*", x$response)))), par.strip.text=list(cex=0.8), strip=strip.custom(..., strip.names=c(factor.names, TRUE), sep=" = ", par.strip.text=list(cex=cex.strip), par.strip.text=list(cex=cex.strip)), panel=function(x, y, subscripts, x.vals, rug, lower, upper, ... ){ if (grid) ticksGrid(x=1:length(levs), y=tickmarks$at) good <- !is.na(y) effect.llines(x[good], y[good], lwd=lwd, lty=lty, type="b", pch=19, col=colors[1], cex=cex, ...) subs <- subscripts+as.numeric(rownames(Data)[1])-1 if (ci.style == "bars"){ larrows(x0=x[good], y0=lower[subs][good], x1=x[good], y1=upper[subs][good], angle=90, code=3, col=colors[.modc(2)], length=0.125*cex/1.5) } else if(ci.style == "lines"){ effect.llines(x[good], lower[subs][good], lty=2, col=colors[.modc(2)]) effect.llines(x[good], upper[subs][good], lty=2, col=colors[.modc(2)]) } else { if(ci.style == "bands") { panel.bands(x[good], y[good], lower[subs][good], upper[subs][good], fill=band.colors[1], alpha=band.transparency) }} }, ylab=ylab, ylim= if (is.null(ylim)) c(min(lower), max(upper)) else ylim, xlab=if (is.null(xlab)) predictors[x.var] else xlab[[x.var]], main=main, x.vals=x$data[[predictors[x.var]]], rug=rug, lower=lower, upper=upper, scales=list(x=list(at=1:length(levs), labels=levs, rot=rotx, cex=cex.x), y=list(at=tickmarks$at, labels=tickmarks$labels, rot=roty, cex=cex.y), alternating=alternating), layout=layout, data=Data, ...) result$split <- split result$more <- more class(result) <- c("plot.eff", class(result)) } else { if(use.splines) effect.llines <- spline.llines range <- range(c(lower, upper), na.rm=TRUE) ylim <- if (!any(is.na(ylim))) ylim else c(range[1] - .025*(range[2] - range[1]), range[2] + .025*(range[2] - range[1])) tickmarks <- make.ticks(ylim, link=I, inverse=I, at=ticks$at, n=ticks$n) nm <- predictors[x.var] x.vals <- x$data[[nm]] if (nm %in% names(ticks.x)){ at <- ticks.x[[nm]]$at n <- ticks.x[[nm]]$n } else{ at <- NULL n <- 5 } xlm <- if (nm %in% names(xlim)){ xlim[[nm]] } else range.adj(Data[nm]) tickmarks.x <- if ((nm %in% names(transform.x)) && !(is.null(transform.x))){ trans <- transform.x[[nm]]$trans make.ticks(trans(xlm), link=transform.x[[nm]]$trans, inverse=transform.x[[nm]]$inverse, at=at, n=n) } else { trans <- I make.ticks(xlm, link=I, inverse=I, at=at, n=n) } if (show.strip.values){ for (pred in predictors[-x.var]){ Data[[pred]] <- as.factor(Data[[pred]]) } } result <- xyplot(eval(if (type=="probability") parse(text=if (n.predictors==1) paste("prob ~ trans(", predictors[x.var],") |", x$response) else paste("prob ~ trans(", predictors[x.var],") |", paste(predictors[-x.var], collapse="*"), paste("*", x$response))) else parse(text=if (n.predictors==1) paste("logit ~ trans(", predictors[x.var],") |", x$response) else paste("logit ~ trans(", predictors[x.var],") |", paste(predictors[-x.var], collapse="*"), paste("*", x$response))) ), par.strip.text=list(cex=0.8), strip=strip.custom(strip.names=c(factor.names, TRUE), sep=" = ", par.strip.text=list(cex=cex.strip), par.strip.text=list(cex=cex.strip)), panel=function(x, y, subscripts, x.vals, rug, lower, upper, ... ){ if (grid) ticksGrid(x=tickmarks.x$at, y=tickmarks$at) if (rug) lrug(trans(x.vals)) good <- !is.na(y) effect.llines(x[good], y[good], lwd=lwd, lty=lty, col=colors[1], ...) subs <- subscripts+as.numeric(rownames(Data)[1])-1 if (ci.style == "bars"){ larrows(x0=x[good], y0=lower[subs][good], x1=x[good], y1=upper[subs][good], angle=90, code=3, col=colors[.modc(2)], length=0.125*cex/1.5) } else if(ci.style == "lines"){ effect.llines(x[good], lower[subs][good], lty=2, col=colors[.modc(2)]) effect.llines(x[good], upper[subs][good], lty=2, col=colors[.modc(2)]) } else { if(ci.style == "bands") { panel.bands(x[good], y[good], lower[subs][good], upper[subs][good], fill=band.colors[1], alpha=band.transparency) }} }, ylab=ylab, xlim=suppressWarnings(trans(xlm)), ylim= if (is.null(ylim)) c(min(lower), max(upper)) else ylim, xlab=if (is.null(xlab)) predictors[x.var] else xlab[[x.var]], main=main, x.vals=x$data[[predictors[x.var]]], rug=rug, lower=lower, upper=upper, scales=list(y=list(at=tickmarks$at, labels=tickmarks$labels, rot=roty, cex=cex.y), x=list(at=tickmarks.x$at, labels=tickmarks.x$labels, rot=rotx, cex=cex.x), alternating=alternating), layout=layout, data=Data, ...) result$split <- split result$more <- more class(result) <- c("plot.eff", class(result)) } } else { layout <- if (is.null(layout)){ lay <- c(prod(n.predictor.cats[-(n.predictors - 1)]), prod(n.predictor.cats[(n.predictors - 1)]), 1) if (lay[1] > 1) lay else lay[c(2, 1, 3)] } else layout if (n.y.lev > min(c(length(colors), length(lines), length(symbols)))) warning('Colors, lines and symbols may have been recycled') if (is.factor(x$data[[predictors[x.var]]])){ range <- range(c(lower, upper), na.rm=TRUE) ylim <- if (!any(is.na(ylim))) ylim else c(range[1] - .025*(range[2] - range[1]), range[2] + .025*(range[2] - range[1])) tickmarks <- make.ticks(ylim, link=I, inverse=I, at=ticks$at, n=ticks$n) key <- list(title=x$response, cex.title=1, border=TRUE, text=list(as.character(unique(response))), lines=list(col=colors[.modc(1:n.y.lev)], lty=lines[.modl(1:n.y.lev)], lwd=lwd), points=list(pch=symbols[.mods(1:n.y.lev)], col=colors[.modc(1:n.y.lev)]), columns = if ("x" %in% names(key.args)) 1 else find.legend.columns(length(n.y.lev), space=if("x" %in% names(key.args)) "top" else key.args$space)) for (k in names(key.args)) key[k] <- key.args[k] if (show.strip.values){ for (pred in predictors[-x.var]){ Data[[pred]] <- as.factor(Data[[pred]]) } } result <- xyplot(eval(if (type=="probability") parse(text=if (n.predictors==1) paste("prob ~ as.numeric(", predictors[x.var], ")") else paste("prob ~ as.numeric(", predictors[x.var],") | ", paste(predictors[-x.var], collapse="*"))) else parse(text=if (n.predictors==1) paste("logit ~ as.numeric(", predictors[x.var], ")") else paste("logit ~ as.numeric(", predictors[x.var],") | ", paste(predictors[-x.var], collapse="*")))), strip=strip.custom(strip.names=c(factor.names, TRUE), sep=" = ", par.strip.text=list(cex=cex.strip), par.strip.text=list(cex=cex.strip)), panel=function(x, y, subscripts, rug, z, x.vals, lower, upper, ...){ if (grid) ticksGrid(x=1:length(levs), y=tickmarks$at) for (i in 1:n.y.lev){ os <- if (ci.style == "bars"){ (i - (n.y.lev + 1)/2) * (2/(n.y.lev-1)) * .01 * (n.y.lev - 1) } else { 0 } sub <- z[subscripts] == y.lev[i] good <- !is.na(y[sub]) effect.llines(x[sub][good] + os, y[sub][good], lwd=lwd, type="b", col=colors[.modc(i)], lty=lines[.modl(i)], pch=symbols[i], cex=cex, ...) if (ci.style == "bars"){ larrows(x0=x[sub][good] + os, y0=lower[ ][sub][good], x1=x[sub][good] + os, y1=upper[subscripts][sub][good], angle=90, code=3, col=colors[.modc(i)], length=0.125*cex/1.5) } else if(ci.style == "lines"){ effect.llines(x[sub][good], lower[subscripts][sub][good], lty=lines[.modl(i)], col=colors[.modc(i)]) effect.llines(x[sub][good], upper[subscripts][sub][good], lty=lines[.modl(i)], col=colors[.modc(i)]) } else { if(ci.style == "bands") { panel.bands(x[sub][good], y[sub][good], lower[subscripts][sub][good], upper[subscripts][sub][good], fill=colors[.modc(i)], alpha=band.transparency) }} } }, ylab=ylab, ylim= if (is.null(ylim)) c(min(lower), max(upper)) else ylim, xlab=if (is.null(xlab)) predictors[x.var] else xlab[[x.var]], x.vals=x$data[[predictors[x.var]]], rug=rug, z=response, lower=lower, upper=upper, scales=list(x=list(at=1:length(levs), labels=levs, rot=rotx, cex=cex.x), y=list(at=tickmarks$at, labels=tickmarks$labels, rot=roty, cex=cex.y), alternating=alternating), main=main, key=key, layout=layout, data=Data, ...) result$split <- split result$more <- more class(result) <- c("plot.eff", class(result)) } else { if(use.splines) effect.llines <- spline.llines range <- range(c(lower, upper), na.rm=TRUE) ylim <- if (!any(is.na(ylim))) ylim else c(range[1] - .025*(range[2] - range[1]), range[2] + .025*(range[2] - range[1])) tickmarks <- make.ticks(ylim, link=I, inverse=I, at=ticks$at, n=ticks$n) nm <- predictors[x.var] x.vals <- x$data[[nm]] if (nm %in% names(ticks.x)){ at <- ticks.x[[nm]]$at n <- ticks.x[[nm]]$n } else{ at <- NULL n <- 5 } xlm <- if (nm %in% names(xlim)){ xlim[[nm]] } else range.adj(Data[nm]) tickmarks.x <- if ((nm %in% names(transform.x)) && !(is.null(transform.x))){ trans <- transform.x[[nm]]$trans make.ticks(trans(xlm), link=transform.x[[nm]]$trans, inverse=transform.x[[nm]]$inverse, at=at, n=n) } else { trans <- I make.ticks(xlm, link=I, inverse=I, at=at, n=n) } key <- list(title=x$response, cex.title=1, border=TRUE, text=list(as.character(unique(response))), lines=list(col=colors[.modc(1:n.y.lev)], lty=lines[.modl(1:n.y.lev)], lwd=lwd), columns = if ("x" %in% names(key.args)) 1 else find.legend.columns(length(n.y.lev), space=if("x" %in% names(key.args)) "top" else key.args$space)) for (k in names(key.args)) key[k] <- key.args[k] if (show.strip.values){ for (pred in predictors[-x.var]){ Data[[pred]] <- as.factor(Data[[pred]]) } } result <- xyplot(eval(if (type=="probability") parse(text=if (n.predictors==1) paste("prob ~ trans(", predictors[x.var], ")") else paste("prob ~ trans(", predictors[x.var],") |", paste(predictors[-x.var], collapse="*"))) else parse(text=if (n.predictors==1) paste("logit ~ trans(", predictors[x.var], ")") else paste("logit ~ trans(", predictors[x.var],") | ", paste(predictors[-x.var], collapse="*")))), strip=strip.custom(strip.names=c(factor.names, TRUE), sep=" = ", par.strip.text=list(cex=cex.strip), par.strip.text=list(cex=cex.strip)), panel=function(x, y, subscripts, rug, z, x.vals, lower, upper, ...){ if (grid) ticksGrid(x=tickmarks.x$at, y=tickmarks$at) if (rug) lrug(trans(x.vals)) for (i in 1:n.y.lev){ sub <- z[subscripts] == y.lev[i] good <- !is.na(y[sub]) effect.llines(x[sub][good], y[sub][good], lwd=lwd, type="l", col=colors[.modc(i)], lty=lines[.modl(i)], ...) if (ci.style == "bars"){ larrows(x0=x[sub][good], y0=lower[subscripts][sub][good], x1=x[sub][good], y1=upper[subscripts][sub][good], angle=90, code=3, col=colors[.modc(i)], length=0.125*cex/1.5) } else if(ci.style == "lines"){ effect.llines(x[sub][good], lower[subscripts][sub][good], lty=lines[.modl(i)], col=colors[.modc(i)]) effect.llines(x[sub][good], upper[subscripts][sub][good], lty=lines[.modl(i)], col=colors[.modc(i)]) } else { if(ci.style == "bands") { panel.bands(x[sub][good], y[sub][good], lower[subscripts][sub][good], upper[subscripts][sub][good], fill=colors[.modc(i)], alpha=band.transparency) }} } }, ylab=ylab, xlim=suppressWarnings(trans(xlm)), ylim= if (is.null(ylim)) c(min(lower), max(upper)) else ylim, xlab=if (is.null(xlab)) predictors[x.var] else xlab[[x.var]], x.vals=x$data[[predictors[x.var]]], rug=rug, z=response, lower=lower, upper=upper, scales=list(x=list(at=tickmarks.x$at, labels=tickmarks.x$labels, rot=rotx, cex=cex.x), y=list(at=tickmarks$at, labels=tickmarks$labels, rot=roty, cex=cex.y), alternating=alternating), main=main, key=key, layout=layout, data=Data, ...) result$split <- split result$more <- more class(result) <- c("plot.eff", class(result)) } } } result }
shape_file.split= function(im,shapefile,namesFile="test",path=getwd(),type="jpg"){ pbbb = txtProgressBar(min = 0, max = length(unique(shapefile[,1])), initial = 0) Nomes=NULL print("Progress:") for(i in unique(shapefile[,1])){ setTxtProgressBar(pbbb,i) id=shapefile[,1]==i pa=shapefile[id,3:4][1,] pb=shapefile[id,3:4][2,] pc=shapefile[id,3:4][3,] pd=shapefile[id,3:4][4,] sh1=round(rbind(pa,pb,pc,pd),0) ii=im [email protected][,,][email protected][,,]*0+1 ii[sh1[1,1],sh1[1,2],]=0 ii[sh1[2,1],sh1[2,2],]=0 ii[sh1[3,1],sh1[3,2],]=0 ii[sh1[4,1],sh1[4,2],]=0 pa0=pa;pb0=pb;pc0=pc;pd0=pd pb[2]=pa[2]=min(pb0[2],pa0[2]) pc[1]=pb[1]=max(pc0[1],pb0[1]) pd[2]=pc[2]=max(pd0[2],pc0[2]) pa[1]=pd[1]=min(pa0[1],pd0[1]) sh2=rbind(pa,pb,pc,pd) im2= crop_image(im,w=round(min(sh2[,1]),0):round(max(sh2[,1]),0), h=round(min(sh2[,2]),0):round(max(sh2[,2]),0),plot = F) nome=paste0(path,"/",namesFile,"_",i,".",type) write_image(im2,files = nome) Nomes=c(Nomes,nome) } print("Arquivos criados (files created):") print(Nomes) return(Nomes) }
test_that_cli("make_line", { expect_equal(make_line(1, "-"), "-") expect_equal(make_line(0, "-"), "") expect_equal(make_line(2, "-"), "--") expect_equal(make_line(10, "-"), "----------") expect_equal(make_line(2, "12"), "12") expect_equal(make_line(0, "12"), "") expect_equal(make_line(1, "12"), "1") expect_equal(make_line(9, "12"), "121212121") expect_equal(make_line(10, "12"), "1212121212") }) test_that("width option", { expect_equal( rule(width = 11, line = "-"), rule_class("-----------") ) }) test_that("left label", { expect_equal( rule("label", width = 12, line = "-"), rule_class("-- label ---") ) expect_equal( rule("l", width = 12, line = "-"), rule_class("-- l -------") ) expect_equal( rule("label", width = 9, line = "-"), rule_class("-- label ") ) expect_equal( rule("label", width = 8, line = "-"), rule_class("-- label") ) expect_equal( rule("label", width = 6, line = "-"), rule_class("-- lab") ) }) test_that("centered label", { expect_error( rule(left = "label", center = "label"), "cannot be specified" ) expect_error( rule(center = "label", right = "label"), "cannot be specified" ) expect_equal( rule(center = "label", width = 13, line = "-"), rule_class("--- label ---") ) expect_equal( rule(center = "label", width = 14, line = "-"), rule_class("---- label ---") ) expect_equal( rule(center = "label", width = 9, line = "-"), rule_class("- label -") ) expect_equal( rule(center = "label", width = 8, line = "-"), rule_class("- labe -") ) expect_equal( rule(center = "label", width = 7, line = "-"), rule_class("- lab -") ) }) test_that("right label", { expect_equal( rule(right = "label", width = 12, line = "-"), rule_class("--- label --") ) expect_equal( rule(right = "l", width = 12, line = "-"), rule_class("------- l --") ) expect_equal( rule(right = "label", width = 9, line = "-"), rule_class(" label --") ) expect_equal( rule(right = "label", width = 8, line = "-"), rule_class(" label -") ) expect_equal( rule(right = "label", width = 6, line = "-"), rule_class(" label") ) expect_equal( rule(right = "label", width = 5, line = "-"), rule_class(" labe") ) expect_equal( rule(right = "label", width = 4, line = "-"), rule_class(" lab") ) }) test_that("line_col", { withr::with_options( list(cli.num_colors = 256L), { expect_true(ansi_has_any( rule(line_col = "red") )) expect_true(ansi_has_any( rule(left = "left", line_col = "red") )) expect_true(ansi_has_any( rule(left = "left", right = "right", line_col = "red") )) expect_true(ansi_has_any( rule(center = "center", line_col = "red") )) expect_true(ansi_has_any( rule(right = "right", line_col = "red") )) expect_true(ansi_has_any( rule(line_col = col_red) )) } ) }) test_that_cli("get_line_char", { expect_equal(get_line_char(1), cli::symbol$line) expect_equal(get_line_char(2), cli::symbol$double_line) expect_equal(get_line_char("bar1"), cli::symbol$lower_block_1) expect_equal(get_line_char("bar2"), cli::symbol$lower_block_2) expect_equal(get_line_char("bar3"), cli::symbol$lower_block_3) expect_equal(get_line_char("bar4"), cli::symbol$lower_block_4) expect_equal(get_line_char("bar5"), cli::symbol$lower_block_5) expect_equal(get_line_char("bar6"), cli::symbol$lower_block_6) expect_equal(get_line_char("bar7"), cli::symbol$lower_block_7) expect_equal(get_line_char("bar8"), cli::symbol$lower_block_8) expect_equal(get_line_char("xxx"), "xxx") expect_equal(get_line_char(c("x", "y", "z")), "xyz") }) test_that("print.cli_rule", { withr::local_options(cli.width = 20) expect_snapshot(rule("foo")) })
df2list <- function(x, start.col = 1) { end.col <- ncol(x); x <- lapply(x[,start.col:end.col], function(x, label){label[x!=0]}, rownames(x)); return (x); }
"_PACKAGE" setOldClass(c("hms", "difftime")) NULL hms <- function(seconds = NULL, minutes = NULL, hours = NULL, days = NULL) { args <- list(seconds = seconds, minutes = minutes, hours = hours, days = days) check_args(args) arg_secs <- map2(args, c(1, 60, 3600, 86400), `*`) secs <- reduce(arg_secs[!map_lgl(args, is.null)], `+`) if (is.null(secs)) secs <- numeric() new_hms(as.numeric(secs)) } new_hms <- function(x = numeric()) { vec_assert(x, numeric()) out <- new_duration(x, units = "secs") class(out) <- c("hms", class(out)) out } is_hms <- function(x) inherits(x, "hms") NULL is.hms <- function(x) { deprecate_soft("0.5.0", "hms::is.hms()", "hms::is_hms()") is_hms(x) } vec_ptype_abbr.hms <- function(x) { "time" } vec_ptype_full.hms <- function(x) { "time" } as_hms <- function(x, ...) { check_dots_used() UseMethod("as_hms") } as_hms.default <- function(x, ...) { vec_cast(x, new_hms()) } as.hms <- function(x, ...) { deprecate_soft("0.5.0", "hms::as.hms()", "hms::as_hms()") UseMethod("as.hms", x) } as.hms.default <- function(x, ...) { as_hms(x) } as.hms.POSIXt <- function(x, tz = pkgconfig::get_config("hms::default_tz", ""), ...) { time <- as.POSIXlt(x, tz = tz) vec_cast(time, new_hms()) } as.hms.POSIXlt <- function(x, tz = pkgconfig::get_config("hms::default_tz", ""), ...) { time <- as.POSIXlt(as.POSIXct(x), tz = tz) vec_cast(time, new_hms()) } as.POSIXct.hms <- function(x, ...) { vec_cast(x, new_datetime()) } as.POSIXlt.hms <- function(x, ...) { vec_cast(x, as.POSIXlt(new_datetime())) } as.character.hms <- function(x, ...) { vec_cast(x, character()) } format_hms <- function(x) { xx <- decompose(x) ifelse(is.na(x), NA_character_, paste0( ifelse(xx$sign, "-", ""), format_hours(xx$hours), ":", format_two_digits(xx$minute_of_hour), ":", format_two_digits(xx$second_of_minute), format_tics(xx$tics))) } `[[.hms` <- function(x, ...) { vec_restore(NextMethod(), x) } `[<-.hms` <- function(x, i, value) { if (missing(i)) { i <- TRUE } x <- vec_data(x) if (identical(class(value), "numeric")) { attr(value, "units") <- NULL } value <- vec_cast(value, new_hms()) x[i] <- vec_data(value) new_hms(x) } c.hms <- function(x, ...) { vec_c(x, ...) } `units<-.hms` <- function(x, value) { if (!identical(value, "secs")) { warning("hms always uses seconds as unit.", call. = FALSE) } x } format.hms <- function(x, ...) { if (length(x) == 0L) { "hms()" } else { format(as.character(x), justify = "right") } } print.hms <- function(x, ...) { cat(format(x), sep = "\n") invisible(x) }
update_candidate <- function(add_active_group.index, active_group.index, candidate.group, order, level){ new_candidate.group <- list() active.group <- candidate.group[active_group.index] unique.active.group <- lapply(active.group, FUN = function(x) x[[length(x)]]) for(group.index in add_active_group.index){ new_active.group <- candidate.group[[group.index]] new_active.resolution <- max(sapply(new_active.group, function(x) x$resolution)) new_active.order <- max(sapply(new_active.group, function(x) length(x$effect))) if(new_active.resolution < level){ group.add <- new_active.group[sapply(new_active.group, FUN = function(x) x$resolution == new_active.resolution)] group.add <- lapply(group.add, function(x) { x$resolution <- x$resolution + 1 return(x)}) if(new_active.order == 1){ new_candidate.add <- c(new_active.group, group.add) new_candidate.group <- c(new_candidate.group, list(new_candidate.add)) }else{ dupicate.index <- is.anydupicate(group.add, unique.active.group, type = 2) if(all(dupicate.index[-length(dupicate.index)])){ new_candidate.add <- c(new_active.group, group.add) new_candidate.group <- c(new_candidate.group, list(new_candidate.add)) } } } if(new_active.order < order & length(active.group) > 0){ same_order_level.group <- active.group[sapply(active.group, function(x.ls) max(sapply(x.ls, function(x) x$resolution)) == new_active.resolution & max(sapply(x.ls, function(x) length(x$effect))) == new_active.order)] same_order_level.group <- c(same_order_level.group, list(new_active.group)) if(length(same_order_level.group) > new_active.order){ test.table <- combn(length(same_order_level.group) - 1, new_active.order) test.table <- rbind(test.table, length(same_order_level.group)) temp.group <- lapply(same_order_level.group, function(x.ls) x.ls[length(x.ls)]) group.tmp <- sapply(temp.group, function(x.ls) x.ls[sapply(x.ls, function(x) length(x$effect) == new_active.order)]) effect_heredity.index <- which(apply(test.table, 2, function(x){ group.tbl <- table(c(sapply(group.tmp[x], function(x.ls) x.ls$effect))) all(group.tbl == new_active.order) & length(group.tbl) == (new_active.order + 1) })) for(ii in effect_heredity.index){ effect.new <- sort(unique(c(sapply(group.tmp[test.table[,ii]], function(x.ls) x.ls$effect)))) group.new <- vector("list", new_active.resolution) for(jj in 1:new_active.resolution) group.new[[jj]] <- list(effect = effect.new, resolution = jj) if(new_active.resolution > 1){ dupicate.index <- is.anydupicate(group.new[jj-1], unique.active.group, type = 2) }else { dupicate.index <- TRUE } if(dupicate.index){ new_candidate.add <- c(unique(unlist(same_order_level.group[test.table[,ii]], recursive = FALSE)), group.new) new_candidate.group <- c(new_candidate.group, list(new_candidate.add)) } } } } } if(length(new_candidate.group) > 1) new_candidate.group <- list.unique(new_candidate.group) if(length(new_candidate.group) > 0){ delete.fg <- !is.anydupicate(new_candidate.group, candidate.group, type = 1) if(any(delete.fg)){ new_candidate.group <- new_candidate.group[delete.fg] } } return(new_candidate.group) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(tidycomm) WoJ WoJ %>% add_index(ethical_flexibility, ethics_1, ethics_2, ethics_3, ethics_4) %>% dplyr::select(ethical_flexibility, ethics_1, ethics_2, ethics_3, ethics_4) WoJ %>% add_index(ethical_flexibility, ethics_1, ethics_2, ethics_3, ethics_4, type = "sum") %>% dplyr::select(ethical_flexibility, ethics_1, ethics_2, ethics_3, ethics_4) WoJ <- WoJ %>% add_index(ethical_flexibility, ethics_1, ethics_2, ethics_3, ethics_4) %>% add_index(trust_in_politics, trust_parliament, trust_government, trust_parties, trust_politicians) WoJ %>% get_reliability() WoJ %>% get_reliability(trust_in_politics) WoJ %>% get_reliability(type = 'omega', interval.type = 'mlr')
"new_jersey_counts"
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library("FMM") generateFMM(M=2,A=3,alpha=1.5,beta=2.3,omega=0.1, plot=TRUE,outvalues=FALSE) fmm2.data <-generateFMM(M=0,A=c(2,2),alpha=c(1.5,3.4),beta=c(0.2,2.3),omega=c(0.1,0.2), plot=FALSE, outvalues=TRUE) str(fmm2.data) set.seed(15) fmm2.data <-generateFMM(M=0,A=c(2,2),alpha=c(1.5,3.4),beta=c(0.2,2.3),omega=c(0.1,0.2), plot=TRUE, outvalues=TRUE, sigmaNoise=0.3) fit.fmm2 <- fitFMM(vData = fmm2.data$y, timePoints = fmm2.data$t, nback = 2) summary(fit.fmm2) getFMMPeaks(fit.fmm2, timePointsIn2pi = TRUE) fit1 <- fitFMM(vData = fmm2.data$y, timePoints = fmm2.data$t, nback = 2, lengthAlphaGrid = 48, lengthOmegaGrid = 24, numReps = 3, showTime = TRUE) fit2 <- fitFMM(vData = fmm2.data$y, timePoints = fmm2.data$t, nback = 2, lengthAlphaGrid = 14, lengthOmegaGrid = 7, numReps = 6, showTime = TRUE) getR2(fit1) getR2(fit2) fit3 <- fitFMM(vData = fmm2.data$y, timePoints = fmm2.data$t, nback = 2, maxiter = 5, stopFunction = R2(difMax = 0.01), showTime = TRUE, showProgress = TRUE) set.seed(1115) rfmm.data <-generateFMM(M = 3, A = c(4,3,1.5,1), alpha = c(3.8,1.2,4.5,2), beta = c(rep(3,2),rep(1,2)), omega = c(rep(0.1,2),rep(0.05,2)), plot = TRUE, outvalues = TRUE, sigmaNoise = 0.3) fit.rfmm <- fitFMM(vData = rfmm.data$y, timePoints = rfmm.data$t, nback = 4, betaOmegaRestrictions = c(1, 1, 2, 2), lengthAlphaGrid = 24, lengthOmegaGrid = 15, numReps = 5) summary(fit.rfmm) titleText <- "Two FMM waves" par(mfrow=c(1,2)) plotFMM(fit.fmm2, textExtra = titleText) plotFMM(fit.fmm2, components = TRUE, textExtra = titleText, legendInComponentsPlot = TRUE) library("RColorBrewer") library("ggplot2") library("gridExtra") titleText <- "Four restricted FMM waves" defaultrFMM2 <- plotFMM(fit.rfmm, use_ggplot2 = TRUE, textExtra = titleText) defaultrFMM2 <- defaultrFMM2 + theme(plot.margin=unit(c(1,0.25,1.3,1), "cm")) + ylim(-5, 6) comprFMM2 <- plotFMM(fit.rfmm, components=TRUE, use_ggplot2 = TRUE, textExtra = titleText) comprFMM2 <- comprFMM2 + theme(plot.margin=unit(c(1,0.25,0,1), "cm")) + ylim(-5, 6) + scale_color_manual(values = brewer.pal("Set1",n = 8)[3:6]) grid.arrange(defaultrFMM2, comprFMM2, nrow = 1)