code
stringlengths
1
13.8M
mean_auc_log <- function(auc, backtransform=TRUE){ if(length(auc) ==1) stop("\n", "AUC contains only one value, include more AUC values", "\n") mean_auc <- mean(log(auc/(1-auc))) if(backtransform) mean_auc <- exp(mean_auc) /(1 + exp(mean_auc)) return(mean_auc) }
rmInvalidLines <- function(df, RELEVANTVN_ES = NULL) { idxNA <- which(is.na(lubridate::ymd_hms(df[,RELEVANTVN_ES[["ES_START_DATETIME"]]]))) if(length(idxNA) > 0) { dfNew <- df[-idxNA,] list(dfNew=dfNew, removedLines=df[idxNA,]) } else { list(dfNew=df, removedLines=NA) } }
random.longshort <- function( n=2, k=n, segments=NULL, x.t.long=1, x.t.short=x.t.long, max.iter=2000, eps=0.001 ) { if ( x.t.long < 0 ) stop( "Argument 'x.t'.long is less than zero" ) if ( x.t.short < 0 ) stop( "Argument 'x.t'.short is less than zero" ) if ( k > n ) stop( "Argument 'k' is greater than 'm'" ) iter <- 0 more <- TRUE gross.t <- x.t.long + x.t.short if ( n < 2 ) { stop( "argument n is less than 2" ) } if ( !is.null( segments ) ) { segmentInvestments <- collapse.segments( segments ) numberInvestments <- length( segmentInvestments ) if ( numberInvestments > n || max( segmentInvestments ) > n ) stop( "Argument 'segments' has investments that are not allowed" ) weights <- random.longshort( n=numberInvestments, k=numberInvestments, segments=NULL, x.t.long, x.t.short, max.iter, eps ) investments <- sample( segmentInvestments, numberInvestments, replace=FALSE ) x <- rep( 0, n ) x[investments] <- weights return( x ) } if ( k < n ) { if ( k < 2 ) { stop( "cardinality k is less than 2" ) } weights <- random.longshort( n=k, k, segments=NULL, x.t.long, x.t.short, max.iter, eps ) investments <- sample( 1:n, k, replace=FALSE ) x <- rep( 0, n ) x[investments] <- weights return( x ) } if ( n == 2 ) { long <- sample( 1:2, 1, replace=FALSE ) short <- 3 - long x <- rep( 0, 2 ) x[long] <- x.t.long x[short] <- - x.t.short return( x ) } while (more ) { signs <- 2 * rbinom(n, 1, 0.5 ) - 1 if ( abs( sum( signs ) ) < n ) { investments <- seq( 1, n, 1 ) long.segment <- investments[ signs == 1 ] short.segment <- investments[ signs == -1 ] x.long <- random.longonly( n, k, segments=long.segment, x.t=x.t.long, x.l=0, x.u=x.t.long, max.iter ) x.short <- random.shortonly( n, k, segments=short.segment, x.t=x.t.short, x.l=0, x.u=x.t.short, max.iter ) x.longshort <- x.long + x.short x.gross <- sum( abs( x.longshort ) ) if ( abs( x.gross - gross.t ) <= eps ) { return( x.longshort ) } } iter <- iter + 1 if ( iter > max.iter ) { stop( "Iteration limit exceeded in random.longshort" ) } } return ( x ) }
getParamNr = function(par.set, devectorize = FALSE) { assertClass(par.set, "ParamSet") assertFlag(devectorize) if (devectorize) { return(sum(getParamLengths(par.set))) } else { return(length(par.set$pars)) } }
cnd_message <- function(cnd, ..., inherit = TRUE, prefix = FALSE) { orig <- cnd if (!inherit) { cnd$parent <- NULL } if (prefix) { msg <- cnd_message_format_prefixed(cnd, ..., parent = FALSE) } else { msg <- cnd_message_format(cnd, ...) } while (is_condition(cnd <- cnd$parent)) { parent_msg <- cnd_message_format_prefixed(cnd, parent = TRUE) msg <- paste_line(msg, parent_msg) } backtrace_on_error <- cnd_backtrace_on_error(orig) %||% "none" trace_footer <- format_onerror_backtrace(orig, opt = backtrace_on_error) c(msg, trace_footer) } cnd_message_lines <- function(cnd, ...) { c( cnd_header(cnd, ...), cnd_body(cnd, ...), cnd_footer(cnd, ...) ) } cnd_set_backtrace_on_error <- function(cnd, opt) { cnd$rlang$internal$backtrace_on_error <- opt cnd } cnd_backtrace_on_error <- function(cnd) { cnd[["rlang"]]$internal$backtrace_on_error } cnd_message_format <- function(cnd, ..., alert = FALSE) { lines <- cnd_message_lines(cnd, ...) if (is_string(lines, "")) { return("") } needs_alert <- alert && length(lines) && is_string(names2(lines)[[1]], "") if (!is_true(cnd$use_cli_format)) { out <- paste_line(lines) if (needs_alert) { out <- paste(ansi_alert(), out) } return(out) } if (needs_alert) { names2(lines)[[1]] <- "!" } cli_format <- switch( cnd_type(cnd), error = format_error, warning = format_warning, format_message ) cli_format(glue_escape(lines)) } local_cli_indent <- function(frame = caller_env()) { cli::cli_div( class = "indented", theme = list(div.indented = list("margin-left" = 2)), .envir = frame ) } cnd_header <- function(cnd, ...) { if (is_null(cnd[["header"]])) { UseMethod("cnd_header") } else { exec_cnd_method("header", cnd) } } cnd_header.default <- function(cnd, ...) { cnd$message } cnd_body <- function(cnd, ...) { if (is_null(cnd[["body"]])) { UseMethod("cnd_body") } else { exec_cnd_method("body", cnd) } } cnd_body.default <- function(cnd, ...) { chr() } cnd_footer <- function(cnd, ...) { if (is_null(cnd[["footer"]])) { UseMethod("cnd_footer") } else { exec_cnd_method("footer", cnd) } } cnd_footer.default <- function(cnd, ...) { chr() } exec_cnd_method <- function(name, cnd) { method <- cnd[[name]] if (is_function(method)) { method(cnd) } else if (is_bare_formula(method)) { method <- as_function(method) method(cnd) } else if (is_character(method)) { method } else { msg <- sprintf( "%s field must be a character vector or a function.", format_code(name) ) abort(msg, call = caller_env()) } } cnd_message_format_prefixed <- function(cnd, ..., parent = FALSE, alert = NULL) { type <- cnd_type(cnd) if (is_null(alert)) { alert <- is_error(cnd) || parent } if (parent) { prefix <- sprintf("Caused by %s", type) } else { prefix <- col_yellow(capitalise(type)) } call <- format_error_call(cnd$call) message <- cnd_message_format(cnd, ..., alert = alert) message <- strip_trailing_newline(message) if (!nzchar(message)) { return(NULL) } has_loc <- FALSE if (is_null(call)) { prefix <- sprintf("%s:", prefix) } else { src_loc <- src_loc(attr(cnd$call, "srcref")) if (nzchar(src_loc) && peek_call_format_srcref()) { prefix <- sprintf("%s in %s at %s:", prefix, call, src_loc) has_loc <- TRUE } else { prefix <- sprintf("%s in %s:", prefix, call) } } prefix <- style_bold(prefix) paste0(prefix, "\n", message) } peek_call_format_srcref <- function() { opt <- peek_option("rlang_call_format_srcrefs") if (is_null(opt)) { !is_testing() } else { check_bool(opt, arg = "rlang_call_format_srcrefs") opt } } conditionMessage.rlang_message <- function(c) { cnd_message(c) } conditionMessage.rlang_warning <- function(c) { cnd_message(c) } conditionMessage.rlang_error <- function(c) { cnd_message(c) } as.character.rlang_message <- function(x, ...) { paste0(cnd_message(x, prefix = TRUE), "\n") } as.character.rlang_warning <- function(x, ...) { paste0(cnd_message(x, prefix = TRUE), "\n") } as.character.rlang_error <- function(x, ...) { paste0(cnd_message(x, prefix = TRUE), "\n") } on_load({ s3_register("knitr::sew", "rlang_error", function(x, options, ...) { local_interactive() poke_last_error(x) x <- cnd_set_backtrace_on_error(x, peek_backtrace_on_error_report()) NextMethod() }) }) format_error_bullets <- function(x) { if (is_null(names(x))) { x <- set_names(x, "*") } .rlang_cli_format_fallback(x) } can_format <- function(x) { !is_string(x, "") && !inherits(x, "AsIs") }
htmlH6 <- function(children=NULL, id=NULL, n_clicks=NULL, n_clicks_timestamp=NULL, key=NULL, role=NULL, accessKey=NULL, className=NULL, contentEditable=NULL, contextMenu=NULL, dir=NULL, draggable=NULL, hidden=NULL, lang=NULL, spellCheck=NULL, style=NULL, tabIndex=NULL, title=NULL, loading_state=NULL, ...) { wildcard_names = names(dash_assert_valid_wildcards(attrib = list('data', 'aria'), ...)) props <- list(children=children, id=id, n_clicks=n_clicks, n_clicks_timestamp=n_clicks_timestamp, key=key, role=role, accessKey=accessKey, className=className, contentEditable=contentEditable, contextMenu=contextMenu, dir=dir, draggable=draggable, hidden=hidden, lang=lang, spellCheck=spellCheck, style=style, tabIndex=tabIndex, title=title, loading_state=loading_state, ...) if (length(props) > 0) { props <- props[!vapply(props, is.null, logical(1))] } component <- list( props = props, type = 'H6', namespace = 'dash_html_components', propNames = c('children', 'id', 'n_clicks', 'n_clicks_timestamp', 'key', 'role', 'accessKey', 'className', 'contentEditable', 'contextMenu', 'dir', 'draggable', 'hidden', 'lang', 'spellCheck', 'style', 'tabIndex', 'title', 'loading_state', wildcard_names), package = 'dashHtmlComponents' ) structure(component, class = c('dash_component', 'list')) }
print.critvalues <- function(x, digits = 3, latex.output = FALSE, template = 1, ...) { class(x) <- paste("critvalues", template, sep = "") print(x, digits, latex.output, ...) }
web <- setup({ app <- new_app() app$use(mw_static(root = test_path("fixtures", "static"))) set_headers <- function(req, res) { res$set_header("foo", "bar") } app$use(mw_static(root = test_path("fixtures", "static2"), set_headers = set_headers)) app$get("/static.html", function(req, res) { res$send("this is never reached") }) app$get("/fallback", function(req, res) { res$send("this is the fallback") }) new_app_process(app) }) teardown(web$stop()) test_that("static file", { url <- web$url("/static.html") resp <- curl::curl_fetch_memory(url) expect_equal(resp$status_code, 200L) expect_equal(resp$type, "text/html") expect_equal( rawToChar(resp$content), read_char(test_path("fixtures", "static", "static.html")) ) }) test_that("static file in subdirectory", { url <- web$url("/subdir/static.json") resp <- curl::curl_fetch_memory(url) expect_equal(resp$status_code, 200L) expect_equal(resp$type, "application/json") expect_equal( rawToChar(resp$content), read_char(test_path("fixtures", "static", "subdir", "static.json")) ) }) test_that("file not found", { url <- web$url("/notfound") resp <- curl::curl_fetch_memory(url) expect_equal(resp$status_code, 404L) }) test_that("file not found falls back", { url <- web$url("/fallback") resp <- curl::curl_fetch_memory(url) expect_equal(resp$status_code, 200L) expect_equal(resp$type, "text/plain") expect_equal( rawToChar(resp$content), "this is the fallback" ) }) test_that("directory is 404", { url <- web$url("/subdir") resp <- curl::curl_fetch_memory(url) expect_equal(resp$status_code, 404L) }) test_that("set_headers callback", { url <- web$url("/static.tar.gz") resp <- curl::curl_fetch_memory(url) expect_equal(resp$status_code, 200L) expect_equal(resp$type, "application/gzip") headers <- curl::parse_headers_list(resp$headers) expect_equal(headers$foo, "bar") expect_equal( resp$content, read_bin(test_path("fixtures", "static2", "static.tar.gz")) ) })
.bioclimDismo <- function(formula,data,...) { nsp <- deparse(formula[[2]]) w <- data[,nsp] == 1 x <- data[w,colnames(data) != nsp] nFact <- .where(is.factor,x) if (any(nFact)) x <- x[,-which(nFact),drop=FALSE] if (ncol(x) < 2) stop('At least two continous variables are needed to fit the model!') dismo::bioclim(x=x,...) } .domainDismo <- function(formula,data,...) { nsp <- deparse(formula[[2]]) w <- data[,nsp] == 1 x <- data[w,colnames(data) != nsp] nFact <- .where(is.factor,x) if (any(nFact)) x <- x[,-which(nFact),drop=FALSE] if (ncol(x) < 2) stop('At least two continous variables are needed to fit the model!') dismo::domain(x=x,...) } .mahalDismo <- function(formula,data,...) { nsp <- deparse(formula[[2]]) w <- data[,nsp] == 1 x <- data[w,colnames(data) != nsp] nFact <- .where(is.factor,x) if (any(nFact)) x <- x[,-which(nFact),drop=FALSE] if (ncol(x) < 2) stop('At least two continous variables are needed to fit the model!') dismo::mahal(x=x,...) }
library(testthat) context("largestContinuousMinimum") library(penaltyLearning) test_that("(start, end) when zero on both sides", { indices <- largestContinuousMinimumR( c(0, 0, 1, 15, 2, 0), c(Inf, 1, 1, 1, 1, Inf)) expect_equal(indices[["start"]], 1) expect_equal(indices[["end"]], 6) }) test_that("(1, 2) when two zeros on left", { indices <- largestContinuousMinimumR( c(0, 0, 1, 15, 2, 1), c(Inf, 1, 1, 1, 1, Inf)) expect_equal(indices[["start"]], 1) expect_equal(indices[["end"]], 2) }) test_that("(end, end) when one zero on right", { indices <- largestContinuousMinimumR( c(1, 1, 1, 15, 2, 0), c(Inf, 1, 1, 1, 1, Inf)) expect_equal(indices[["start"]], 6) expect_equal(indices[["end"]], 6) }) test_that("(mid, mid) when one zero in middle", { indices <- largestContinuousMinimumR( c(1, 1, 1, 0, 2, 2), c(Inf, 1, 1, 1, 1, Inf)) expect_equal(indices[["start"]], 4) expect_equal(indices[["end"]], 4) }) test_that("(minStart, minEnd) when two zeros in middle", { indices <- largestContinuousMinimumR( c(1, 1, 0, 0, 2, 2), c(Inf, 1, 1, 1, 1, Inf)) expect_equal(indices[["start"]], 3) expect_equal(indices[["end"]], 4) }) test_that("(start, end) when zero on both sides", { indices <- largestContinuousMinimumC( c(0, 0, 1, 15, 2, 0), c(Inf, 1, 1, 1, 1, Inf)) expect_equal(indices[["start"]], 1) expect_equal(indices[["end"]], 6) }) test_that("(1, 2) when two zeros on left", { indices <- largestContinuousMinimumC( c(0, 0, 1, 15, 2, 1), c(Inf, 1, 1, 1, 1, Inf)) expect_equal(indices[["start"]], 1) expect_equal(indices[["end"]], 2) }) test_that("(end, end) when one zero on right", { indices <- largestContinuousMinimumC( c(1, 1, 1, 15, 2, 0), c(Inf, 1, 1, 1, 1, Inf)) expect_equal(indices[["start"]], 6) expect_equal(indices[["end"]], 6) }) test_that("(mid, mid) when one zero in middle", { indices <- largestContinuousMinimumC( c(1, 1, 1, 0, 2, 2), c(Inf, 1, 1, 1, 1, Inf)) expect_equal(indices[["start"]], 4) expect_equal(indices[["end"]], 4) }) test_that("(minStart, minEnd) when two zeros in middle", { indices <- largestContinuousMinimumC( c(1, 1, 0, 0, 2, 2), c(Inf, 1, 1, 1, 1, Inf)) expect_equal(indices[["start"]], 3) expect_equal(indices[["end"]], 4) })
ammonia <- function(total_ammonia, temperature, ph, type_of_temperature) { if (type_of_temperature == "C"){ temperature <- temperature +273 } if (type_of_temperature == "F"){ temperature = 5 * (temperature - 32) / 9 + 273 } pka <- 0.09018 + 2729.92/temperature pka_ph <- pka-ph ten_pka_ph <- 10^pka_ph nh3 <- 1/(ten_pka_ph+1) perc_nh3 <- nh3*100 nh3_mgL <- total_ammonia*perc_nh3/100 list(pka = pka, pka_ph = pka_ph, ten_pka_ph = ten_pka_ph, nh3 = nh3, nh3_mgL = nh3_mgL) }
print.indicators <- function (x, At = 0, Bt = 0, sqrtIVt = 0, alpha = 1.0, selection = NULL, confint=FALSE,...) { if(is.null(selection)) selection = rep(TRUE, nrow(x$C)) if(length(dim(x$A))==2) { A = x$A[selection,] B = x$B[selection,] sqrtIV = x$sqrtIV[selection,] } else { A = x$A[selection] B = x$B[selection] sqrtIV = x$sqrtIV[selection] } p.value = x$p.value[selection] C = subset(x$C,selection) spnames = colnames(C) if(length(dim(A))==2) { sel = A$stat>=At & B$stat>=Bt & sqrtIV$stat>=sqrtIVt & p.value<=alpha if(confint) { nc= 10 A = A[sel,] B = B[sel,] sqrtIV = sqrtIV[sel,] } else { nc= 4 A = A$stat[sel] B = B$stat[sel] sqrtIV = sqrtIV$stat[sel] } p.value = p.value[sel] } else { sel = A>=At & B>=Bt & sqrtIV >=sqrtIVt & p.value<=alpha A = A[sel] B = B[sel] sqrtIV = sqrtIV[sel] p.value = p.value[sel] nc = 4 } sel[is.na(sel)]=FALSE CM = subset(C,sel) m = data.frame(matrix(0,nrow = sum(sel), ncol=nc)) if(nc==4) names(m) = c("A","B","sqrtIV", "p.value") else if(nc==10) names(m) = c("A","LA","UA","B","LB","UB","sqrtIV", "LsqrtIV","UsqrtIV", "p.value") if(sum(sel)>0) { if(nc==4) { m[,1] = A m[,2] = B m[,3] = sqrtIV m[,4] = p.value } else if (nc==10){ m[,1:3] = A m[,4:6] = B m[,7:9] = sqrtIV m[,10] = p.value } row.names(m) = rownames(CM) } m = m[order(m[["sqrtIV"]],decreasing=TRUE),] print(m,...) }
write_fasta <- function(x, name, file, width = 80, NA_letter = getOption("tidysq_NA_letter")) { assert_class(x, "sq") assert_character(name, len = vec_size(x), any.missing = FALSE) assert_string(file) assert_count(width, positive = TRUE) assert_string(NA_letter, min.chars = 1) CPP_write_fasta(x, name, file, width, NA_letter) }
context("column names") test_that( "col.names() returns all columns and column names", { sbc <- biclustermd(synthetic) expect_equal(nrow(col.names(sbc)), ncol(synthetic)) expect_equal(ncol(col.names(sbc)), 2) expect_equal(all(colnames(synthetic) %in% col.names(sbc)$col_name), TRUE) } ) test_that( "col.names() is a subset of gather()", { sbc <- biclustermd(synthetic) library(dplyr) expect_equal( col.names(sbc), gather(sbc) %>% distinct(col_cluster, col_name) %>% select(col_cluster, col_name) ) } )
effort_redistribute <- function (aDataFrame, column_name = "REVIEWERS", reviewer = NULL, remove_effort = 100, reviewers = NULL, effort = NULL, save_split = FALSE, directory = getwd()) { if(remove_effort == 0) return(aDataFrame) if(is.null(reviewers)) .metagearPROBLEM("error", "no reviewers were assigned") if(is.null(aDataFrame)) .metagearPROBLEM("error", "a dataframe with refs was not specified") split_dataFrame <- split(aDataFrame, aDataFrame[, column_name]) redist_dataFrame <- split_dataFrame[reviewer] split_dataFrame[reviewer] <- NULL if (length(reviewers) == 1) { .metagearPROBLEM("warning", "since reviewers had only one team member, all effort was distributed to them") new_dataFrame <- redist_dataFrame new_dataFrame[[1]][column_name] <- reviewers } else { theTeam <- reviewers number_reviewers <- length(theTeam) if(is.null(effort)) { teamEffort <- rep(ceiling(remove_effort/(number_reviewers - 1)), number_reviewers - 1) effort <- c(100 - remove_effort, teamEffort) if(sum(effort) > 100) effort[number_reviewers] <- effort[number_reviewers] - (sum(effort) - 100) } new_dataFrame <- list(effort_distribute(redist_dataFrame[[1]], theTeam, effort = effort, column_name = column_name, dual = FALSE, initialize = FALSE, save_split = FALSE)) } newDataFrame <- Reduce(function(...) rbind(...), c(split_dataFrame, new_dataFrame)) if(save_split == TRUE) effort_save(newDataFrame, column_name, directory) return(newDataFrame) }
"_PACKAGE" NULL NULL NULL if(getRversion() >= "2.15.1") utils::globalVariables(".")
data("Woods2010") p1 <- pairwise(treatment, event = r, n = N, studlab = author, data = Woods2010, sm = "OR") net1 <- netmeta(p1) net1 test_that("Default execution of nmarank without condition", { p1 = nmarank(net1)$probabilityOfSelection expect_type(p1, "double") }) A = condition("retainOrder", c("Placebo", "Salmeterol", "SFC")) B = condition("specificPosition", "Placebo", 1) C = condition("sameHierarchy", c("Placebo", "Fluticasone", "Salmeterol", "SFC")) D = condition("betterEqual", "Fluticasone", 2) G = condition("betterEqual", "Placebo", 2) test_that("Build selection tree", { st = (A %AND% (B %OR% (C %XOR% D))) expect_equal( st$root$isRoot , T ) }) test_that("small.values='good' should give Placebo last for this mortality outcome", { st1 <- condition("specificPosition", "Placebo", 1) placeboFirst = nmarank(net1, condition=st1,small.values="good")$probabilityOfSelection st2 <- condition("specificPosition", "Placebo", 4) placeboLast = nmarank(net1, condition=st2,small.values="good")$probabilityOfSelection expect_true(placeboLast>placeboFirst) }) test_that("check Selection tree", { st = (A %OR% (B %XOR% (C %OR% (D %AND% G)))) st1 = (B %XOR% (C %OR% (D %AND% G))) %OR% A effs <- nmarank:::nmaEffects(net1$TE.random, net1$Cov.random) ranksrow = effs$TE holds = selectionHolds(st, small.values="bad", ranksrow) expect_true(holds) expect_equal(selectionHolds(st, small.values="bad", ranksrow), selectionHolds(st1, small.values="bad", ranksrow)) }) test_that("Commutative selections", { st = (B %XOR% (C %OR% (D %AND% G))) %OR% A st1 = st %AND% G p1 = nmarank(net1, st1)$probabilityOfSelection expect_type(p1, "double") }) test_that("test opposite (not) function", { st = B %AND% opposite(B) p1 = nmarank(net1, st)$probabilityOfSelection expect_equal(p1, 0) })
fastEGO.nsteps <-function(model, fun, nsteps, lower, upper, control=NULL, trace=0, n.cores=1, ...) { n <- nrow(model@X) n.proxy <- n.unif <- 0 d <- model@d added.obs <- c() added.X <- c() if (is.null(control$warping)) control$warping <- FALSE if (is.null(control$cov.reestim)) control$cov.reestim <- TRUE if (!is.null(control$gpmean.freq)) gpmean.freq <- control$gpmean.freq else gpmean.freq <- 1e4 if (!is.null(control$gpmean.trick)) gpmean.trick <- control$gpmean.trick else gpmean.trick <- FALSE if (!is.null(control$always.sample)) always.sample <- control$always.sample else always.sample <- FALSE observations <- model@y if (trace > 1) message("Ite | max(EI) || ", colnames(model@X),"| obj \n") for (i in 1:nsteps) { if (((i %% gpmean.freq)==0) && (gpmean.trick)) { sol <- list(value=0) } else { sol <- try(max_crit(model=model, lower=lower, upper=upper, control=control, n.cores=n.cores)) } if (typeof(sol) == "character") { warning("Unable to maximize EI at iteration ", i, "- optimization stopped \n Last model returned \n") par <- values <- c() if (i > 1) { par <- model@X[(n+1):model@n,, drop = FALSE] values <- model@y[(n+1):model@n] } return(list(par=par, values=values, nsteps = i-1, lastmodel = model)) } if (sol$value < max(1e-16, sqrt(model@covariance@sd2/1e16)) && gpmean.trick) { if (trace>0) if ((i %% gpmean.freq)==0) { message("Forcing proxy acquisition criterion.\n") } else { message("No point found with non-null EI, restarted with proxy criterion.\n") n.proxy <- n.proxy+1 } sol <- try(max_crit(model=model, lower=lower, upper=upper, control=control, proxy=TRUE, n.cores=n.cores)) if (typeof(sol) == "character") { warning("Unable to maximize proxy criterion - optimization stopped \n Last model returned \n") par <- values <- c() if (i > 1) { par <- model@X[(n+1):model@n,, drop = FALSE] values <- model@y[(n+1):model@n] } return(list(par=par, values=values, nsteps = i-1, lastmodel = model)) } } else { n.proxy <- 0 } replace.point = FALSE if (!always.sample) { if (checkPredict(sol$par, model= list(model), threshold = 1e-6)){ if (trace>0) message("Optimization failed (an existing point was selected), so a random point is taken instead.\n") sol$par <- matrix(runif(d) * (upper - lower) + lower, nrow = 1) n.unif <- n.unif + 1 } else { n.unif <- 0 } } else { if (checkPredict(sol$par, model= list(model), threshold = 1e-6)){ if (trace>0) message("Point too close to an existing one - replacement scheme activated.\n") replace.point = TRUE } } X.new <- matrix(as.numeric(sol$par), nrow=1, ncol=d) Y.new <- try(fun(as.numeric(sol$par),...)) if (typeof(Y.new) == "character") { if (trace>0) { warning("Unable to compute objective function at iteration ", i, "- optimization stopped \n") warning("Problem occured for the design: ", X.new, "\n Last model returned \n") } par <- values <- c() if (i > 1) { par <- added.X values <- added.obs } return(list(par=par, values=values, nsteps = i-1, lastmodel = model)) } if (trace > 1) message( i, "|", signif(sol$val,3), "||", signif(X.new,3), "|", signif(Y.new,3), "\n") added.obs <- c(added.obs, Y.new) added.X <- rbind(added.X, X.new) if (control$warping) { Y.new <- warp(Y.new, control$wparam) } observations <- rbind(observations, Y.new) newmodel <- model if (!replace.point) { if (n.proxy < 5 && n.unif <3) { newmodel <- try(update(object = model, newX = X.new, newy=Y.new, newX.alreadyExist=FALSE, cov.reestim = control$cov.reestim), silent = TRUE) if (typeof(newmodel) == "character" && control$cov.reestim) { newmodel <- try(update(object = model, newX = X.new, newy=Y.new, newX.alreadyExist=FALSE, cov.reestim = FALSE), silent = TRUE) if (typeof(newmodel) != "character") { if (trace > 0) message("Error in hyperparameter estimation - old hyperparameter values used instead for the objective model \n") } else { if (length(model@covariance@nugget) == 0) { newmodel <- try(km([email protected], design=rbind(model@X, X.new), response=c(model@y, Y.new), covtype=model@covariance@name, [email protected], nugget= model@covariance@sd2/1e12, multistart=model@control$multistart, coef.cov=covparam2vect(model@covariance), coef.var=model@covariance@sd2, iso=is(model@covariance,"covIso"))) if (typeof(newmodel) != "character") { if (trace > 0) message("Error in hyperparameter estimation - nugget added to the model \n") } } } } } else { newmodel <- try(km([email protected], design=rbind(model@X, X.new), response=c(model@y, Y.new), covtype=model@covariance@name, [email protected], nugget= model@covariance@nugget, multistart=model@control$multistart, coef.cov=covparam2vect(model@covariance)/1.5, coef.var=model@covariance@sd2, iso=is(model@covariance,"covIso"))) if (typeof(newmodel) == "character" && length(model@covariance@nugget) == 0) { newmodel <- try(km([email protected], design=rbind(model@X, X.new), response=c(model@y, Y.new), covtype=model@covariance@name, [email protected], nugget= model@covariance@sd2/1e12, multistart=model@control$multistart, coef.cov=covparam2vect(model@covariance)/1.5, coef.var=model@covariance@sd2, iso=is(model@covariance,"covIso"))) if (typeof(newmodel) != "character") { if (trace > 0) message("Too many proxy/random iterations - model updated with smaller covariance ranges and nugget \n") model@lower <- model@lower/1.5 model@upper <- model@upper/1.5 } } else { if (trace > 0) message("Too many proxy/random iterations - model updated with smaller covariance ranges \n") } } } else { if (Y.new < min(model@y)) { ibest <- which.min(model@y) model@y[ibest] <- Y.new model@X[ibest,] <- X.new newmodel <- computeAuxVariables(model) } } if (typeof(newmodel) == "character") { warning("Unable to udpate kriging model at iteration", i-1, "- optimization stopped \n") warning("lastmodel is the model at iteration", i-1, "\n") warning("par and values contain the ",i, "th observation \n \n") if (i > 1) allX.new <- rbind(model@X[(n+1):model@n,, drop=FALSE], X.new) return(list( par = added.X, values = added.obs, nsteps = i, lastmodel = model)) } else { [email protected] <- [email protected] newmodel@case <- model@case [email protected] <- [email protected] newmodel@method <- model@method newmodel@penalty <- model@penalty [email protected] <- [email protected] newmodel@lower <- model@lower newmodel@upper <- model@upper newmodel@control <- model@control model <- newmodel } if (trace > 2) message("Covariance parameters: ", model@covariance@sd2, "|", covparam2vect(model@covariance), "\n") } if(trace>0) message("\n") return(list(par=added.X, value=added.obs, npoints=1, nsteps=nsteps, lastmodel=model)) }
context("ascii") test_that("ASCII encoding detected works", { skip_if(!isTRUE(l10n_info()$"Latin-1") && !isTRUE(l10n_info()$"UTF-8")) expect_equal( encoding(c( "a", iconv("\u00e4", to = "UTF-8"), iconv("\u00e4", to = "latin1"), as_unknown("\u00e4") )), c("ASCII", "UTF-8", "latin1", "unknown")) }) test_that("encoding() accepts only character vectors", { expect_error(encoding(1:3), "character vector") }) test_that("all_utf8()", { expect_true(all_utf8(character())) expect_true(all_utf8("a")) expect_true(all_utf8(iconv("ä", to = "UTF-8"))) expect_true(all_utf8(c("a", iconv("ä", to = "UTF-8")))) expect_false(all_utf8(iconv("ä", to = "latin1"))) expect_false(all_utf8(c("a", iconv("ä", to = "latin1")))) expect_false(all_utf8(c("a", as_unknown("ä")))) }) test_that("all_utf8() accepts only character vectors", { expect_error(all_utf8(1:3), "character vector") })
eth_protocolVersion <- function() { get_post_response("eth_protocolVersion") %>% hex_to_dec() } eth_syncing <- function() { get_post_response("eth_syncing") } eth_coinbase <- function() { get_post_response("eth_coinbase") } eth_mining <- function() { get_post_response("eth_mining") } eth_hashrate <- function() { get_post_response("eth_hashrate") %>% hex_to_dec() } eth_gasPrice <- function() { get_post_response("eth_gasPrice") %>% mpfr(base = 16) } eth_accounts <- function() { get_post_response("eth_accounts") %>% unlist() } eth_blockNumber <- function() { get_post_response("eth_blockNumber") %>% hex_to_dec() } eth_getBalance <- function(address = NULL, number = "latest") { if (is.null(address)) { address = eth_coinbase() if (is.null(address)) stop("Must specify address.") } get_post_response("eth_getBalance", list(address, number)) %>% mpfr(base = 16) } eth_getStorageAt <- function(address, position, number = "latest") { get_post_response("eth_getStorageAt", list(address, position, number)) } eth_getTransactionCount <- function(address = NULL, number = "latest") { if (is.null(address)) address = eth_coinbase() get_post_response("eth_getTransactionCount", list(address, number)) %>% hex_to_dec() } eth_getBlockTransactionCountByHash <- function(hash) { get_post_response("eth_getBlockTransactionCountByHash", list(hash)) %>% hex_to_dec() } eth_getBlockTransactionCountByNumber <- function(number = "latest") { get_post_response("eth_getBlockTransactionCountByNumber", list(number)) %>% hex_to_dec() } eth_getUncleCountByBlockHash <- function(hash) { get_post_response("eth_getUncleCountByBlockHash", list(hash)) %>% hex_to_dec() } eth_getUncleCountByBlockNumber <- function(number) { get_post_response("eth_getUncleCountByBlockNumber", list(number)) %>% hex_to_dec() } eth_getBlock <- function(hash = NULL, number = "latest", full = TRUE) { if (!is.null(hash)) block <- get_post_response("eth_getBlockByHash", list(hash, full)) else block <- get_post_response("eth_getBlockByNumber", list(number, full)) block$timestamp <- hex_to_dec(block$timestamp) if (!block$timestamp) { block$timestamp <- NA } else { block$timestamp <- as.POSIXct(block$timestamp, origin = "1970-01-01", tz = "UTC") } if (length(block$transactions)) { block$transactions <- lapply(block$transactions, function(transaction) { if (is.null(transaction$to)) transaction$to <- NA transaction }) %>% bind_rows() %>% rename_(index = "transactionIndex") } else { block$transactions = NA } block } eth_getTransactionByHash <- function(hash) { get_post_response("eth_getTransactionByHash", list(hash)) } eth_getTransactionByBlockHashAndIndex <- function(hash, index) { get_post_response("eth_getTransactionByBlockHashAndIndex", list(hash, index)) } eth_getTransactionByBlockNumberAndIndex <- function(number, index) { get_post_response("eth_getTransactionByBlockNumberAndIndex", list(number, index)) } eth_getTransactionReceipt <- function(hash) { get_post_response("eth_getTransactionReceipt", list(hash)) } eth_getUncleByBlockHashAndIndex <- function(hash, index) { get_post_response("eth_getUncleByBlockHashAndIndex", list(hash, index)) } eth_getUncleByBlockNumberAndIndex <- function(number, index) { get_post_response("eth_getUncleByBlockNumberAndIndex", list(number, index)) }
ThresholdGram<- function(gram.full,delta=1/log(dim(gram.full)[1])) { gram.bias<-gram.full*(abs(gram.full)<delta) gram.sd<-gram.full-gram.bias return(list(gram=gram.sd,gram.bias=gram.bias)) }
monitor_isEmpty <- function(ws_monitor) { return( nrow(ws_monitor$meta) == 0 ) }
predict.hrq_glasso<- function(object, newX, s=NULL, ...){ lambda<- object$lambda if(length(lambda)==1){ beta<- as.vector(object$beta) if(length(beta)==ncol(newX)+1){ pred<- as.matrix(cbind(1,newX))%*%beta }else{ stop("newX has wrong dimension!") } }else{ if(is.null(s)){ beta<- as.matrix(object$beta) if(nrow(beta)==ncol(newX)+1){ pred<- as.matrix(cbind(1,newX))%*%beta }else{ stop("new X has wrong dimension!") } }else{ ind<- which.min((lambda-s)^2) beta<- as.vector(object$beta[,ind]) if(length(beta)==ncol(newX)+1){ pred<- as.matrix(cbind(1,newX))%*%beta }else{ stop("new X has wrong dimension!") } } } return(pred) } predict.cv.hrq_glasso<- function(object, newX, s, ...){ lambda<- object$lambda if(missing(s)) s<- "lambda.min" if(s == "lambda.min") s<- object$lambda.min if(s == "lambda.1se") s<- object$lambda.1se ind<- which.min(abs(s-lambda))[1] beta<- as.vector(object$beta[,ind]) if(length(beta)==ncol(newX)+1){ pred<- as.matrix(cbind(1,newX))%*%beta }else{ stop("new X has wrong dimension!") } return(pred) }
library(checkargs) context("isNaOrStringScalarOrNull") test_that("isNaOrStringScalarOrNull works for all arguments", { expect_identical(isNaOrStringScalarOrNull(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNaOrStringScalarOrNull(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNaOrStringScalarOrNull(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull("", stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNaOrStringScalarOrNull("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNaOrStringScalarOrNull(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNaOrStringScalarOrNull(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNaOrStringScalarOrNull(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNaOrStringScalarOrNull(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNaOrStringScalarOrNull(0, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNaOrStringScalarOrNull("", stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNaOrStringScalarOrNull("X", stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNaOrStringScalarOrNull(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNaOrStringScalarOrNull(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) })
context("validate_state") test_that("get TRUE if correct State and FALSE in another case", { expect_false(validate_state("IM"), FALSE) expect_true(validate_state(us_congressional_districts$state_abb[[1]]), TRUE) expect_true(validate_state("MI"), TRUE) }) test_that("warnings", { expect_warning(validate_state(16), "State Abbreviation should be a character") expect_warning(validate_state(us_congressional_districts$state_name[1]), "State abbreviations should be two letters.") expect_warning(validate_state("im"), "State Abbreviation should be upper case.") }) test_that("get 50 TRUE if use data state_abb", { expect_equal(dim(array(sapply(unlist(unique(us_congressional_districts$state_abb)), validate_state))), 50) })
mdt.ui <- function(id) { ns <- NS(id) column(12, textInput(inputId = ns("arg1"), label = "Special case elements", value = "NA, NaN, Inf"), numericInput(inputId = ns("arg2"), label = "Number of splitting groups for each node", value = 50, min = 2, max = 150), selectInput(inputId = ns("arg3"), label = "How to treat special cases?", choices = c("together", "separately")), selectInput(inputId = ns("arg4"), label = "Type of target variable", choices = c(NA, "bina", "cont")), numericInput(inputId = ns("arg5"), label = "Minimum pct. of observations per bin", value = 0.05, min = 0, max = 1), numericInput(inputId = ns("arg6"), label = "Minimum avg. target rate per bin", value = 0.01, min = 0, max = 1), selectInput(inputId = ns("arg7"), label = "Force trend", choices = c(NA, "i", "d")) ) } cum.ui <- function(id) { ns <- NS(id) column(12, textInput(inputId = ns("arg1"), label = "Special case elements", value = "NA, NaN, Inf"), selectInput(inputId = ns("arg2"), label = "How to treat special cases?", choices = c("together", "separately")), numericInput(inputId = ns("arg3"), label = "Number of starting groups", value = 15, min = 2, max = 40), selectInput(inputId = ns("arg4"), label = "Type of target variable", choices = c(NA, "bina", "cont")), selectInput(inputId = ns("arg5"), label = "Force trend", choices = c(NA, "i", "d")) ) } iso.ui <- function(id) { ns <- NS(id) column(12, textInput(inputId = ns("arg1"), label = "Special case elements", value = "NA, NaN, Inf"), selectInput(inputId = ns("arg2"), label = "How to treat special cases?", choices = c("together", "separately")), selectInput(inputId = ns("arg3"), label = "Type of target variable", choices = c(NA, "bina", "cont")), numericInput(inputId = ns("arg4"), label = "Minimum pct. of observations per bin", value = 0.05, min = 0, max = 1), numericInput(inputId = ns("arg5"), label = "Minimum avg. target rate per bin", value = 0.01, min = 0, max = 1), selectInput(inputId = ns("arg6"), label = "Force trend", choices = c(NA, "i", "d")) ) } ndr.sts.ui <- function(id) { ns <- NS(id) column(12, textInput(inputId = ns("arg1"), label = "Special case elements", value = "NA, NaN, Inf"), selectInput(inputId = ns("arg2"), label = "How to treat special cases?", choices = c("together", "separately")), selectInput(inputId = ns("arg3"), label = "Type of target variable", choices = c(NA, "bina", "cont")), numericInput(inputId = ns("arg4"), label = "Minimum pct of observations per bin", value = 0.05, min = 0, max = 1), numericInput(inputId = ns("arg5"), label = "Minimum avg target rate per bin", value = 0.01, min = 0, max = 1), numericInput(inputId = ns("arg6"), label = "p-value", value = 0.05, min = 0, max = 1), selectInput(inputId = ns("arg7"), label = "Force trend", choices = c(NA, "i", "d")) ) } pct.ui <- function(id) { ns <- NS(id) column(12, textInput(inputId = ns("arg1"), label = "Special case elements", value = "NA, NaN, Inf"), selectInput(inputId = ns("arg2"), label = "How to treat special cases?", choices = c("together", "separately")), numericInput(inputId = ns("arg3"), label = "Number of starting groups", value = 15, min = 2, max = 40), selectInput(inputId = ns("arg4"), label = "Type of target variable", choices = c(NA, "bina", "cont")), selectInput(inputId = ns("arg5"), label = HTML("Force WoE trend</br> (applied only for continuous target)"), choices = c(TRUE, FALSE)), selectInput(inputId = ns("arg6"), label = "Force trend", choices = c(NA, "i", "d")) ) } woe.ui <- function(id) { ns <- NS(id) column(12, textInput(inputId = ns("arg1"), label = "Special case elements", value = "NA, NaN, Inf"), selectInput(inputId = ns("arg2"), label = "How to treat special cases?", choices = c("together", "separately")), selectInput(inputId = ns("arg3"), label = "Type of target variable", choices = c(NA, "bina", "cont")), numericInput(inputId = ns("arg4"), label = "Minimum pct of observations per bin", value = 0.05, min = 0, max = 1), numericInput(inputId = ns("arg5"), label = "Minimum avg target rate per bin", value = 0.01, min = 0, max = 1), numericInput(inputId = ns("arg6"), label = "WoE threshold", value = 0.1, min = 0, max = 1), selectInput(inputId = ns("arg7"), label = "Force trend", choices = c(NA, "i", "d")) ) } algo.ui <- function(id) { moduleServer(id, function(input, output, session) { observeEvent(input$monobin.method, { algo.select <- input$monobin.method output$algo.args <- renderUI({ tagList(switch(algo.select, "cum.bin" = cum.ui(id = id), "iso.bin" = iso.ui(id = id), "ndr.bin" = ndr.sts.ui(id = id), "sts.bin" = ndr.sts.ui(id = id), "pct.bin" = pct.ui(id = id), "woe.bin" = woe.ui(id = id), "mdt.bin" = mdt.ui(id = id))) }) }) }) } check.vars <- function(tbl) { check <- !sapply(tbl, is.numeric) check.col <- names(tbl)[check] if (length(check.col) == 0) { msg <- "All variables of numeric type." } else { cols <- paste(check.col, collapse = ", ") msg <- paste0("Following variables identified as non-numeric:", cols, ".") } return(msg) } sc.check <- function(x) { if (""%in%x) { return(list(NULL, 2, "Empty input field.")) } if (is.na(x)) { sc <- NA } else { sc <- trimws(strsplit(x, ",")[[1]]) } if (length(sc) == 1) { if (is.na(x) | is.infinite(x)) { return(list(x, 0, x)) } if (!sc%in%c("NA", "NaN", "Inf") & suppressWarnings(is.na(as.numeric(sc)))) { return(list(NULL, 2, sc)) } } sc.num <- suppressWarnings(as.numeric(sc)) check.01 <- is.na(sc.num) check.02 <- is.nan(sc.num) check.99 <- check.01 & !check.02 check.val <- sc[check.99] if (length(check.val) > 0) { if (length(check.val) == 1) { if (check.val != "NA") { check.sum <- 2 } else { check.sum <- 1 } } else { check.sum <- sum(check.99) } } else { check.sum <- 0 } return(list(sc.num, check.sum, check.val)) } sc.impute <- function(tbl, rf, sc, sc.replace, imp.method) { rfl <- length(rf) rfn <- paste0(rf, "_sc_", imp.method) rfn.f <- rfn info.tbl <- vector("list", rfl) info.msg <- "Imputed value cannot be calculated properly. Selected risk factor is not processed. Check the risk factor manually." eval.exp <- paste0(imp.method, "(rf.imp[!rf.imp%in%sc])") for (i in 1:rfl) { rf.l <- rf[i] rfn.l <- rfn[i] rf.imp <- tbl[, rf.l] rf.imp.val <- eval(parse(text = eval.exp)) if (rf.imp.val%in%c(NA, Inf, NaN)) { info.tbl[[i]] <- data.frame(risk.factor = rf.l, info = info.msg, imputation.method = imp.method) rfn.f <- rfn.f[!rfn.f%in%rfn.l] next } else { rf.imp[rf.imp%in%sc.replace] <- rf.imp.val if (rfn.l%in%names(tbl)) { tbl[, rfn.l] <- rf.imp } else { tbl <- cbind.data.frame(tbl, rf.imp) names(tbl)[ncol(tbl)] <- rfn.l } } } info.tbl <- bind_rows(info.tbl) return(list(tbl, rf.imp = rfn.f, info = data.frame(info.tbl))) } out.impute <- function(tbl, rf, ub, lb, sc) { rfl <- length(rf) rfn <- paste0(rf, "_out_", ub, "_", lb) rfn.f <- rfn info.tbl <- vector("list", rfl) info.msg <- "Imputed outlier value(s) cannot be calculated properly. Selected risk factor is not processed. Check the risk factor manually." for (i in 1:rfl) { rf.l <- rf[i] rfn.l <- rfn[i] rf.imp <- tbl[, rf.l] complete.c <- rf.imp[!rf.imp%in%sc] rf.imp.ub <- try(quantile(complete.c, ub), silent = TRUE) rf.imp.lb <- try(quantile(complete.c, lb), silent = TRUE) cond <- class(rf.imp.ub)%in%"try-error" | class(rf.imp.lb)%in%"try-error" | rf.imp.ub%in%c(NA, Inf, NaN) | rf.imp.lb%in%c(NA, Inf, NaN) if (cond) { info.tbl[[i]] <- data.frame(risk.factor = rf.l, info = info.msg, pct.selected = paste0("upper bound = ", ub, "; lower bound = ", lb)) rfn.f <- rfn.f[!rfn.f%in%rfn.l] next } else { rf.imp[!rf.imp%in%sc & rf.imp > rf.imp.ub] <- rf.imp.ub rf.imp[!rf.imp%in%sc & rf.imp < rf.imp.lb] <- rf.imp.lb if (rfn.l%in%names(tbl)) { tbl[, rfn.l] <- rf.imp } else { tbl <- cbind.data.frame(tbl, rf.imp) names(tbl)[ncol(tbl)] <- rfn.l } } } info.tbl <- bind_rows(info.tbl) return(list(tbl, rf.imp = rfn.f, info = data.frame(info.tbl))) } desc.report <- function(target, rf, sc, sc.method, db) { y <- db[, target] rfl <- length(rf) res <- vector("list", rfl) for (i in 1:rfl) { rf.n <- rf[i] incProgress(1 / (rfl - i + 1), detail = paste("Processing risk factor:", rf.n)) x <- db[, rf.n] desc.l <- suppressWarnings( desc.stat(y = y, x = x, sc = sc, sc.method = sc.method) ) desc.l <- cbind.data.frame(risk.factor = rf.n, desc.l) res[[i]] <- desc.l } res <- data.frame(bind_rows(res)) return(res) } num.inputs <- function(x) { switch(x, "cum.bin" = list(3, "Number of starting groups"), "iso.bin" = list(c(4, 5), c("Minimum pct. of observations per bin", "Minimum avg. target rate per bin")), "ndr.bin" = list(c(4, 5, 6), c("Minimum pct. of observations per bin", "Minimum avg. target rate per bin", "p-value")), "pct.bin" = list(3, "Number of starting groups"), "sts.bin" = list(c(4, 5, 6), c("Minimum pct. of observations per bin", "Minimum avg. target rate per bin", "p-value")), "woe.bin" = list(c(4, 5, 6), c("Minimum pct. of observations per bin", "Minimum avg. target rate per bin", "WoE threshold")), "mdt.bin" = list(c(2, 5, 6), c("Number of splitting groups for each node", "Minimum pct. of observations per bin", "Minimum avg. target rate per bin"))) } mono.inputs.check <- function(x, args.e) { inp.indx <- num.inputs(x = x) num.args <- c(args.e[inp.indx[[1]]], recursive = TRUE) check.01 <- any(is.na(num.args)) if (check.01) { msg <- paste0("Numeric input(s) required for: ", paste0(paste0(" return(list(check.ok = FALSE, msg = msg)) } if (x%in%c("cum.bin", "pct.bin")) { if (num.args[1] < 2 | num.args[1] > 40) { msg <- paste0("Input return(list(check.ok = FALSE, msg = msg)) } } if (x%in%c("iso.bin", "woe.bin")) { if (any(num.args[1:2] < 0) | any(num.args[1:2] > 0.5)) { msg <- paste0("Inputs: ", paste0(paste0(" " have to be between 0 and 0.5") return(list(check.ok = FALSE, msg = msg)) } } if (x%in%c("ndr.bin", "sts.bin")) { if (any(num.args[1:2] < 0) | any(num.args[1:2] > 0.5)) { msg <- paste0("Inputs: ", paste0(paste0(" " have to be between 0 and 0.5") return(list(check.ok = FALSE, msg = msg)) } if (num.args[3] < 0.001 | num.args[3] > 0.2) { msg <- paste0("Input return(list(check.ok = FALSE, msg = msg)) } } if (x%in%c("mdt.bin")) { if (num.args[1] < 2 | num.args[1] > 150) { msg <- paste0("Input return(list(check.ok = FALSE, msg = msg)) } if (any(num.args[2:3] < 0) | any(num.args[2:3] > 0.5)) { msg <- paste0("Inputs: ", paste0(paste0(" " have to be between 0 and 0.5") return(list(check.ok = FALSE, msg = msg)) } } return(list(check.ok = TRUE, msg = "Inputs validated.")) } monobin.fun <- function(x) { switch(x, "cum.bin" = "cum.bin(y = target, x = rf.l, sc = sc, sc.method = args.e[[2]], g = args.e[[3]], y.type = args.e[[4]], force.trend = args.e[[5]])", "iso.bin" = "iso.bin(y = target, x = rf.l, sc = sc, sc.method = args.e[[2]], y.type = args.e[[3]], min.pct.obs = args.e[[4]], min.avg.rate = args.e[[5]], force.trend = args.e[[6]])", "ndr.bin" = "ndr.bin(y = target, x = rf.l, sc = sc, sc.method = args.e[[2]], y.type = args.e[[3]], min.pct.obs = args.e[[4]], min.avg.rate = args.e[[5]], p.val = args.e[[6]], force.trend = args.e[[7]])", "pct.bin" = "pct.bin(y = target, x = rf.l, sc = sc, sc.method = args.e[[2]], g = args.e[[3]], y.type = args.e[[4]], woe.trend = args.e[[5]], force.trend = args.e[[6]])", "sts.bin" = "sts.bin(y = target, x = rf.l, sc = sc, sc.method = args.e[[2]], y.type = args.e[[3]], min.pct.obs = args.e[[4]], min.avg.rate = args.e[[5]], p.val = args.e[[6]], force.trend = args.e[[7]])", "woe.bin" = "woe.bin(y = target, x = rf.l, sc = sc, sc.method = args.e[[2]], y.type = args.e[[3]], min.pct.obs = args.e[[4]], min.avg.rate = args.e[[5]], woe.gap = args.e[[6]], force.trend = args.e[[7]])", "mdt.bin" = "mdt.bin(y = target, x = rf.l, sc = sc, g = args.e[[2]], sc.method = args.e[[3]], y.type = args.e[[4]], min.pct.obs = args.e[[5]], min.avg.rate = args.e[[6]], force.trend = args.e[[7]])") } monobin.run <- function(algo, target.n, rf, sc, args.e, db) { target <- db[, target.n] expr.eval <- monobin.fun(x = algo) rfl <- length(rf) res <- vector("list", rfl) res.trans <- vector("list", rfl) for (i in 1:rfl) { rf.n <- rf[i] incProgress(1 / (rfl - i + 1), detail = paste("Processing risk factor:", rf.n)) rf.l <- db[, rf.n] res.l <- eval(parse(text = expr.eval)) if (length(res.l) == 1) { res.tbl <- res.l[1] res.trans[[i]] <- NULL } else { res.tbl <- res.l[[1]] res.trans[[i]] <- data.frame(x = res.l[[2]]) names(res.trans[[i]]) <- rf.n } res.tbl <- cbind.data.frame(risk.factor = rf.n, res.tbl) res[[i]] <- res.tbl } res <- bind_rows(res) res.trans <- bind_cols(res.trans) if (nrow(res.trans) == 0) { res.trans <- cbind.data.frame(target = target) } else { res.trans <- cbind.data.frame(target = target, res.trans) } names(res.trans)[1] <- target.n return(list(res, res.trans)) }
rearrange_center_by <- function(data, cols, shuffle_sides, what = "max", ...) { stopifnot(length(cols) == 1) col <- cols size <- nrow(data) if (size < 2) { return(data) } data <- data[order(data[[col]], decreasing = what == "min"), , drop = FALSE ] middle_row <- NULL if (size %% 2 == 1) { if (what == "max") { middle_val <- max(data[[col]]) } else if (what == "min") { middle_val <- min(data[[col]]) } middle_row <- data[min(which(data[[col]] == middle_val)), , drop = FALSE] data <- data[-min(which(data[[col]] == middle_val)), , drop = FALSE] size <- size - 1 } extreme_pairs <- create_rearrange_factor_pair_extremes_( size = size ) if (isTRUE(shuffle_sides)) { member_noise <- runif(length(extreme_pairs), -0.1, 0.1) extreme_pairs <- as.numeric(extreme_pairs) + member_noise } new_order <- seq_len(size)[order(extreme_pairs)] tmp_order_var <- create_tmp_var(data, tmp_var = ".tmp_ordering_factor") data[[tmp_order_var]] <- new_order data <- data[order(data[[tmp_order_var]]), ] data[[tmp_order_var]] <- NULL if (!is.null(middle_row)) { data <- insert_row_( data = data, new_row = middle_row, after = size %/% 2 ) } data } order_by_group <- function(data, group_col, shuffle_members, shuffle_groups, ...) { backup_group_col <- isTRUE(shuffle_groups) || isTRUE(shuffle_members) if (isTRUE(backup_group_col)) { tmp_backup_group_col <- create_tmp_var(data, tmp_var = "group_col_backup_") data[[tmp_backup_group_col]] <- data[[group_col]] } if (isTRUE(shuffle_groups)) { data[[group_col]] <- as.numeric( factor(data[[group_col]], levels = sample(unique(data[[group_col]]))) ) } if (isTRUE(shuffle_members)) { indices_noise <- runif(nrow(data), -0.1, 0.1) data[[group_col]] <- as.numeric(data[[group_col]]) + indices_noise } data <- data[order(data[[group_col]]), , drop = FALSE] if (isTRUE(backup_group_col)) { data[[group_col]] <- data[[tmp_backup_group_col]] data[[tmp_backup_group_col]] <- NULL } data } rearrange_position_at <- function(data, cols, position, shuffle_sides, what = "max", ...) { stopifnot(length(cols) == 1) col <- cols size <- nrow(data) even_nrows <- size %% 2 == 0 if (position > nrow(data)) { stop("'position' was higher than the number of rows in 'data'.") } if (size < 2) { return(data) } if (is_between_(position, 0, 1)) { position <- floor(unname( quantile(seq_len(size), probs = position) )) } middle_position <- size / 2 above_midline <- position > middle_position if (position %in% c(size, 1)) { data <- data[order(data[[col]], decreasing = ifelse( what == "max", !isTRUE(above_midline), isTRUE(above_midline) ) ), , drop = FALSE ] return(data) } if (isTRUE(above_midline)) { n_extra_positions <- size - 2 * (size - position) - 1 if (n_extra_positions == 0) { return( centering_rearranger_( data = data, col = col, shuffle_sides = shuffle_sides, what = what ) ) } data <- data[order(data[[col]], decreasing = what != "max"), , drop = FALSE] extra_positions <- seq_len(n_extra_positions) } else { n_extra_positions <- size - 2 * position + 1 data <- data[order(data[[col]], decreasing = what == "max"), , drop = FALSE] extra_positions <- rev((size + 1) - seq_len(n_extra_positions)) } extra_rows <- data[extra_positions, , drop = FALSE] center_rows <- data[-extra_positions, , drop = FALSE] center_rows <- centering_rearranger_( data = center_rows, col = col, shuffle_sides = shuffle_sides, what = what ) if (isTRUE(above_midline)) { data <- dplyr::bind_rows(extra_rows, center_rows) } else { data <- dplyr::bind_rows(center_rows, extra_rows) } data } rearrange_rev_windows <- function(data, window_size, factor_name, cols = NULL, overwrite, ...) { size <- nrow(data) if (size < 2) { return(data) } num_windows <- ceiling(size / window_size) windows <- rep(seq_len(num_windows), each = window_size) rev_indices <- rep(rev(seq_len(window_size)), times = num_windows) new_order <- windows + (rev_indices * (0.5 / window_size)) new_order <- head(new_order, size) data <- add_info_col_( data = data, nm = factor_name, content = head(windows, size), overwrite = overwrite ) data[order(new_order), , drop = FALSE] } rearrange_by_distance <- function(data, grp_id, cols, overwrite, origin, origin_fn, shuffle_ties, decreasing, origin_col_name, distance_col_name, ...) { if (nrow(data) < 2) { return(data) } num_dims <- length(cols) dim_vectors <- as.list(data[, cols, drop = FALSE]) origin <- apply_coordinate_fn_( dim_vectors = dim_vectors, coordinates = origin, fn = origin_fn, num_dims = length(cols), coordinate_name = "origin", fn_name = "origin_fn", dim_var_name = "cols", grp_id = grp_id, allow_len_one = TRUE ) tmp_distances_col <- create_tmp_var(data, ".tmp_distances") data[[tmp_distances_col]] <- calculate_distances_(dim_vectors = dim_vectors, to = origin) if (isTRUE(shuffle_ties)) { data <- data[sample(seq_len(nrow(data))), , drop = FALSE] } else { data <- data %>% dplyr::arrange(!!!rlang::syms(cols)) } data <- data[order(data[[tmp_distances_col]], decreasing = decreasing), , drop = FALSE] distances <- data[[tmp_distances_col]] data[[tmp_distances_col]] <- NULL data <- add_info_col_( data = data, nm = origin_col_name, content = list_coordinates_(origin, cols), overwrite = overwrite ) data <- add_info_col_( data = data, nm = distance_col_name, content = distances, overwrite = overwrite ) data } rearrange_pair_extremes <- function(data, cols, overwrite, unequal_method, num_pairings, balance, order_by_aggregates, shuffle_members, shuffle_pairs, factor_name, ...) { stopifnot(length(cols) == 1) col <- cols if (nrow(data) < 2) { return(data) } equal_nrows <- nrow(data) %% 2 == 0 factor_names <- factor_name if (!is.null(factor_names) && num_pairings > 1){ factor_names <- paste0(factor_name, "_", seq_len(num_pairings)) } tmp_rearrange_vars <- purrr::map(.x = seq_len(num_pairings), .f = ~ { create_tmp_var(data, paste0(".tmp_rearrange_col_", .x)) }) %>% unlist(recursive = TRUE) tmp_aggregate_vars <- character(0) if (num_pairings > 1) { tmp_aggregate_vars <- purrr::map(.x = seq_len(num_pairings - 1), .f = ~ { create_tmp_var(data, paste0(".tmp_aggregate_col_", .x)) }) %>% unlist(recursive = TRUE) } data <- order_and_group_extremes_( data = data, col = col, new_col = tmp_rearrange_vars[[1]], group_fn = create_rearrange_factor_pair_extremes_, unequal_method = unequal_method ) data <- order_by_group( data = data, group_col = tmp_rearrange_vars[[1]], shuffle_members = FALSE, shuffle_groups = FALSE ) if (num_pairings > 1){ pairing_env <- environment() plyr::l_ply(seq_len(num_pairings - 1), function(i) { summ_fn <- get_summ_fn_(balance = balance, i = i) tmp_group_aggr_col <- tmp_aggregate_vars[[i]] tmp_group_scores <- data %>% dplyr::group_by(!!as.name(tmp_rearrange_vars[[i]])) %>% dplyr::summarize(!!tmp_group_aggr_col := summ_fn(!!as.name(col))) %>% dplyr::arrange(!!as.name(tmp_group_aggr_col)) if (num_pairings > 1 && nrow(tmp_group_scores) < 2){ warning( simpleWarning( "Fewer than 2 aggregated scores. Consider reducing `num_pairings`.", call = if (p <- sys.parent(9)) sys.call(p) ) ) } if (!equal_nrows & unequal_method == "first") { tmp_group_scores_sorted <- tmp_group_scores %>% dplyr::filter(dplyr::row_number() == 1) %>% dplyr::bind_rows( tmp_group_scores %>% dplyr::filter(dplyr::row_number() != 1) %>% dplyr::arrange(!!as.name(tmp_group_aggr_col))) } else { tmp_group_scores_sorted <- tmp_group_scores %>% dplyr::arrange(!!as.name(tmp_group_aggr_col)) } tmp_rearrange <- order_and_group_extremes_( data = tmp_group_scores_sorted, col = tmp_group_aggr_col, new_col = tmp_rearrange_vars[[i + 1]], group_fn = create_rearrange_factor_pair_extremes_, unequal_method = unequal_method ) data <- data %>% dplyr::left_join(tmp_rearrange, by = tmp_rearrange_vars[[i]]) data <- data %>% dplyr::arrange( !!as.name(tmp_rearrange_vars[[i + 1]]), !!as.name(tmp_group_aggr_col), !!as.name(col) ) pairing_env[["data"]] <- data }) } if (isTRUE(order_by_aggregates)) { new_order <- c( rev(tmp_rearrange_vars)[[1]], rev(tmp_aggregate_vars), rev(tmp_rearrange_vars)[-1], col ) data <- data %>% dplyr::arrange(!!!rlang::syms(new_order)) } else { data <- data %>% dplyr::arrange(!!!rlang::syms(rev(tmp_rearrange_vars)),!!as.name(col)) } data <- data %>% base_deselect_(cols = tmp_aggregate_vars) data <- shuffle_extreme_groups_( data = data, col = col, tmp_rearrange_vars = tmp_rearrange_vars, shuffle_members = shuffle_members, shuffle_groups = shuffle_pairs ) data <- pick_extreme_group_factors_( data = data, tmp_rearrange_vars = tmp_rearrange_vars, factor_names = factor_names, overwrite = overwrite ) data } order_and_group_extremes_ <- function(data, col, new_col, group_fn, ...){ data <- data[order(data[[col]]), , drop = FALSE] data[[new_col]] <- group_fn( size = nrow(data), ... ) data } get_summ_fn_ <- function(balance, i) { if (length(balance) > 1) { current_balance_target <- balance[[i]] } else { current_balance_target <- balance } if (current_balance_target == "mean") { summ_fn <- sum } else if (current_balance_target == "spread") { summ_fn <- function(v) { sum(abs(diff(v))) } } else if (current_balance_target == "min") { summ_fn <- min } else if (current_balance_target == "max") { summ_fn <- max } summ_fn } shuffle_extreme_groups_ <- function(data, col, tmp_rearrange_vars, shuffle_members, shuffle_groups) { shuffling_group_cols <- rev(tmp_rearrange_vars) cols_to_shuffle <- character(0) if (isTRUE(shuffle_groups)) cols_to_shuffle <- shuffling_group_cols if (isTRUE(shuffle_members)) { shuffling_group_cols <- c(shuffling_group_cols, col) cols_to_shuffle <- c(cols_to_shuffle, col) } if (length(cols_to_shuffle) > 0) { data <- dplyr::ungroup(data) %>% shuffle_hierarchy( group_cols = shuffling_group_cols, cols_to_shuffle = cols_to_shuffle, leaf_has_groups = !shuffle_members ) } data } pick_extreme_group_factors_ <- function(data, tmp_rearrange_vars, factor_names, overwrite){ if (!is.null(factor_names)){ rearrange_factors <- as.list(data[, tmp_rearrange_vars, drop=FALSE]) rearrange_factors <- purrr::map(rearrange_factors, .f = ~{as.factor(.x)}) names(rearrange_factors) <- factor_names data <- base_deselect_(data, cols = tmp_rearrange_vars) %>% add_dimensions_(new_vectors = rearrange_factors, overwrite = overwrite) } else { data <- base_deselect_(data, cols = tmp_rearrange_vars) } data } rearrange_triplet_extremes <- function(data, cols, overwrite, middle_is, unequal_method_1, unequal_method_2, num_groupings, balance, order_by_aggregates, shuffle_members, shuffle_triplets, factor_name, ...) { stopifnot(length(cols) == 1) col <- cols if (nrow(data) < 2) { return(data) } divisible_by_three <- nrow(data) %% 3 == 0 factor_names <- factor_name if (!is.null(factor_names) && num_groupings > 1){ factor_names <- paste0(factor_name, "_", seq_len(num_groupings)) } tmp_rearrange_vars <- purrr::map(.x = seq_len(num_groupings), .f = ~ { create_tmp_var(data, paste0(".tmp_rearrange_col_", .x)) }) %>% unlist(recursive = TRUE) tmp_aggregate_vars <- character(0) if (num_groupings > 1) { tmp_aggregate_vars <- purrr::map(.x = seq_len(num_groupings - 1), .f = ~ { create_tmp_var(data, paste0(".tmp_aggregate_col_", .x)) }) %>% unlist(recursive = TRUE) } data <- order_and_group_extremes_( data = data, col = col, new_col = tmp_rearrange_vars[[1]], group_fn = create_rearrange_factor_triplet_extreme_grouping_, middle_is = middle_is, unequal_method_1 = unequal_method_1, unequal_method_2 = unequal_method_2 ) data <- data %>% dplyr::arrange( !!as.name(tmp_rearrange_vars[[1]]), !!as.name(col) ) if (num_groupings > 1){ grouping_env <- environment() plyr::l_ply(seq_len(num_groupings - 1), function(i) { summ_fn <- get_summ_fn_(balance = balance, i = i) tmp_group_aggr_col <- tmp_aggregate_vars[[i]] tmp_group_scores <- data %>% dplyr::group_by(!!as.name(tmp_rearrange_vars[[i]])) %>% dplyr::summarize(!!tmp_group_aggr_col := summ_fn(!!as.name(col))) %>% dplyr::arrange(!!as.name(tmp_group_aggr_col)) if (num_groupings > 1 && nrow(tmp_group_scores) < 3){ warning( simpleWarning( "Fewer than 3 aggregated scores. Consider reducing `num_groupings`.", call = if (p <- sys.parent(9)) sys.call(p) ) ) } tmp_rearrange <- order_and_group_extremes_( data = tmp_group_scores, col = tmp_group_aggr_col, new_col = tmp_rearrange_vars[[i + 1]], group_fn = create_rearrange_factor_triplet_extreme_grouping_, middle_is = middle_is, unequal_method_1 = unequal_method_1, unequal_method_2 = unequal_method_2 ) data <- data %>% dplyr::left_join(tmp_rearrange, by = tmp_rearrange_vars[[i]]) data <- data %>% dplyr::arrange( !!as.name(tmp_rearrange_vars[[i + 1]]), !!as.name(tmp_group_aggr_col), !!as.name(col) ) grouping_env[["data"]] <- data }) } if (isTRUE(order_by_aggregates)) { new_order <- c( rev(tmp_rearrange_vars)[[1]], rev(tmp_aggregate_vars), rev(tmp_rearrange_vars)[-1], col ) data <- data %>% dplyr::arrange(!!!rlang::syms(new_order)) } else { data <- data %>% dplyr::arrange(!!!rlang::syms(rev(tmp_rearrange_vars)), !!as.name(col)) } data <- data %>% base_deselect_(cols = tmp_aggregate_vars) data <- shuffle_extreme_groups_( data = data, col = col, tmp_rearrange_vars = tmp_rearrange_vars, shuffle_members = shuffle_members, shuffle_groups = shuffle_triplets ) data <- pick_extreme_group_factors_( data = data, tmp_rearrange_vars = tmp_rearrange_vars, factor_names = factor_names, overwrite = overwrite ) data }
rank.test <- function(x, alternative="two.sided") { dname <- deparse(substitute(x)) stopifnot(is.numeric(x)) x<-na.omit(x) n <- length(x) p <- 0 for (i in 1:(n-1)){ t <- x[(i+1):n] p <- p+length(t[t>x[i]]) } mu <- n*(n-1)/4 vr <- n*(n-1)*(2*n+5)/72 test <- (p-mu)/sqrt(vr) pv0 <- pnorm(test) if (alternative=="two.sided"){ pv <- 2*min(pv0,1-pv0) alternative<-"trend" } if (alternative=="left.sided"){ pv <- pv0 alternative<-"downnward trend" } if (alternative=="right.sided"){ pv <- 1-pv0 alternative<-"upward trend" } rval <- list(statistic = c(statistic=test), P=p, mu=mu, var=vr, p.value = pv, method = "Mann-Kendall Rank Test", data.name = dname, parameter=c(n=n), alternative=alternative) class(rval) <- "htest" return(rval) }
context("occ_download_queue") Sys.setenv(RGBIF_BASE_URL = "https://api.gbif-uat.org/v1") keys <- c("GBIF_USER", "GBIF_PWD", "GBIF_EMAIL") lkeys <- tolower(keys) env_vars <- as.list(Sys.getenv(keys)) r_opts <- stats::setNames(lapply(lkeys, getOption), lkeys) test_that("occ_download_queue: real request works", { skip_on_cran() skip_on_ci() vcr::use_cassette("occ_download_queue", { tt <- occ_download_queue( occ_download(pred("country", "NZ"), pred("year", 1993), pred("month", 1)), occ_download(pred("catalogNumber", "Bird.27847588"), pred("year", 1971), pred("month", 4)), occ_download(pred("taxonKey", 2435240), pred("year", 1974), pred("month", 2)) ) }, match_requests_on = c("method", "uri", "body")) expect_is(tt, "list") for (i in tt) expect_is(i, "occ_download") for (i in tt) expect_is(unclass(i), "character") for (i in tt) expect_equal(attr(i, "user"), "sckott") for (i in tt) expect_equal(attr(i, "email"), "[email protected]") for (i in tt) expect_equal(occ_download_meta(i)$status, "SUCCEEDED") }) test_that("occ_download_queue fails well", { skip_on_cran() skip_on_ci() expect_error(occ_download_queue(), "no requests submitted") expect_error( occ_download_queue(occ_download(pred("country", "NZ"), pred("year", 1999), pred("month", 3)), status_ping = 3), "is not TRUE" ) options(gbif_user = NULL, gbif_pwd = NULL, gbif_email = NULL) Sys.unsetenv("GBIF_USER"); Sys.unsetenv("GBIF_PWD"); Sys.unsetenv("GBIF_EMAIL") expect_error( suppressMessages(occ_download_queue( occ_download(pred("country", "NZ"), pred("year", 1999), pred("month", 3)) )), "supply a username" ) Sys.setenv(GBIF_USER = "foobar") expect_error( suppressMessages(occ_download_queue( occ_download(pred("country", "NZ"), pred("year", 1999), pred("month", 3)) )), "supply a password" ) Sys.setenv(GBIF_PWD = "helloworld") expect_error( suppressMessages(occ_download_queue( occ_download(pred("country", "NZ"), pred("year", 1999), pred("month", 3)) )), "supply an email" ) }) test_that("occ_download_queue fails well", { skip_on_cran() expect_error(occ_download_queue(status_ping = "foobar"), "status_ping must be of class") }) Sys.unsetenv("RGBIF_BASE_URL") invisible(do.call(Sys.setenv, env_vars)) invisible(do.call(options, r_opts))
convexLogisticPCA <- function(x, k = 2, m = 4, quiet = TRUE, partial_decomp = FALSE, max_iters = 1000, conv_criteria = 1e-6, random_start = FALSE, start_H, mu, main_effects = TRUE, ss_factor = 4, weights, M) { if (!missing(M)) { m = M warning("M is depricated. Use m instead. ", "Using m = ", m) } if (partial_decomp) { if (!requireNamespace("rARPACK", quietly = TRUE)) { message("rARPACK must be installed to use partial_decomp") partial_decomp = FALSE } } x = as.matrix(x) n = nrow(x) d = ncol(x) q = 2 * x - 1 q[is.na(q)] <- 0 eta = q * abs(m) if (k >= d & partial_decomp) { message("k >= dimension. Setting partial_decomp = FALSE") partial_decomp = FALSE k = d } if (missing(weights) || length(weights) == 1) { weights = 1.0 sum_weights = sum(!is.na(x)) } else { if (!all(dim(weights) == dim(x))) { stop("x and weights are not the same dimension") } weights[is.na(x)] <- 0 if (any(is.na(weights))) { stop("Can't have NA in weights") } if (any(weights < 0)) { stop("weights must be non-negative") } sum_weights = sum(weights) } if (main_effects) { if (missing(mu)) { if (length(weights) == 1) { x_bar = colMeans(x, na.rm = TRUE) } else { x_bar = colSums(x * weights, na.rm = TRUE) / colSums(weights, na.rm = TRUE) } if (any(x_bar == 0 | x_bar == 1)) { stop("Some column(s) all 0 or 1. Remove and try again.") } mu = log(x_bar) - log(1 - x_bar) } } else { mu = rep(0, d) } if (!missing(start_H)) { HU = project.Fantope(start_H, k) H = HU$H } else if (random_start) { U = matrix(rnorm(d * d), d, d) U = qr.Q(qr(U)) HU = project.Fantope(U %*% t(U), k) H = HU$H } else { if (partial_decomp) { udv = rARPACK::svds(scale(q, center = main_effects, scale = F), k = k) } else { udv = svd(scale(q, center = main_effects, scale = F), nu = k, nv = k) } HU = project.Fantope(udv$v[, 1:k] %*% t(udv$v[, 1:k]), k) H = HU$H } mu_mat = outer(rep(1, n), mu) eta_centered = scale(eta, mu, FALSE) eta_centered[q == 0] <- 0 L = sum(eta_centered^2) * max(weights) / 2 x[q == 0] <- 0 etatX = t(eta_centered) %*% (weights * x) theta = mu_mat + eta_centered %*% H loglike = log_like_Bernoulli_weighted(q = q, theta = theta, weights) min_loss = -loglike / sum_weights best_HU = HU best_loglike = loglike if (!quiet) { cat(0," ", min_loss, "\n") } loss_trace <- proj_loss_trace <- numeric(max_iters + 1) loss_trace[1] <- proj_loss_trace[1] <- min_loss H_lag = H for (i in 1:max_iters) { y = H + (i - 2) / (i + 1) * (H - H_lag) H_lag = H step = ss_factor / L Phat = inv.logit.mat(mu_mat + eta_centered %*% y) Phat[q == 0] <- 0 etatP = t(eta_centered) %*% (Phat * weights) deriv = etatX - etatP deriv = deriv + t(deriv) - diag(diag(deriv)) H = y + step * deriv HU = project.Fantope(H, k) H = HU$H theta = mu_mat + eta_centered %*% H loglike = log_like_Bernoulli_weighted(q = q, theta = theta, weights) loss_trace[i + 1] = -loglike / sum_weights proj_theta = mu_mat + eta_centered %*% tcrossprod(HU$U) proj_loglike = log_like_Bernoulli_weighted(q = q, theta = proj_theta, weights) proj_loss_trace[i + 1] = -proj_loglike / sum_weights if (!quiet) { cat(i," ",loss_trace[i + 1]," ",proj_loss_trace[i + 1],"\n") } if (loss_trace[i + 1] < min_loss) { min_loss = loss_trace[i + 1] best_HU = HU best_loglike = loglike } if (abs(loss_trace[i + 1]-loss_trace[i]) < conv_criteria | min_loss == 0) { break } } null_loglike = log_like_Bernoulli_weighted(q = q, theta = mu_mat, weights) object = list(mu = mu, H = best_HU$H, U = best_HU$U, PCs = eta_centered %*% best_HU$U, m = m, M = m, iters = i, loss_trace = loss_trace[1:(i + 1)], proj_loss_trace = proj_loss_trace[1:(i + 1)], prop_deviance_expl = 1 - best_loglike / null_loglike) class(object) <- "clpca" return(object) } project.Fantope <- function(x, k) { eig = eigen(x, symmetric = TRUE) vals = eig$values lower = vals[length(vals)] - k / length(vals) upper = max(vals) while(TRUE) { theta = (lower + upper) / 2 sum.eig.vals = sum(pmin(pmax(vals - theta, 0), 1)) if (abs(sum.eig.vals - k) < 1e-10) { break } else if (sum.eig.vals > k) { lower = theta } else { upper = theta } } vals = pmin(pmax(vals - theta, 0), 1) return(list(H = eig$vectors %*% diag(vals) %*% t(eig$vectors), U = matrix(eig$vectors[, 1:ceiling(k)], nrow(x), ceiling(k)))) } predict.clpca <- function(object, newdata, type = c("PCs", "link", "response"), ...) { type = match.arg(type) if (type == "PCs") { if (missing(newdata)) { PCs = object$PCs } else { eta = ((as.matrix(newdata) * 2) - 1) * object$m eta_centered = scale(eta, center = object$mu, scale = FALSE) eta_centered[is.na(newdata)] <- 0 PCs = eta_centered %*% object$U } return(PCs) } else { eta = ((as.matrix(newdata) * 2) - 1) * object$m eta_centered = scale(eta, center = object$mu, scale = FALSE) eta_centered[is.na(newdata)] <- 0 theta = outer(rep(1, nrow(eta)), object$mu) + eta_centered %*% object$H if (type == "link") { return(theta) } else { return(inv.logit.mat(theta)) } } } plot.clpca <- function(x, type = c("trace", "loadings", "scores"), ...) { type = match.arg(type) if (type == "trace") { df = data.frame(Iteration = 0:x$iters, NegativeLogLikelihood = x$loss_trace) p <- ggplot2::ggplot(df, ggplot2::aes_string("Iteration", "NegativeLogLikelihood")) + ggplot2::geom_line() } else if (type == "loadings") { df = data.frame(x$U) colnames(df) <- paste0("PC", 1:ncol(df)) if (ncol(df) == 1) { df$PC2 = 0 p <- ggplot2::ggplot(df, ggplot2::aes_string("PC1", "PC2")) + ggplot2::geom_point() + ggplot2::labs(y = NULL) } else { p <- ggplot2::ggplot(df, ggplot2::aes_string("PC1", "PC2")) + ggplot2::geom_point() } } else if (type == "scores") { df = data.frame(x$PCs) colnames(df) <- paste0("PC", 1:ncol(df)) if (ncol(df) == 1) { df$PC2 = 0 p <- ggplot2::ggplot(df, ggplot2::aes_string("PC1", "PC2")) + ggplot2::geom_point() + ggplot2::labs(y = NULL) } else { p <- ggplot2::ggplot(df, ggplot2::aes_string("PC1", "PC2")) + ggplot2::geom_point() } } return(p) } print.clpca <- function(x, ...) { cat(nrow(x$PCs), "rows and ") cat(nrow(x$H), "columns\n") cat("Rank", ncol(x$U), "Fantope solution with m =", x$m, "\n") cat("\n") cat(round(x$prop_deviance_expl * 100, 1), "% of deviance explained\n", sep = "") cat(x$iters, "iterations to converge\n") invisible(x) } cv.clpca <- function(x, ks, ms = seq(2, 10, by = 2), folds = 5, quiet = TRUE, Ms, ...) { if (!missing(Ms)) { ms = Ms warning("Ms is depricated. Use ms instead.\n", "Using ms in ", paste(ms, collapse = ",")) } q = 2 * as.matrix(x) - 1 q[is.na(q)] <- 0 if (length(folds) > 1) { if (length(unique(folds)) <= 1) { stop("If inputing CV split, must be more than one level") } if (length(folds) != nrow(x)) { stop("if folds is a vector, it should be of same length as nrow(x)") } cv = folds } else { cv = sample(1:folds, nrow(q), replace = TRUE) } log_likes = matrix(0, length(ks), length(ms), dimnames = list(k = ks, m = ms)) for (k in ks) { for (m in ms) { if (!quiet) { cat("k =", k, "m =", m, "") } for (c in unique(cv)) { if (!quiet) { cat(".") } clpca = convexLogisticPCA(x[c != cv, ], k = k, m = m, ...) pred_theta = predict(clpca, newdat = x[c == cv, ], type = "link") log_likes[k == ks, m == ms] = log_likes[k == ks, m == ms] + log_like_Bernoulli(q = q[c == cv, ], theta = pred_theta) } if (!quiet) { cat("", -log_likes[k == ks, m == ms], "\n") } } } class(log_likes) <- c("matrix", "cv.lpca") which_min = which(log_likes == max(log_likes), arr.ind = TRUE) if (!quiet) { cat("Best: k =", ks[which_min[1]], "m =", ms[which_min[2]], "\n") } return(-log_likes) }
ZRA <- function(data,FP = 10, SL = c(0.80,0.95), ...) { startvalue <- end(data)[1]+1 f <- frequency(data) d <- data if (is.ts(d)== TRUE) { if (is.matrix(d)==TRUE) { result <- NULL stop("Only 1 Time Series can analyzed at once") } else { prognose <- forecast(d, h = FP, level=SL, ...) result <- list() result$series <- data result$SL <- SL result$FP <- FP if (length(SL)==1) { up1 <- ts(prognose$upper[,1],start=startvalue,frequency = f) low1 <- ts(prognose$lower[,1],start=startvalue,frequency = f) fit1 <- (up1 + low1)/2 result$up1 <- up1 result$low1 <- low1 result$fit1 <- fit1 result$piv1 <- cbind(fit1,up1,low1) } if (length(SL)==2) { up1 <- ts(prognose$upper[,1],start=startvalue,frequency = f) low1 <- ts(prognose$lower[,1],start=startvalue,frequency = f) fit1 <- (up1 + low1)/2 up2 <- ts(prognose$upper[,2],start=startvalue,frequency = f) low2 <- ts(prognose$lower[,2],start=startvalue,frequency = f) fit2 <- (up2 + low2)/2 result$up1 <- up1 result$low1 <- low1 result$fit1 <- fit1 result$piv1 <- cbind(fit1,up1,low1) result$up2 <- up2 result$low2 <- low2 result$fit2 <- fit2 result$piv2 <- cbind(fit2,up2,low2) } if (length(SL)!=1 & length(SL)!=2 ) { stop("Only 2 Significance levels can be plotted at once.") } } } else { result <- NULL stop("Data have to be a Time Series Obejct, with the Class ts.") } class(result) <- "ZRA" return(result) } print.ZRA <- function(x, ...){ sl <- as.character(x$SL) if (length(x$SL)==1) { colnames(x$piv1) <- c(paste("Fit",sl,sep = "-"),paste("Up",sl,sep = "-"),paste("Low",sl,sep = "-")) cat("Time Series: \n") print(x$series) cat("\n Forecast: \n") print(round(x$piv1,3)) } if (length(x$SL)==2) { tabelle <- cbind(x$piv1,x$piv2) colnames(tabelle) <- c(paste("Fit",sl[1],sep = "-"),paste("Up",sl[1],sep = "-"),paste("Low",sl[1],sep = "-"),paste("Fit",sl[2],sep = "-"),paste("Up",sl[2],sep = "-"),paste("Low",sl[2],sep = "-")) cat("Time Series: \n") print(x$series) cat("\n Forecast: \n") print(round(tabelle,3)) } if (length(x$SL)!=1 & length(x$SL)!=2 ) { stop("Only 2 Significance levels can be plotted at once.") } } plot.ZRA <- function(x, zero =TRUE, ...) { if (length(x$SL)==1 || length(x$SL)==2) { result <- ZRAplot(x, ...) return(result) } if (length(x$SL)!=1 & length(x$SL)!=2 ) { stop("Only 2 Significance levels can be plotted at once." ) } } ZRAplot <- function(x,zero=TRUE, ...) { sl <- as.character(x$SL) h <- as.character(x$FP) if (length(x$SL)==1) { plotreihe1 <- cbind(x$series, x$piv1, x$up1, x$low1) plot1 <- dygraph(plotreihe1) %>% dySeries("x$series",label = "Time Series",color="blue",fillGraph = TRUE) %>% dyLimit(limit=0) %>% dySeries("x$up1",label = "Upper Interval limit",color="chocolate",strokePattern = "dotted") %>% dySeries("x$low1",label = "Lower Interval limit",color="chocolate",strokePattern = "dotted") %>% dySeries(c("x$piv1.up1","x$piv1.fit1","x$piv1.low1"),label="Point Estimator", color="red") %>% dyOptions(includeZero = TRUE,fillAlpha =0.1 ) %>% dyRangeSelector() print(paste("Significance level:",sl)) print(paste("Prediction interval:",h,"Periods")) return(plot1) } if (length(x$SL)==2) { plotreihe2 <- cbind(x$series, x$piv1, x$up1, x$low1, x$piv2, x$up2, x$low2) plot2 <- dygraph(plotreihe2) %>% dySeries("x$series",label = "Time Series",color="blue",fillGraph = TRUE) %>% dyLimit(limit=0) %>% dySeries("x$up1",label = paste("Up",sl[1]),color="chocolate",strokePattern = "dotted") %>% dySeries("x$low1",label = paste("Low",sl[1]),color="chocolate",strokePattern = "dotted") %>% dySeries("x$up2",label = paste("Up",sl[2]),color="darkseagreen",strokePattern = "dotted") %>% dySeries("x$low2",label = paste("Low",sl[2]),color="darkseagreen",strokePattern = "dotted") %>% dySeries(c("x$piv1.up1","x$piv1.fit1","x$piv1.low1"),label=paste("Point Estimator",sl[1]), color="red") %>% dySeries(c("x$piv2.up2","x$piv2.fit2","x$piv2.low2"),label=paste("Point Estimator",sl[2]), color="green") %>% dyOptions(includeZero = zero,fillAlpha =0.1 ) %>% dyRangeSelector() print(paste("Significance levels:",sl[1],"(red),",sl[2],"(green)")) print(paste("Prediction interval:",h,"Periods")) return(plot2) } }
cat("\014") rm(list = ls()) setwd("~/git/of_dollars_and_data") source(file.path(paste0(getwd(),"/header.R"))) library(ggplot2) library(scales) library(grid) library(gridExtra) library(gtable) library(RColorBrewer) library(stringr) library(ggrepel) library(lubridate) library(ggjoy) library(tidyr) library(dplyr) n_years_working <- 40 income <- 50000 annual_return <- 0.05 create_value_path <- function(savings_rate, annual_return, name){ results_df <- data.frame(matrix(NA, nrow = n_years_working, ncol = 0)) for (i in 1:n_years_working){ results_df[i, "rate_label"] <- paste0(savings_rate*100, "%") results_df[i, "rate"] <- savings_rate results_df[i , "year"] <- i results_df[i, "return"] <- annual_return if (i==1){ results_df[i, "value"] <- income * savings_rate } else { results_df[i, "value"] <- (results_df[(i -1), "value"] * (1+annual_return)) + income*savings_rate } } assign(name, results_df, envir = .GlobalEnv) print(results_df[n_years_working, "value"]) } create_value_path(0.05, annual_return, "sr_5_5") create_value_path(0.1, annual_return, "sr_10_5") create_value_path(0.15, annual_return, "sr_15_5") results_df <- bind_rows(sr_5_5, sr_10_5, sr_15_5) results_df$rate_label <- factor(results_df$rate_label, levels = unique(results_df$rate_label[order(results_df$rate)])) years_to_plot <- c(seq(2, n_years_working, 2), n_years_working, n_years_working) for (i in 1:length(years_to_plot)){ if (i < 10){ i_string <- paste0("0", i) } else{ i_string <- i } to_plot <- filter(results_df, year == years_to_plot[i]) file_path = paste0(exportdir, "0045_the_constant_reminder/saving-plot-", i_string, ".jpeg") plot <- ggplot(data = to_plot, aes(x = rate_label, y = value, fill = rate_label)) + geom_bar(stat="identity") + scale_fill_discrete(guide = FALSE) + ggtitle(paste0("Total Wealth by Savings Rate\nAfter ", years_to_plot[i], " Years")) + scale_y_continuous(label = dollar, limits = c(0, 1000000)) + of_dollars_and_data_theme + labs(x = "Savings Rate" , y = "Total Wealth") source_string <- paste0("Source: Simulated data (OfDollarsAndData.com)") note_string <- paste0("Note: Assumes an annual income of $", formatC(as.numeric(income), format="f", digits=0, big.mark=","), " with a ", annual_return*100,"% annual return.") my_gtable <- ggplot_gtable(ggplot_build(plot)) source_grob <- textGrob(source_string, x = (unit(0.5, "strwidth", source_string) + unit(0.2, "inches")), y = unit(0.1, "inches"), gp =gpar(fontfamily = "my_font", fontsize = 8)) note_grob <- textGrob(note_string, x = (unit(0.5, "strwidth", note_string) + unit(0.2, "inches")), y = unit(0.15, "inches"), gp =gpar(fontfamily = "my_font", fontsize = 8)) my_gtable <- arrangeGrob(my_gtable, bottom = source_grob) my_gtable <- arrangeGrob(my_gtable, bottom = note_grob) ggsave(file_path, my_gtable, width = 15, height = 12, units = "cm") }
keywords <- function(topic) { file <- file.path(R.home("doc"), "KEYWORDS") if (missing(topic)) { file.show(file) } else { kw <- scan(file = file, what = character(), sep = "\n", quiet = TRUE) kw <- grep("&", kw, value = TRUE) kw <- gsub("&[^&]*$", "", kw) kw <- gsub("&+", " ", kw) kw <- na.omit(trimws(kw)) ischar <- tryCatch(is.character(topic) && length(topic) == 1L, error = identity) if (inherits(ischar, "error")) { ischar <- FALSE } if (!ischar) { topic <- deparse(substitute(topic)) } item <- paste("^", topic, "$", sep = "") topics <- function(k) { matches <- help.search(keyword = k)$matches matches[, match("topic", tolower(colnames(matches)))] } matches <- lapply(kw, topics) names(matches) <- kw tmp <- unlist(lapply(matches, function(m) grep(item, m, value = TRUE))) names(tmp) } }
library(highcharter) hc <- highchart() %>% hc_plotOptions( series = list( boderWidth = 0, dataLabels = list(enabled = TRUE) ) ) %>% hc_chart(type = "column") %>% hc_xAxis(type = "category") %>% hc_add_series( name = "Things", data = list( list(name = "Animals", y = 5, drilldown = "animals") ) ) hc hc <- hc %>% hc_drilldown( series = list( list( id = "animals", name = "Animals", data = list( list(name = "Cats", y = 4, drilldown = "cats"), list(name = "Dogs", y = 1) ) ), list( id = "cats", data = list( list(name = "purr", y = 1), list(name = "miau", y = 2) ) ) ) ) hc jsonlite::toJSON(hc$x$hc_opts$series, pretty = TRUE, auto_unbox = TRUE) jsonlite::toJSON(hc$x$hc_opts$drilldown, pretty = TRUE, auto_unbox = TRUE)
data("gam_example") set.seed(42L) test_that("rmwcs solver can be constructed with specific parameters", { solver <- rmwcs_solver() expect_equal(solver$separation, "strong") timelimit(solver) <- 20 expect_equal(solver$timelimit, 20) }) test_that("one vertex best solution is returned", { solver <- rmwcs_solver() g <- igraph::make_graph(c("A", "B"), directed = FALSE) V(g)$weight <- c(5, -2) solution <- solve_mwcsp(solver, g) expect_equal(solution$weight, 5) }) test_that("rmwcs solver works on specific test", { solver <- rmwcs_solver() g <- make_ring(5) %>% set.vertex.attribute("weight", value = 2:-2) s <- solve_mwcsp(solver, g) expect_equal(s$weight, 3) expect_true(s$solved_to_optimality) }) test_that("rmwcs solver doesn't crash on simple graphs", { solver <- rmwcs_solver() size <- 10 card <- 3 test_graph <- function(make) { scores <- runif(size) - 0.5; g <- make(size) %>% set.vertex.attribute("weight", value = scores) solve_mwcsp(solver, g) solution <- solve_mwcsp(solver, g, max_cardinality = card) expect_lte(length(V(solution$graph)), 3) g <- set.vertex.attribute(g, name = "budget_cost", value = runif(size)) V(g)$weight <- 1 solution <- solve_mwcsp(solver, g, budget = card) expect_lte(sum(V(solution$graph)$budget_cost), card) } test_graph(make_ring) test_graph(function(x) make_star(x, mode = "undirected")) test_graph(make_full_graph) }) test_that("rmwcs solver builds connected solutions on a GAM instance", { solver <- rmwcs_solver() sol <- solve_mwcsp(solver, gam_example) expect_true(is.connected(sol$graph)) })
"bmi_insulin"
isSymmetric <- function(object, ...) UseMethod("isSymmetric") isSymmetric.matrix <- function(object, tol = 100*.Machine$double.eps, ...) { if(!is.matrix(object)) return(FALSE) d <- dim(object) if(d[1L] != d[2L]) return(FALSE) test <- if(is.complex(object)) all.equal.numeric(object, Conj(t(object)), tolerance = tol, ...) else all.equal(object, t(object), tolerance = tol, ...) isTRUE(test) } eigen <- function(x, symmetric, only.values = FALSE, EISPACK = FALSE) { x <- unname(as.matrix(x)) n <- nrow(x) if (!n) stop("0 x 0 matrix") if (n != ncol(x)) stop("non-square matrix in 'eigen'") n <- as.integer(n) if(is.na(n)) stop("invalid nrow(x)") complex.x <- is.complex(x) if (!all(is.finite(x))) stop("infinite or missing values in 'x'") if(missing(symmetric)) symmetric <- isSymmetric.matrix(x) if (symmetric) { z <- if(!complex.x) .Internal(La_rs(x, only.values)) else .Internal(La_rs_cmplx(x, only.values)) ord <- rev(seq_along(z$values)) } else { z <- if(!complex.x) .Internal(La_rg(x, only.values)) else .Internal(La_rg_cmplx(x, only.values)) ord <- sort.list(Mod(z$values), decreasing = TRUE) } return(list(values = z$values[ord], vectors = if (!only.values) z$vectors[, ord, drop = FALSE])) }
invest <- function(object, ...) { UseMethod("invest") } invest.lm <- function(object, y0, interval = c("inversion", "Wald", "percentile", "none"), level = 0.95, mean.response = FALSE, x0.name, newdata, data, boot.type = c("parametric", "nonparametric"), nsim = 999, seed = NULL, progress = FALSE, lower, upper, extendInt = "no", tol = .Machine$double.eps^0.25, maxiter = 1000, adjust = c("none", "Bonferroni"), k, ...) { .data <- if (!missing(data)) data else eval(object$call$data, envir = parent.frame()) yname <- all.vars(formula(object)[[2]]) multi <- FALSE xnames <- intersect(all.vars(formula(object)[[3]]), colnames(.data)) if (length(xnames) != 1) { multi <- TRUE if (missing(x0.name)) { stop("'x0.name' is missing, please select a valid predictor variable") } xnames <- xnames[xnames != x0.name] if (missing(newdata)) { stop("'newdata' must be supplied when multiple predictor variables exist!") } if (!is.data.frame(newdata)) { stop("'newdata' must be a data frame") } if (nrow(newdata) != 1) { stop("'newdata' must have a single row") } if (ncol(newdata) != length(xnames) || !all(xnames %in% names(newdata))) { stop(paste0("'newdata' must contain a column for each predictor variable", " used by ", deparse(substitute(object)), " (except ", x0.name, ")")) } } else { x0.name <- xnames } if (missing(lower)) lower <- min(.data[, x0.name]) if (missing(upper)) upper <- max(.data[, x0.name]) m <- length(y0) if(mean.response && m > 1) stop("Only one mean response value allowed.") eta <- mean(y0) n <- length(resid(object)) p <- length(coef(object)) df1 <- n - p df2 <- m - 1 var1 <- Sigma(object)^2 var2 <- if (m == 1) 0 else var(y0) var_pooled <- (df1*var1 + df2*var2) / (df1 + df2) rat <- var_pooled / var1 x0_est <- try(uniroot(function(x) { nd <- if (multi) { cbind(newdata, makeData(x, x0.name)) } else { makeData(x, x0.name) } predict(object, newdata = nd) - eta }, interval = c(lower, upper), extendInt = extendInt, tol = tol, maxiter = maxiter)$root, silent = TRUE) if (inherits(x0_est, "try-error")) { stop(paste("Point estimate not found in the search interval (", lower, ", ", upper, "). ", "Try tweaking the values of lower and upper. ", "Use plotFit for guidance.", sep = ""), call. = FALSE) } interval <- match.arg(interval) if (interval == "none") { return(setNames(x0_est, x0.name)) } if (interval == "percentile") { stopifnot((nsim <- as.integer(nsim[1])) > 0) if (progress) { pb <- txtProgressBar(min = 0, max = nsim, style = 3) } if (!exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) runif(1) if (is.null(seed)) RNGstate <- get(".Random.seed", envir = .GlobalEnv) else { R.seed <- get(".Random.seed", envir = .GlobalEnv) set.seed(seed) RNGstate <- structure(seed, kind = as.list(RNGkind())) on.exit(assign(".Random.seed", R.seed, envir = .GlobalEnv)) } ftd <- fitted(object) res <- residuals(object) boot.type <- match.arg(boot.type) if (boot.type == "parametric") { ss <- simulate(object, nsim = nsim) } else { ss <- replicate(nsim, ftd + sample(res, replace = TRUE), simplify = FALSE) } x0Fun <- function(i) { boot_data <- eval(object$call$data) boot_data[, yname] <- ss[[i]] boot_object <- tryCatch(update(object, data = boot_data), error = function(e) NULL) if (is.null(boot_object)) { ret <- NA } else { if (mean.response) { y0_star <- y0 } else { if (boot.type == "parametric") { y0_star <- y0 + rnorm(length(y0), sd = Sigma(object)) } else { y0_star <- y0 + sample(res, size = length(y0), replace = TRUE) } } ret <- tryCatch(uniroot(function(x) { predict(boot_object, newdata = makeData(x, x0.name)) - mean(y0_star) }, interval = c(lower, upper), extendInt = extendInt, tol = tol, maxiter = maxiter)$root, error = function(e) NA) } if (progress) { setTxtProgressBar(pb, i) } ret } x0_star <- sapply(seq_len(nsim), x0Fun) if (AnyNA(x0_star)) { num_fail <- sum(is.na(x0_star)) warning("some bootstrap runs failed (", num_fail, "/", nsim, ")") x0_star <- na.omit(x0_star) attributes(x0_star) <- NULL } else { num_fail <- NULL } perc <- unname(quantile(x0_star, probs = c((1-level)/2, (1+level)/2))) res <- list("estimate" = x0_est, "lower" = perc[1], "upper" = perc[2], "se" = sd(x0_star), "bias" = mean(x0_star) - x0_est, "bootreps" = x0_star, "nsim" = nsim, "level" = level, "interval" = interval) class(res) = c("invest", "bootCal") attr(res, "bootFail") <- num_fail return(res) } adjust <- match.arg(adjust) crit <- if (adjust == "Bonferroni" && m == 1) { qt((level + 2*k - 1) / (2*k), n+m-p-1) } else { qt((level+1) / 2, n+m-p-1) } if (interval == "inversion") { inversionFun <- function(x) { nd <- if (multi) { cbind(newdata, makeData(x, x0.name)) } else { makeData(x, x0.name) } pred <- predict(object, newdata = nd, se.fit = TRUE) denom <- if (mean.response) pred$se.fit^2 else var_pooled/m + rat*pred$se.fit^2 (eta - pred$fit)^2/denom - crit^2 } lwr <- try(uniroot(inversionFun, interval = c(lower, x0_est), extendInt = extendInt, tol = tol, maxiter = maxiter)$root, silent = TRUE) upr <- try(uniroot(inversionFun, interval = c(x0_est, upper), extendInt = extendInt, tol = tol, maxiter = maxiter)$root, silent = TRUE) if (inherits(lwr, "try-error")) { stop(paste("Lower confidence limit not found in the search interval (", lower, ", ", upper, "). ", "Try tweaking the values of lower and upper. ", "Use plotFit for guidance.", sep = ""), call. = FALSE) } if (inherits(upr, "try-error")) { stop(paste("Upper confidence limit not found in the search interval (", lower, ", ", upper, "). ", "Try tweaking the values of lower and upper. ", "Use plotFit for guidance.", sep = ""), call. = FALSE) } res <- list("estimate" = x0_est, "lower" = lwr, "upper" = upr, "interval" = interval) } if (interval == "Wald") { object_copy <- object dmFun <- function(params) { if (mean.response) { object_copy$coefficients <- params z <- eta } else { object_copy$coefficients <- params[-length(params)] z <- params[length(params)] } uniroot(function(x) { nd <- if (multi) { cbind(newdata, makeData(x, x0.name)) } else { makeData(x, x0.name) } predict(object_copy, newdata = nd) - z }, interval = c(lower, upper), extendInt = extendInt, tol = tol, maxiter = maxiter)$root } if (mean.response) { params <- coef(object) covmat <- vcov(object) } else { params <- c(coef(object), eta) covmat <- diag(p + 1) covmat[p + 1, p + 1] <- var_pooled / m covmat[1:p, 1:p] <- vcov(object) } gv <- attr(numericDeriv(quote(dmFun(params)), "params"), "gradient") se <- as.numeric(sqrt(gv %*% covmat %*% t(gv))) res <- list("estimate" = x0_est, "lower" = x0_est - crit * se, "upper" = x0_est + crit * se, "se" = se, "interval" = interval) } class(res) <- "invest" res } invest.glm <- function(object, y0, interval = c("inversion", "Wald", "percentile", "none"), level = 0.95, lower, upper, x0.name, newdata, data, tol = .Machine$double.eps^0.25, maxiter = 1000, ...) { .data <- if (!missing(data)) data else eval(object$call$data, envir = parent.frame()) if (missing(lower)) lower <- min(.data[, x0.name]) if (missing(upper)) upper <- max(.data[, x0.name]) eta <- family(object)$linkfun(y0) multi <- FALSE xnames <- intersect(all.vars(formula(object)[[3]]), colnames(.data)) if (length(xnames) != 1) { multi <- TRUE if (missing(x0.name)) { stop("'x0.name' is missing, please select a valid predictor variable") } xnames <- xnames[xnames != x0.name] if (missing(newdata)) { stop("'newdata' must be supplied when multiple predictor variables exist!") } if (!is.data.frame(newdata)) { stop("'newdata' must be a data frame") } if (nrow(newdata) != 1) { stop("'newdata' must have a single row") } if (ncol(newdata) != length(xnames) || !all(xnames %in% names(newdata))) { stop(paste0("'newdata' must contain a column for each predictor variable", " used by ", deparse(substitute(object)), " (except ", x0.name, ")")) } } else { x0.name <- xnames } x0_est <- try(uniroot(function(x) { nd <- if (multi) { cbind(newdata, makeData(x, x0.name)) } else { makeData(x, x0.name) } predict(object, newdata = nd, type = "link") - eta }, interval = c(lower, upper), tol = tol, maxiter = maxiter)$root, silent = TRUE) if (inherits(x0_est, "try-error")) { stop(paste("Point estimate not found in the search interval (", lower, ", ", upper, "). ", "Try tweaking the values of lower and upper. ", "Use plotFit for guidance.", sep = ""), call. = FALSE) } interval <- match.arg(interval) if (interval == "none") { return(setNames(x0_est, x0.name)) } if (interval == "percentile") { stop("Bootstrap intervals not available for 'glm' objects.", call. = FALSE) } crit <- qnorm((level + 1) / 2) if (interval == "inversion") { inversionFun <- function(x) { nd <- if (multi) { cbind(newdata, makeData(x, x0.name)) } else { makeData(x, x0.name) } pred <- predict(object, newdata = nd, se.fit = TRUE, type = "link") ((eta - pred$fit) ^ 2) / (pred$se.fit ^ 2) - crit^2 } lwr <- try(uniroot(inversionFun, interval = c(lower, x0_est), tol = tol, maxiter = maxiter)$root, silent = TRUE) upr <- try(uniroot(inversionFun, interval = c(x0_est, upper), tol = tol, maxiter = maxiter)$root, silent = TRUE) if (inherits(lwr, "try-error")) { stop(paste("Lower confidence limit not found in the search interval (", lower, ", ", upper, "). ", "Try tweaking the values of lower and upper. ", "Use plotFit for guidance.", sep = ""), call. = FALSE) } if (inherits(upr, "try-error")) { stop(paste("Upper confidence limit not found in the search interval (", lower, ", ", upper, "). ", "Try tweaking the values of lower and upper. ", "Use plotFit for guidance.", sep = ""), call. = FALSE) } res <- list("estimate" = x0_est, "lower" = lwr, "upper" = upr, "interval" = interval) } if (interval == "Wald") { object_copy <- object dmFun <- function(params) { object_copy$coefficients <- params z <- eta uniroot(function(x) { nd <- if (multi) { cbind(newdata, makeData(x, x0.name)) } else { makeData(x, x0.name) } predict(object_copy, newdata = nd, type = "link") - z }, interval = c(lower, upper), tol = tol, maxiter = maxiter)$root } params <- coef(object) covmat <- vcov(object) gv <- attr(numericDeriv(quote(dmFun(params)), "params"), "gradient") se <- as.numeric(sqrt(gv %*% covmat %*% t(gv))) res <- list("estimate" = x0_est, "lower" = x0_est - crit * se, "upper" = x0_est + crit * se, "se" = se, "interval" = interval) } class(res) <- "invest" res } invest.nls <- function(object, y0, interval = c("inversion", "Wald", "percentile", "none"), level = 0.95, mean.response = FALSE, data, boot.type = c("parametric", "nonparametric"), nsim = 1, seed = NULL, progress = FALSE, lower, upper, tol = .Machine$double.eps^0.25, maxiter = 1000, adjust = c("none", "Bonferroni"), k, ...) { if (object$call$algorithm == "plinear") { stop(paste("The Golub-Pereyra algorithm for partially linear least-squares models is currently not supported.")) } .data <- if (!missing(data)) data else eval(object$call$data, envir = parent.frame()) x0.name <- intersect(all.vars(formula(object)[[3]]), colnames(.data)) yname <- all.vars(formula(object)[[2]]) if (length(x0.name) != 1) stop("Only one independent variable allowed.") if (missing(lower)) lower <- min(.data[, x0.name]) if (missing(upper)) upper <- max(.data[, x0.name]) m <- length(y0) if(mean.response && m > 1) stop("Only one mean response value allowed.") eta <- mean(y0) n <- length(resid(object)) p <- length(coef(object)) var_pooled <- Sigma(object)^2 x0_est <- try(uniroot(function(x) { predict(object, newdata = makeData(x, x0.name)) - eta }, interval = c(lower, upper), tol = tol, maxiter = maxiter)$root, silent = TRUE) if (inherits(x0_est, "try-error")) { stop(paste("Point estimate not found in the search interval (", lower, ", ", upper, "). ", "Try tweaking the values of lower and upper. ", "Use plotFit for guidance.", sep = ""), call. = FALSE) } interval <- match.arg(interval) if (interval == "none") return(x0_est) if (interval == "percentile") { stopifnot((nsim <- as.integer(nsim[1])) > 0) if (progress) { pb <- txtProgressBar(min = 0, max = nsim, style = 3) } if (!exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) runif(1) if (is.null(seed)) RNGstate <- get(".Random.seed", envir = .GlobalEnv) else { R.seed <- get(".Random.seed", envir = .GlobalEnv) set.seed(seed) RNGstate <- structure(seed, kind = as.list(RNGkind())) on.exit(assign(".Random.seed", R.seed, envir = .GlobalEnv)) } ftd <- fitted(object) res <- residuals(object) boot.type <- match.arg(boot.type) if (boot.type == "parametric") { ss <- simulate(object, nsim = nsim) } else { ss <- replicate(nsim, ftd + sample(res, replace = TRUE), simplify = FALSE) } x0Fun <- function(i) { boot_data <- eval(object$call$data) boot_data[, yname] <- ss[[i]] boot_object <- tryCatch(update(object, data = boot_data), error = function(e) NULL) if (is.null(boot_object)) { ret <- NA } else { if (mean.response) { y0_star <- y0 } else { if (boot.type == "parametric") { y0_star <- y0 + rnorm(length(y0), sd = Sigma(object)) } else { y0_star <- y0 + sample(res, size = length(y0), replace = TRUE) } } ret <- tryCatch(uniroot(function(x) { predict(boot_object, newdata = makeData(x, x0.name)) - mean(y0_star) }, interval = c(lower, upper), tol = tol, maxiter = maxiter)$root, error = function(e) NA) } if (progress) { setTxtProgressBar(pb, i) } ret } x0_star <- sapply(seq_len(nsim), x0Fun) if (AnyNA(x0_star)) { num_fail <- sum(is.na(x0_star)) warning("some bootstrap runs failed (", num_fail, "/", nsim, ")") x0_star <- na.omit(x0_star) attributes(x0_star) <- NULL } else { num_fail <- NULL } perc <- unname(quantile(x0_star, probs = c((1-level)/2, (1+level)/2))) res <- list("estimate" = x0_est, "lower" = perc[1], "upper" = perc[2], "se" = sd(x0_star), "bias" = mean(x0_star) - x0_est, "bootreps" = x0_star, "nsim" = nsim, "level" = level, "interval" = interval) class(res) = c("invest", "bootCal") attr(res, "bootFail") <- num_fail return(res) } adjust <- match.arg(adjust) crit <- if (adjust == "Bonferroni" && m == 1) { qt((level + 2*k - 1) / (2*k), n+m-p-1) } else { qt((level + 1) / 2, n+m-p-1) } if (interval == "inversion") { inversionFun <- function(x) { pred <- predFit(object, newdata = makeData(x, x0.name), se.fit = TRUE) denom <- if (mean.response) { pred$se.fit^2 } else { var_pooled/m + pred$se.fit^2 } (eta - pred$fit)^2/denom - crit^2 } lwr <- try(uniroot(inversionFun, interval = c(lower, x0_est), tol = tol, maxiter = maxiter)$root, silent = TRUE) upr <- try(uniroot(inversionFun, interval = c(x0_est, upper), tol = tol, maxiter = maxiter)$root, silent = TRUE) if (inherits(lwr, "try-error")) { stop(paste("Lower confidence limit not found in the search interval (", lower, ", ", upper, "). ", "Try tweaking the values of lower and upper. ", "Use plotFit for guidance.", sep = ""), call. = FALSE) } if (inherits(upr, "try-error")) { stop(paste("Upper confidence limit not found in the search interval (", lower, ", ", upper, "). ", "Try tweaking the values of lower and upper. ", "Use plotFit for guidance.", sep = ""), call. = FALSE) } res <- list("estimate" = x0_est, "lower" = lwr, "upper" = upr, "interval" = interval) } if (interval == "Wald") { object_copy <- object dmFun <- function(params) { if (mean.response) { object_copy$m$setPars(params) z <- eta } else { object_copy$m$setPars(params[-length(params)]) z <- params[length(params)] } uniroot(function(x) { predict(object_copy, newdata = makeData(x, x0.name)) - z }, interval = c(lower, upper), tol = tol, maxiter = maxiter)$root } if (mean.response) { params <- coef(object) covmat <- vcov(object) } else { params <- c(coef(object), eta) covmat <- diag(p + 1) covmat[p + 1, p + 1] <- var_pooled/m covmat[1:p, 1:p] <- vcov(object) } gv <- attr(numericDeriv(quote(dmFun(params)), "params"), "gradient") se <- as.numeric(sqrt(gv %*% covmat %*% t(gv))) res <- list("estimate" = x0_est, "lower" = x0_est - crit * se, "upper" = x0_est + crit * se, "se" = se, "interval" = interval) } class(res) <- "invest" res } invest.lme <- function(object, y0, interval = c("inversion", "Wald", "percentile", "none"), level = 0.95, mean.response = FALSE, data, lower, upper, q1, q2, tol = .Machine$double.eps^0.25, maxiter = 1000, ...) { .data <- if (!missing(data)) data else object$data x0.name <- intersect(all.vars(formula(object)[[3]]), colnames(.data)) yname <- all.vars(formula(object)[[2]]) if (length(x0.name) != 1) stop("Only one independent variable allowed.") if (missing(lower)) lower <- min(.data[, x0.name]) if (missing(upper)) upper <- max(.data[, x0.name]) m <- length(y0) if(mean.response && m > 1) stop("Only one mean response value allowed.") eta <- mean(y0) if (m != 1) stop('Only a single unknown allowed for objects of class "lme".') N <- length(resid(object)) p <- length(fixef(object)) if (missing(q1)) q1 <- qnorm((1-level) / 2) if (missing(q2)) q2 <- qnorm((1+level) / 2) x0_est <- try(uniroot(function(x) { predict(object, newdata = makeData(x, x0.name), level = 0) - eta }, interval = c(lower, upper), tol = tol, maxiter = maxiter)$root, silent = TRUE) if (inherits(x0_est, "try-error")) { stop(paste("Point estimate not found in the search interval (", lower, ", ", upper, "). ", "Try tweaking the values of lower and upper.", sep = ""), call. = FALSE) } interval <- match.arg(interval) if (interval == "none") return(x0_est) if (interval == "percentile") { stop("Bootstrap intervals not available for 'lme' objects.", call. = FALSE) } if (!mean.response) var.y0 <- varY(object, newdata = makeData(x0_est, x0.name)) if (interval == "inversion") { inversionFun <- function(x, bound = c("lower", "upper")) { pred <- predFit(object, newdata = makeData(x, x0.name), se.fit = TRUE) denom <- if (mean.response) { pred[, "se.fit"] } else { sqrt(var.y0 + pred[, "se.fit"]^2) } bound <- match.arg(bound) if (bound == "upper") { (eta - pred[, "fit"])/denom - q1 } else { (eta - pred[, "fit"])/denom - q2 } } lwr <- try(uniroot(inversionFun, interval = c(lower, x0_est), bound = "lower", tol = tol, maxiter = maxiter)$root, silent = TRUE) upr <- try(uniroot(inversionFun, interval = c(x0_est, upper), bound = "upper", tol = tol, maxiter = maxiter)$root, silent = TRUE) if (inherits(lwr, "try-error")) { stop(paste("Lower confidence limit not found in the search interval (", lower, ", ", upper, "). ", "Try tweaking the values of lower and upper.", sep = ""), call. = FALSE) } if (inherits(upr, "try-error")) { stop(paste("Upper confidence limit not found in the search interval (", lower, ", ", upper, "). ", "Try tweaking the values of lower and upper.", sep = ""), call. = FALSE) } res <- list("estimate" = x0_est, "lower" = lwr, "upper" = upr, "interval" = interval) } if (interval == "Wald") { dmFun <- function(params) { fun <- function(x) { X <- model.matrix(eval(object$call$fixed)[-2], data = makeData(x, x0.name)) if (mean.response) { X %*% params - eta } else { X %*% params[-length(params)] - params[length(params)] } } uniroot(fun, lower = lower, upper = upper, tol = tol, maxiter = maxiter)$root } if (mean.response) { params <- fixef(object) covmat <- vcov(object) } else { params <- c(fixef(object), eta) covmat <- diag(p + 1) covmat[p + 1, p + 1] <- var.y0 covmat[1:p, 1:p] <- vcov(object) } gv <- attr(numericDeriv(quote(dmFun(params)), "params"), "gradient") se <- as.numeric(sqrt(gv %*% covmat %*% t(gv))) res <- list("estimate" = x0_est, "lower" = x0_est - q2 * se, "upper" = x0_est + q2 * se, "se" = se, "interval" = interval) } class(res) <- "invest" res } print.invest <- function(x, digits = getOption("digits"), ...) { if (x$interval == "inversion") print(round(unlist(x[1:3]), digits)) if (x$interval == "Wald") print(round(unlist(x[1:4]), digits)) if (x$interval == "percentile") print(round(unlist(x[1:5]), digits)) invisible(x) } plot.bootCal <- function(x, ...) { t <- x$bootreps t0 <- x$estimate if (!is.null(t0)) { nclass <- min(max(ceiling(length(t)/25), 10), 100) rg <- range(t) if (t0 < rg[1L]) rg[1L] <- t0 else if (t0 > rg[2L]) rg[2L] <- t0 rg <- rg + 0.05 * c(-1, 1) * diff(rg) lc <- diff(rg)/(nclass - 2) n1 <- ceiling((t0 - rg[1L])/lc) n2 <- ceiling((rg[2L] - t0)/lc) bks <- t0 + (-n1:n2) * lc } par(mfrow = c(1, 2)) hist(t, breaks = bks, probability = TRUE, main = "", xlab = "Bootstrap replicate") qqnorm(t, xlab = "Standard normal quantile", ylab = "Bootstrap quantile", main = "") qqline(t) par(mfrow = c(1, 1)) invisible(x) }
new.bounds <- function(K=3, J=2, alpha=0.05, nMat=matrix(c(10,20), nrow=2, ncol=4), u=NULL, l=NULL, ushape="obf", lshape="fixed", ufix=NULL, lfix=0, N=20, parallel=TRUE, print=TRUE){ mesh<-function(x,d,w=1/length(x)+x*0){ n<-length(x) W<-X<-matrix(0,n^d,d) for (i in 1:d){ X[,i]<-x W[,i]<-w x<-rep(x,rep(n,length(x))) w<-rep(w,rep(n,length(w))) } w<-exp(rowSums(log(W))) list(X=X,w=w) } R_prodsum1_nb <-function(x, l, u, R, r0, r0diff, J, K, Sigma){ .Call("C_prodsum1_nb", x2 = as.double(x), l2 = as.double(l), u2 = as.double(u), R2 = as.double(R), r02 = as.double(r0), r0diff2 = as.double(r0diff), Jfull2 = as.integer(J), K2 = as.integer(K), Sigma2 = Sigma, maxpts2 = as.integer(25000), releps2 = as.double(0), abseps2 = as.double(0.001), tol2 = as.double(0.0001)) } typeI<-function(C,alpha,N,R,r0,r0diff,J,K,Sigma,mmp, u,l,ushape,lshape,lfix=NULL,ufix=NULL, parallel=parallel, print=print){ if(!is.null(l)){ j <- length(l) }else{ j <- 0 } Jleft <- J-j if(Jleft==1){ ind <- J }else{ ind <- (j+1):J } if(!is.function(ushape)){ if (ushape=='obf'){ ub<-c(u,C*sqrt(J/(1:J))[ind]) } else if (ushape=='pocock'){ ub<-c(u,rep(C,Jleft)) } else if (ushape=='fixed'){ ub<-c(u,rep(ufix,Jleft-1),C) } else if (ushape=='triangular') { ub<-c(u,(C*(1+(1:J)/J)/sqrt(1:J))[ind]) } }else{ ub <- c(u,C*ushape(J)[(j+1):J]) } if(!is.function(lshape)){ if (lshape=='obf'){ lb<- c(l,-C*sqrt(J/(1:(J-1)))[(j+1):(J-1)],ub[J]) } else if (lshape=='pocock'){ lb<-c(l,rep(-C,Jleft-1),ub[J]) } else if (lshape=='fixed'){ lb<-c(l,rep(lfix,Jleft-1),ub[J]) } else if (lshape=='triangular') { lb<-c(l,(-C*(1-3*(1:J)/J)/sqrt(1:J))[ind]) } }else{ lb <- c(l,C*lshape(J)[(j+1):(J-1)],ub[J]) } if(parallel){ evs <- future.apply::future_apply(mmp$X,1,R_prodsum1_nb, l=lb,u=ub,R=R,r0=r0,r0diff=r0diff,J=J,K=K,Sigma=Sigma, future.seed=TRUE,future.packages="MAMS") }else{ evs <- apply(mmp$X,1,R_prodsum1_nb, l=lb,u=ub,R=R,r0=r0,r0diff=r0diff,J=J,K=K,Sigma=Sigma) } if(print){ message(".",appendLF=FALSE) } truealpha<-1-mmp$w%*%evs return(truealpha-alpha) } if(K%%1>0 | J%%1>0){stop("K and J need to be integers.")} if(K < 1 | J < 1){stop("The number of stages and treatments must be at least 1.")} if(N<=3){stop("Number of points for integration by quadrature to small or negative.")} if(N>3 & N<=10){warning("Number of points for integration by quadrature is small which may result in inaccurate solutions.")} if(alpha<0 | alpha>1){stop("Error rate not between 0 and 1.")} if(!is.function(ushape)){ if(!ushape%in%c("pocock","obf","triangular","fixed")){stop("Upper boundary does not match the available options")} if(ushape=="fixed" & is.null(ufix)){stop("ufix required when using a fixed upper boundary shape.")} }else{ b <- ushape(J) if(!all(sort(b,decreasing=TRUE)==b)){stop("Upper boundary shape is increasing")} } if(!is.function(lshape)){ if(!lshape%in%c("pocock","obf","triangular","fixed")){stop("Lower boundary does not match the available options")} if(lshape=="fixed" & is.null(lfix)){stop("lfix required when using a fixed lower boundary shape.")} }else{ b <- lshape(J) if(!all(sort(b,decreasing=FALSE)==b)){stop("Lower boundary shape is decreasing")} } if(!all(diff(nMat)>=0)){stop("Total sample size per arm can not decrease between stages")} if(ncol(nMat)!=K+1){stop("Number of columns in nMat not equal to K+1")} if(nrow(nMat)!=J){stop("Number of rows in nMat not equal to J")} if(length(l)!=length(u)){stop("Length of l must be the same as length of u")} if(length(l)>(J-1)){stop("Maximum number of stages, J, greater or equal to length of boundary vector")} r0 <- nMat[,1]/nMat[1,1] R <- nMat[,-1]/nMat[1,1] mmp_j = as.list(rep(NA,J)) for(j in 1:J){ mmp_j[[j]] = mesh(x=(1:N-.5)/N*12-6,j,w=rep(12/N,N)) } bottom<-array(R,dim=c(J,K,J)) top<-array(rep(t(R),rep(J,K*J)),dim=c(J,K,J)) for (i in 1:K){ top[,i,][upper.tri(top[,i,])]<-t(top[,i,])[upper.tri(top[,i,])] bottom[,i,][upper.tri(bottom[,i,])]<-t(bottom[,i,])[upper.tri(bottom[,i,])] } tmp <-sqrt(top/bottom) Sigma <- array(NA,dim=c(J,J,K)) for(k in 1:K){ Sigma[,,k] = tmp[,k,] } r0lag1<-c(0,r0[1:J-1]) r0diff<-r0-r0lag1 if(print){ message(" i) find new lower and upper boundaries\n ",appendLF=FALSE) } uJ <- NULL try(uJ<-uniroot(typeI,c(0,5),alpha=alpha,N=N,R=R,r0=r0,r0diff=r0diff, J=J,K=K,Sigma=Sigma,mmp=mmp_j[[J]], u=u,l=l,ushape=ushape,lshape=lshape,lfix=lfix,ufix=ufix, parallel=parallel,print=print,tol=0.001)$root,silent=TRUE) if(is.null(uJ)) { stop("No solution found") } if(!is.null(l)){ j <- length(l) }else{ j <- 0 } Jleft <- J-j if(Jleft==1){ ind <- J }else{ ind <- (j+1):J } if(!is.function(ushape)){ if (ushape=='obf'){ ub<-c(u,uJ*sqrt(J/(1:J))[ind]) } else if (ushape=='pocock'){ ub<-c(u,rep(uJ,Jleft)) } else if (ushape=='fixed'){ ub<-c(u,rep(ufix,Jleft),uJ) } else if (ushape=='triangular') { ub<-c(u,(uJ*(1+(1:J)/J)/sqrt(1:J))[ind]) } }else{ ub <- c(u,uJ*ushape(J)[(j+1):J]) } if(!is.function(lshape)){ if (lshape=='obf'){ lb<- c(l,-uJ*sqrt(J/(1:(J-1)))[(j+1):(J-1)],ub[J]) } else if (lshape=='pocock'){ lb<-c(l,rep(-uJ,Jleft-1),ub[J]) } else if (lshape=='fixed'){ lb<-c(l,rep(lfix,Jleft-1),ub[J]) } else if (lshape=='triangular') { lb<-c(l,(-uJ*(1-3*(1:J)/J)/sqrt(1:J))[ind]) } }else{ lb <- c(l,uJ*lshape(J)[(j+1):(J-1)],ub[J]) } if(print){ message("\n ii) define alpha star\n",appendLF=FALSE) } alpha.star <- numeric(J) alpha.star[1] <- typeI(ub[1], alpha = 0, N = N, R = t(as.matrix(R[1,])), r0 = r0[1], r0diff = r0diff[1], J = 1, K = K, Sigma = Sigma, mmp = mmp_j[[1]], u = NULL, l = NULL, ushape = "fixed", lshape = "fixed", lfix = NULL, ufix = NULL, parallel = parallel, print = FALSE) if (J > 1){ for (j in 2:J){ alpha.star[j] <- typeI(ub[j], alpha = 0, N = N, R = R[1:j,], r0 = r0[1:j], r0diff = r0diff[1:j], J = j, K = K, Sigma = Sigma, mmp = mmp_j[[j]], u = NULL, l = NULL, ushape = "fixed", lshape = "fixed", lfix = lb[1:(j - 1)], ufix = ub[1:(j - 1)], parallel = parallel, print = FALSE) } } res <- NULL res$l <- lb res$u <- ub res$n <- nMat[1,1] res$rMat <- rbind(r0,t(R)) res$N <- sum(res$rMat[,J]*res$n) res$K <- K res$J <- J res$alpha <- alpha res$alpha.star <- alpha.star res$power <- NA res$type <- "new.bounds" class(res) <- "MAMS" return(res) }
test_that("Logical extension work", { x <- c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, NA, NA, NA) y <- c(TRUE, FALSE, NA, TRUE, FALSE, NA, TRUE, FALSE, NA) z <- c(TRUE, TRUE, FALSE, FALSE, NA, NA, TRUE, FALSE, NA) xL <- as.integer(x) xD <- as.double(x) res_n <- logical(length(x)) res_xy_and <- res_n res_xy_and_na <- res_n res_xy_or <- res_n res_xy_or_na <- res_n res_xyz_and <- res_n res_xyz_and_na <- res_n res_xyz_or <- res_n res_xyz_or_na <- res_n for (i in seq_along(x)) { res_xy_and[i] <- x[i] & y[i] res_xy_or[i] <- x[i] | y[i] res_xyz_and[i] <- x[i] & y[i] & z[i] res_xyz_or[i] <- x[i] | y[i] | z[i] res_xy_and_na[i] <- all(x[i], y[i], na.rm = TRUE) res_xy_or_na[i] <- any(x[i], y[i], na.rm = TRUE) res_xyz_and_na[i] <- all(x[i], y[i], z[i], na.rm = TRUE) res_xyz_or_na[i] <- any(x[i], y[i], z[i], na.rm = TRUE) } expect_equal(is_true(x), sapply(x, isTRUE, USE.NAMES = FALSE)) expect_equal(is_false(x), sapply(x, isFALSE, USE.NAMES = FALSE)) expect_identical(is_true(c( TRUE, FALSE, NA)), c(TRUE, FALSE, FALSE)) expect_identical(is_false(c(TRUE, FALSE, NA)), c(FALSE, TRUE, FALSE)) expect_true(is_boolean(x)) expect_true(is_boolean(xL)) expect_true(is_boolean(xD)) expect_equal(AND(x, y), res_xy_and) expect_equal(AND(x, y, na.rm = TRUE), res_xy_and_na) expect_equal(AND(x, y, z), res_xyz_and) expect_equal(AND(x, y, z, na.rm = TRUE), res_xyz_and_na) expect_equal(OR(x, y), res_xy_or) expect_equal(OR(x, y, na.rm = TRUE), res_xy_or_na) expect_equal(OR(x, y, na.rm = TRUE), res_xy_or_na) expect_equal(OR(x, y, z, na.rm = TRUE), res_xyz_or_na) }) test_that("logical helpers", { expect_error(null_check(NULL)) expect_error(null_check(integer())) expect_error(apply_logical_matrix(1L, mean, TRUE), "must be a matrix") expect_error(apply_logical_matrix(matrix("a"), mean, TRUE), "must be boolean") expect_error(apply_logical_matrix(matrix(3L), mean, TRUE), "must be boolean") })
kp_pomeroy_ratings <- function(min_year, max_year = most_recent_mbb_season()){ tryCatch( expr = { if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination,\n set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE) browser <- login() if(!(is.numeric(min_year) && nchar(min_year) == 4 && min_year>=2002)) { cli::cli_abort("Enter valid min_ as a number (YYYY), data only goes back to 2002") } years <- min_year:max_year for(year in years) { url <- paste0("https://kenpom.com/index.php?y=", year) page <- rvest::session_jump_to(browser, url) header_cols <- c("Rk", "Team", "Conf", "W-L", "AdjEM", "AdjO", "AdjO.Rk", "AdjD", "AdjD.Rk", "AdjT", "AdjT.Rk", "Luck", "Luck.Rk", "SOS.AdjEM", "SOS.AdjEM.Rk", "SOS.OppO", "SOS.OppO.Rk", "SOS.OppD", "SOS.OppD.Rk", "NCSOS.AdjEM", "NCSOS.AdjEM.Rk") x <- (page %>% xml2::read_html() %>% rvest::html_elements(" rvest::html_table() colnames(x) <- header_cols suppressWarnings( x <- x %>% dplyr::filter(!is.na(as.numeric(.data$SOS.OppO))) ) x <- dplyr::mutate(x, "NCAA_Seed" = NA_integer_, "NCAA_Seed" = sapply(.data$Team, function(arg) { as.numeric(gsub("[^0-9]", "", arg)) }), "Team" = sapply(.data$Team, function(arg) { stringr::str_trim(stringr::str_replace(stringr::str_remove(arg,'\\d+| \\*| \\*+'),'\\*+','')) }), "Year" = year) %>% as.data.frame() x <- x %>% dplyr::mutate_at( c("Rk","AdjEM","AdjO","AdjO.Rk","AdjD","AdjD.Rk","AdjT","AdjT.Rk", "Luck","Luck.Rk","SOS.AdjEM","SOS.AdjEM.Rk","SOS.OppO","SOS.OppO.Rk", "SOS.OppD","SOS.OppD.Rk","NCSOS.AdjEM","NCSOS.AdjEM.Rk"), as.numeric) %>% dplyr::select(.data$Year, tidyr::everything()) if(year == min_year) { kenpom <- x }else { kenpom <- dplyr::bind_rows(kenpom, x) } } kenpom <- kenpom %>% dplyr::arrange(-.data$Year, .data$Rk) %>% janitor::clean_names() }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no pomeroy ratings data for {min_year} - {max_year} available!")) }, warning = function(w) { }, finally = { } ) return(kenpom) } kp_efficiency <- function(min_year, max_year = most_recent_mbb_season()){ tryCatch( expr = { if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination,\n set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE) browser <- login() if(!(is.numeric(min_year) && nchar(min_year) == 4 && min_year>=2002)) { cli::cli_abort("Enter valid min_year as a number (YYYY), data only goes back to 2002") } years <- min_year:max_year for(year in years) { url <- paste0("https://kenpom.com/summary.php?y=", year) page <- rvest::session_jump_to(browser, url) if(year<2010){ header_cols <- c("Team", "Conf", "AdjT", "AdjT.Rk","RawT", "RawT.Rk", "AdjO", "AdjO.Rk", "RawO", "RawO.Rk", "AdjD", "AdjD.Rk", "RawD", "RawD.Rk") x <- (page %>% xml2::read_html() %>% rvest::html_elements(" rvest::html_table() x <- x[,1:14] colnames(x) <- header_cols suppressWarnings( x <- x %>% dplyr::filter(!is.na(as.numeric(.data$AdjO))) ) x <- x %>% dplyr::mutate( AvgPossLengthOff = 0.0, AvgPossLengthOff.Rk = 0, AvgPossLengthDef = 0.0, AvgPossLengthDef.Rk = 0) x <- x[,c("Team", "Conf", "AdjT", "AdjT.Rk","RawT", "RawT.Rk", "AvgPossLengthOff","AvgPossLengthOff.Rk", "AvgPossLengthDef","AvgPossLengthDef.Rk", "AdjO", "AdjO.Rk", "RawO", "RawO.Rk", "AdjD", "AdjD.Rk", "RawD", "RawD.Rk")] x <- dplyr::mutate(x, "NCAA_Seed" = NA_integer_, "NCAA_Seed" = sapply(.data$Team, function(arg) { as.numeric(gsub("[^0-9]", "", arg)) }), "Team" = sapply(.data$Team, function(arg) { stringr::str_trim(str_replace(stringr::str_remove(arg,'\\d+| \\*| \\*+'),'\\*+','')) }), "Year" = year) %>% dplyr::mutate_at( c("AdjT", "AdjT.Rk","RawT", "RawT.Rk", "AvgPossLengthOff","AvgPossLengthOff.Rk", "AvgPossLengthDef","AvgPossLengthDef.Rk", "AdjO", "AdjO.Rk", "RawO", "RawO.Rk", "AdjD", "AdjD.Rk", "RawD", "RawD.Rk", "Year"), as.numeric) %>% as.data.frame() }else{ header_cols <- c("Team", "Conf", "AdjT", "AdjT.Rk","RawT", "RawT.Rk", "AvgPossLengthOff","AvgPossLengthOff.Rk", "AvgPossLengthDef","AvgPossLengthDef.Rk", "AdjO", "AdjO.Rk", "RawO", "RawO.Rk", "AdjD", "AdjD.Rk", "RawD", "RawD.Rk") x <- (page %>% xml2::read_html() %>% rvest::html_elements(" rvest::html_table() x <- x[,1:18] colnames(x) <- header_cols suppressWarnings( x <- x %>% dplyr::filter(!is.na(as.numeric(.data$AdjO))) ) x <- dplyr::mutate(x, "NCAA_Seed" = NA_integer_, "NCAA_Seed" = sapply(.data$Team, function(arg) { as.numeric(gsub("[^0-9]", "", arg)) }), "Team" = sapply(.data$Team, function(arg) { stringr::str_trim(stringr::str_replace(stringr::str_remove(arg,'\\d+| \\*| \\*+'),'\\*+','')) }), "Year" = year) %>% dplyr::mutate_at( c("AdjT", "AdjT.Rk","RawT", "RawT.Rk", "AvgPossLengthOff","AvgPossLengthOff.Rk", "AvgPossLengthDef","AvgPossLengthDef.Rk", "AdjO", "AdjO.Rk", "RawO", "RawO.Rk", "AdjD", "AdjD.Rk", "RawD", "RawD.Rk", "Year"), as.numeric) %>% as.data.frame() } if(year == min_year) { kenpom <- x }else { kenpom <- dplyr::bind_rows(kenpom, x) } } kenpom <- kenpom %>% dplyr::arrange(-.data$Year, .data$AdjT.Rk) %>% janitor::clean_names() }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no efficiency data for {min_year} - {max_year} available!")) }, warning = function(w) { }, finally = { } ) return(kenpom) } kp_fourfactors <- function(min_year, max_year = most_recent_mbb_season()){ tryCatch( expr = { if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination,\n set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE) browser <- login() if(!(is.numeric(min_year) && nchar(min_year) == 4 && min_year>=2002)) { cli::cli_abort("Enter valid min_year as a number (YYYY), data only goes back to 2002") } years <- min_year:max_year for(year in years) { url <- paste0("https://kenpom.com/stats.php?", "y=", year) page <- rvest::session_jump_to(browser, url) header_cols <- c("Team", "Conf", "AdjT", "AdjT.Rk", "AdjO", "AdjO.Rk", "Off.eFG.Pct", "Off.eFG.Pct.Rk", "Off.TO.Pct", "Off.TO.Pct.Rk", "Off.OR.Pct", "Off.OR.Pct.Rk", "Off.FTRate", "Off.FTRate.Rk", "AdjD", "AdjD.Rk", "Def.eFG.Pct", "Def.eFG.Pct.Rk", "Def.TO.Pct", "Def.TO.Pct.Rk", "Def.OR.Pct", "Def.OR.Pct.Rk", "Def.FTRate", "Def.FTRate.Rk") x <- (page %>% xml2::read_html() %>% rvest::html_elements(css=' rvest::html_table() x <- x[,1:24] colnames(x) <- header_cols suppressWarnings( x <- x %>% dplyr::filter(!is.na(as.numeric(.data$AdjO))) ) x <- dplyr::mutate(x, "NCAA_Seed" = NA_integer_, "NCAA_Seed" = sapply(.data$Team, function(arg) { as.numeric(gsub("[^0-9]", "", arg)) }), "Team" = sapply(.data$Team, function(arg) { stringr::str_trim(stringr::str_replace(stringr::str_remove(arg,'\\d+| \\*| \\*+'),'\\*+','')) }), "Year" = year) %>% dplyr::mutate_at( c("AdjT", "AdjT.Rk", "AdjO", "AdjO.Rk", "Off.eFG.Pct", "Off.eFG.Pct.Rk", "Off.TO.Pct", "Off.TO.Pct.Rk", "Off.OR.Pct", "Off.OR.Pct.Rk", "Off.FTRate", "Off.FTRate.Rk", "AdjD", "AdjD.Rk", "Def.eFG.Pct", "Def.eFG.Pct.Rk", "Def.TO.Pct", "Def.TO.Pct.Rk", "Def.OR.Pct", "Def.OR.Pct.Rk", "Def.FTRate", "Def.FTRate.Rk", "Year"), as.numeric) %>% as.data.frame() if(year == min_year) { kenpom <- x }else { kenpom <- dplyr::bind_rows(kenpom, x) } } kenpom <- kenpom %>% dplyr::arrange(-.data$Year,.data$AdjO.Rk) %>% janitor::clean_names() }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no four factors data for {min_year} - {max_year} available!")) }, warning = function(w) { }, finally = { } ) return(kenpom) } kp_pointdist <- function(min_year, max_year = most_recent_mbb_season()){ tryCatch( expr = { if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination,\n set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE) browser <- login() if(!(is.numeric(min_year) && nchar(min_year) == 4 && min_year>=2002)) { cli::cli_abort("Enter valid min_year as a number (YYYY), data only goes back to 2002") } years <- min_year:max_year for(year in years) { url <- paste0("https://kenpom.com/pointdist.php?", "y=", year) page <- rvest::session_jump_to(browser, url) header_cols <- c("Team", "Conf", "Off.FT.Pct", "Off.FT.Pct.Rk", "Off.FG_2.Pct", "Off.FG_2.Pct.Rk", "Off.FG_3.Pct", "Off.FG_3.Pct.Rk", "Def.FT.Pct", "Def.FT.Pct.Rk", "Def.FG_2.Pct", "Def.FG_2.Pct.Rk", "Def.FG_3.Pct", "Def.FG_3.Pct.Rk") x <- (page %>% xml2::read_html() %>% rvest::html_elements(css=' rvest::html_table() x <- x[,1:14] colnames(x) <- header_cols suppressWarnings( x <- x %>% dplyr::filter(!is.na(as.numeric(.data$Off.FT.Pct))) ) x <- dplyr::mutate(x, "NCAA_Seed" = NA_integer_, "NCAA_Seed" = sapply(.data$Team, function(arg) { as.numeric(gsub("[^0-9]", "", arg)) }), "Team" = sapply(.data$Team, function(arg) { stringr::str_trim(stringr::str_replace(stringr::str_remove(arg,'\\d+| \\*| \\*+'),'\\*+','')) }), "Year" = year) %>% dplyr:: mutate_at( c("Off.FT.Pct", "Off.FT.Pct.Rk", "Off.FG_2.Pct", "Off.FG_2.Pct.Rk", "Off.FG_3.Pct", "Off.FG_3.Pct.Rk", "Def.FT.Pct", "Def.FT.Pct.Rk", "Def.FG_2.Pct", "Def.FG_2.Pct.Rk", "Def.FG_3.Pct", "Def.FG_3.Pct.Rk","Year"), as.numeric) %>% as.data.frame() if(year == min_year) { kenpom <- x }else { kenpom <- dplyr::bind_rows(kenpom, x) } } kenpom <- kenpom %>% janitor::clean_names() }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no point distribution data for {min_year} - {max_year} available!")) }, warning = function(w) { }, finally = { } ) return(kenpom) } kp_height <- function(min_year,max_year = most_recent_mbb_season()){ tryCatch( expr = { if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination,\n set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE) browser <- login() if(!(is.numeric(min_year) && nchar(min_year) == 4 && min_year>=2007)) { cli::cli_abort("Enter valid min_year as a number (YYYY), data only goes back to 2007") } years <- min_year:max_year for(year in years) { url <- paste0("https://kenpom.com/height.php?", "y=", year) page <- rvest::session_jump_to(browser, url) if(year<2008){ header_cols <- c("Team", "Conf", "Avg.Hgt", "Avg.Hgt.Rk", "Eff.Hgt", "Eff.Hgt.Rk", "C.Hgt", "C.Hgt.Rk", "PF.Hgt", "PF.Hgt.Rk", "SF.Hgt", "SF.Hgt.Rk", "SG.Hgt", "SG.Hgt.Rk", "PG.Hgt", "PG.Hgt.Rk", "Experience", "Experience.Rk", "Bench", "Bench.Rk") x <- (page %>% xml2::read_html() %>% rvest::html_elements(css=' rvest::html_table() x <- x[,1:20] colnames(x) <- header_cols x <- x %>% dplyr::mutate( Continuity = 0.0, Continuity.Rk = 0) x <- dplyr::mutate(x, "NCAA_Seed" = NA_integer_, "NCAA_Seed" = sapply(.data$Team, function(arg) { as.numeric(gsub("[^0-9]", "", arg)) }), "Team" = sapply(.data$Team, function(arg) { stringr::str_trim(stringr::str_replace(stringr::str_remove(arg,'\\d+| \\*| \\*+'),'\\*+','')) }), "Year" = year) %>% dplyr:: mutate_at( c("Avg.Hgt", "Avg.Hgt.Rk", "Eff.Hgt", "Eff.Hgt.Rk", "C.Hgt", "C.Hgt.Rk", "PF.Hgt", "PF.Hgt.Rk", "SF.Hgt", "SF.Hgt.Rk", "SG.Hgt", "SG.Hgt.Rk", "PG.Hgt", "PG.Hgt.Rk", "Experience", "Experience.Rk", "Bench", "Bench.Rk","Continuity","Continuity.Rk"), as.numeric) %>% as.data.frame() }else{ header_cols <- c("Team", "Conf", "Avg.Hgt", "Avg.Hgt.Rk", "Eff.Hgt", "Eff.Hgt.Rk", "C.Hgt", "C.Hgt.Rk", "PF.Hgt", "PF.Hgt.Rk", "SF.Hgt", "SF.Hgt.Rk", "SG.Hgt", "SG.Hgt.Rk", "PG.Hgt", "PG.Hgt.Rk", "Experience", "Experience.Rk", "Bench", "Bench.Rk", "Continuity", "Continuity.Rk") x <- (page %>% xml2::read_html() %>% rvest::html_elements(css=' rvest::html_table() x <- x[,1:22] colnames(x) <- header_cols } suppressWarnings( x <- x %>% dplyr::filter(!is.na(as.numeric(.data$Avg.Hgt))) ) x <- dplyr::mutate(x, "NCAA_Seed" = NA_integer_, "NCAA_Seed" = sapply(.data$Team, function(arg) { as.numeric(gsub("[^0-9]", "", arg)) }), "Team" = sapply(.data$Team, function(arg) { stringr::str_trim(stringr::str_replace(stringr::str_remove(arg,'\\d+| \\*| \\*+'),'\\*+','')) }), "Year" = year) %>% dplyr:: mutate_at( c("Avg.Hgt", "Avg.Hgt.Rk", "Eff.Hgt", "Eff.Hgt.Rk", "C.Hgt", "C.Hgt.Rk", "PF.Hgt", "PF.Hgt.Rk", "SF.Hgt", "SF.Hgt.Rk", "SG.Hgt", "SG.Hgt.Rk", "PG.Hgt", "PG.Hgt.Rk", "Experience", "Experience.Rk", "Bench", "Bench.Rk","Continuity","Continuity.Rk"), as.numeric) %>% as.data.frame() if(year == min_year) { kenpom <- x }else { kenpom <- dplyr::bind_rows(kenpom, x) } } kenpom <- kenpom %>% janitor::clean_names() }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no height data for {min_year} - {max_year} available!")) }, warning = function(w) { }, finally = { } ) return(kenpom) } kp_foul_trouble <- function(min_year, max_year = most_recent_mbb_season()){ tryCatch( expr = { if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination,\n set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE) browser <- login() if(!(is.numeric(min_year) && nchar(min_year) == 4 && min_year>=2010)) { cli::cli_abort("Enter valid min_year as a number (YYYY), data only goes back to 2010") } years <- min_year:max_year for(year in years) { url <- paste0("https://kenpom.com/foul_trouble.php?", "y=", year) page <- rvest::session_jump_to(browser, url) header_cols <- c("Team", "Conf", "TwoFoulParticpation.Pct", "TwoFoulParticpation.Pct.Rk", "Adj2FP", "Adj2FP.Rk", "TwoFoulTotalTime","TwoFoulTotalTime.Rk", "TwoFoulTimeOn","TwoFoulTimeOn.Rk", "Bench.Pct","Bench.Pct.Rk") x <- (page %>% xml2::read_html() %>% rvest::html_elements(css=' rvest::html_table() x <- x[,1:12] colnames(x) <- header_cols suppressWarnings( x <- x %>% dplyr::filter(!is.na(as.numeric(.data$TwoFoulParticpation.Pct))) ) x <- dplyr::mutate(x, "NCAA_Seed" = NA_integer_, "NCAA_Seed" = sapply(.data$Team, function(arg) { as.numeric(gsub("[^0-9]", "", arg)) }), "Team" = sapply(.data$Team, function(arg) { stringr::str_trim(stringr::str_replace(stringr::str_remove(arg,'\\d+| \\*| \\*+'),'\\*+','')) }), "Year" = year) %>% dplyr:: mutate_at( c("TwoFoulParticpation.Pct", "TwoFoulParticpation.Pct.Rk", "Adj2FP", "Adj2FP.Rk", "Bench.Pct","Bench.Pct.Rk"), as.numeric) %>% as.data.frame() if(year == min_year) { kenpom <- x }else { kenpom <- dplyr::bind_rows(kenpom, x) } } kenpom <- kenpom %>% janitor::clean_names() }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no foul trouble data for {min_year} - {max_year} available!")) }, warning = function(w) { }, finally = { } ) return(kenpom) } kp_teamstats <- function(min_year, max_year=most_recent_mbb_season(), defense = FALSE){ tryCatch( expr = { if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination,\n set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE) browser <- login() if(!(is.numeric(min_year) && nchar(min_year) == 4 && min_year>=2002)) { cli::cli_abort("Enter valid min_year as a number (YYYY), data only goes back to 2002") } years <- min_year:max_year for(year in years) { url <- paste0("https://kenpom.com/teamstats.php?", "y=", year, "&od=o") page <- rvest::session_jump_to(browser, url) header_cols <- c("Team", "Conf", "Off.FG_3.Pct", "Off.FG_3.Pct.Rk", "Off.FG_2.Pct", "Off.FG_2.Pct.Rk", "Off.FT.Pct", "Off.FT.Pct.Rk", "Off.Blk.Pct", "Off.Blk.Pct.Rk", "Off.Stl.Pct", "Off.Stl.Pct.Rk", "Off.NonStl.Pct", "Off.NonStl.Pct.Rk", "Off.A.Pct", "Off.A.Pct.Rk", "Off.FG_3A.Pct", "Off.FG_3A.Pct.Rk", "AdjO","AdjO.Rk") x <- (page %>% xml2::read_html() %>% rvest::html_elements(css=' rvest::html_table() x <- x[,1:20] colnames(x) <- header_cols suppressWarnings( x <- x %>% dplyr::filter(!is.na(as.numeric(.data$Off.FG_3.Pct))) ) x <- dplyr::mutate(x, "NCAA_Seed" = NA_integer_, "NCAA_Seed" = sapply(.data$Team, function(arg) { as.numeric(gsub("[^0-9]", "", arg)) }), "Team" = sapply(.data$Team, function(arg) { stringr::str_trim(stringr::str_replace(stringr::str_remove(arg,'\\d+| \\*| \\*+'),'\\*+','')) }), "Year" = year) %>% dplyr::mutate_at( c("Off.FG_3.Pct", "Off.FG_3.Pct.Rk", "Off.FG_2.Pct", "Off.FG_2.Pct.Rk", "Off.FT.Pct", "Off.FT.Pct.Rk", "Off.Blk.Pct", 'Off.Blk.Pct.Rk', "Off.Stl.Pct", "Off.Stl.Pct.Rk", "Off.NonStl.Pct", "Off.NonStl.Pct.Rk", "Off.A.Pct", "Off.A.Pct.Rk", "Off.FG_3A.Pct", "Off.FG_3A.Pct.Rk", "AdjO", "AdjO.Rk", "Year"), as.numeric) %>% as.data.frame() url <- paste0("https://kenpom.com/teamstats.php?", "y=", year, "&od=d") page <- rvest::session_jump_to(browser, url) d_header_cols <- c("Team", "Conf", "Def.FG_3.Pct", "Def.FG_3.Pct.Rk", "Def.FG_2.Pct", "Def.FG_2.Pct.Rk", "Def.FT.Pct", "Def.FT.Pct.Rk", "Def.Blk.Pct", 'Def.Blk.Pct.Rk', "Def.Stl.Pct", "Def.Stl.Pct.Rk", "Def.NonStl.Pct", "Def.NonStl.Pct.Rk", "Def.A.Pct", "Def.A.Pct.Rk", "Def.FG_3A.Pct", "Def.FG_3A.Pct.Rk", "AdjD","AdjD.Rk") y <- (page %>% xml2::read_html() %>% rvest::html_elements(css=' rvest::html_table() y <- y[,1:20] colnames(y) <- d_header_cols suppressWarnings( y <- y %>% dplyr::filter(!is.na(as.numeric(.data$Def.FG_3.Pct))) ) y <- y %>% dplyr::mutate_at( c("Def.FG_3.Pct", "Def.FG_3.Pct.Rk", "Def.FG_2.Pct", "Def.FG_2.Pct.Rk", "Def.FT.Pct", "Def.FT.Pct.Rk", "Def.Blk.Pct", 'Def.Blk.Pct.Rk', "Def.Stl.Pct", "Def.Stl.Pct.Rk", "Def.NonStl.Pct", "Def.NonStl.Pct.Rk", "Def.A.Pct", "Def.A.Pct.Rk", "Def.FG_3A.Pct", "Def.FG_3A.Pct.Rk", "AdjD", "AdjD.Rk"), as.numeric) %>% as.data.frame() y <- y %>% dplyr::select(-.data$Team, -.data$Conf) z <- dplyr::bind_cols(x, y) if(year == min_year) { kenpom <- z }else { kenpom <- dplyr::bind_rows(kenpom, z) } } kenpom <- kenpom %>% janitor::clean_names() }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no team stats data for {min_year} - {max_year} available!")) }, warning = function(w) { }, finally = { } ) return(kenpom) } kp_playerstats <- function(metric = 'eFG', conf = NULL, conf_only = FALSE, year=most_recent_mbb_season()){ tryCatch( expr = { if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination,\n set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE) browser <- login() m_list <- c('ORtg', 'Min', 'eFG', 'Poss', 'Shots', 'OR', 'DR', 'TO', 'ARate', 'Blk', 'FTRate', 'Stl', 'TS', 'FC40', 'FD40', '2P', '3P', 'FT') url_ext <- c('ORtg','PctMin', 'eFG', 'PctPoss','PctShots', 'ORPct', 'DRPct','TORate', 'ARate', 'PctBlocks', 'FTRate', 'PctStls', 'TS', 'FCper40', 'FDper40', 'FG2Pct', 'FG3Pct', 'FTPct') metrics_data <- data.frame(m_list, url_ext) conf_list <- c('A10', 'ACC', 'AE', 'AMER', 'ASUN', 'B10', 'B12', 'BE', 'BSKY', 'BSTH', 'BW', 'CAA', 'CUSA', 'HORZ', 'IND', 'IVY', 'MAAC', 'MAC', 'MEAC', 'MVC', 'MWC', 'NEC', 'OVC', 'P12', 'PAT', 'SB', 'SC', 'SEC', 'SLND', 'SUM', 'SWAC', 'WAC', 'WCC') metric_url <- metrics_data$url_ext[m_list == metric] if(!(is.numeric(year) && nchar(year) == 4 && year>=2004)) { cli::cli_abort("Enter valid year as a number (YYYY), data only goes back to 2004") } if(metric=="ORtg"){ url <- paste0("https://kenpom.com/playerstats.php?", "y=", year, "&s=", metric_url, "&f=", conf, "&c=", conf_only) page <- rvest::session_jump_to(browser, url) header_cols <- c("Rk","Player","Team", metric, "Hgt","Wgt","Yr") y <- list() for(i in 1:4){ groups <- c("At least 28% of possessions used", "At least 24% of possessions used", "At least 20% of possessions used", "All players") x <- (page %>% xml2::read_html() %>% rvest::html_elements("table"))[[i]] %>% rvest::html_table() x <- x[,1:7] colnames(x) <- header_cols suppressWarnings( x <- x %>% dplyr::filter(!is.na(as.numeric(.data$Wgt))) ) x <- dplyr::mutate(x, "Team" = sapply(.data$Team, function(arg) { stringr::str_trim(stringr::str_replace(stringr::str_remove(arg,'\\d+| \\*| \\*+'),'\\*+','')) }), "Year" = year, "Group" = groups[i]) %>% as.data.frame() %>% janitor::clean_names() y <- c(y,list(x)) } kenpom <- y }else{ url <- paste0("https://kenpom.com/playerstats.php?", "y=", year, "&s=", metric_url, "&f=", conf, "&c=", conf_only) page <- rvest::session_jump_to(browser, url) header_cols <- c("Rk","Player","Team", metric, "Hgt","Wgt","Yr") x <- (page %>% xml2::read_html() %>% rvest::html_elements(css=' rvest::html_table() x <- x[,1:7] colnames(x) <- header_cols suppressWarnings( x <- x %>% dplyr::filter(!is.na(as.numeric(.data$Wgt))) ) x <- dplyr::mutate(x, "Team" = sapply(.data$Team, function(arg) { stringr::str_trim(stringr::str_replace(stringr::str_remove(arg,'\\d+| \\*| \\*+'),'\\*+','')) }), "Year" = year)%>% as.data.frame() kenpom <- x %>% janitor::clean_names() } }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no player stats data for {year} {metric} available!")) }, warning = function(w) { }, finally = { } ) return(kenpom) } kp_kpoy <- function(year=most_recent_mbb_season()){ tryCatch( expr = { if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination,\n set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE) browser <- login() if(!(is.numeric(year) && nchar(year) == 4 && year>=2011)) { cli::cli_abort("Enter valid year as a number (YYYY), data only goes back to 2011") } url <- paste0("https://kenpom.com/kpoy.php?", "y=", year) page <- rvest::session_jump_to(browser, url) y <- list() for(i in 1:2){ groups <- c("kPoY Rating", "Game MVP Leaders") x <- (page %>% xml2::read_html() %>% rvest::html_elements(css=' rvest::html_table() %>% as.data.frame() if(i == 1){ header_cols <- c("Rk","Player","kpoyRating")} else{ header_cols <- c("Rk","Player","GameMVPs") } colnames(x) <- header_cols x <- x %>% tidyr::separate(.data$Player, into = c("Player","col"), sep = ",", extra = "merge") x <- x %>% dplyr::mutate( Team = stringr::str_extract( stringr::str_extract(.data$col,'[^\\d-\\d{1,}]+'),".+"), Hgt = stringr::str_extract( stringi::stri_extract_first_regex(.data$col, '[^,]+'),"\\d{1,}-\\d{1,}+"), Wgt = stringr::str_extract(.data$col,'\\d{3}'), Exp = stringr::str_extract(.data$col, "Fr|So|Jr|Sr|r-Fr|r-So|r-Jr|r-Sr"), HomeTown = stringr::str_extract( stringi::stri_extract_last_regex(.data$col, '[^\u00b7]+'),".*") ) suppressWarnings( if(i == 1){x <- x %>% dplyr::mutate_at(c("kpoyRating","Wgt"), as.numeric) }else{x <- x %>% dplyr::mutate_at(c("GameMVPs","Wgt"), as.numeric)} ) x <- dplyr::mutate(x, "Year" = year, "Group" = groups[i]) %>% as.data.frame() x <- x %>% dplyr::select(-.data$col) if(i == 2) { replace_na_with_last <- function(x, p = is.na, d = 0){c(d, x)[cummax(seq_along(x)*(!p(x))) + 1]} x$Rk <- replace_na_with_last(x$Rk) } x <- x %>% janitor::clean_names() y <- c(y,list(x)) } kenpom <- y }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no KenPom player of the year data for {year} available!")) }, warning = function(w) { }, finally = { } ) return(kenpom) }
makeids <- function(){ id.list <- data.table(year=c(1968:1997,seq(1999,2019,by=2))) id.list$ind.interview <- c("ER30001","ER30020","ER30043","ER30067", "ER30091","ER30117","ER30138","ER30160", "ER30188","ER30217","ER30246","ER30283", "ER30313","ER30343","ER30373","ER30399", "ER30429","ER30463","ER30498","ER30535", "ER30570","ER30606","ER30642","ER30689", "ER30733","ER30806","ER33101","ER33201", "ER33301","ER33401","ER33501","ER33601", "ER33701","ER33801","ER33901","ER34001", "ER34101","ER34201","ER34301","ER34501","ER34701") id.list$ind.seq <- c(NA,"ER30021","ER30044","ER30068","ER30092","ER30118","ER30139", "ER30161","ER30189","ER30218","ER30247","ER30284","ER30314", "ER30344","ER30374","ER30400","ER30430","ER30464","ER30499", "ER30536","ER30571","ER30607","ER30643","ER30690","ER30734", "ER30807","ER33102","ER33202","ER33302","ER33402","ER33502", "ER33602","ER33702","ER33802","ER33902","ER34002","ER34102", "ER34202","ER34302","ER34502","ER34702") id.list$ind.head <- c("ER30003", "ER30022", "ER30045", "ER30069", "ER30093", "ER30119", "ER30140", "ER30162", "ER30190", "ER30219", "ER30248", "ER30285", "ER30315", "ER30345", "ER30375", "ER30401", "ER30431", "ER30465", "ER30500", "ER30537", "ER30572", "ER30608", "ER30644", "ER30691", "ER30735", "ER30808", "ER33103", "ER33203", "ER33303", "ER33403", "ER33503", "ER33603", "ER33703", "ER33803", "ER33903", "ER34003", "ER34103", "ER34203", "ER34303", "ER34503", "ER34703") id.list$ind.head.num <- c(rep(1,15),rep(10,26)) id.list$fam.interview <- c("V3" , "V442" , "V1102" , "V1802" , "V2402" , "V3002" , "V3402" , "V3802" , "V4302" , "V5202" , "V5702" , "V6302" , "V6902" , "V7502" , "V8202" , "V8802" , "V10002" , "V11102" , "V12502" , "V13702" , "V14802" , "V16302" , "V17702" , "V19002" , "V20302" , "V21602" , "ER2002" , "ER5002" , "ER7002" , "ER10002" , "ER13002" , "ER17002" , "ER21002" , "ER25002" , "ER36002" , "ER42002" , "ER47302" , "ER53002" , "ER60002" , "ER66002" , "ER72002") id.list$stratum <- rep("ER31996",nrow(id.list)) setkey(id.list,year) return(id.list) } makeids.wealth <- function(){ id = data.table(year=c(1984, 1989, 1994, 1999, 2001, 2003, 2005, 2007),interview = c("S101","S201","S301","S401","S501","S601","S701","S801")) setkey(id,year) return(id) } get.psid <- function( file , name , params , curl ){ html = postForm('http://simba.isr.umich.edu/u/Login.aspx', .params = params, curl = curl) if ( !grepl('Logout', html) ) stop( 'no longer logged in' ) tf <- tempfile() ; td <- tempdir() flog.info('downloading file %s',name) file <- getBinaryURL( paste0( "http://simba.isr.umich.edu/Zips/GetFile.aspx?file=" , file ) , curl = curl ) writeBin( file , tf ) z <- unzip( tf , exdir = td ) fn <- z[ grepl( ".txt" , tolower( z ) , fixed = TRUE ) & ! grepl( "_vdm|readme|doc|errata" , tolower( z ) ) ] sas_ri <- z[ grepl( '.sas' , z , fixed = TRUE ) ] flog.info('now reading and processing SAS file %s into R',name) x <- read.SAScii( fn , sas_ri ) save( x , file = paste0( name , '.rda' ) ) file.remove( tf , z ) rm( x ) gc() TRUE } make.char <- function(x){ if (is.factor(x)){ return(as.character(x)) } else { return(x) } } testPSID <-function(N=100,N.attr = 0){ ER30001 <- ER30002 <-intnum86 <- intnum85 <- Money85 <- Money86 <- age85 <- age86 <- smpls <- NULL stopifnot(N %% 4 == 0) smpl <- ceiling(1:N / (N/4)) IND2009ER <- data.table(smpls=c(smpl,smpl)) IND2009ER[, ER30001 := 0L] IND2009ER[smpls==1, ER30001 := sample(1:2999,size=sum(smpls==1))] IND2009ER[smpls==2, ER30001 := sample(3001:4999,size=sum(smpls==2))] IND2009ER[smpls==3, ER30001 := sample(5001:6999,size=sum(smpls==3))] IND2009ER[smpls==4, ER30001 := sample(7001:9308,size=sum(smpls==4))] IND2009ER[,c("intnum85","intnum86") := lapply(1:2,function(x) sample(1:(2*N)))] IND2009ER[sample(1:(2*N),size=N),c("intnum85") := 0] if (N.attr>0){ out = sample(which(IND2009ER[["intnum85"]] != 0),size=N.attr,replace=FALSE) IND2009ER[out,"intnum86" := 0] } IND2009ER[,ER30002 := sample(1:(2*N))] IND2009ER$ER30465 <- sample(rep(c(10,20),c(N,N)),size=2*N,replace=TRUE) IND2009ER$ER30500 <- sample(rep(c(10,20),c(N,N)),size=2*N,replace=TRUE) IND2009ER$ER30464 <- sample(rep(c(1,20),c(ceiling(0.75*2*N),ceiling(0.5*N))),size=2*N,replace=TRUE) IND2009ER$ER30499 <- sample(rep(c(1,20),c(ceiling(0.75*2*N),ceiling(0.5*N))), size=2*N,replace=TRUE) IND2009ER$ER30497 <- runif(2*N) IND2009ER$ER30534 <- runif(2*N) fam85 <- data.table(intnum85 = IND2009ER[intnum85>0,sample(intnum85,size=N)],Money85=rlnorm(n=N,10,1),age85=sample(20:80,size=N,replace=TRUE)) fam86 <- data.table(intnum86 = IND2009ER[intnum86>0,sample(intnum86,size=sum(intnum86>0))],Money86 = rlnorm(n=IND2009ER[,sum(intnum86>0)],10,1),age86 = sample(20L:80L,size=IND2009ER[,sum(intnum86>0)],replace=TRUE)) continuers85 = IND2009ER[intnum85>0 & intnum86>0][["intnum85"]] continuers86 = IND2009ER[intnum85>0 & intnum86>0][["intnum86"]] for (i in 1:nrow(fam86)){ if (fam86[i,intnum86] %in% continuers86){ int86 = fam86[i,intnum86] fam86[i,Money86 := fam85[intnum85==IND2009ER[intnum86==int86,intnum85], Money85 + rnorm(1,500,30)]] fam86[i,age86 := fam85[intnum85==IND2009ER[intnum86==int86,intnum85], age85 + 1]] } } setnames(fam85,"intnum85", "V11102") setnames(fam86,"intnum86","V12502") setnames(IND2009ER,c("intnum85","intnum86"), c("ER30463","ER30498")) return(list(famvars1985=fam85,famvars1986=fam86,IND2019ER=IND2009ER)) }
getCall <- function(MLCall){ bracketLocation <- gregexpr(pattern ='\\(',MLCall)[[1]][1] parentFunction <- substr(MLCall,1,bracketLocation-1) functionCall <- match.call(eval(parse(text=parentFunction)),parse(text=MLCall)) return(functionCall) }
effTypesFromMFVB <- function(mu.q.betaTilde,sigsq.q.betaTilde,mu.q.gamma.beta, mu.q.uTilde,sigsq.q.uTilde,mu.q.gamma.u, lowerMakesSparser,effectiveZero) { numPred <- length(mu.q.gamma.beta) dGeneral <- length(mu.q.gamma.u) dLinear <- numPred - dGeneral effectTypesHat <- rep("zero",numPred) for (iPred in 1:numPred) { isBetaZero <- coefZeroMFVB((1-mu.q.gamma.beta[iPred]),lowerMakesSparser,effectiveZero) if (!isBetaZero) effectTypesHat[iPred] <- "linear" } if (dGeneral>0) { iColSttPos <- 1 for (jNon in 1:dGeneral) { for (iCol in iColSttPos:length(mu.q.gamma.u[[jNon]])) { isUkZero <- coefZeroMFVB((1-mu.q.gamma.u[[jNon]][iCol]),lowerMakesSparser,effectiveZero) if (!isUkZero) effectTypesHat[dLinear+jNon] <- "nonlinear" } } } return(effectTypesHat) }
tam_aggregate_derivative_information <- function(deriv, groups) { res <- stats::aggregate(deriv, list(groups), sum) res[ res[,1]==0, 2] <- 0 ind <- match(groups, res[,1]) return(res[ind,2]) }
bargraph_twofactor=function(analysis, labels=NULL, ocult.facet=FALSE, ocult.box=FALSE, facet.size=14, ylab=NULL, width.bar=0.3, sup=NULL){ requireNamespace("ggplot2") results=as.list(1:length(analysis)) for(i in 1:length(analysis)){ if(is.null(labels)==TRUE){analysis[[i]][[2]]$plot$graph$facet=rep(i, e=nrow(analysis[[i]][[2]]$plot$graph))}else{ analysis[[i]][[2]]$plot$graph$facet=rep(labels[i],e=nrow(analysis[[i]][[2]]$plot$graph))} results[[i]]=analysis[[i]][[2]]$plot$graph} tabela=do.call("rbind",results) if(is.null(sup)==TRUE){sup=0.1*mean(tabela$media)} media=tabela$media desvio=tabela$desvio f1=tabela$f1 f2=tabela$f2 numero=tabela$numero letra=tabela$letra graph=ggplot(tabela,aes(y=media,x=f1,fill=f2))+ geom_col(color="black",position = position_dodge(width = 0.9))+ facet_grid(~facet,scales = "free", space='free')+ geom_errorbar(aes(ymin=media-desvio,ymax=media+desvio),width=width.bar,position = position_dodge(width=0.9))+ geom_text(aes(y=media+desvio+sup,x=f1,label=numero),position = position_dodge(width=0.9))+xlab("")+ analysis[[1]][[2]]$theme+theme(strip.text = element_text(size=facet.size)) if(is.null(ylab)==TRUE){graph=graph+ylab(analysis[[1]][[2]]$plot$ylab)}else{graph=graph+ylab(ylab)} if(ocult.facet==TRUE){graph=graph+theme(strip.text = element_blank())} if(ocult.box==TRUE){graph=graph+theme(strip.background = element_blank())} list(graph)[[1]]}
extractX <- function(cand.set, ...){ cand.set <- formatCands(cand.set) UseMethod("extractX", cand.set) } extractX.default <- function(cand.set, ...){ stop("\nFunction not yet defined for this object class\n") } extractX.AICaov.lm <- function(cand.set, ...) { form.list <- as.character(lapply(cand.set, FUN = function(x) formula(x)[[3]])) form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] resp <- unique(as.character(sapply(cand.set, FUN = function(x) formula(x)[[2]]))) if(length(resp) > 1) stop("\nThe response variable should be identical in all models\n") dsets <- lapply(cand.set, FUN = function(i) i$model) names(dsets) <- NULL combo <- do.call(what = "cbind", dsets) dframe <- combo[, unique(names(combo))] dframe <- dframe[, names(dframe) != resp] result <- list("predictors" = unique.predictors, "data" = dframe) class(result) <- "extractX" return(result) } extractX.AICglm.lm <- function(cand.set, ...) { form.list <- as.character(lapply(cand.set, FUN = function(x) formula(x)[[3]])) form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] resp <- unique(as.character(sapply(cand.set, FUN = function(x) formula(x)[[2]]))) if(length(resp) > 1) stop("\nThe response variable should be identical in all models\n") dsets <- lapply(cand.set, FUN = function(i) i$model) names(dsets) <- NULL combo <- do.call(what = "cbind", dsets) dframe <- combo[, unique(names(combo))] dframe <- dframe[, names(dframe) != resp] result <- list("predictors" = unique.predictors, "data" = dframe) class(result) <- "extractX" return(result) } extractX.AICglmmTMB <- function(cand.set, ...) { form.list <- as.character(lapply(cand.set, FUN = function(x) formula(x)[[3]])) form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] resp <- unique(as.character(sapply(cand.set, FUN = function(x) formula(x)[[2]]))) if(length(resp) > 1) stop("\nThe response variable should be identical in all models\n") pipe.id <- which(regexpr("\\|", unique.predictors) != -1) if(length(pipe.id) > 0) {unique.predictors <- unique.predictors[-pipe.id]} dsets <- lapply(cand.set, FUN = function(i) (i$frame)) names(dsets) <- NULL combo <- do.call(what = "cbind", dsets) dframe <- combo[, unique(names(combo))] dframe <- dframe[, names(dframe) != resp] inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) I.id <- which(regexpr("I\\(", final.predictors) != -1) if(length(I.id) > 0) { dframe <- dframe[, final.predictors[-I.id], drop = FALSE] } else { dframe <- dframe[, final.predictors, drop = FALSE] } result <- list("predictors" = unique.predictors, "data" = dframe) class(result) <- "extractX" return(result) } extractX.AICgls <- function(cand.set, ...) { form.list <- as.character(lapply(cand.set, FUN = function(x) formula(x)[[3]])) form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] resp <- unique(as.character(sapply(cand.set, FUN = function(x) formula(x)[[2]]))) if(length(resp) > 1) stop("\nThe response variable should be identical in all models\n") dsets <- lapply(cand.set, FUN = function(i) getData(i)) names(dsets) <- NULL combo <- do.call(what = "cbind", dsets) dframe <- combo[, unique(names(combo))] dframe <- dframe[, names(dframe) != resp] inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) I.id <- which(regexpr("I\\(", final.predictors) != -1) if(length(I.id) > 0) { dframe <- dframe[, final.predictors[-I.id], drop = FALSE] } else { dframe <- dframe[, final.predictors, drop = FALSE] } result <- list("predictors" = unique.predictors, "data" = dframe) class(result) <- "extractX" return(result) } extractX.AIClm <- function(cand.set, ...) { form.list <- as.character(lapply(cand.set, FUN = function(x) formula(x)[[3]])) form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] resp <- unique(as.character(sapply(cand.set, FUN = function(x) formula(x)[[2]]))) if(length(resp) > 1) stop("\nThe response variable should be identical in all models\n") dsets <- lapply(cand.set, FUN = function(i) i$model) names(dsets) <- NULL combo <- do.call(what = "cbind", dsets) dframe <- combo[, unique(names(combo))] dframe <- dframe[, names(dframe) != resp] result <- list("predictors" = unique.predictors, "data" = dframe) class(result) <- "extractX" return(result) } extractX.AIClme <- function(cand.set, ...) { form.list <- as.character(lapply(cand.set, FUN = function(x) formula(x)[[3]])) form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] resp <- unique(as.character(sapply(cand.set, FUN = function(x) formula(x)[[2]]))) if(length(resp) > 1) stop("\nThe response variable should be identical in all models\n") dsets <- lapply(cand.set, FUN = function(i) getData(i)) names(dsets) <- NULL combo <- do.call(what = "cbind", dsets) dframe <- combo[, unique(names(combo))] dframe <- dframe[, names(dframe) != resp] inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) I.id <- which(regexpr("I\\(", final.predictors) != -1) if(length(I.id) > 0) { dframe <- dframe[, final.predictors[-I.id], drop = FALSE] } else { dframe <- dframe[, final.predictors, drop = FALSE] } result <- list("predictors" = unique.predictors, "data" = dframe) class(result) <- "extractX" return(result) } extractX.AICglmerMod <- function(cand.set, ...) { form.list <- as.character(lapply(cand.set, FUN = function(x) formula(x)[[3]])) form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] resp <- unique(as.character(sapply(cand.set, FUN = function(x) formula(x)[[2]]))) if(length(resp) > 1) stop("\nThe response variable should be identical in all models\n") pipe.id <- which(regexpr("\\|", unique.predictors) != -1) if(length(pipe.id) > 0) {unique.predictors <- unique.predictors[-pipe.id]} dsets <- lapply(cand.set, FUN = function(i) (i@frame)) names(dsets) <- NULL combo <- do.call(what = "cbind", dsets) dframe <- combo[, unique(names(combo))] dframe <- dframe[, names(dframe) != resp] inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) I.id <- which(regexpr("I\\(", final.predictors) != -1) if(length(I.id) > 0) { dframe <- dframe[, final.predictors[-I.id], drop = FALSE] } else { dframe <- dframe[, final.predictors, drop = FALSE] } result <- list("predictors" = unique.predictors, "data" = dframe) class(result) <- "extractX" return(result) } extractX.AIClmerMod <- function(cand.set, ...) { form.list <- as.character(lapply(cand.set, FUN = function(x) formula(x)[[3]])) form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] resp <- unique(as.character(sapply(cand.set, FUN = function(x) formula(x)[[2]]))) if(length(resp) > 1) stop("\nThe response variable should be identical in all models\n") pipe.id <- which(regexpr("\\|", unique.predictors) != -1) if(length(pipe.id) > 0) {unique.predictors <- unique.predictors[-pipe.id]} dsets <- lapply(cand.set, FUN = function(i) i@frame) names(dsets) <- NULL combo <- do.call(what = "cbind", dsets) dframe <- combo[, unique(names(combo))] dframe <- dframe[, names(dframe) != resp] inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) I.id <- which(regexpr("I\\(", final.predictors) != -1) if(length(I.id) > 0) { dframe <- dframe[, final.predictors[-I.id], drop = FALSE] } else { dframe <- dframe[, final.predictors, drop = FALSE] } result <- list("predictors" = unique.predictors, "data" = dframe) class(result) <- "extractX" return(result) } extractX.AIClmerModLmerTest <- function(cand.set, ...) { form.list <- as.character(lapply(cand.set, FUN = function(x) formula(x)[[3]])) form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] resp <- unique(as.character(sapply(cand.set, FUN = function(x) formula(x)[[2]]))) if(length(resp) > 1) stop("\nThe response variable should be identical in all models\n") pipe.id <- which(regexpr("\\|", unique.predictors) != -1) if(length(pipe.id) > 0) {unique.predictors <- unique.predictors[-pipe.id]} dsets <- lapply(cand.set, FUN = function(i) i@frame) names(dsets) <- NULL combo <- do.call(what = "cbind", dsets) dframe <- combo[, unique(names(combo))] dframe <- dframe[, names(dframe) != resp] inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) I.id <- which(regexpr("I\\(", final.predictors) != -1) if(length(I.id) > 0) { dframe <- dframe[, final.predictors[-I.id], drop = FALSE] } else { dframe <- dframe[, final.predictors, drop = FALSE] } result <- list("predictors" = unique.predictors, "data" = dframe) class(result) <- "extractX" return(result) } extractX.AICrlm.lm <- function(cand.set, ...) { form.list <- as.character(lapply(cand.set, FUN = function(x) formula(x)[[3]])) form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] resp <- unique(as.character(sapply(cand.set, FUN = function(x) formula(x)[[2]]))) if(length(resp) > 1) stop("\nThe response variable should be identical in all models\n") dsets <- lapply(cand.set, FUN = function(i) i$model) names(dsets) <- NULL combo <- do.call(what = "cbind", dsets) dframe <- combo[, unique(names(combo))] dframe <- dframe[, names(dframe) != resp] result <- list("predictors" = unique.predictors, "data" = dframe) class(result) <- "extractX" return(result) } extractX.AICsurvreg <- function(cand.set, ...) { form.list <- as.character(lapply(cand.set, FUN = function(x) formula(x)[[3]])) form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) eval(i$call$data)) names(dsets) <- NULL combo <- do.call(what = "cbind", dsets) dframe <- combo[, unique(names(combo))] inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) I.id <- which(regexpr("I\\(", final.predictors) != -1) if(length(I.id) > 0) { dframe <- dframe[, final.predictors[-I.id], drop = FALSE] } else { dframe <- dframe[, final.predictors, drop = FALSE] } result <- list("predictors" = unique.predictors, "data" = dframe) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitOccu <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "psi")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formula[[3]])) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formula[[2]])) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitColExt <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "psi")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@psiformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "gamma")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@gamformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "epsilon")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@epsformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@detformula)) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) yearlyVars <- yearlySiteCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} if(!is.null(yearlyVars)) { yearlyID <- yearlyVars[, intersect(final.predictors, names(yearlyVars)), drop = FALSE] if(nrow(yearlyID) > 0) { yearlyID.info <- capture.output(str(yearlyID))[-1] } else { yearlyID.info <- NULL } } else {yearlyID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} if(is.null(yearlyVars)) { data.out$yearlySiteCovs <- NULL } else {data.out$yearlySiteCovs <- yearlyID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitOccuRN <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "psi")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formula[[3]])) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formula[[2]])) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitPCO <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "lambda")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$lambdaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "gamma")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$gammaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "omega")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$omegaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "iota")) { parfreq <- sum(sapply(cand.set, FUN = function(i) any(names(i@estimates@estimates) == parm.type))) if(!identical(length(cand.set), parfreq)) { stop("\nParameter \'iota\' does not appear in all models\n") } form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$iotaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$pformula)) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) yearlyVars <- yearlySiteCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} if(!is.null(yearlyVars)) { yearlyID <- yearlyVars[, intersect(final.predictors, names(yearlyVars)), drop = FALSE] if(nrow(yearlyID) > 0) { yearlyID.info <- capture.output(str(yearlyID))[-1] } else { yearlyID.info <- NULL } } else {yearlyID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} if(is.null(yearlyVars)) { data.out$yearlySiteCovs <- NULL } else {data.out$yearlySiteCovs <- yearlyID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitPCount <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "lambda")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formula[[3]])) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formula[[2]])) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitDS <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "lambda")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formula[[3]])) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formula[[2]])) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitGDS <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "lambda")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$lambdaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "phi")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$phiformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$pformula[[2]])) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) yearlyVars <- yearlySiteCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} if(!is.null(yearlyVars)) { yearlyID <- yearlyVars[, intersect(final.predictors, names(yearlyVars)), drop = FALSE] if(nrow(yearlyID) > 0) { yearlyID.info <- capture.output(str(yearlyID))[-1] } else { yearlyID.info <- NULL } } else {yearlyID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} if(is.null(yearlyVars)) { data.out$yearlySiteCovs <- NULL } else {data.out$yearlySiteCovs <- yearlyID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitOccuFP <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "psi")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@stateformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "falsepos") || identical(parm.type, "fp")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@FPformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "certain")) { parfreq <- sum(sapply(cand.set, FUN = function(i) any(names(i@estimates@estimates) == parm.type))) if(!identical(length(cand.set), parfreq)) { stop("\nParameter \'b\' does not appear in all models\n") } form.list <- as.character(lapply(cand.set, FUN = function(x) x@Bformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@detformula)) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitMPois <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "lambda")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formula[[3]])) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formula[[2]])) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitGMM <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "lambda")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$lambdaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "phi")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$phiformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$pformula)) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) yearlyVars <- yearlySiteCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} if(!is.null(yearlyVars)) { yearlyID <- yearlyVars[, intersect(final.predictors, names(yearlyVars)), drop = FALSE] if(nrow(yearlyID) > 0) { yearlyID.info <- capture.output(str(yearlyID))[-1] } else { yearlyID.info <- NULL } } else {yearlyID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} if(is.null(yearlyVars)) { data.out$yearlySiteCovs <- NULL } else {data.out$yearlySiteCovs <- yearlyID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitGPC <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "lambda")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$lambdaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "phi")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$phiformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$pformula)) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) yearlyVars <- yearlySiteCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} if(!is.null(yearlyVars)) { yearlyID <- yearlyVars[, intersect(final.predictors, names(yearlyVars)), drop = FALSE] if(nrow(yearlyID) > 0) { yearlyID.info <- capture.output(str(yearlyID))[-1] } else { yearlyID.info <- NULL } } else {yearlyID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} if(is.null(yearlyVars)) { data.out$yearlySiteCovs <- NULL } else {data.out$yearlySiteCovs <- yearlyID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitOccuMulti <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "psi")) { form.list <- lapply(cand.set, FUN = function(x) names(x@estimates@estimates$state@estimates)) } if(identical(parm.type, "detect")) { form.list <- lapply(cand.set, FUN = function(x) names(x@estimates@estimates$det@estimates)) } formStrings <- unlist(form.list) notInclude <- grep(pattern = "(Intercept)", x = formStrings) formNoInt <- formStrings[-notInclude] formJustVars <- unlist(strsplit(formNoInt, split = "\\]")) formMat <- matrix(data = formJustVars, ncol = 2, byrow = TRUE) form.clean <- gsub("(^ +)|( +$)", "", formMat[, 2]) unique.predictors <- unique(form.clean) dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitOccuMS <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "psi")) { form.list <- lapply(cand.set, FUN = function(x) x@psiformulas) } if(identical(parm.type, "detect")) { form.list <- lapply(cand.set, FUN = function(x) x@detformulas) } if(identical(parm.type, "phi")) { nseasons <- unique(sapply(cand.set, FUN = function(i) i@data@numPrimary)) if(nseasons == 1) { stop("\nParameter \'phi\' does not appear in single-season models\n") } form.list <- lapply(cand.set, FUN = function(x) x@phiformulas) } formStrings <- gsub(pattern = "~", replacement = "", x = unlist(form.list)) formNoInt <- formStrings[formStrings != "1"] form.clean <- gsub("(^ +)|( +$)", "", formNoInt) unique.predictors <- unique(form.clean) dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitOccuTTD <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "psi")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@psiformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "gamma")) { nseasons <- unique(sapply(cand.set, FUN = function(i) i@data@numPrimary)) if(nseasons == 1) { stop("\nParameter \'gamma\' does not appear in single-season models\n") } form.list <- as.character(lapply(cand.set, FUN = function(x) x@gamformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "epsilon")) { nseasons <- unique(sapply(cand.set, FUN = function(i) i@data@numPrimary)) if(nseasons == 1) { stop("\nParameter \'epsilon\' does not appear in single-season models\n") } form.list <- as.character(lapply(cand.set, FUN = function(x) x@epsformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@detformula)) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) yearlyVars <- yearlySiteCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} if(!is.null(yearlyVars)) { yearlyID <- yearlyVars[, intersect(final.predictors, names(yearlyVars)), drop = FALSE] if(nrow(yearlyID) > 0) { yearlyID.info <- capture.output(str(yearlyID))[-1] } else { yearlyID.info <- NULL } } else {yearlyID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} if(is.null(yearlyVars)) { data.out$yearlySiteCovs <- NULL } else {data.out$yearlySiteCovs <- yearlyID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitMMO <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "lambda")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$lambdaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "gamma")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$gammaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "omega")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$omegaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "iota")) { parfreq <- sum(sapply(cand.set, FUN = function(i) any(names(i@estimates@estimates) == parm.type))) if(!identical(length(cand.set), parfreq)) { stop("\nParameter \'iota\' does not appear in all models\n") } form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$iotaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$pformula)) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) yearlyVars <- yearlySiteCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} if(!is.null(yearlyVars)) { yearlyID <- yearlyVars[, intersect(final.predictors, names(yearlyVars)), drop = FALSE] if(nrow(yearlyID) > 0) { yearlyID.info <- capture.output(str(yearlyID))[-1] } else { yearlyID.info <- NULL } } else {yearlyID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} if(is.null(yearlyVars)) { data.out$yearlySiteCovs <- NULL } else {data.out$yearlySiteCovs <- yearlyID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } extractX.AICunmarkedFitDSO <- function(cand.set, parm.type = NULL, ...) { if(is.null(parm.type)) {stop("\n'parm.type' must be specified for this model type, see ?extractX for details\n")} if(identical(parm.type, "lambda")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$lambdaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "gamma")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$gammaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "omega")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$omegaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "iota")) { parfreq <- sum(sapply(cand.set, FUN = function(i) any(names(i@estimates@estimates) == parm.type))) if(!identical(length(cand.set), parfreq)) { stop("\nParameter \'iota\' does not appear in all models\n") } form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$iotaformula)) form.list <- gsub("~", replacement = "", x = form.list) } if(identical(parm.type, "detect")) { form.list <- as.character(lapply(cand.set, FUN = function(x) x@formlist$pformula)) form.list <- gsub("~", replacement = "", x = form.list) } form.noplus <- unlist(sapply(form.list, FUN = function(i) strsplit(i, split = "\\+"))) form.clean <- gsub("(^ +)|( +$)", "", form.noplus) unique.clean <- unique(form.clean) unique.predictors <- unique.clean[nchar(unique.clean) != 0 & unique.clean != "1"] dsets <- lapply(cand.set, FUN = function(i) unmarked::getData(i)) unique.dsets <- unique(dsets) if(length(unique.dsets) != 1) stop("\nData sets differ across models:\n check data carefully\n") unFrame <- unique.dsets[[1]] siteVars <- siteCovs(unFrame) obsVars <- obsCovs(unFrame) yearlyVars <- yearlySiteCovs(unFrame) inter.star <- any(regexpr("\\*", unique.predictors) != -1) inter.id <- any(regexpr("\\:", unique.predictors) != -1) if(inter.star && inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.nostar.clean <- gsub("(^ +)|( +$)", "", terms.nostar) terms.nointer <- unlist(sapply(terms.nostar.clean, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(inter.star && !inter.id) { terms.nostar <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\*"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nostar) } if(!inter.star && inter.id) { terms.nointer <- unlist(sapply(unique.predictors, FUN = function(i) strsplit(i, split = "\\:"))) terms.clean <- gsub("(^ +)|( +$)", "", terms.nointer) } if(!inter.star && !inter.id) { terms.clean <- unique.predictors } final.predictors <- unique(terms.clean) if(!is.null(obsVars)) { obsID <- obsVars[, intersect(final.predictors, names(obsVars)), drop = FALSE] if(nrow(obsID) > 0) { obsID.info <- capture.output(str(obsID))[-1] } else { obsID.info <- NULL } } else {obsID.info <- NULL} if(!is.null(siteVars)) { siteID <- siteVars[, intersect(final.predictors, names(siteVars)), drop = FALSE] if(nrow(siteID) > 0) { siteID.info <- capture.output(str(siteID))[-1] } else { siteID.info <- NULL } } else {siteID.info <- NULL} if(!is.null(yearlyVars)) { yearlyID <- yearlyVars[, intersect(final.predictors, names(yearlyVars)), drop = FALSE] if(nrow(yearlyID) > 0) { yearlyID.info <- capture.output(str(yearlyID))[-1] } else { yearlyID.info <- NULL } } else {yearlyID.info <- NULL} data.out <- list( ) if(is.null(obsVars)) { data.out$obsCovs <- NULL } else {data.out$obsCovs <- obsID} if(is.null(siteVars)) { data.out$siteCovs <- NULL } else {data.out$siteCovs <- siteID} if(is.null(yearlyVars)) { data.out$yearlySiteCovs <- NULL } else {data.out$yearlySiteCovs <- yearlyID} result <- list("predictors" = unique.predictors, "data" = data.out) class(result) <- "extractX" return(result) } print.extractX <- function(x, ...) { if(length(x$predictors) > 0) { cat("\nPredictors appearing in candidate models:\n") cat(x$predictors, sep = " ") cat("\n") if(!is.data.frame(x$data)) { nitems <- length(x$data) for(i in 1:nitems) { if(ncol(x$data[[i]]) > 0) { cat("\nStructure of predictors in ", names(x$data)[i], ":\n", sep = "") cat(capture.output(str(x$data[[i]]))[-1], sep = "\n") } } cat("\n") } else { cat("\nStructure of predictors:", "\n") cat(capture.output(str(x$data))[-1], sep = "\n") cat("\n") } } else { cat("\nNo predictors appear in candidate models\n") cat("\n") } }
utils::globalVariables("where") utils::globalVariables(".") if (FALSE) { lifecycle::is_present() }
faConfInt <- function(fa) { if (('psych' %in% tolower(class(fa))) && ('fa.ci' %in% tolower(class(fa)))) { lc <- data.frame(unclass(fa$loadings), fa$ci$ci); CIs <- list(); for (i in 1:fa$factors) { CIs[[i]] <- lc[, c(i + fa$factors, i, i + fa$factors * 2)]; names(CIs[[i]]) <- c('lo', 'est', 'hi'); } return(CIs); } else { stop("This function can only process the resulting objects ", "as produced by the `fa` function in the `psych` package!)"); } }
test_that("can create multiple traces from name argument", { l <- plot_ly() %>% add_markers(x = 1:10, y = 1:10, name = rep(c("a", "b"), 5)) %>% plotly_build() expect_length(l$x$data, 2) expect_equal(l$x$data[[1]]$name, "a") expect_equal(l$x$data[[2]]$name, "b") }) test_that("can override name argument", { l <- plot_ly() %>% add_markers(x = 1:10, y = 1:10, split = rep(c("a", "b"), 5), name = "z") %>% plotly_build() expect_length(l$x$data, 2) expect_equal(l$x$data[[1]]$name, "z") expect_equal(l$x$data[[2]]$name, "z") l2 <- plot_ly() %>% add_markers(x = 1:10, y = 1:10, split = rep(c("a", "b"), 5), name = paste0(rep(c("a", "b"), 5), "<br>z")) %>% plotly_build() expect_length(l2$x$data, 2) expect_equal(l2$x$data[[1]]$name, "a<br>z") expect_equal(l2$x$data[[2]]$name, "b<br>z") }) test_that("doesn't break old behavior", { density1 <- density(diamonds[diamonds$cut %in% "Fair", ]$carat) density2 <- density(diamonds[diamonds$cut %in% "Ideal",]$carat) l <- plot_ly(x = ~density1$x, y = ~density1$y, type = 'scatter', mode = 'lines', name = 'Fair cut', fill = 'tozeroy', fillcolor = 'rgba(168, 216, 234, 0.5)', line = list(width = 0.5)) %>% add_trace(x = ~density2$x, y = ~density2$y, name = 'Ideal cut', fill = 'tozeroy', fillcolor = 'rgba(255, 212, 96, 0.5)') %>% plotly_build() expect_equal(l$x$data[[1]]$name, "Fair cut") expect_equal(l$x$data[[2]]$name, "Ideal cut") }) test_that("adding trace name with frame does not throw frameOrder warning", { dt <- data.frame(source = rep(c(rep("TEL", 2) , rep("WEB", 2), rep("OTH",2)),2), period = rep(c("AM", "PM"), 6), y_val = runif(12), year = c(rep(2020,6), rep(2021,6))) p1 <- plot_ly() for (yr in unique(dt$year)){ which_lines <- which(dt$year==yr) p1 <- add_trace(p1, x = dt$period[which_lines], y = dt$y_val[which_lines], frame = dt$source[which_lines], type = "scatter", mode = "lines+markers", name = yr) } expect_warning(l <- plotly_build(p1), NA) expect_equal(l$x$data[[1]]$name, 2020) expect_equal(l$x$data[[2]]$name, 2021) }) test_that("adding trace name does not throw error", { df <- data.frame(category=c('a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'), year=c(2000, 2000, 2000, 2000, 2001, 2001, 2001, 2001), val_a=c(1,2,2,1,2,5,6,8), val_b=c(3,5,4,7,1,9,2,12)) p1 <- plot_ly(data = df, frame = ~year) %>% add_markers(x = ~val_a, y = ~category, name = "Val_A", color = I("red")) %>% add_markers(x = ~val_b, y = ~category, name = "Val_B", color = I("blue")) %>% add_segments(x = ~val_a, xend = ~val_b, y = ~category, yend = ~category, showlegend=F) %>% layout( title = "Val A v Val B", xaxis = list(title = "Value"), yaxis = list(title = ""), margin = list(l = 65) ) expect_error(l <- plotly_build(p1), NA) expect_equal(l$x$data[[1]]$name, "Val_A") expect_equal(l$x$data[[2]]$name, "Val_B") df1 <- data.frame(frame = 1:10, x = 1:10, y = 0) df2 <- data.frame(frame = rep(1:10, 1:10), x = unlist(lapply(1:10, function(x) 1:x)), y = 1) p2 <- plot_ly() %>% add_trace(data = df1, type = "scatter", mode = "markers", x = ~x, y = ~y, frame = ~frame, name= "A") %>% add_trace(data = df2, type = "scatter", mode = "lines", x = ~x, y = ~y, frame = ~frame, name = "B") expect_error(l1 <- plotly_build(p2), NA) })
library('fda') library('odesolve') library('maxLik') library('MASS') library('Matrix') library('SparseM') source('ProfileR.R') source('sse.shortcut.R') source('fhn.R') source('findif.ode.R') source('SSElik.R') source('SSEproc.R') source('makeid.R') source('inneropt.R') t = seq(0,20,0.05) pars = c(0.2,0.2,3) names(pars) = c('a','b','c') x0 = c(-1,1) names(x0)= c('V','R') y = lsoda(x0,times=t,func=make.fhn()$fn.ode,pars) y = y[,2:3] data = y + matrix(rnorm(802),401,2) knots = seq(0,20,0.2) norder = 3 nbasis = length(knots) + norder - 2 range = c(0,20) bbasis = create.bspline.basis(range=range,nbasis=nbasis, norder=norder,breaks=knots) fd.data = array(data,c(dim(data)[1],1,dim(data)[2])) DEfd = data2fd( fd.data,t,bbasis,fdnames=list(NULL,NULL,c('V','R')) ) coefs = matrix(DEfd$coefs,dim(DEfd$coefs)[1],dim(DEfd$coefs)[3]) colnames(coefs) = DEfd$fdnames[[3]] lambda = c(10000,10000) qpts = knots qwts = rep(1/length(knots),length(knots)) qwts = qwts%*%t(lambda) weights = array(1,dim(data)) varnames = c('V','R') parnames = c('a','b','c') likmore = make.id() likmore$weights = weights lik = make.SSElik() lik$more = likmore lik$bvals = Matrix(eval.basis(t,bbasis),sparse=TRUE) procmore = make.fhn() procmore$names = varnames procmore$parnames = parnames procmore$weights = qwts procmore$qpts = qpts proc = make.SSEproc() proc$more = procmore proc$bvals = list(bvals=Matrix(eval.basis(procmore$qpts,bbasis,0),sparse=TRUE), dbvals = Matrix(eval.basis(procmore$qpts,bbasis,1),sparse=TRUE)) spars = c(0.2,0.2,2) control=list() control$trace = 0 control$maxit = 1000 control$maxtry = 10 control$reltol = 1e-6 control$meth = "BFGS" control.in = control control.in$reltol = 1e-12 control.out = control control.out$trace = 2 control.in$print.level = 0 control.in$iterlim = 1000 res = sse.setup(pars=pars,coefs=coefs,fn=make.fhn(),basisvals=bbasis,lambda=lambda,times=t) res = smooth.sse(make.fhn(),data,t,pars,coefs,bbasis,lambda=lambda,control.in=control.in) res = profile.sse(make.fhn(),data,t,pars,coefs,bbasis,lambda=lambda,out.meth='nls', control.in=control.in,control.out=control.out) res = sse.setup(pars=pars,fd.obj=DEfd,fn=make.fhn(),lambda=lambda,times=t) res = smooth.sse(pars=pars,fd.obj=DEfd,fn=make.fhn(),lambda=lambda,times=t,data=fd.data,control.in=control.in) res = profile.sse(fn=make.fhn(),data=fd.data,times=t,pars=pars,fd.obj=DEfd,lambda=lambda,out.meth='house', control.in=control.in,control.out=control.out) f = SplineCoefsErr(coefs,times=t,data=data,lik=lik,proc=proc,pars=spars) g = SplineCoefsDC(coefs,times=t,data=data,lik=lik,proc=proc,pars=spars) h = SplineCoefsDC2(coefs,times=t,data=data,lik=lik,proc=proc,pars=spars) g2 = SplineCoefsDP(coefs,times=t,data=data,lik=lik,proc=proc,pars=spars) h2 = SplineCoefsDCDP(coefs,times=t,data=data,lik=lik,proc=proc,pars=spars) res = optim(coefs,SplineCoefsErr,gr=SplineCoefsDC,hessian=T, method="BFGS",control=control.out, times=t,data=data,lik=lik,proc=proc,pars=spars) res0 = nlminb(coefs+2,SplineCoefsErr,gradient=SplineCoefsDC,hessian=SplineCoefsDC2, control=control.out,times=t,data=data,lik=lik,proc=proc,pars=spars) res2 = maxNR(SplineCoefsErr,start=as.vector(coefs),times=t,data=data,lik=lik,proc=proc,pars=spars,sgn=-1, grad=SplineCoefsDC,hess=SplineCoefsDC2,print.level=2,iterlim=100) res3 = SplineEst.NewtRaph(coefs,t,data,lik,proc,spars) ncoefs = array(res0$par,c(bbasis$nbasis,ncol(data))) ProfileEnv = new.env() assign('optcoef',ncoefs,3,ProfileEnv) assign('curcoefs',ncoefs,3,ProfileEnv) f = ProfileErr(pars,pars,t,data,ncoefs,lik,proc,in.meth="nlminb",control.in=control.in) g = ProfileDP(pars,pars,t,data,ncoefs,lik,proc,sum=FALSE) res4 = ProfileSSE(pars,t,data,ncoefs,lik,proc,in.meth="nlminb",control.in) res5 = Profile.GausNewt(spars,t,data,ncoefs,lik,proc,in.meth="nlminb",control.in) res6 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc,in.meth,control.in), data = list(times=t,data=data,coefs=ncoefs,lik=lik,proc=proc, in.meth="nlminb",control.in=control.in),start = list(pars=pars), trace=TRUE) g = res6$m$gradient() df = diag(res6$m$resid())%*%g C6 = NeweyWest.Var(t(g)%*%g, df[1:401,]+df[402:802,],5) res7 = Profile.GausNewt(spars,t,data,ncoefs,lik,proc,in.meth='house',control.in) res8 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc,in.meth,control.in), data = list(times=t,data=data,coefs=ncoefs,lik=lik,proc=proc, in.meth='house',control.in=control.in), start = list(pars=spars),trace=TRUE) res9 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc,in.meth,control.in), data = list(times=t,data=data,coefs=ncoefs,lik=lik,proc=proc, in.meth='nlminb',control.in=control.in), start = list(pars=spars),trace=TRUE) res10 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc,in.meth,control.in), data = list(times=t,data=data,coefs=ncoefs,lik=lik,proc=proc, in.meth='maxNR',control.in=control.in), start = list(pars=spars),trace=TRUE) res11 = optim(pars,ProfileErr,allpars=pars,times=t,data=data,coef=ncoefs,lik=lik,proc=proc,hessian=T, in.meth='nlminb',control.in=control.in,control=control.out,gr=ProfileDP,method="BFGS") g = ProfileDP(res11$par,res11$par,t,data,ncoefs,lik,proc,sum=FALSE) gg = apply(g,2,sum) H = 0*res11$hess for(i in 1:length(pars)){ tpars = res11$par tpars[i] = tpars[i] + 1e-4 tf = ProfileErr(tpars,tpars,t,data,ncoefs,lik,proc,in.meth="nlminb",control.in=control.in) tg = ProfileDP(tpars,tpars,t,data,ncoefs,lik,proc,sum=TRUE) H[,i] = (tg-gg)*1e4 } C11 = NeweyWest.Var(H,g,5) res12 = nlminb(pars,ProfileErr,allpars=pars,times=t,data=data,coef=ncoefs,lik=lik,proc=proc, in.meth='nlminb',control.in=control.in,control=control.out,gr=ProfileDP) proc2more = make.findif.ode() proc2more$more = list() proc2more$more$fn = fhn.fun proc2more$names = varnames proc2more$parnames = parnames proc2more$more$eps = 1e-6 proc2more$weights = qwts proc2more$qpts = qpts proc2 = make.SSEproc() proc2$more = proc2more proc2$bvals = list(bvals=eval.basis(procmore$qpts,bbasis,0), dbvals = eval.basis(procmore$qpts,bbasis,1)) res13 = Profile.GausNewt(pars,t,data,ncoefs,lik,proc2,in.meth='nlminb',control.in) res14 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc2,in.meth,control.in), data = list(times=t,data=data,coefs=ncoefs,lik=lik,proc=proc, in.meth='nlminb',control.in=control.in), start = list(pars=spars),trace=TRUE) data2 = data data2[,2] = NA res15 = Profile.GausNewt(pars,t,data2,ncoefs,lik,proc,in.meth='nlminb',control.in) res16 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc2,in.meth,control.in), data = list(times=t,data=data2,coefs=ncoefs,lik=lik,proc=proc, in.meth='nlminb',control.in=control.in), start = list(pars=spars),trace=TRUE) source('genlin.R') lik2more = make.genlin() lik2more$more = list() lik2more$weights = weights[,1] lik2more$more = list() lik2more$more$mat = matrix(c(1,0),1,2) lik2more$more$sub = matrix(0,0,3) lik2 = lik; lik2$more = lik2more; data3 = as.matrix(data[,1],nrow(data),1) res17 = Profile.GausNewt(pars,t,data3,ncoefs,lik2,proc,in.meth='house',control.in) lik3more = lik2more lik3more$more$mat = matrix(0,1,2) lik3more$more$sub = matrix(c(1,1,4,1,2,5),2,3,byrow=T) lik3 = lik2 lik3$more = lik3more proc2 = proc proc2$more$parnames = c(proc$more$parnames,'l1','l2') pars2 = c(pars,1,0) names(pars2) = proc2$more$parnames res18 = Profile.GausNewt(pars2,t,data3,ncoefs,lik3,proc2,in.meth='nlminb',control.in) res19 = optim(pars2,ProfileErr,allpars=pars2,times=t,data=data3,ncoefs,lik=lik3,proc=proc2, in.meth='nlminb',control.in=control.in,control=control.out,gr=ProfileDP,method="BFGS") res20 = nlminb(pars2,ProfileErr,allpars=pars2,times=t,data=data3,coef=ncoefs,lik=lik3,proc=proc2, in.meth='nlminb',control.in=control.in,control=control.out,gr=ProfileDP) f = ProfileErr(res20$par,res20$par,t,data3,ncoefs,lik3,proc2,in.meth="nlminb",control.in=control.in) g = ProfileDP(res20$par,res20$par,t,data3,ncoefs,lik3,proc2,sum=FALSE) gg = apply(g,2,sum) H = matrix(0,5,5) for(i in 1:5){ tpars = res20$par tpars[i] = tpars[i] + 1e-4 tf = ProfileErr(tpars,tpars,t,data3,ncoefs,lik3,proc2,in.meth="nlminb",control.in=control.in) tg = ProfileDP(tpars,tpars,t,data3,ncoefs,lik3,proc2,sum=TRUE) H[,i] = (tg-gg)*1e4 } C20 = NeweyWest.Var(0.5*(H+t(H)),g,5) res21 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc,in.meth,control.in), data = list(times=t,data=data3,coefs=ncoefs,lik=lik3,proc=proc2, in.meth='nlminb',control.in=control.in), start = list(pars=pars2),trace=TRUE) ff = ProfileSSE(res20$par,t,data3,ncoefs,lik3,proc2,in.meth="nlminb",control.in) res22 = maxNR(ProfileErr,start=pars2,allpars=pars2,times=t,data=data3,coef=ncoefs,lik=lik3,proc=proc2, in.meth='nlminb',control.in=control.in,sgn=-1,grad=ProfileDP,print.level=2,iterlim=100) x02 = c(1,-1) names(x02)= c('V','R') y2 = lsoda(x02,times=t,func=fhn.fun.ode,pars) y2 = y2[,2:3] data2 = y2 + matrix(rnorm(802),401,2) replik = lik replik$bvals = diag(rep(1,2))%x%lik$bvals replik$more$weights = rbind(lik$more$weights,lik$more$weights) repproc = proc repproc$bvals = list(bvals = diag(rep(1,2))%x%proc$bvals$bvals, dbvals=diag(rep(1,2))%x%proc$bvals$dbvals) repproc$more$weights = rbind(proc$more$weights,proc$more$weights) reptimes = c(t,t+max(t)) repdata = rbind(data,data2) coefs3 = solve( t(replik$bvals)%*%replik$bvals )%*%( t(replik$bvals)%*%repdata ) res23 = nlminb(coefs3,SplineCoefsErr,gradient=SplineCoefsDC,hessian=SplineCoefsDC2, control=control.out,times=reptimes,data=repdata,lik=replik,proc=repproc,pars=spars) ncoefs = array(res23$par,dim(coefs3)) ProfileEnv = new.env() assign('optcoef',ncoefs,3,ProfileEnv) assign('curcoefs',ncoefs,3,ProfileEnv) res24 = Profile.GausNewt(spars,reptimes,repdata,ncoefs,replik,repproc,in.meth="nlminb",control.in) fd.data2 = array(0,c(nrow(data2),2,2)) fd.data2[,2,] = data2 fd.data2[,1,] = data DEfd2 = data2fd(fd.data2,t,bbasis,fdnames=list(NULL,NULL,c('V','R')) ) res = sse.setup(pars=pars,fd.obj=DEfd2,fn=make.fhn(),lambda=100,times=t) res = smooth.sse(pars=pars,fd.obj=DEfd2,fn=make.fhn(),lambda=100,times=t,data=fd.data2,control.in=control.in) res = profile.sse(fn=make.fhn(),data=fd.data2,times=t,pars=pars,fd.obj=DEfd2,,lambda=100,out.meth='nls', control.in=control.in,control.out=control.out) coefs2 = DEfd2$coefs dimnames(coefs2) = list(NULL,NULL,c('V','R')) res = sse.setup(pars=pars,coefs=coefs,fn=make.fhn(),basisvals=bbasis,lambda=100,times=t) res = smooth.sse(make.fhn(),data,t,pars,coefs,bbasis,lambda=100,control.in=control.in) res = profile.sse(make.fhn(),data,t,pars,coefs,bbasis,lambda=100,out.meth='nls', control.in=control.in,control.out=control.out) res = sse.setup(pars=pars,fd.obj=DEfd,fn=make.fhn(),lambda=100,times=t) res = smooth.sse(pars=pars,fd.obj=DEfd,fn=make.fhn(),lambda=100,times=t,data=fd.data,control.in=control.in) res = profile.sse(fn=make.fhn(),data=fd.data,times=t,pars=pars,fd.obj=DEfd,,lambda=100,out.meth='nls', control.in=control.in,control.out=control.out) f = SplineCoefsErr(coefs,times=t,data=data,lik=lik,proc=proc,pars=spars) g = SplineCoefsDC(coefs,times=t,data=data,lik=lik,proc=proc,pars=spars) h = SplineCoefsDC2(coefs,times=t,data=data,lik=lik,proc=proc,pars=spars) g2 = SplineCoefsDP(coefs,times=t,data=data,lik=lik,proc=proc,pars=spars) h2 = SplineCoefsDCDP(coefs,times=t,data=data,lik=lik,proc=proc,pars=spars) res = optim(coefs,SplineCoefsErr,gr=SplineCoefsDC,hessian=T, method="BFGS",control=control.out, times=t,data=data,lik=lik,proc=proc,pars=spars) res0 = nlminb(coefs+2,SplineCoefsErr,gradient=SplineCoefsDC,hessian=SplineCoefsDC2, control=control.out,times=t,data=data,lik=lik,proc=proc,pars=spars) res2 = maxNR(SplineCoefsErr,start=as.vector(coefs),times=t,data=data,lik=lik,proc=proc,pars=spars,sgn=-1, grad=SplineCoefsDC,hess=SplineCoefsDC2,print.level=2,iterlim=100) res3 = SplineEst.NewtRaph(coefs,t,data,lik,proc,spars) ncoefs = array(res0$par,c(bbasis$nbasis,ncol(data))) ProfileEnv = new.env() assign('optcoef',ncoefs,3,ProfileEnv) assign('curcoefs',ncoefs,3,ProfileEnv) f = ProfileErr(pars,pars,t,data,ncoefs,lik,proc,in.meth="nlminb",control.in=control.in) g = ProfileDP(pars,pars,t,data,ncoefs,lik,proc,sum=FALSE) res4 = ProfileSSE(pars,t,data,ncoefs,lik,proc,in.meth="nlminb",control.in) res5 = Profile.GausNewt(spars,t,data,ncoefs,lik,proc,in.meth="nlminb",control.in) res6 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc,in.meth,control.in), data = list(times=t,data=data,coefs=ncoefs,lik=lik,proc=proc, in.meth="nlminb",control.in=control.in),start = list(pars=pars), trace=TRUE) g = res6$m$gradient() df = diag(res6$m$resid())%*%g C6 = NeweyWest.Var(t(g)%*%g, df[1:401,]+df[402:802,],5) res7 = Profile.GausNewt(spars,t,data,ncoefs,lik,proc,in.meth='house',control.in) res8 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc,in.meth,control.in), data = list(times=t,data=data,coefs=ncoefs,lik=lik,proc=proc, in.meth='house',control.in=control.in), start = list(pars=spars),trace=TRUE) res9 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc,in.meth,control.in), data = list(times=t,data=data,coefs=ncoefs,lik=lik,proc=proc, in.meth='nlminb',control.in=control.in), start = list(pars=spars),trace=TRUE) res10 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc,in.meth,control.in), data = list(times=t,data=data,coefs=ncoefs,lik=lik,proc=proc, in.meth='maxNR',control.in=control.in), start = list(pars=spars),trace=TRUE) res11 = optim(pars,ProfileErr,allpars=pars,times=t,data=data,coef=ncoefs,lik=lik,proc=proc,hessian=T, in.meth='nlminb',control.in=control.in,control=control.out,gr=ProfileDP,method="BFGS") g = ProfileDP(res11$par,res11$par,t,data,ncoefs,lik,proc,sum=FALSE) gg = apply(g,2,sum) H = 0*res11$hess for(i in 1:length(pars)){ tpars = res11$par tpars[i] = tpars[i] + 1e-4 tf = ProfileErr(tpars,tpars,t,data,ncoefs,lik,proc,in.meth="nlminb",control.in=control.in) tg = ProfileDP(tpars,tpars,t,data,ncoefs,lik,proc,sum=TRUE) H[,i] = (tg-gg)*1e4 } C11 = NeweyWest.Var(H,g,5) res12 = nlminb(pars,ProfileErr,allpars=pars,times=t,data=data,coef=ncoefs,lik=lik,proc=proc, in.meth='nlminb',control.in=control.in,control=control.out,gr=ProfileDP) proc2more = make.findif.ode() proc2more$more = list() proc2more$more$fn = fhn.fun proc2more$names = varnames proc2more$parnames = parnames proc2more$more$eps = 1e-6 proc2more$weights = qwts proc2more$qpts = qpts proc2 = make.SSEproc() proc2$more = proc2more proc2$bvals = list(bvals=eval.basis(procmore$qpts,bbasis,0), dbvals = eval.basis(procmore$qpts,bbasis,1)) res13 = Profile.GausNewt(pars,t,data,ncoefs,lik,proc2,in.meth='nlminb',control.in) res14 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc2,in.meth,control.in), data = list(times=t,data=data,coefs=ncoefs,lik=lik,proc=proc, in.meth='nlminb',control.in=control.in), start = list(pars=spars),trace=TRUE) data2 = data data2[,2] = NA res15 = Profile.GausNewt(pars,t,data2,ncoefs,lik,proc,in.meth='nlminb',control.in) res16 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc2,in.meth,control.in), data = list(times=t,data=data2,coefs=ncoefs,lik=lik,proc=proc, in.meth='nlminb',control.in=control.in), start = list(pars=spars),trace=TRUE) source('genlin.R') lik2more = make.genlin() lik2more$more = list() lik2more$weights = weights[,1] lik2more$more = list() lik2more$more$mat = matrix(c(1,0),1,2) lik2more$more$sub = matrix(0,0,3) lik2 = lik; lik2$more = lik2more; data3 = as.matrix(data[,1],nrow(data),1) res17 = Profile.GausNewt(pars,t,data3,ncoefs,lik2,proc,in.meth='house',control.in) lik3more = lik2more lik3more$more$mat = matrix(0,1,2) lik3more$more$sub = matrix(c(1,1,4,1,2,5),2,3,byrow=T) lik3 = lik2 lik3$more = lik3more proc2 = proc proc2$more$parnames = c(proc$more$parnames,'l1','l2') pars2 = c(pars,1,0) names(pars2) = proc2$more$parnames res18 = Profile.GausNewt(pars2,t,data3,ncoefs,lik3,proc2,in.meth='nlminb',control.in) res19 = optim(pars2,ProfileErr,allpars=pars2,times=t,data=data3,ncoefs,lik=lik3,proc=proc2, in.meth='nlminb',control.in=control.in,control=control.out,gr=ProfileDP,method="BFGS") res20 = nlminb(pars2,ProfileErr,allpars=pars2,times=t,data=data3,coef=ncoefs,lik=lik3,proc=proc2, in.meth='nlminb',control.in=control.in,control=control.out,gr=ProfileDP) f = ProfileErr(res20$par,res20$par,t,data3,ncoefs,lik3,proc2,in.meth="nlminb",control.in=control.in) g = ProfileDP(res20$par,res20$par,t,data3,ncoefs,lik3,proc2,sum=FALSE) gg = apply(g,2,sum) H = matrix(0,5,5) for(i in 1:5){ tpars = res20$par tpars[i] = tpars[i] + 1e-4 tf = ProfileErr(tpars,tpars,t,data3,ncoefs,lik3,proc2,in.meth="nlminb",control.in=control.in) tg = ProfileDP(tpars,tpars,t,data3,ncoefs,lik3,proc2,sum=TRUE) H[,i] = (tg-gg)*1e4 } C20 = NeweyWest.Var(0.5*(H+t(H)),g,5) res21 = nls(~ProfileSSE(pars,times,data,coefs,lik,proc,in.meth,control.in), data = list(times=t,data=data3,coefs=ncoefs,lik=lik3,proc=proc2, in.meth='nlminb',control.in=control.in), start = list(pars=pars2),trace=TRUE) ff = ProfileSSE(res20$par,t,data3,ncoefs,lik3,proc2,in.meth="nlminb",control.in) res22 = maxNR(ProfileErr,start=pars2,allpars=pars2,times=t,data=data3,coef=ncoefs,lik=lik3,proc=proc2, in.meth='nlminb',control.in=control.in,sgn=-1,grad=ProfileDP,print.level=2,iterlim=100) x02 = c(1,-1) names(x02)= c('V','R') y2 = lsoda(x02,times=t,func=fhn.fun.ode,pars) y2 = y2[,2:3] data2 = y2 + matrix(rnorm(802),401,2) replik = lik replik$bvals = diag(rep(1,2))%x%lik$bvals replik$more$weights = rbind(lik$more$weights,lik$more$weights) repproc = proc repproc$bvals = list(bvals = diag(rep(1,2))%x%proc$bvals$bvals, dbvals=diag(rep(1,2))%x%proc$bvals$dbvals) repproc$more$weights = rbind(proc$more$weights,proc$more$weights) reptimes = c(t,t+max(t)) repdata = rbind(data,data2) coefs3 = solve( t(replik$bvals)%*%replik$bvals )%*%( t(replik$bvals)%*%repdata ) res23 = nlminb(coefs3,SplineCoefsErr,gradient=SplineCoefsDC,hessian=SplineCoefsDC2, control=control.out,times=reptimes,data=repdata,lik=replik,proc=repproc,pars=spars) ncoefs = array(res23$par,dim(coefs3)) ProfileEnv = new.env() assign('optcoef',ncoefs,3,ProfileEnv) assign('curcoefs',ncoefs,3,ProfileEnv) res24 = Profile.GausNewt(spars,reptimes,repdata,ncoefs,replik,repproc,in.meth="nlminb",control.in) fd.data2 = array(0,c(nrow(data2),2,2)) fd.data2[,2,] = data2 fd.data2[,1,] = data DEfd2 = data2fd(fd.data2,t,bbasis,fdnames=list(NULL,NULL,c('V','R')) ) res = sse.setup(pars=pars,fd.obj=DEfd2,fn=make.fhn(),lambda=lambda,times=t) res = smooth.sse(pars=pars,fd.obj=DEfd2,fn=make.fhn(),lambda=lambda,times=t,data=fd.data2,control.in=control.in,in.meth='house') res = profile.sse(fn=make.fhn(),data=fd.data2,times=t,pars=pars,fd.obj=DEfd2,,lambda=lambda,out.meth='nls', control.in=control.in,control.out=control.out) coefs2 = DEfd2$coefs dimnames(coefs2) = list(NULL,NULL,c('V','R')) res = sse.setup(pars=pars,coefs=coefs2,fn=make.fhn(),basisvals=bbasis,lambda=10000,times=t) res = smooth.sse(fn=make.fhn(),data=fd.data2,times=t,pars=pars,coefs=coefs2,basisvals=bbasis, lambda=10000,control.in=control.in) res = profile.sse(fn=make.fhn(),data=fd.data2,times=t,pars=pars,coefs=coefs2,basisvals=bbasis, lambda=1e8,out.meth='nls',control.in=control.in,control.out=control.out,in.meth='house')
context("phylomatic_names") mynames <- c("Poa annua", "Salix goodingii", "Helianthus annuus") test_that("phylomatic_names - rsubmit works", { skip_on_cran() skip_on_ci() nms <- suppressMessages(phylomatic_names(mynames, format = 'rsubmit')) expect_is(nms, "character") expect_true(grepl("\\%", nms[1])) expect_equal(strsplit(nms[1], "\\%")[[1]][1], "poaceae") }) test_that("phylomatic_names - isubmit (default) works", { skip_on_cran() skip_on_ci() nms <- suppressMessages(phylomatic_names(taxa = mynames, format = 'isubmit')) expect_is(nms, "character") expect_false(grepl("\\%", nms[1])) expect_true(grepl("\\/", nms[1])) expect_equal(strsplit(nms[1], "\\/")[[1]][1], "poaceae") }) test_that("phylomatic_names - db=apg works", { skip_on_cran() skip_on_ci() nms <- suppressMessages(phylomatic_names(mynames, db = "apg")) expect_is(nms, "character") expect_false(grepl("\\%", nms[1])) expect_true(grepl("\\/", nms[1])) expect_equal(strsplit(nms[1], "\\/")[[1]][1], "poaceae") }) test_that("phylomatic fails as expected", { skip_on_cran() skip_on_ci() expect_error(phylomatic_names(), "argument \"taxa\" is missing") expect_error(phylomatic_names(mynames, format = "asdfadf"), "'arg' should be one of") expect_error(phylomatic_names(mynames, db = "things"), "'arg' should be one of") }) test_that("phylomatic_names behaves as expected if no Entrez env var set", { skip_on_cran() skip_on_ci() myname <- "Salix goodingii" mynames <- c("Salix goodingii", "Poa annua") expect_silent(phylomatic_names(myname)) env_var <- Sys.getenv("ENTREZ_KEY") Sys.unsetenv("ENTREZ_KEY") res <- conditionz::capture_message(phylomatic_names(mynames)) expect_equal(length(res$text), 1) Sys.setenv("ENTREZ_KEY" = env_var) })
garchFitControl <- function( llh = c("filter", "internal", "testing"), nlminb.eval.max = 2000, nlminb.iter.max = 1500, nlminb.abs.tol = 1.0e-20, nlminb.rel.tol = 1.0e-14, nlminb.x.tol = 1.0e-14, nlminb.step.min = 2.2e-14, nlminb.scale = 1, nlminb.fscale = FALSE, nlminb.xscale = FALSE, sqp.mit = 200, sqp.mfv = 500, sqp.met = 2, sqp.mec = 2, sqp.mer = 1, sqp.mes = 4, sqp.xmax = 1.0e3, sqp.tolx = 1.0e-16, sqp.tolc = 1.0e-6, sqp.tolg = 1.0e-6, sqp.told = 1.0e-6, sqp.tols = 1.0e-4, sqp.rpf = 1.0e-4, lbfgsb.REPORT = 10, lbfgsb.lmm = 20, lbfgsb.pgtol = 1e-14, lbfgsb.factr = 1, lbfgsb.fnscale = FALSE, lbfgsb.parscale = FALSE, nm.ndeps = 1e-14, nm.maxit = 10000, nm.abstol = 1e-14, nm.reltol = 1e-14, nm.alpha = 1.0, nm.beta = 0.5, nm.gamma = 2.0, nm.fnscale = FALSE, nm.parscale = FALSE) { control <- list( llh = llh, nlminb.eval.max = nlminb.eval.max, nlminb.iter.max = nlminb.iter.max, nlminb.abs.tol = nlminb.abs.tol, nlminb.rel.tol = nlminb.rel.tol, nlminb.x.tol = nlminb.x.tol, nlminb.step.min = nlminb.step.min, nlminb.scale = nlminb.scale, nlminb.fscale = nlminb.fscale, nlminb.xscale = nlminb.xscale, sqp.mit = sqp.mit, sqp.mfv = sqp.mfv, sqp.met = sqp.met, sqp.mec = sqp.mec, sqp.mer = sqp.mer, sqp.mes = sqp.mes, sqp.xmax = sqp.xmax, sqp.tolx = sqp.tolx, sqp.tolc = sqp.tolc, sqp.tolg = sqp.tolg, sqp.told = sqp.told, sqp.tols = sqp.tols, sqp.rpf = sqp.rpf, lbfgsb.REPORT = lbfgsb.REPORT, lbfgsb.lmm = lbfgsb.lmm, lbfgsb.pgtol = lbfgsb.pgtol, lbfgsb.factr = lbfgsb.factr, lbfgsb.fnscale = lbfgsb.fnscale, lbfgsb.parscale = lbfgsb.parscale, nm.ndeps = nm.ndeps, nm.maxit = nm.maxit, nm.abstol = nm.abstol, nm.reltol = nm.reltol, nm.alpha = nm.alpha, nm.beta = nm.beta, nm.gamma = nm.gamma, nm.fnscale = nm.fnscale, nm.parscale = nm.parscale ) control }
library(RoughSets) data(RoughSetData) decision.table <- RoughSetData$hiring.dt res.1 <- FS.greedy.heuristic.reduct.RST(decision.table) print(res.1) new.decTable <- SF.applyDecTable(decision.table, res.1) print(new.decTable)
genSaveTSRData<-function(src,AppRoot=NULL,ts.name="TS.Name",startDate=NULL,endDate=NULL,dextent=FALSE,recursive=FALSE){ src<-pathWinLx(src) if(!is.null(AppRoot)){AppRoot<-pathWinLx(AppRoot)} flist<-list.files(src,full.names = TRUE,pattern="\\.tif$",recursive=recursive) allDates<-genGetDates(flist) if(!is.null(startDate)){ flist<-flist[allDates>startDate] allDates<-allDates[allDates>startDate] } if(!is.null(startDate)){ flist<-flist[allDates<endDate] allDates<-allDates[allDates<endDate] } if(dextent){ imgs<-lapply(flist,raster) rstack<-NULL for(result in imgs){ if(is.null(rstack)){ rstack<-result }else{ result<-extend(result,rstack) rstack<-extend(rstack,result) rstack<-addLayer(rstack,result) } } assign(ts.name,readAll(rstack)) }else{ rstack<-readAll(stack(flist)) assign(ts.name,rstack) } if(!is.null(AppRoot)){ save(list=c(ts.name), file = paste0(AppRoot,"/",ts.name,".RData")) message(paste0("The time series of images in ",src," have been saved as RData.\nYou can find the RDAta in: ",paste0(AppRoot,"/",ts.name,".RData"))) }else{ return(rstack) } }
test_that("constructor has sensible defaults", { first <- step_first(data.table(x = 1), "DT") step <- step_mutate(first) expect_s3_class(step, "dtplyr_step_mutate") expect_equal(step$parent, first) expect_equal(step$vars, "x") expect_equal(step$groups, character()) expect_equal(step$new_vars, list()) }) test_that("need to copy when there's a mutate", { dt <- lazy_dt(data.table(x = 1)) expect_false(dt %>% .$needs_copy) expect_false(dt %>% filter(x == 1) %>% .$needs_copy) expect_false(dt %>% head() %>% .$needs_copy) expect_true(dt %>% mutate(y = 1) %>% .$needs_copy) expect_true(dt %>% mutate(y = 1) %>% filter(x == 1) %>% .$needs_copy) expect_true(dt %>% mutate(y = 1) %>% head() %>% .$needs_copy) }) test_that("unless there's already an implicit copy", { dt <- lazy_dt(data.table(x = 1)) expect_true(dt %>% filter(x == 1) %>% .$implicit_copy) expect_false(dt %>% filter(x == 1) %>% mutate(y = 1) %>% .$needs_copy) expect_true(dt %>% head() %>% .$implicit_copy) expect_false(dt %>% head() %>% mutate(y = 1) %>% .$needs_copy) }) test_that("generates single calls as expect", { dt <- lazy_dt(data.table(x = 1), "DT") expect_equal( dt %>% mutate(x2 = x * 2) %>% show_query(), expr(copy(DT)[, `:=`(x2 = x * 2)]) ) expect_equal( dt %>% group_by(x) %>% mutate(x2 = x * 2) %>% show_query(), expr(copy(DT)[, `:=`(x2 = x * 2), by = .(x)]) ) expect_equal( dt %>% transmute(x2 = x * 2) %>% show_query(), expr(DT[, .(x2 = x * 2)]) ) }) test_that("mutate generates compound expression if needed", { dt <- lazy_dt(data.table(x = 1, y = 2), "DT") expect_equal( dt %>% mutate(x2 = x * 2, x4 = x2 * 2) %>% show_query(), expr(copy(DT)[, c("x2", "x4") := { x2 <- x * 2 x4 <- x2 * 2 .(x2, x4) }]) ) }) test_that("allows multiple assignment to the same variable", { dt <- lazy_dt(data.table(x = 1, y = 2), "DT") expect_equal( dt %>% mutate(x = x * 2, x = x * 2) %>% show_query(), expr(copy(DT)[, c("x") := { x <- x * 2 x <- x * 2 .(x) }]) ) }) test_that("can use across", { dt <- lazy_dt(data.table(x = 1, y = 2), "DT") expect_equal( dt %>% mutate(across(everything(), ~ . + 1)) %>% show_query(), expr(copy(DT)[, `:=`(x = x + 1, y = y + 1)]) ) expect_equal( dt %>% mutate(across(.fns = ~ . + 1)) %>% show_query(), expr(copy(DT)[, `:=`(x = x + 1, y = y + 1)]) ) }) test_that("vars set correctly", { dt <- lazy_dt(data.frame(x = 1:3, y = 1:3)) expect_equal(dt %>% mutate(z = 1) %>% .$vars, c("x", "y", "z")) expect_equal(dt %>% mutate(x = NULL, z = 1) %>% .$vars, c("y", "z")) }) test_that("emtpy mutate returns input", { dt <- lazy_dt(data.frame(x = 1)) expect_equal(mutate(dt), dt) expect_equal(mutate(dt, !!!list()), dt) }) test_that("can use .before and .after to control column position", { dt <- lazy_dt(data.frame(x = 1, y = 2)) expect_named( mutate(dt, z = 1) %>% as_tibble(), c("x", "y", "z") ) expect_named( mutate(dt, z = 1, .before = x) %>% as_tibble(), c("z", "x", "y") ) expect_named( mutate(dt, z = 1, .after = x) %>% as_tibble(), c("x", "z", "y") ) expect_named( mutate(dt, x = 1, .after = y) %>% as_tibble(), c("x", "y") ) })
to.igraph <- function(g) { net.ig <- igraph::graph_from_adj_list(g) net.ig }
context("OSDquery() -- requires internet connection") test_that("OSDquery() works", { skip_if_offline() skip_on_cran() res <- suppressMessages(OSDquery(geog_assoc_soils = 'pardee')) expect_true(inherits(res, 'data.frame')) res <- suppressMessages(OSDquery(everything = 'floodplain', mlra = '18')) expect_true(inherits(res, 'data.frame')) }) test_that("OSDquery() returns NULL with bogus query", { skip_if_offline() skip_on_cran() res <- suppressMessages(OSDquery(geog_assoc_soils = 'XXXXXX')) expect_null(res) })
setMethod("show","NpdeData", function(object) { cat("Object of class NpdeData\n") if(length([email protected])==0) cat(" no data\n") else { st1<-paste([email protected]," ~ ",paste([email protected],collapse=" + ")," | ", [email protected],sep="") cat(" Structured data:",st1,"\n") if(length([email protected])>0) cat(" Covariates:",[email protected],"\n") cat("This object has the following components:\n") cat(" data: data\n") cat(" with",object@N,"subjects\n") cat(" ",[email protected],"observations\n") cat("The data has the following components\n") cat(" X:",[email protected],paste("(",object@units$x,")",sep=""),"\n") cat(" Y:",[email protected],paste("(",object@units$y,")",sep=""),"\n") if(length([email protected])>0) cat(" individual model predictions:", [email protected],"\n") if(length([email protected])>0) cat(" missing data:",[email protected]," (1=missing)\n") if(length([email protected])>0) cat(" censored data:",[email protected]," (1=censored)\n") if(length(object@loq)>0) cat(" LOQ: ",object@loq,"\n") } } ) setMethod("show","NpdeSimData", function(object) { print(object) } ) setMethod("read", signature="NpdeData", function(object, dat, detect=TRUE,verbose=FALSE, ...) { if(!is.na(as.integer([email protected]))) { [email protected]<-colnames(dat)[as.integer([email protected])] } if(is.na([email protected]) || [email protected]=="") { if(!detect) { if(verbose) cat("Missing ID column and automatic detection is OFF. Please provide a valid name for the ID column\n") return("Creation of npdeData failed") } if(verbose) cat("Missing ID column, attempting to detect it\n") [email protected]<-"" i1<-match("id",tolower(colnames(dat))) if(length(i1)==0 | is.na(i1)) { i1<-c(match(c("subject","sujet","group"),tolower(colnames(dat)))) } if(length(i1)>0) { [email protected]<-colnames(dat)[i1[1]] if(verbose) cat(" no name for the group variable (ID) given, will use column --",[email protected],"-- in the dataset.\n") } } if([email protected]=="" | is.na(match([email protected],colnames(dat)))) { if(verbose) cat("Please provide a name for the ID column.\n") return("Creation of npdeData failed") } i1<-as.integer([email protected][!is.na(as.integer([email protected]))]) if(length(i1)>0) { [email protected][!is.na(as.integer([email protected]))]<- colnames(dat)[i1] } if(is.na([email protected]) | length([email protected])==0 | (length([email protected])==1 & [email protected][1]=="")) { if(!detect) { if(verbose) cat("Missing X column and automatic detection is OFF. Please provide a valid name for the column with the predictor.\n") return("Creation of npdeData failed") } if(verbose) cat("Missing predictor column, attempting to detect it\n") [email protected]<-"" i1<-c(match(c("xobs","time","temps","tps","tim","x","dose"), tolower(colnames(dat)))) i1<-i1[!is.na(i1)] if(length(i1)>0) { [email protected]<-colnames(dat)[i1][1] if(verbose) cat(" no name for the predictor variable given, will use column(s) --",[email protected],"-- in the dataset.\n") } } id1<-match([email protected],colnames(dat),nomatch=0) if(length(id1[id1==0])>0) { if(verbose) cat(" cannot find column(s) --",[email protected][id1==0],"-- dropping them from the data.\n") } xnam<[email protected][id1>0] if(length(xnam)==0) [email protected]<-"" else [email protected]<-xnam if(length(xnam)==0) { if(verbose) cat("Please provide at least one predictor.\n") return("Creation of npdeData failed: missing predictor name") } if(!is.na(as.integer([email protected]))) { [email protected]<-colnames(dat)[as.integer([email protected])] } if(is.na([email protected]) || [email protected]=="") { if(!detect) { if(verbose) cat("Missing response column and automatic detection is OFF. Please provide a valid name for the column with the response.\n") return("Creation of npdeData failed: missing response column") } if(verbose) cat("Missing response column, attempting to detect it\n") [email protected]<-"" i1<-match("y",tolower(colnames(dat))) if(length(i1)==0 | is.na(i1)) { i1<-c( match(c("yobs","resp","conc"),tolower(colnames(dat))), grep("response",tolower(colnames(dat)),fixed=TRUE),grep("concentration", tolower(colnames(dat)),fixed=TRUE)) i1<-i1[!is.na(i1)] } if(length(i1)>0) { [email protected]<-colnames(dat)[i1[1]] if(verbose) cat(" no name for the response variable given, will use column --",[email protected],"-- in the dataset.\n") } } if(is.na([email protected])) [email protected]<-"" if([email protected]=="" | is.na(match([email protected],colnames(dat)))) { if(verbose) cat("Please provide a name for the response column.\n") return("Creation of npdeData failed: no response name") } detect.ipred<-FALSE if(length([email protected])>0 && !is.na(as.integer([email protected]))) [email protected]<-colnames(dat)[as.integer([email protected])] if(length([email protected])>0 && match([email protected],colnames(dat),nomatch=0)==0) { if(detect & verbose) cat("Can't find a column named",[email protected],"in the dataset for individual predictions, will attempt automatic detection.\n") [email protected]<-character() } if(length([email protected])==0 || is.na([email protected])) detect.ipred<-TRUE if(detect.ipred) { i1<-c(grep("ipred",tolower(colnames(dat)),fixed=T)) if(length(i1)>0) { [email protected]<-colnames(dat)[i1[1]] if(detect.ipred & verbose) cat(" assuming that individual predictions are given in column --",[email protected],"-- in the dataset (to ignore this column, add the argument detect=FALSE in the call to npdeData()).\n") } } detect.cens<-FALSE if(length([email protected])>0 && !is.na(as.integer([email protected]))) [email protected]<-colnames(dat)[as.integer([email protected])] if(length([email protected])>0 && match([email protected],colnames(dat),nomatch=0)==0) { if(detect & verbose) cat("Can't find a column named",[email protected],"in the dataset containing censoring, will attempt automatic detection.\n") [email protected]<-character() } if(length([email protected])==0 || is.na([email protected])) detect.cens<-TRUE if(detect.cens) { i1<-c(grep("cens",tolower(colnames(dat)),fixed=T)) if(length(i1)>0) { [email protected]<-colnames(dat)[i1[1]] if(detect.cens & verbose) cat(" assuming that censoring information is given in column --",[email protected],"-- in the dataset (to ignore this column, add the argument detect=FALSE in the call to npdeData()).\n") } } if(length([email protected])>0) { if(!isTRUE(all.equal(sort(unique(dat[,[email protected]]), na.last=TRUE),as.integer(c(0,1))))) { if(verbose) cat("The column with censoring information should only contain 0 and 1s.\n") [email protected]<-character() }} detect.miss<-FALSE if(length([email protected])>0 && !is.na(as.integer([email protected]))) [email protected]<-colnames(dat)[as.integer([email protected])] if(length([email protected])>0 && match([email protected],colnames(dat),nomatch=0)==0) { if(detect & verbose) cat("Can't find a column named",[email protected],"in the dataset containing missing data status, will attempt automatic detection.\n") [email protected]<-character() } if(length([email protected])==0 || is.na([email protected])) detect.miss<-TRUE if(detect.miss) { i1<-c(grep("mdv",tolower(colnames(dat)),fixed=T), grep("miss",tolower(colnames(dat)),fixed=T)) if(length(i1)>0) { [email protected]<-colnames(dat)[i1[1]] if(detect.miss & verbose) cat(" assuming that column --",[email protected],"-- in the dataset contains missing data information (to ignore this column, add the argument detect=FALSE in the call to npdeData()).\n") } } if(length([email protected])>0) { if(!isTRUE(all.equal(sort(unique(dat[,[email protected]]), na.last=TRUE),as.integer(c(0,1)))) & !isTRUE(all.equal(sort(unique(dat[,[email protected]]), na.last=TRUE),as.integer(c(0)))) & !isTRUE(all.equal(sort(unique(dat[,[email protected]]), na.last=TRUE),as.integer(c(1))))) { if(verbose) cat("The column with information about missing data should only contain 0 and 1s.\n") [email protected]<-character() }} if(length([email protected])>0 & [email protected][1]!="") { is.int <- which(!is.na(as.integer([email protected]))) is.int <- is.int[as.integer([email protected][is.int])<=dim(dat)[2]] [email protected][is.int] <- colnames(dat)[as.integer([email protected][is.int])] nam2 <- colnames(dat)[match([email protected],colnames(dat))] if(sum(is.na(nam2))>0 & verbose) cat("Covariates not found:","-",paste([email protected][is.na(nam2)],collapse=" - "),"-\n") [email protected] <- [email protected][!is.na(nam2)] object@units$covariates <- object@units$covariates[!is.na(nam2)] object@units$covariates<-object@units$covariates[!duplicated([email protected])] [email protected]<[email protected][!duplicated([email protected])] } if(nchar([email protected])*length([email protected])* nchar([email protected])<=0) { stop("Please check the structure of the data file and provide information concerning which columns specify the group structure (ID), the predictors (eg dose, time) and the response (eg Y, conc). See documentation for automatic recognition of column names for these elements.\n") } all.names<-c([email protected],[email protected],[email protected], [email protected],[email protected],[email protected],[email protected]) tab<-dat[,all.names] id<-tab[,[email protected]] object@N<-length(unique(id)) nind.obs.full<-tapply(id,id,length) nind.obs.full<-nind.obs.full[match(unique(id),names(nind.obs.full))] tab<-data.frame(index=rep(1:object@N,times=nind.obs.full),tab) if(length([email protected])>0) mdv<-tab[,[email protected]] else { mdv<-rep(0,length(id)) [email protected]<-"mdv" } mdv[is.na(tab[,[email protected]])]<-1 tab[,[email protected]]<-mdv object@data<-tab object@ind<-which(mdv==0) icens<-numeric() if(length([email protected])>0) { icens<-which(mdv==0 & dat[,[email protected]]==1) } object@icens<-icens [email protected]<-(mdv==0) if(length([email protected])>0 && sum(is.na(object@data[[email protected],[email protected]]))>0) { tab<-object@data for(icov in [email protected]) { for(i in 2:dim(tab)) { if(is.na(tab[i,icov])) tab[i,icov]<-tab[(i-1),icov] } } object@data<-tab } tb1<-tab[tab[,[email protected]]==0,] id1<-tb1[,1] [email protected]<-dim(tb1)[1] nind.obs<-tapply(id1,id1,length) nind.obs<-nind.obs[match(unique(id1),names(nind.obs))] [email protected]<-c(nind.obs) validObject(object) return(object) } ) setMethod("read", signature="NpdeSimData", function(object, dat, detect=FALSE,verbose=FALSE, ...) { if(detect) { dat1<-dat[,c("idsim","xsim","ysim")] if(dim(dat1)[2] != 3) { return("Creation of NpdeSimData object failed: could not find columns idsim, xsim, ysim\n") } else dat<-dat1 } else { if(verbose) message("Using the first 3 columns of the dataset as idsim, xsim, ysim\n") dat<-dat[,1:3] colnames(dat)<-c("idsim","xsim","ysim") } object@datsim<-dat validObject(object) return(object) } ) npdeData<-function(name.data,header=TRUE,sep="",na.strings=c(".","NA"),name.group, name.predictor, name.response, name.covariates,name.cens,name.miss,name.ipred, units=list(x="",y="",covariates=c()),detect=TRUE,verbose=FALSE) { if(missing(name.data) || length(name.data)==0 || sum(is.na(match(c("character","data.frame"), class(name.data))))==2) { if(verbose) cat("Error in npdeData: please provide the name of the datafile or dataframe (between quotes)\n") return("Creation of NpdeData failed: no data given") } if(is(name.data, "character")) { if(verbose) cat("Reading data from file",name.data,"\n") dat<-try(read.table(name.data, header=header, sep=sep, na.strings=na.strings)) if(class(dat)=="try-error") stop("The file ",name.data," does not exist. Please check the name and path.\n") if(dim(dat)[2]<2) { if(verbose) cat("The dataset contains only one column. To compute npde, we need at least 3 columns, with subject ID, predictor (at least one) and response. \nPlease check the field separator, currently given as:", paste("sep=\"",sep,"\"",sep=""), "\n") return("Creation of npdeData failed") } if(verbose) { cat("These are the first lines of the dataset as read into R. Please check the format of the data is appropriate, if not, modify the na and/or sep items and retry:\n") print(head(dat)) } } else dat<-name.data if(missing(name.group)) name.group<-"" else name.group<-as.character(name.group) if(missing(name.predictor)) name.predictor<-"" else name.predictor<-as.character(name.predictor) if(missing(name.response)) name.response<-"" else name.response<-as.character(name.response) if(missing(name.covariates) || name.covariates[1]==0) name.covariates<-character() else name.covariates<-as.character(name.covariates) if(missing(name.miss) || name.miss==0) name.miss<-character() else name.miss<-as.character(name.miss) if(missing(name.cens) || name.cens==0) name.cens<-character() else name.cens<-as.character(name.cens) if(missing(name.ipred) || name.ipred==0) name.ipred<-character() else name.ipred<-as.character(name.ipred) if(missing(detect)) detect<-TRUE x<-new(Class="NpdeData",name.group=name.group, name.predictor=name.predictor,name.response=name.response, name.covariates=name.covariates,name.cens=name.cens,name.miss=name.miss, name.ipred=name.ipred,units=units) if(detect & verbose) cat("Automatic detection of variables is ON. The program will attempt to detect both mandatory variables (ID, X, Y) and optional variables (IPRED, MDV, CENS) when they are not specifically given or when the user-specified names are not found in the dataset, by looking in the names of the columns (to override this behaviour, please use argument detect=FALSE in the call to npdeData().\n") x1<-read(x, dat, detect=detect, verbose=verbose) if( is(x1, "NpdeData")) { if(length(x1["name.cens"])==0) loq<-as.numeric(NA) else { if(sum(x1["data"][x1["data"][,x1["name.miss"]]==0,x1["name.cens"]])>0) { yloq<-x1["data"][x1["data"][,x1["name.cens"]]==1 & x1["data"][,x1["name.miss"]]==0,x1["name.response"]] if(length(unique(yloq))==1) { loq<-unique(yloq) if(verbose) cat("Same LOQ for all missing data, loq=",loq,"\n") } else { loq<-min(unique(yloq),na.rm=TRUE) if(verbose) cat("There are different LOQ for different observations, setting loq to the lowest value of",loq,"\n") } } } x1["loq"]<-loq if(verbose) { cat("\n\nThe following NpdeData object was successfully created:\n\n") print(x1,nlines=0) } } else x1<-"Creation of NpdeData failed" return(x1) } npdeSimData<-function(npde.data, name.simdata, header=TRUE, sep="", na.strings=c("NA","."), detect=FALSE, verbose=FALSE) { if(missing(npde.data) || !is(npde.data,"NpdeData")) { if(verbose) message(" Error: Missing first argument.\n") return("Creation of NpdeSimData failed: please provide a valid npde.data object") } if(missing(name.simdata) || length(name.simdata)==0 || sum(is.na(match(c("character","data.frame"), class(name.simdata))))==2) { if(verbose) cat("Error in npdeSimData: please provide the name of the datafile or dataframe (between quotes)\n") return("Creation of NpdeSimData failed: no simulated data given") } if(is(name.simdata, "character")) { if(verbose) cat("Reading data from file",name.simdata,"\n") dat<-try(read.table(name.simdata, header=header, sep=sep, na.strings=na.strings)) if(class(dat)=="try-error") stop("The file ",name.simdata," does not exist. Please check the name and path.\n") if(verbose) { cat("These are the first lines of the dataset as read into R. Please check the format of the data is appropriate, if not, modify the na and/or sep items and retry:\n") print(head(dat)) } } else dat<-name.simdata x1<-new(Class="NpdeSimData") x<-read(x1, dat, detect=detect, verbose=verbose) if(sum(npde.data["data"][,npde.data["name.miss"]])>0) { if(verbose) message("There are rows with MDV=1 in the original dataset, the corresponding rows will be removed from the simulated dataset.\n") } nrep<-dim(x@datsim)[1]/dim(npde.data@data)[1] x@nrep<-as.integer(nrep) if(nrep<1000 & verbose) { message("Warning: the number of simulations is ",nrep," which may be too small.\n") message("We advise performing at least 1000 simulations to compute npde.\n") } irsim<-rep(1:nrep,each=dim(npde.data@data)[1]) x@datsim$irsim<-irsim return(x) } print.NpdeData <- function(x,nlines=10,...) { digits<-2;nsmall<-2 cat("Object of class NpdeData\n") cat(" longitudinal data\n") if(length([email protected])>0) { st1<-paste([email protected]," ~ ",paste([email protected],collapse=" + ")," | ", [email protected],sep="") cat(" Structured data:",st1,"\n") cat(" predictor:",[email protected],paste("(",x@units$x,")",sep=""),"\n") if(length([email protected])>0) { vecunit<-paste(" (",x@units$covariates,")",sep="") vecunit[x@units$covariates==""]<-"" cat(" covariates:",paste(paste([email protected],vecunit,sep=""),collapse=", "),"\n") } if(dim(x@data)[1]>0) { if(nlines==0) return() cat("Dataset characteristics:\n") cat(" number of subjects: ",x@N,"\n") cat(" number of non-missing observations:",[email protected],"\n") cat(" average/min/max nb obs:",format(mean([email protected]),digits=digits, nsmall=nsmall), " / ", min([email protected])," / ",max([email protected]),"\n") if(length(x@loq)>0) cat(" LOQ: ",x@loq,"\n") if(nlines==(-1)) { cat("Data:\n") print(x@data) } else { cat("First",nlines,"lines of data:\n") nrowShow <- min (nlines , nrow(x@data)) print(x@data[1:nrowShow,]) } } else message("No data.\n") } else message("Empty object\n") } print.NpdeSimData <- function(x,nlines=10,...) { digits<-2;nsmall<-2 cat("Object of class NpdeSimData\n") cat(" simulated data\n") if(length(x@nrep)>0) { cat(" Number of replications:",x@nrep,"\n") if(dim(x@datsim)[1]>0) { if(nlines==0) return() if(nlines==(-1)) { cat("Data:\n") print(x@datsim) } else { cat("First",nlines,"lines of data:\n") nrowShow <- min (nlines , nrow(x@datsim)) print(x@datsim[1:nrowShow,]) } } else message("No data.\n") } else message("Empty object\n") } showall <- function(object) UseMethod("showall",object) showall.default <- function(object) print(object) showall.NpdeData <- function(object) { digits<-2;nsmall<-2 cat("Object of class NpdeData\n") cat(" longitudinal data\n") if(length(object@N)>0) { st1<-paste([email protected]," ~ ",paste([email protected],collapse=" + ")," | ", [email protected],sep="") cat(" Structured data:",st1,"\n") cat(" subject identifier: ",[email protected],"\n") cat(" predictor: ",[email protected], paste("(",object@units$x,")",sep=""),"\n") cat(" response: ",[email protected],paste("(",object@units$y,")",sep=""),"\n") if(length([email protected])>0) { cat(" covariates:",paste(paste([email protected]," (", object@units$covariates,")",sep=""),collapse=", "),"\n") } cat("This object has the following components:\n") cat(" data: data\n") cat(" with",object@N,"subjects\n") cat(" ",[email protected],"observations\n") cat("The data has the following components\n") cat(" X:",[email protected],"\n") cat(" Y:",[email protected],"\n") if(length([email protected])>0) cat(" individual model predictions:", [email protected],"\n") if(length([email protected])>0) cat(" missing data:",[email protected]," (1=missing)\n") if(length([email protected])>0) cat(" censored data:",[email protected]," (1=censored)\n") if(length(object@loq)>0) cat(" LOQ: ",object@loq,"\n") cat("Dataset characteristics:\n") cat(" number of subjects: ",object@N,"\n") if(object@N>0) { cat(" number of non-missing observations:",[email protected],"\n") cat(" average/min/max nb obs:",format(mean([email protected]),digits=digits, nsmall=nsmall), " / ", min([email protected])," / ",max([email protected]),"\n") } if(dim(object@data)[1]>0) { cat("First lines of data:\n") nrowShow <- min (10 , nrow(object@data)) print(object@data[1:nrowShow,]) } else message("No data.\n") } else message("Empty object\n") } summary.NpdeData <- function(object, print=TRUE, ...) { if(length(object@data)==0) { message("Object of class NpdeData, empty.\n") return() } res<-list(N=object@N,data=object@data, [email protected],[email protected]) if(length(object@loq)>0) res$loq<-object@loq invisible(res) } subset.NpdeData<-function (x, subset, ...) { if (missing(subset)) return(x) else { e <- substitute(subset) xdat<-x["data"] r <- eval(e, xdat, parent.frame()) if (!is.logical(r)) stop("'subset' must evaluate to logical") r <- r & !is.na(r) } x1<-x x1["data"]<-x["data"][r,,drop=FALSE] if(length(x1["not.miss"])>0) { x1["not.miss"]<-x["not.miss"][r] x1["icens"]<-which(!x1["not.miss"]) } id<-x1["data"][,x1["name.group"]] x1["N"]<-length(unique(id)) nind.obs<-tapply(id,id,length) nind.obs<-c(nind.obs[match(unique(id),names(nind.obs))]) x1["nind.obs"]<-nind.obs x1["ntot.obs"]<-length(id) x1["ind"]<-rep(1:x1["N"],times=nind.obs) return(x1) }
pclm.fit <- function(x, y, nlast, offset, out.step, verbose, lambda, kr, deg, diff, max.iter, tol, type){ if (verbose) { pb = startpb(0, 100) setpb(pb, 50) cat(" Ungrouping data ") } CM <- build_C_matrix(x, y, nlast, offset, out.step, type) BM <- build_B_spline_basis(CM$gx, CM$gy, kr, deg, diff, type) P <- build_P_matrix(BM$BA, BM$BY, lambda, type) C <- CM$C B <- BM$B y_ <- as.vector(unlist(y)) ny_ <- length(y_) K <- pclm_loop(asSparseMat(C), P, B, y_, max.iter, tol) QmQ <- K$QmQ QmQP <- K$QmQP fit <- as.numeric(K$mu) H <- solve(QmQP, QmQ) trace <- sum(diag(H)) y_[y_ == 0] <- 10^-4 dev <- 2 * sum(y_ * log(y_ / K$muA), na.rm = TRUE) out <- as.list(environment()) return(out) } build_C_matrix <- function(x, y, nlast, offset, out.step, type) { nx <- length(x) gx <- seq(min(x), max(x) + nlast - out.step, by = out.step) gu <- c(diff(x), nlast)/out.step CA <- matrix(0, nrow = nx, ncol = sum(gu), dimnames = list(x, gx)) xr <- c(x[-1], max(x) + nlast) for (j in 1:nx) CA[j, which(gx >= x[j] & gx < xr[j])] <- 1 if (type == "1D") { ny <- length(y) CY <- NULL C <- CA } else { ny <- ncol(y) CY <- diag(1, ncol = ny, nrow = ny) C <- CY %x% CA } gy <- 1:ny if (!is.null(offset)) C <- C %*% diag(as.vector(unlist(offset))) out <- as.list(environment()) return(out) } build_B_spline_basis <- function(X, Y, kr, deg, diff, type) { bsb <- function(Z, kr, deg, diff) { zl <- min(Z) zr <- max(Z) zmin <- zl - 0.01 * (zr - zl) zmax <- zr + 0.01 * (zr - zl) ndx <- trunc(length(Z)/kr) B <- MortSmooth_bbase(x = Z, zmin, zmax, ndx, deg) dg <- diag(ncol(B)) D <- diff(dg, diff = diff) tD <- t(D) %*% D list(B = B, tD = tD, dg = dg) } BA <- bsb(X, kr, deg, diff) BY <- bsb(Y, kr, deg, diff) B <- if (type == "1D") BA$B else BY$B %x% BA$B out <- as.list(environment()) return(out) } build_P_matrix <- function(BA, BY, lambda, type){ L <- sqrt(lambda) if (type == "1D") { P <- L * BA$tD } else { Px <- BY$dg %x% BA$tD Py <- BY$tD %x% BA$dg P <- L[1] * Px + L[2] * Py } return(P) } create.artificial.bin <- function(i, vy = 1, vo = 1.01){ with(i, { x <- c(x, max(x) + nlast) nlast <- out.step fn <- if (is.vector(y)) c else rbind y <- fn(y, vy) if (!is.null(offset)) offset <- fn(offset, vo) out <- list(x = x, y = y, nlast = nlast, offset = offset) return(out) }) } delete.artificial.bin <- function(M){ n <- 1 N <- 1:n f1 <- function(x) { A <- rev(rev(x)[-N]) B <- sum(rev(x)[N] - n) B * (A/sum(A)) + A } f2 <- function(x) { rev(rev(x)[-N]) } L <- !is.matrix(M$fit) M$fit <- with(M, if (L) f1(fit) else apply(fit, 2, FUN = f1)) M$lower <- with(M, if (L) f1(lower) else apply(lower, 2, FUN = f1)) M$upper <- with(M, if (L) f1(upper) else apply(upper, 2, FUN = f1)) M$SE <- with(M, if (L) f1(SE) else apply(SE, 2, FUN = f2)) return(M) } map.bins <- function(x, nlast, out.step) { step <- c(diff(x), nlast) xl <- rev(rev(c(0, cumsum(step)))[-1]) + 1 xr <- xl + step - 1 N <- length(xl) delta <- x[1] - xl[1] bl <- round(xl + delta, 3) br <- c(bl[-1], xr[N] + 1 + delta) dnames <- list(c("left", "right"), rep("", N)) breaks <- matrix(c(bl, br), nrow = 2, byrow = T, dimnames = dnames) loc <- matrix(c(xl, xr), nrow = 2, byrow = T, dimnames = dnames) input <- list(n = N, length = xr - xl + 1, names = paste0("[", bl,",", br, ")"), breaks = breaks, location = loc) output <- NULL if (!is.null(out.step)) { X <- range(breaks) X <- seqlast(X[1], X[2], by = out.step) output <- map.bins(X, NULL, NULL)$input } out <- list(input = input, output = output) return(out) }
print.mark <- function(x,...,input=FALSE) { os=R.Version()$os if(!exists("MarkViewer")) if(os=="mingw32") MarkViewer="notepad" else MarkViewer="pico" model=load.model(x) if(!input) { if(!is.null(model$output)) { if(file.exists(paste(model$output,".out",sep=""))) { if(os=="mingw32") system(paste(shQuote(MarkViewer),paste(model$output,".out",sep="")),invisible=FALSE,wait=FALSE) else system(paste(MarkViewer,paste(model$output,".out",sep="")),wait=FALSE) } else cat(paste("Cannot locate file ",model$output,".out\n",sep="")) }else print.default(model) } else { if(!is.null(model$output)) { if(file.exists(paste(model$output,".inp",sep=""))) { if(os=="mingw32") system(paste(shQuote(MarkViewer),paste(model$output,".inp",sep="")),invisible=FALSE,wait=FALSE) else system(paste(MarkViewer,paste(model$output,".inp",sep="")),wait=FALSE) } else cat(paste("Cannot locate file ",model$output,".inp\n",sep="")) }else print.default(model) } invisible() } print.marklist<-function(x,...) { ncol=dim(x$model.table)[2] if(!is.null(x$model.table)) { if(is.null(x$model.table$chat)) print(x$model.table[,(ncol-5):ncol]) else print(x$model.table[,(ncol-6):ncol]) } else cat("No model.table is available") }
jackstraw_cluster <- function(dat, k, cluster = NULL, centers = NULL, algorithm = function(x, centers) kmeans(x, centers, ...), s = 1, B = 1000, center = TRUE, noise = NULL, covariate = NULL, verbose = FALSE, seed = NULL, ...) { if (is.null(seed)) set.seed(seed) m <- nrow(dat) n <- ncol(dat) if (is.null(cluster) | is.null(centers)) { stop("Supply the original cluster assignments and estimated centers.") } algorithm <- match.fun(algorithm) if (k != length(unique(cluster))) { stop("The input k must equal the number of clusters available.") } if (k != nrow(centers)) { stop("The input k must equal the number of available centers, that are rows of `center`.") } if (length(unique(cluster)) != nrow(centers)) { stop("The number of clusters must equal the number of centers, that are rows of `center`.") } F.obs <- vector("numeric", m) for (i in 1:k) { F.obs[cluster == i] <- FSTAT(dat[cluster == i, , drop = FALSE], LV = t(centers[i, , drop = FALSE]), covariate = covariate)$fstat } if (!is.null(noise)) { noise <- match.fun(noise) message("The distribution for the noise term is specified; performing the parametric jackstraw test.") } if (verbose == TRUE) { cat(paste0("\nComputating null statistics (", B, " total iterations): ")) } F.null <- vector("list", length = k) for (j in 1:B) { if (verbose == TRUE) { cat(paste(j, " ")) } jackstraw.dat <- dat ind <- sample(seq(m), s) if (!is.null(noise)) { jackstraw.dat[ind, ] <- matrix(noise(n * s), nrow = s, ncol = n) } else { jackstraw.dat[ind, ] <- apply(dat[ind, , drop = FALSE], 1, function(x) sample(x, replace = TRUE)) } if(center == TRUE) { jackstraw.dat[ind, ] <- t(scale(t(jackstraw.dat[ind, ]), center = TRUE, scale = FALSE)) } recluster <- algorithm(jackstraw.dat, centers = centers, ...) for (i in 1:k) { ind.i <- intersect(ind, which(recluster$cluster == i)) if (length(ind.i) > 0) { F.null[[i]] <- c(F.null[[i]], as.vector(FSTAT(dat = jackstraw.dat[ind.i, , drop = FALSE], LV = t(recluster$centers[i, , drop = FALSE]), covariate = covariate)$fstat)) } } } p.F <- vector("numeric", m) for (i in 1:k) { if (length(F.null[[i]]) < (B * s/k * 0.1)) { warning(paste0("The number of empirical null statistics for the cluster [", i, "] is [", length(F.null[[i]]), "].")) } p.F[cluster == i] <- empPvals(F.obs[cluster == i], F.null[[i]]) } return(list(call = match.call(), F.obs = F.obs, F.null = F.null, p.F = p.F)) }
SDMXOrganisationSchemes <- function(xmlObj, namespaces){ new("SDMXOrganisationSchemes", SDMX(xmlObj, namespaces), organisationSchemes = organisationSchemes.SDMXOrganisationSchemes(xmlObj, namespaces) ) } organisationSchemes.SDMXOrganisationSchemes <- function(xmlObj, namespaces){ agSchemes <- list() sdmxVersion <- version.SDMXSchema(xmlObj, namespaces) VERSION.21 <- sdmxVersion == "2.1" messageNsString <- "message" if(isRegistryInterfaceEnvelope(xmlObj, FALSE)) messageNsString <- "registry" messageNs <- findNamespace(namespaces, messageNsString) strNs <- findNamespace(namespaces, "structure") if(VERSION.21){ agXML <- getNodeSet(xmlObj,"//mes:Structures/str:OrganisationSchemes/str:AgencyScheme", namespaces = c(mes = as.character(messageNs), str = as.character(strNs))) agSchemes <- lapply(agXML, SDMXAgencyScheme, namespaces) } return(agSchemes) } as.data.frame.SDMXOrganisationSchemes <- function(x, ...){ out <- do.call("rbind.fill", lapply(x@organisationSchemes, function(as){ asf <- data.frame( id = slot(as, "id"), agencyID = slot(as, "agencyID"), version = slot(as, "version"), uri = slot(as, "uri"), urn = slot(as, "urn"), isExternalReference = slot(as, "isExternalReference"), isFinal = slot(as, "isFinal"), validFrom = slot(as, "validFrom"), validTo = slot(as, "validTo"), stringsAsFactors = FALSE ) return(asf) }) ) return(encodeSDMXOutput(out)) } setAs("SDMXOrganisationSchemes", "data.frame", function(from) as.data.frame.SDMXOrganisationSchemes(from))
plot_svg_shapes <- function(svg_list, dgp, as, iter = 1){ params <- svg_list$params shapes <- svg_list$shapes z.index <- svg_list$z.index z_order <- order(z.index) for(lnum in z_order){ shape <- shapes[[lnum]] xyz <- shape$xyz if(length(dim(xyz)) == 2){ if(nrow(xyz) == 1){ citer <- 1 }else if(nrow(xyz) > 1 && nrow(xyz) >= iter){ citer <- iter }else{ next } xyz <- xyz[citer, ] }else{ xyz <- xyz[, , citer] } gparams <- dgp for(pname in names(gparams)){ if(!is.null(shape[[pname]])){ if(length(shape[[pname]]) == 1){ gparams[[pname]] <- shape[[pname]] }else if(length(shape[[pname]]) > 1 && length(shape[[pname]]) >= iter){ gparams[[pname]] <- shape[[pname]][iter] }else{ gparams[[pname]] <- shape[[pname]][(iter-1) %% length(shape[[pname]]) + 1] } } if(pname %in% c('stroke', 'fill')) if(!is.na(gparams[[pname]]) && gparams[[pname]] == 'none') gparams[[pname]] <- 'NA' } if(is.matrix(xyz)){ u1 <- -(params$depth - params$eyez) / (xyz[,3] - params$eyez) xy <- cbind((u1 * xyz[,1])*params$scaling.add + params$shift.add[1], -(u1 * xyz[,2])*params$scaling.add + params$shift.add[2]) }else{ u1 <- -(params$depth - params$eyez) / (xyz[3] - params$eyez) xy1 <- c(u1 * xyz[1], -(u1 * xyz[2]))*params$scaling.add + params$shift.add u2 <- -(params$depth - params$eyez) / (xyz[6] - params$eyez) xy2 <- c(u2 * xyz[4], -(u2 * xyz[5]))*params$scaling.add + params$shift.add } if(shape$type %in% c('arrow', 'line')){ grid.lines(x=c(xy1[1], xy2[1]), y=c(xy1[2], xy2[2]), gp=gpar(col=gparams[['stroke']], lwd=gparams[['stroke-width']], alpha=gparams[['stroke-opacity']]), default.units="native") if(shape$type %in% c('arrow')){ v21 <- c(xyz[4:6]-xyz[1:3]) v12 <- c(xyz[1:3]-xyz[4:6]) v12u <- uvector_svg(v12) c_prod1 <- uvector_svg(cprod_svg(v21, c(0,0,1))) c_prod2 <- uvector_svg(cprod_svg(v21, c_prod1)) if(sum(c_prod2) == 0) c_prod2 <- c(0,1,0) if(abs(c_prod2[1]) > 0.98) c_prod2 <- c(0,1,0) rm1 <- tMatrixEP_svg(c_prod2, shape$a); rm2 <- tMatrixEP_svg(c_prod2, -shape$a); ahl <- shape$l+(abs(v12u[3])^10)*0.6*shape$l -(abs(v12u[1]*v12u[2])/0.5)*0.2*shape$l ahl <- shape$l+(abs(v12u[3])^10)*0.6*shape$l -(abs(v12u[1]*v12u[2])/0.5)*0.2*shape$l ha <- c(rm1 %*% v12u*ahl) + xyz[4:6] hb <- c(rm2 %*% v12u*ahl) + xyz[4:6] hau <- -(params$depth - params$eyez) / (ha[3] - params$eyez); hbu <- -(params$depth - params$eyez) / (hb[3] - params$eyez); ha <- c((hau * ha[1]), -(hau * ha[2]))*params$scaling.add + params$shift.add hb <- c((hbu * hb[1]), -(hbu * hb[2]))*params$scaling.add + params$shift.add grid.lines(x=c(xy2[1], ha[1]), y=c(xy2[2], ha[2]), gp=gpar(col=gparams[['stroke']], lwd=gparams[['stroke-width']], alpha=gparams[['stroke-opacity']]), default.units="native") grid.lines(x=c(xy2[1], hb[1]), y=c(xy2[2], hb[2]), gp=gpar(col=gparams[['stroke']], lwd=gparams[['stroke-width']], alpha=gparams[['stroke-opacity']]), default.units="native") } next } if(shape$type %in% c('point', 'circle')){ grid.circle(x=xy1[1], y=xy1[2], r=gparams[['r']], gp=gpar(col='NA', fill=gparams[['fill']], lwd=0, alpha=gparams[['fill-opacity']]), default.units="native") grid.circle(x=xy1[1], y=xy1[2], r=gparams[['r']], gp=gpar(col=gparams[['stroke']], fill='NA', lwd=gparams[['stroke-width']], alpha=gparams[['stroke-opacity']]), default.units="native") next } if(shape$type %in% c('text')){ text_hjust <- 0 if(shape[['text-anchor']] == "start") text_hjust <- 0 if(shape[['text-anchor']] == "middle") text_hjust <- 0.5 if(shape[['text-anchor']] == "end") text_hjust <- 1 grid.text(label=shape[['value']], x=xy1[1], y=xy1[2], just="bottom", hjust=text_hjust, vjust = NULL, rot = 0, gp=gpar(fontface="plain", fontfamily=gparams[['font-family']], fontsize=max(round(shape[['font-size']]), 1), col=gparams[['fill']], alpha=gparams[['opacity']]), default.units="native") next } if(shape$type %in% c('pathC')){ if(is.null(gparams[['fill']]) || gparams[['fill']] == 'none'){ grid.lines(x=xy[,1], y=xy[,2], gp=gpar(col=gparams[['stroke']], fill='NA', lwd=gparams[['stroke-width']], alpha=gparams[['stroke-opacity']]), default.units="native") }else{ grid.polygon(x=xy[,1], y=xy[,2], gp=gpar(col='NA', fill=gparams[['fill']], lwd=0, alpha=gparams[['fill-opacity']]), default.units="native") grid.polygon(x=xy[,1], y=xy[,2], gp=gpar(col=gparams[['stroke']], fill='NA', lwd=gparams[['stroke-width']], alpha=gparams[['stroke-opacity']]), default.units="native") } } if(shape$type %in% c('path')){ } } }
con.search.D <- function(x, y, n, jlo, jhi, klo, khi,plot) { fjk <- matrix(0, n, n) fxy <- matrix(0, (jhi - jlo + 1), (khi - klo + 1)) jkgrid <- expand.grid(jlo:jhi, klo:khi) res <- data.frame(j = jkgrid[,1], k = jkgrid[,2], k.ll = apply(jkgrid, 1, con.parmsFUN.D, x = x, y = y, n = n)) fxy <- matrix(res$k.ll, nrow = jhi-jlo+1, ncol = khi-klo+1) rownames(fxy) <- jlo:jhi colnames(fxy) <- klo:khi if (plot == "TRUE") { jx<-jlo:jhi ky<-klo:khi persp(jx, ky, fxy, xlab = "j", ylab = "k", zlab = "LL(x,y,j,k)") title("Log-likelihood Surface") } z <- findmax(fxy) jcrit <- z$imax + jlo - 1 kcrit <- z$jmax + klo - 1 list(jhat = jcrit, khat = kcrit, value = max(fxy)) } con.parmsFUN.D <- function(jk, x, y, n){ j = jk[1] k = jk[2] a <- con.parms.D(x,y,n,j,k,1,1,1) nr <- nrow(a$theta) est <- a$theta[nr, ] b<-con.est.D(x[j],x[k],est) s2<-1/b$eta1 t2<-1/b$eta2 u2<-1/b$eta3 return(p.ll.D(n, j, k, s2, t2, u2)) } con.parms.D <- function(x,y,n,j0,k0,e10,e20,e30){ th <- matrix(0,100,7) th[1,1] <- e10 th[1,2] <- e20 th[1,3] <- e30 bc <- beta.calc.D(x,y,n,j0,k0,e10,e20,e30) th[1,4:7] <- bc$B for (iter in 2:100){ m <- iter-1 ec <- eta.calc.D(x,y,n,j0,k0,th[m,4:7]) th[iter,1] <- ec$eta1 th[iter,2] <- ec$eta2 th[iter,3] <- ec$eta3 bc <- beta.calc.D(x,y,n,j0,k0,ec$eta1,ec$eta2,ec$eta3) th[iter,4:7] <- bc$B theta <- th[1:iter,] delta <- abs(th[iter,]-th[m,])/th[m,] if( (delta[1]<.001) & (delta[2]<.001) & (delta[3]<.001) & (delta[4]<.001) & (delta[5]<.001) & (delta[6]<.001) &(delta[7]<.001)) break } list(theta=theta) } con.est.D <- function(xj, xk, est) { eta1 <- est[1] eta2 <- est[2] eta3 <- est[3] a0 <- est[4] a1 <- est[5] b1 <- est[6] c1 <- est[7] b0 <- a0 + (a1 - b1) * xj c0 <- b0 + (b1 - c1) * xk list(eta1 = eta1, eta2 = eta2,eta3 = eta3, a0 = a0, a1 = a1, b0 = b0, b1 = b1, c0 = c0, c1 = c1) } con.vals.D <- function(x, y, n, j, k) { a <- con.parms.D(x, y, n, j, k, 1, 1, 1) nr <- nrow(a$theta) est <- a$theta[nr, ] b <- con.est.D(x[j], x[k], est) eta <- c(b$eta1, b$eta2, b$eta3) beta <- c(b$a0, b$a1, b$b0, b$b1, b$c0, b$c1) tau <- c(x[j], x[k]) list(eta = eta, beta = beta, tau = tau) } p.ll.D <-function(n, j, k, s2, t2, u2){ q1 <- n * log(sqrt(2 * pi)) q2 <- 0.5 * (j) * (1 + log(s2)) q3 <- 0.5 * (k - j) * (1 + log(t2)) q4<-0.5*(n-k)*(1+log(u2)) - (q1 + q2 + q3 + q4) } findmax <-function(a){ maxa<-max(a) imax<- which(a==max(a),arr.ind=TRUE)[1] jmax<-which(a==max(a),arr.ind=TRUE)[2] list(imax = imax, jmax = jmax, value = maxa) } beta.calc.D <- function(x, y, n, j, k, e1, e2,e3) { aa <- wmat.D(x, y, n, j, k, e1, e2, e3) W <- aa$w bb <- rvec.D(x, y, n, j, k, e1, e2, e3) R <- bb$r beta <- solve(W, R) list(B = beta) } eta.calc.D <- function(x, y, n, j, k, theta) { jp1 <- j + 1 kp1 <- k + 1 a0 <- theta[1] a1 <- theta[2] b1 <- theta[3] c1 <- theta[4] b0 <- a0 + (a1 - b1) * x[j] c0 <- b0 + (b1 - c1) * x[k] rss1 <- sum((y[1:j] - a0 - a1 * x[1:j])^2) rss2 <- sum((y[jp1:k] - b0 - b1 * x[jp1:k])^2) rss3 <- sum((y[kp1:n] - c0 - c1 * x[kp1:n])^2) e1 <- j/rss1 e2 <- (k - j)/rss2 e3 <- (n - k)/rss3 list(eta1 = e1, eta2 = e2, eta3 = e3) } wmat.D <- function(x, y, n, j, k, e1, e2, e3) { W <- matrix(0, 4, 4) jp1 <- j + 1 kp1 <- k + 1 W[1, 1] <- e1 * j + e2 * (k - j) + e3 * (n - k) W[1, 2] <- e1 * sum(x[1:j]) + e2 * (k - j) * x[j] + e3 * (n - k) * x[j] W[1, 3] <- e2 * sum(x[jp1:k] - x[j]) + e3 * (n - k) * (x[k] - x[j]) W[1, 4] <- e3 * sum(x[kp1:n] - x[k]) W[2, 2] <- e1 * sum(x[1:j] * x[1:j]) + e2 * (k - j) * x[j] * x[j] + e3 * (n - k) * x[j] * x[j] W[2, 3] <- e2 * x[j] * sum(x[jp1:k] - x[j]) + e3 * (n - k) * x[j] * (x[k] - x[j]) W[2, 4] <- e3 * x[j] * sum(x[kp1:n] - x[k]) W[3, 3] <- e2 * sum((x[jp1:k] - x[j]) * (x[jp1:k] - x[j])) + e3 * (n - k) * (x[k] - x[j]) * (x[k] - x[j]) W[3, 4] <- e3 * (x[k] - x[j]) * sum(x[kp1:n] - x[k]) W[4, 4] <- e3 * sum((x[kp1:n] - x[k]) * (x[kp1:n] - x[k])) W[2, 1] <- W[1, 2] W[3, 1] <- W[1, 3] W[4, 1] <- W[1, 4] W[3, 2] <- W[2, 3] W[4, 2] <- W[2, 4] W[4, 3] <- W[3, 4] list(w = W) } rvec.D <- function(x, y, n, j, k, e1, e2, e3) { R <- array(0, 4) jp1 <- j + 1 kp1 <- k + 1 y1j <- sum(y[1:j]) yjk <- sum(y[jp1:k]) ykn <- sum(y[kp1:n]) xy1j <- sum(x[1:j] * y[1:j]) xyjk <- sum(x[jp1:k] * y[jp1:k]) xykn <- sum(x[kp1:n] * y[kp1:n]) R[1] <- e1 * y1j + e3 * ykn + e2 * yjk R[2] <- e1 * xy1j + e3 * x[j] * ykn + e2 * x[j] * yjk R[3] <- e3 * (x[k] - x[j]) * ykn + e2 * (xyjk - x[j] * yjk) R[4] <- e3 * (xykn - x[k] * ykn) list(r = R) }
expected <- eval(parse(text="c(0.0180611564434712, 0.199806872869895, 0.394884192345354, 0.926136025877252, 0.989046036560485, 0.991905590506945, 0.980129135221796, 0.899937333563902, 0.680370377730369, 0.286812077933152, 0.233340281029569, 0.549663348621091, 0.691475200857819, 0.475361079095756, 0.479780548616972, 0.69130277676113, 0.568618716724778, 0.191581496795806, 0.392250413522871, 0.456414511823692, 0.397404767826578, 0.35326235733423, 0.531954854626645, 0.838583707018457, 0.49725003166309, 0.586485658131473, 0.505892190935438, 0.111749834894989, -0.0391566236803424, 0.242088943985611, -0.0310629319447717, 0.0999703535723819, 0.367556921296552, 0.334511565621589, 0.0898406603026375, -0.127823791724485)")); test(id=0, code={ argv <- eval(parse(text="list(c(0.018063120710024, 0.202531388051386, 0.417573408622862, 1.63052300091743, 2.60085453772445, 2.75283670267494, 2.30083138197613, 1.47188976409943, 0.829803307993584, 0.295089115172324, 0.237719196109985, 0.617898787321681, 0.850777050382226, 0.516973890969527, 0.522699166681335, 0.850446724158497, 0.645479182912265, 0.193978409371909, 0.414456893353747, 0.492772947140595, 0.420563171733189, 0.369166401583374, 0.592867562934369, 1.21638206559229, 0.54564621330955, 0.672292186547141, 0.557193544541334, 0.112218530051911, -0.0391766542932368, 0.246991917518619, -0.0310729286667355, 0.100305401934259, 0.385595467685569, 0.347899688300561, 0.0900835492886662, -0.128526864819991))")); do.call(`tanh`, argv); }, o=expected);
base_url <- "http://cranlogs.r-pkg.org/" daily_url <- paste0(base_url, "downloads/daily/") top_url <- paste0(base_url, "top/") cran_downloads <- function(packages = NULL, when = c("last-day", "last-week", "last-month"), from = "last-day", to = "last-day") { if (!missing(when)) { interval <- match.arg(when) } else { if (as.character(from) != "last-day") { check_date(from) } if (as.character(to) != "last-day") { check_date(to) } if (from == to) { interval <- from } else { interval <- paste(from, sep = ":", to) } } if (is.null(packages)) { ppackages <- "" } else { if ("R" %in% packages && any(packages != "R")) { stop("R downloads cannot be mixed with package downloads") } ppackages <- paste(packages, collapse = ",") ppackages <- paste0("/", ppackages) } req <- GET(paste0(daily_url, interval, ppackages)) stop_for_status(req) r <- fromJSON(content(req, as = "text"), simplifyVector = FALSE) if ("error" %in% names(r) && r$error == "Invalid query") { stop("Invalid query, probably invalid dates") } to_df(r, packages) } to_df <- function(res, packages) { if (length(res) == 1 && identical(toupper(packages), "R")) { to_df_r(res[[1]]) } else if (length(res) == 1 && is.null(res[[1]]$package)) { to_df_1(res[[1]]) } else { dfs <- lapply(res, to_df_1) for (i in seq_along(res)) dfs[[i]]$package <- res[[i]]$package do.call(rbind, dfs) } } to_df_1 <- function(res1) { df <- data.frame( stringsAsFactors = FALSE, date = as.Date(vapply(res1$downloads, "[[", "", "day")), count = vapply(res1$downloads, "[[", 1, "downloads") ) fill_in_dates(df, as.Date(res1$start), as.Date(res1$end)) } to_df_r <- function(res1) { df <- data.frame( stringsAsFactors = FALSE, date = as.Date(vapply(res1$downloads, "[[", "", "day")), version = vapply(res1$downloads, "[[", "", "version"), os = vapply(res1$downloads, "[[", "", "os"), count = vapply(res1$downloads, "[[", 1, "downloads") ) df } fill_in_dates <- function(df, start, end) { if (start > end) stop("Empty time interval") if (end > Sys.Date()) warning("Time interval in the future") dates <- seq(start, end, by = as.difftime(1, units = "days")) if (any(! dates %in% df$date)) { df2 <- data.frame( stringsAsFactors = FALSE, date = dates[! dates %in% df$date], count = 0 ) df <- rbind(df, df2) df <- df[order(df$date),] rownames(df) <- NULL } df } cran_top_downloads <- function(when = c("last-day", "last-week", "last-month"), count = 10) { when <- match.arg(when) req <- GET(paste0(top_url, when, '/', count)) stop_for_status(req) r <- fromJSON(content(req, as = "text", encoding = "UTF-8"), simplifyVector = FALSE) df <- data.frame( stringsAsFactors = FALSE, rank = seq_along(r$downloads), package = vapply(r$downloads, "[[", "", "package"), count = as.integer(vapply(r$downloads, "[[", "", "downloads")), from = as.Date(r$start), to = as.Date(r$end) ) if (nrow(df) != count) { warning("Requested ", count, " packages, returned only ", nrow(df)) } df }
alltype <- function(){c("lmg","last", "first", "betasq", "pratt", "genizi", "car")}
ParallelRandomSVD2 <- function(X, fun.scaling, ind.train, block.size, K, I, use.Eigen, backingpath, ncores) { L <- K + 12 n <- length(ind.train) m <- ncol(X) I <- I + 1 stopifnot((n - K) >= (I * L)) TIME <- 0.01 tmp.lock.name <- "mutex" tmp.lock.names <- paste(tmp.lock.name, Sys.getpid(), 1:4, sep = '-') ifelse(file.exists(tmp.lock.names), FALSE, file.create(tmp.lock.names)) G <- big.matrix(n, L, type = "double", shared = TRUE) G[] <- stats::rnorm(n * L) H <- big.matrix(m, L * I, type = "double", shared = TRUE) U <- big.matrix(m, L * I, type = "double", shared = TRUE) T.t <- big.matrix(n, L * I, type = "double", shared = TRUE, init = 0) remains <- big.matrix(4, I - 1, type = "integer", shared = TRUE, init = ncores) X.desc <- describe(X) G.desc <- describe(G) H.desc <- describe(H) U.desc <- describe(U) T.t.desc <- describe(T.t) r.desc <- describe(remains) intervals <- CutBySize(m, nb = ncores) if (is.seq <- (ncores == 1)) { registerDoSEQ() } else { cl <- parallel::makeCluster(ncores) doParallel::registerDoParallel(cl) } scaling <- foreach(ic = seq_len(ncores), .combine = 'cbind') %dopar% { lims <- intervals[ic, ] X.part <- sub.big.matrix(X.desc, firstCol = lims[1], lastCol = lims[2], backingpath = backingpath) multi <- (!is.seq) && detect_MRO() if (multi) nthreads.save <- RevoUtilsMath::setMKLthreads(1) means_sds <- fun.scaling(X.part, ind.train) means <- means_sds$mean sds <- means_sds$sd rm(means_sds) m.part <- ncol(X.part) intervals <- CutBySize(m.part, block.size) nb.block <- nrow(intervals) G <- attach.big.matrix(G.desc) H.part <- sub.big.matrix(H.desc, firstRow = lims[1], lastRow = lims[2]) remains <- attach.big.matrix(r.desc) for (i in 1:(I - 1)) { old.G <- G[,] file.lock1 <- flock::lock(tmp.lock.names[1]) if (remains[1, i] == 1) G[] <- 0 remains[1, i] <- remains[1, i] - 1L flock::unlock(file.lock1) tmp.G <- matrix(0, n, L) for (j in 1:nb.block) { ind <- seq2(intervals[j, ]) tmp <- scaling(X.part[ind.train, ind], means[ind], sds[ind]) tmp.H <- cross(tmp, old.G, use.Eigen) tmp.G <- incrMat(tmp.G, mult(tmp, tmp.H, use.Eigen)) H.part[ind, 1:L + (i - 1) * L] <- tmp.H } while (remains[1, i] > 0) Sys.sleep(TIME) file.lock2 <- flock::lock(tmp.lock.names[2]) incrG(G@address, tmp.G, n, L, 2*m) remains[2, i] <- remains[2, i] - 1L flock::unlock(file.lock2) while (remains[2, i] > 0) Sys.sleep(TIME) } i <- I old.G <- G[,] for (j in 1:nb.block) { ind <- seq2(intervals[j, ]) tmp <- scaling(X.part[ind.train, ind], means[ind], sds[ind]) tmp.H <- cross(tmp, old.G, use.Eigen) H.part[ind, 1:L + (i - 1) * L] <- tmp.H } rm(G, H.part) file.lock3 <- flock::lock(tmp.lock.names[3]) if (remains[3, 1] == 1) { H <- attach.big.matrix(H.desc) U <- attach.big.matrix(U.desc) if (multi) RevoUtilsMath::setMKLthreads(nthreads.save) U[] <- svd(H[,], nv = 0)$u if (multi) nthreads.save <- RevoUtilsMath::setMKLthreads(1) } remains[3, 1] <- remains[3, 1] - 1L flock::unlock(file.lock3) while (remains[3, 1] > 0) Sys.sleep(TIME) U.part <- sub.big.matrix(U.desc, firstRow = lims[1], lastRow = lims[2]) tmp.T.t <- matrix(0, n, I * L) for (j in 1:nb.block) { ind <- seq2(intervals[j, ]) tmp <- scaling(X.part[ind.train, ind], means[ind], sds[ind]) tmp.T.t <- incrMat(tmp.T.t, mult(tmp, U.part[ind, ], use.Eigen)) } rm(U.part) T.t <- attach.big.matrix(T.t.desc) file.lock4 <- flock::lock(tmp.lock.names[4]) incrG(T.t@address, tmp.T.t, n, I * L, 1) remains[4, 1] <- remains[4, 1] - 1L flock::unlock(file.lock4) while (remains[4, 1] > 0) Sys.sleep(TIME) if (multi) RevoUtilsMath::setMKLthreads(nthreads.save) rbind(means, sds) } if (!is.seq) parallel::stopCluster(cl) unlink(tmp.lock.names) T.svd <- svd(T.t[,], nu = K, nv = K) list(d = T.svd$d[1:K], u = T.svd$u, v = U[,] %*% T.svd$v, means = scaling[1, ], sds = scaling[2, ]) }
context("category_vector") test_that("matrix", { x <- matrix(c(1, 0, 0, NA, 0, 1, 0, NA, 0, 0, 0, NA), ncol = 3) y <- category_vector(x) expect_equal(y, c(1, 2, 0, NA)) }) test_that("data.frame", { x <- as.data.frame(matrix(c(1, 0, 0, NA, 0, 1, 0, NA, 0, 0, 0, NA), ncol = 3)) y <- category_vector(x) expect_equal(y, c(1, 2, 0, NA)) }) test_that("Spatial", { data(sim_pu_polygons) x <- sim_pu_polygons[seq_len(4), ] x$V1 <- c(1, 0, 0, NA) x$V2 <- c(0, 1, 0, NA) x$V3 <- c(0, 0, 0, NA) y <- category_vector(x[, c("V1", "V2", "V3")]) expect_equal(y, c(1, 2, 0, NA)) }) test_that("sf", { data(sim_pu_sf) x <- sim_pu_sf[seq_len(4), ] x$V1 <- c(1, 0, 0, NA) x$V2 <- c(0, 1, 0, NA) x$V3 <- c(0, 0, 0, NA) y <- category_vector(x[, c("V1", "V2", "V3")]) expect_equal(y, c(1, 2, 0, NA)) }) test_that("invalid inputs", { expect_error(category_vector(data.frame(integer(0), integer(0)))) expect_error(category_vector(data.frame(a = 1, b = 2))) expect_error(category_vector(data.frame(a = 1, b = -1))) expect_error(category_vector(data.frame(a = 1, b = "a"))) expect_error(category_vector(matrix(c(1, 2), ncol = 2))) expect_error(category_vector(matrix(c(1, -1), ncol = 2))) expect_error(category_vector(matrix(c("a", "b"), ncol = 2))) })
tt_compile <- function(date, auth = github_pat()) { ttmf <- tt_master_file() files <- ttmf[ ttmf$Date == date, c("data_files","data_type","delim")] readme <- try( github_html(file.path("data", year(date), date, "readme.md"), auth = auth), silent = TRUE) if(inherits(readme, "try-error")){ readme <- NULL } list( files = files, readme = readme ) }
optimal_rerandomization_normality_assumed = function( W_base_object, estimator = "linear", q = 0.95, skip_search_length = 1, dot_every_x_iters = 100){ optimal_rerandomization_argument_checks(W_base_object, estimator, q) n = W_base_object$n X = W_base_object$X W_base_sort = W_base_object$W_base_sort max_designs = W_base_object$max_designs imbalance_by_w_sorted = W_base_object$imbalance_by_w_sorted if (estimator == "linear"){ Xt = t(X) XtXinv = solve(Xt %*% X) P = X %*% XtXinv %*% Xt I = diag(n) I_min_P = I - P } s_star = NULL Q_star = Inf Q_primes = array(NA, max_designs) w_w_T_running_sum = matrix(0, n, n) if (estimator == "linear"){ w_w_T_P_w_w_T_running_sum = matrix(0, n, n) } ss = seq(from = 1, to = max_designs, by = skip_search_length) for (i in 1 : length(ss)){ s = ss[i] if (!is.null(dot_every_x_iters)){ if (i %% dot_every_x_iters == 0){ cat(".") } } w_s = W_base_sort[s, , drop = FALSE] w_s_w_s_T = t(w_s) %*% w_s w_w_T_running_sum = w_w_T_running_sum + w_s_w_s_T Sigma_W = 1 / i * w_w_T_running_sum if (estimator == "linear"){ w_w_T_P_w_w_T_running_sum = w_w_T_P_w_w_T_running_sum + w_s_w_s_T %*% P %*% w_s_w_s_T D = 1 / i * w_w_T_P_w_w_T_running_sum G = I_min_P %*% Sigma_W %*% I_min_P eigenvalues = eigen(G + 2 / n * D)$values tryCatch({Q_primes[s] = hall_buckley_eagleson_inverse_cdf(eigenvalues, q, n)}, error = function(e){}) } if (!is.na(Q_primes[s])){ if (Q_primes[s] < Q_star){ Q_star = Q_primes[s] s_star = s } } } cat("\n") all_data_from_run = data.frame( imbalance_by_w_sorted = imbalance_by_w_sorted, Q_primes = Q_primes ) ll = list( type = "normal", estimator = estimator, q = q, W_base_object = W_base_object, W_star = W_base_sort[1 : s_star, ], W_star_size = s_star, a_star = imbalance_by_w_sorted[s_star], a_stars = imbalance_by_w_sorted[1 : s_star], all_data_from_run = all_data_from_run, Q_star = Q_star ) class(ll) = "optimal_rerandomization_obj" ll }
predict.cv.sparseSVM <- function(object, X, lambda = object$lambda.min, type=c("class","coefficients","nvars"), exact = FALSE, ...) { type = match.arg(type) predict.sparseSVM(object$fit, X = X, lambda = lambda, type = type, exact = exact, ...) } coef.cv.sparseSVM <- function(object, lambda = object$lambda.min, exact = FALSE, ...) { coef.sparseSVM(object$fit, lambda = lambda, exact = exact, ...) }
orderv <- function(columns, ..., na.last = TRUE, decreasing = FALSE, method = c("auto", "shell", "radix")) { wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::orderv") if((!is.list(columns)) || (length(columns)<1)) { stop("wrapr::orderv columns must be a list containing at least one atomic vector") } columns <- as.list(columns) names(columns) <- NULL do.call(base::order, c( columns, list( na.last = na.last, decreasing = decreasing, method = method))) } sortv <- function(data, colnames, ..., na.last = TRUE, decreasing = FALSE, method = c("auto", "shell", "radix")) { wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::sortv") if(!is.data.frame(data)) { stop("wrapr::sortv data must be a data.frame") } if(length(colnames)<1) { return(data) } if(!is.character(colnames)) { stop("wrapr::sortv colnames must be of type character") } bads <- setdiff(colnames, colnames(data)) if(length(bads)>0) { stop(paste("wrapr::sortv data colnames that are not in colnames(data):", paste(bads, collapse = ", "))) } perm <- orderv(as.list(data[, colnames, drop = FALSE]), na.last = na.last, decreasing = decreasing, method = method) data[perm, , drop = FALSE] }
dbhatt <- function(x, mu = 0, sigma = 1, a = sigma, log = FALSE) { cpp_dbhatt(x, mu, sigma, a, log[1L]) } pbhatt <- function(q, mu = 0, sigma = 1, a = sigma, lower.tail = TRUE, log.p = FALSE) { cpp_pbhatt(q, mu, sigma, a, lower.tail[1L], log.p[1L]) } rbhatt <- function(n, mu = 0, sigma = 1, a = sigma) { if (length(n) > 1) n <- length(n) cpp_rbhatt(n, mu, sigma, a) }
event_with_headers <- function( request_id = "abc123", request_arn = "arn:aws:lambda:us-west-2:123456789012:function:my-function" ) { structure( list(event_headers = list( "lambda-runtime-aws-request-id" = request_id, "lambda-runtime-invoked-function-arn" = request_arn )), class = "event" ) }
ccp_tree_prior_to_xml_state <- function( inference_model ) { tree_prior <- inference_model$tree_prior testit::assert(beautier::is_id(tree_prior$id)) parameter_xml <- paste0( "<parameter id=\"popSize.t:", tree_prior$id, "\" " ) if (inference_model$beauti_options$beast2_version == "2.6") { parameter_xml <- paste0( parameter_xml, "spec=\"parameter.RealParameter\" " ) } if (!is.na(tree_prior$pop_size_distr$lower)) { parameter_xml <- paste0( parameter_xml, paste0("lower=\"", tree_prior$pop_size_distr$lower, "\" ") ) } parameter_xml <- paste0( parameter_xml, "name=\"stateNode\"" ) if (!is.na(tree_prior$pop_size_distr$upper)) { parameter_xml <- paste0( parameter_xml, " upper=\"", tree_prior$pop_size_distr$upper, "\"" ) } parameter_xml <- paste0( parameter_xml, ">", tree_prior$pop_size_distr$value, "</parameter>" ) parameter_xml }
importGTF <- function(file, skip="auto", nrow=-1, use.data.table=TRUE, level="gene", features=NULL, num.features=c("FPKM", "TPM"), print.features=FALSE, merge.feature=NULL, merge.all=TRUE, class.names=NULL, verbose=TRUE){ if(is.null(merge.feature)){ out <- importGTF.internal(file=file, skip=skip, nrow=nrow, use.data.table=use.data.table, level=level, features=features, num.features=num.features, print.features=print.features, verbose=verbose) } else { if(verbose) cat ("Start to import several gtfs and merge them using the feature",merge.feature,"\n") if(!is.element(merge.feature, features)){ cat("Added",merge.feature,"to features-Option.") } gtfFiles <- list.files(file) gtfFiles <- gtfFiles[grep(".gtf",gtfFiles)] gtfNames <- gsub(".gtf","",gtfFiles) gtfNames <- gsub(".gz","",gtfNames) if(verbose) cat("Start to import", length(gtfFiles),"files:\n", paste(gtfFiles , collapse=" \n"),"\n") features.small <- features[!is.element(features, merge.feature)] mergeThose <- c() allGTFs <- list() for(i in 1:length(gtfFiles)){ if(verbose) cat("Start to import: ", gtfFiles[i],"\n") allGTFs[[i]] <- importGTF.internal(file=file.path(file,gtfFiles[i]), skip=skip, nrow=nrow, use.data.table=use.data.table, level=level, features=features, num.features=num.features, print.features=print.features, verbose=verbose) setkeyv(allGTFs[[i]], merge.feature) takeThose <- which(is.element(colnames(allGTFs[[i]]),features.small)) for(j in 1:length(takeThose)){ mergeThose <- c(paste(gtfNames[i],colnames(allGTFs[[i]])[takeThose[j]],sep=".")) colnames(allGTFs[[i]])[takeThose[j]] <- mergeThose[length(mergeThose)] } if(i==2) tmp <- merge(allGTFs[[1]], allGTFs[[2]][,unique(c(merge.feature,mergeThose)),with=FALSE], all=merge.all) if(i>2){ tmp <- merge(tmp, allGTFs[[i]][,unique(c(merge.feature,mergeThose)),with=FALSE], all=merge.all) } } out <- tmp class(out) <- append(class(out), "gtf") } out } importGTF.internal <- function(file, skip="auto", nrow=-1, use.data.table=TRUE, level="gene", features=NULL, num.features=num.features, print.features=FALSE, merge.feature=NULL, verbose){ gtf <- file if(skip=="auto"){ if(last(strsplit(gtf,"\\.")[[1]])=="gz"){ } else { con <- file(gtf, open = "r") search <- TRUE obsRow <- 0 while(search){ obsRow <- obsRow + 1 tmp <- readLines(con, n = 1, warn = FALSE) if(substr(tmp,1,1)!=" skip <- obsRow -1 search <- FALSE } if(obsRow==1000) search <- FALSE } close(con) } } else { if(!is.numeric(skip)) stop("ERROR: skip needs to be a numeric value!") } if(verbose) cat("Automatically detected number of rows to skip: ", skip,"\n") if(use.data.table){ if(last(strsplit(gtf,"\\.")[[1]])=="gz"){ cuffLoaded <- fread(input = paste('zcat',gtf), sep ="\t", colClasses = c("character", "character", "character", "integer", "integer", "character", "character", "character", "character")) } else { cuffLoaded <- fread(input = gtf, sep="\t", skip=skip, colClasses = c("character", "character", "character", "integer", "integer", "character", "character", "character", "character")) } if(verbose){ if(sum(cuffLoaded$V3==level)==0){ availLevels <- unique(cuffLoaded$V3) stop("The given import level '",level,"' was not found in the gtf! Available level are: \n", paste(availLevels, collapse=" \n ")) } } if(!is.null(level)) cuffLoaded <- cuffLoaded[cuffLoaded$V3==level,] if(nrow>0) cuffLoaded <- cuffLoaded[1:nrow,] } else { stop("Currently the importGTF function supports only data tables.") cuffLoaded <- read.csv(file=gtf, sep="\t", header=FALSE, stringsAsFactors=FALSE, skip=skip, nrow=nrow) } V9 <- cuffLoaded$V9 V9 <- strsplit(V9,"; ") if(print.features || verbose){ cat("List of features in column 9:\n") cat("-----------------------------\n") cat(paste(paste(sapply(strsplit(V9[[1]]," "),"[",1),"\n"), collapse="")) } if(is.null(features)){ gene_id <- sapply(V9, function(x) x[grep("^gene_id",x)]) gene_name <- sapply(V9, function(x) x[grep("^gene_name",x)]) gene_biotype <- sapply(V9, function(x) x[grep("^gene_biotype",x)]) gene_id <- gsub("gene_id ","",gene_id) gene_name <- gsub("gene_name ","",gene_name) gene_biotype <- gsub("gene_biotype ","",gene_biotype) gene_id <- gsub('\"',"",gene_id) gene_name <- gsub('\"',"",gene_name) gene_biotype <- gsub('\"',"",gene_biotype) gene_id <- gsub(';',"",gene_id) gene_name <- gsub(';',"",gene_name) gene_biotype <- gsub(';',"",gene_biotype) cuffLoaded[,V9:=NULL] cuffLoaded[,gene_id:=gene_id] cuffLoaded[,gene_name:=gene_name] cuffLoaded[,gene_biotype:=gene_biotype] } else { for(frun in 1:length(features)){ tmpFeature <- sapply(V9, function(x) x[grep(paste("^",features[frun],sep=""),x)]) tmpFeature <- gsub(" ","",tmpFeature) tmpFeature <- gsub(";","",tmpFeature) tmpFeature <- gsub(eval(features[frun]),"",tmpFeature) tmpFeature <- gsub('\"',"",tmpFeature) if(sum(is.element(features[frun],num.features))>0) tmpFeature <- as.numeric(tmpFeature) cuffLoaded[,eval(features[frun]):=tmpFeature] } cuffLoaded[,V9:=NULL] } class(cuffLoaded) <- append(class(cuffLoaded), "gtf") cuffLoaded }
tar_test("tar_progress() with defaults", { for (result in c("built", "skipped")) { pipeline <- pipeline_init(list(target_init("x", quote(1)))) local_init(pipeline = pipeline)$run() out <- tar_progress() expect_equal(dim(out), c(1L, 2L)) expect_equal(out$name, "x") expect_equal(out$progress, result) } }) tar_test("tar_progress() with fields = NULL", { pipeline <- pipeline_init(list(target_init("x", quote(1)))) local_init(pipeline = pipeline)$run() out <- tar_progress(fields = NULL) expect_equal(dim(out), c(1L, 5L)) expect_equal(out$name, "x") expect_equal(out$type, "stem") expect_equal(out$parent, "x") expect_equal(out$branches, 0L) expect_equal(out$progress, "built") }) tar_test("tar_progress() tidyselect", { pipeline <- pipeline_init(list(target_init("x", quote(1)))) local_init(pipeline = pipeline)$run() out <- tar_progress(fields = type) expect_equal(dim(out), c(1L, 2L)) expect_equal(out$name, "x") expect_equal(out$type, "stem") }) tar_test("tar_progress() with target selection", { tar_script({ envir <- new.env(parent = baseenv()) tar_option_set(envir = envir) list( tar_target(x, seq_len(2)), tar_target(y, 2 * x, pattern = map(x)) ) }) tar_make(callr_function = NULL) out <- tar_progress() expect_equal(nrow(out), 4L) out <- tar_progress(c("y", "x")) expect_equal(out$name, c("y", "x")) out <- tar_progress(c("x", "y")) expect_equal(out$name, c("x", "y")) }) tar_test("custom script and store args", { skip_on_cran() expect_equal(tar_config_get("script"), path_script_default()) expect_equal(tar_config_get("store"), path_store_default()) tar_script({ list( tar_target(w, letters) ) }, script = "example/script.R") tar_make( callr_function = NULL, script = "example/script.R", store = "example/store" ) expect_true(is.data.frame(tar_progress(store = "example/store"))) expect_false(file.exists("_targets.yaml")) expect_equal(tar_config_get("script"), path_script_default()) expect_equal(tar_config_get("store"), path_store_default()) expect_false(file.exists(path_script_default())) expect_false(file.exists(path_store_default())) expect_true(file.exists("example/script.R")) expect_true(file.exists("example/store")) expect_true(file.exists("example/store/meta/meta")) expect_true(file.exists("example/store/objects/w")) tar_config_set(script = "x") expect_equal(tar_config_get("script"), "x") expect_true(file.exists("_targets.yaml")) })
rm(list=ls()) library(tidyverse) library(curl) library(lubridate) library(RcppRoll) library(readxl) library(gtools) library(paletteer) library(extrafont) library(ragg) library(scales) library(forcats) options(scipen=99999) theme_custom <- function() { theme_classic() %+replace% theme(plot.title.position="plot", plot.caption.position="plot", strip.background=element_blank(), strip.text=element_text(face="bold", size=rel(1)), plot.title=element_text(face="bold", size=rel(1.5), hjust=0, margin=margin(0,0,5.5,0)), text=element_text(family="Lato")) } temp <- tempfile() source <- ("https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/833970/File_1_-_IMD2019_Index_of_Multiple_Deprivation.xlsx") temp <- curl_download(url=source, destfile=temp, quiet=FALSE, mode="wb") IMD <- read_excel(temp, sheet="IMD2019", range="A2:F32845", col_names=FALSE) %>% select(c(1,2,5,6)) %>% set_names("LSOA11CD", "LSOA11NM", "IMDrank", "IMDdecile") source <- ("https://opendata.arcgis.com/datasets/fe6c55f0924b4734adf1cf7104a0173e_0.csv") temp <- curl_download(url=source, destfile=temp, quiet=FALSE, mode="wb") lookup <- read.csv(temp) %>% select(LSOA11CD, MSOA11CD, LAD17CD) %>% unique() IMD <- merge(IMD, lookup, by="LSOA11CD") source <- "https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2flowersuperoutputareamidyearpopulationestimates%2fmid2020sape23dt2/sape23dt2mid2020lsoasyoaestimatesunformatted.xlsx" temp <- curl_download(url=source, destfile=temp, quiet=FALSE, mode="wb") pop <- read_excel(temp, sheet="Mid-2020 Persons", range="A6:G34758", col_names=FALSE) %>% select(-c(2:6)) %>% set_names("LSOA11CD", "pop") pop_full <- read_excel(temp, sheet="Mid-2020 Persons", range="A6:CT34758", col_names=FALSE) %>% select(-c(2:7)) %>% set_names("LSOA11CD", c(0:90)) IMD <- merge(IMD, pop) IMD_MSOA <- IMD %>% group_by(MSOA11CD, LAD17CD) %>% summarise(IMDrank=weighted.mean(IMDrank, pop), pop=sum(pop)) %>% ungroup() %>% mutate(decile=quantcut(IMDrank, q=10, labels=FALSE)) IMD_LTLA <- IMD %>% group_by(LAD17CD)%>% summarise(IMDrank=weighted.mean(IMDrank, pop), pop=sum(pop)) %>% ungroup() %>% mutate(decile=quantcut(IMDrank, q=10, labels=FALSE)) u18xIMD <- pop_full %>% gather(age, pop, c(2:ncol(.))) %>% mutate(age=as.numeric(age)) %>% filter(age<18) %>% mutate(ageband=case_when( age<12 ~ "Under 12", age<16 ~ "12-15", TRUE ~ "16-17")) %>% merge(IMD %>% select(LSOA11CD, IMDdecile)) %>% group_by(IMDdecile, ageband) %>% summarise(pop=sum(pop)) %>% ungroup() %>% group_by(IMDdecile) %>% mutate(total=sum(pop)) %>% ungroup() %>% mutate(prop=pop/total, ageband=factor(ageband, levels=c("Under 12", "12-15", "16-17"))) agg_tiff("Outputs/EngU18Pop.tiff", units="in", width=9, height=6, res=500) ggplot(u18xIMD, aes(x=prop, y=as.factor(IMDdecile), fill=fct_rev(ageband)))+ geom_col(position="stack")+ scale_x_continuous(name="Proportion of under 18s", labels=label_percent(accuracy=1))+ scale_y_discrete(name="IMD decile", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ scale_fill_paletteer_d("ggthemr::solarized", name="", guide=guide_legend(reverse=TRUE))+ theme_custom()+ theme(legend.position="top")+ labs(title="You would expect under 18 vaccination rates in deprived areas to be *slightly* lower", subtitle="Age distribution of the under 18s in England by deprivation decile", caption="Population data from ONS 2020 estimates | Plot by @VictimOfMaths") dev.off() temp.cases <- tempfile() caseurl <- "https://api.coronavirus.data.gov.uk/v2/data?areaType=msoa&metric=newCasesBySpecimenDateRollingSum&format=csv" temp.cases <- curl_download(url=caseurl, destfile=temp.cases, quiet=FALSE, mode="wb") cases <- read.csv(temp.cases) %>% select(areaCode, date, newCasesBySpecimenDateRollingSum) %>% set_names("MSOA11CD", "date", "cases") %>% mutate(date=as.Date(date)) %>% merge(IMD_MSOA) %>% group_by(decile, date) %>% summarise(cases=sum(cases), pop=sum(pop)) %>% ungroup() %>% group_by(decile) %>% mutate(caserate=cases*100000/pop) %>% ungroup() cases_MSOA <- read.csv(temp.cases) %>% select(areaCode, date, newCasesBySpecimenDateRollingSum) %>% set_names("MSOA11CD", "date", "cases") %>% mutate(date=as.Date(date)) %>% filter(date==max(date)) %>% merge(IMD_MSOA) %>% rename(allpop=pop) agg_png("Outputs/COVIDCasesxIMD.png", units="in", width=8, height=6, res=800) ggplot(cases, aes(x=date, y=caserate, colour=as.factor(decile)))+ geom_line()+ scale_x_date(name="")+ scale_y_continuous(name="Weekly new cases per 100,000 people", limits=c(0,NA))+ scale_colour_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ theme_custom()+ labs(title="The socioeconomic profile of COVID cases has recently reversed", subtitle="Weekly rate of new COVID cases in England based on neighbourhood-level data.\nCase data is not available for neighbourhoods with fewer than 3 cases in any given week.", caption="Data from coronavirus.data.gov.uk | Plot by Colin Angus") dev.off() agg_tiff("Outputs/COVIDCasesxIMDRecent.tiff", units="in", width=8, height=6, res=800) ggplot(cases %>% filter(date>as.Date("2021-05-01")), aes(x=date, y=caserate, colour=as.factor(decile)))+ geom_line()+ scale_x_date(name="")+ scale_y_continuous(name="Weekly new cases per 100,000 people", limits=c(0,NA))+ scale_colour_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ theme_custom()+ labs(title="The socioeconomic profile of COVID cases has recently reversed", subtitle="Weekly rate of new COVID cases in England based on MSOA-level data.\nCase data is not available for neighbourhoods with fewer than 3 cases in any given week.", caption="Data from coronavirus.data.gov.uk | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDCasesxIMDRecentArea.tiff", units="in", width=8, height=6, res=800) ggplot(cases %>% filter(date>as.Date("2021-05-01")), aes(x=date, y=cases, fill=as.factor(decile)))+ geom_area(position="fill")+ scale_x_date(name="")+ scale_y_continuous(name="Proportion of new cases", limits=c(0,NA), labels=label_percent(accuracy=1))+ scale_fill_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ theme_custom()+ labs(title="The socioeconomic profile of COVID cases has recently reversed", subtitle="Proportion of new COVID cases by deprivation decile in England based on MSOA-level data.\nCase data is not available for neighbourhoods with fewer than 3 cases in any given week.", caption="Data from coronavirus.data.gov.uk | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDCasesxIMDArea.tiff", units="in", width=8, height=6, res=800) ggplot(cases %>% filter(date>as.Date("2020-04-01")), aes(x=date, y=cases, fill=as.factor(decile)))+ geom_area(position="fill")+ scale_x_date(name="")+ scale_y_continuous(name="Proportion of new cases", limits=c(0,NA), labels=label_percent(accuracy=1))+ scale_fill_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ theme_custom()+ labs(title="The socioeconomic profile of COVID cases has recently reversed", subtitle="Proportion of new COVID cases by deprivation decile in England based on MSOA-level data.\nCase data is not available for neighbourhoods with fewer than 3 cases in any given week.", caption="Data from coronavirus.data.gov.uk | Plot by @VictimOfMaths") dev.off() source <- ("https://api.coronavirus.data.gov.uk/v2/data?areaType=ltla&metric=newCasesBySpecimenDate&metric=newDeaths28DaysByDeathDate&format=csv") temp <- curl_download(url=source, destfile=temp, quiet=FALSE, mode="wb") LAcases <- read.csv(temp) %>% rename(cases=newCasesBySpecimenDate, deaths=newDeaths28DaysByDeathDate) %>% mutate(date=as.Date(date)) %>% filter(date<max(date)-days(3)) %>% merge(IMD_LTLA, by.x="areaCode", by.y="LAD17CD") %>% group_by(decile, date) %>% summarise(cases=sum(cases), deaths=sum(deaths), pop=sum(pop)) %>% ungroup() %>% group_by(decile) %>% mutate(caserate=cases*100000/pop, deathrate=deaths*100000/pop, caserate_roll=roll_mean(caserate, 7, align="center", fill=NA), deathrate_roll=roll_mean(deathrate, 7, align="center", fill=NA)) %>% ungroup() agg_tiff("Outputs/COVIDCasesxIMDLTLA.tiff", units="in", width=8, height=6, res=800) ggplot(LAcases, aes(x=date, y=caserate_roll, colour=as.factor(decile)))+ geom_line()+ scale_x_date(name="")+ scale_y_continuous(name="Daily new cases per 100,000 people", limits=c(0,NA))+ scale_colour_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ theme_custom()+ labs(title="The socioeconomic profile of COVID cases has recently reversed", subtitle="Rolling 7-day average daily rate of new COVID cases in England based on Local Authority-level data.\nLocal Authorities are allocated to deprivation deciles based on their average IMD scores.", caption="Data from coronavirus.data.gov.uk | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDCasesxIMDAreaLTLA.tiff", units="in", width=8, height=6, res=800) ggplot(LAcases %>% filter(date>as.Date("2020-04-01")), aes(x=date, y=caserate_roll, fill=as.factor(decile)))+ geom_area(position="fill")+ scale_x_date(name="")+ scale_y_continuous(name="Proportion of new cases", limits=c(0,NA), labels=label_percent(accuracy=1))+ scale_fill_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ theme_custom()+ labs(title="The socioeconomic profile of COVID cases has recently reversed", subtitle="Proportion of new COVID cases in England based on Local Authority-level data.\nLocal Authorities are allocated to deprivation deciles based on their average IMD scores.", caption="Data from coronavirus.data.gov.uk | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDDeathsxIMDLTLA.tiff", units="in", width=8, height=6, res=800) ggplot(LAcases, aes(x=date, y=deathrate_roll, colour=as.factor(decile)))+ geom_line()+ scale_x_date(name="")+ scale_y_continuous(name="Daily deaths per 100,000 people", limits=c(0,NA))+ scale_colour_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ theme_custom()+ labs(title="COVID deaths are still highest in more deprived groups", subtitle="Rolling 7-day average daily rate of deaths within 28 days of a positive COVID test in England\nbased on Local Authority-level data. Local Authorities are allocated to deprivation deciles based on\nthe average IMD scores of neighbourhoods in the Local Authority.", caption="Data from coronavirus.data.gov.uk | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDDeathsxIMDAreaLTLA.tiff", units="in", width=8, height=6, res=800) ggplot(LAcases %>% filter(date>as.Date("2020-04-01")), aes(x=date, y=deathrate_roll, fill=as.factor(decile)))+ geom_area(position="fill")+ scale_x_date(name="")+ scale_y_continuous(name="Proportion of deaths", limits=c(0,NA), labels=label_percent(accuracy=1))+ scale_fill_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ theme_custom()+ labs(title="COVID deaths are still highest in more deprived groups", subtitle="Proportion of deaths within 28 days of a positive COVID test in England based on Local Authority-level data.\nLocal Authorities are allocated to deprivation deciles based on the average IMD scores of neighbourhoods\nin the Local Authority.", caption="Data from coronavirus.data.gov.uk | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDDeathsxIMDLTLARecent.tiff", units="in", width=8, height=6, res=800) ggplot(LAcases %>% filter(date>as.Date("2021-05-01")), aes(x=date, y=deathrate_roll, colour=as.factor(decile)))+ geom_line()+ scale_x_date(name="")+ scale_y_continuous(name="Daily deaths per 100,000 people", limits=c(0,NA))+ scale_colour_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ theme_custom()+ labs(title="COVID deaths are still highest in more deprived groups", subtitle="Rolling 7-day average daily rate of deaths within 28 days of a positive COVID test in England\nbased on Local Authority-level data. Local Authorities are allocated to deprivation deciles based on\nthe average IMD scores of neighbourhoods in the Local Authority.", caption="Data from coronavirus.data.gov.uk | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDDeathsxIMDAreaLTLARecent.tiff", units="in", width=8, height=6, res=800) ggplot(LAcases %>% filter(date>as.Date("2021-05-01")), aes(x=date, y=deathrate_roll, fill=as.factor(decile)))+ geom_area(position="fill")+ scale_x_date(name="")+ scale_y_continuous(name="Proportion of deaths", limits=c(0,NA), labels=label_percent(accuracy=1))+ scale_fill_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ theme_custom()+ labs(title="COVID deaths are still highest in more deprived groups", subtitle="Proportion of deaths within 28 days of a positive COVID test in England based on Local Authority-level data.\nLocal Authorities are allocated to deprivation deciles based on the average IMD scores of neighbourhoods\nin the Local Authority.", caption="Data from coronavirus.data.gov.uk | Plot by @VictimOfMaths") dev.off() url <- "https://www.england.nhs.uk/statistics/wp-content/uploads/sites/2/2022/01/COVID-19-weekly-announced-vaccinations-13-January-2022.xlsx" temp <- curl_download(url=url, destfile=temp, quiet=FALSE, mode="wb") vaxdata <- read_excel(temp, sheet="MSOA", range="F15:I6803", col_names=FALSE, col_types="text") %>% set_names("MSOA11CD", "areaName", "12-15", "16-17") %>% mutate(`12-15`=as.numeric(`12-15`), `16-17`=as.numeric(`16-17`), `12-17`=`12-15`+`16-17`) %>% gather(age, vaccinated, c(3:5)) %>% merge(pop_full %>% select(c(1,14:19)) %>% gather(age, pop, c(2:7)) %>% mutate(age=case_when( age<16 ~ "12-15", TRUE ~ "16-17")) %>% group_by(LSOA11CD, age) %>% summarise(pop=sum(pop)) %>% ungroup() %>% merge(lookup) %>% group_by(MSOA11CD, age) %>% summarise(pop=sum(pop)) %>% ungroup() %>% spread(age, pop) %>% mutate(`12-17`=`12-15`+`16-17`) %>% gather(age, pop, c(2:4))) %>% merge(IMD_MSOA %>% select(MSOA11CD, decile)) %>% group_by(age, decile) %>% summarise(vaccinated=sum(vaccinated, na.rm=TRUE), vaxpop=sum(pop)) %>% ungroup() %>% mutate(vaxrate=vaccinated/vaxpop) vaxdata_MSOA <- read_excel(temp, sheet="MSOA", range="F15:I6803", col_names=FALSE, col_types="text") %>% set_names("MSOA11CD", "areaName", "12-15", "16-17") %>% mutate(`12-15`=as.numeric(`12-15`), `16-17`=as.numeric(`16-17`), `12-17`=`12-15`+`16-17`) %>% gather(age, vaccinated, c(3:5)) %>% merge(pop_full %>% select(c(1,14:19)) %>% gather(age, pop, c(2:7)) %>% mutate(age=case_when( age<16 ~ "12-15", TRUE ~ "16-17")) %>% merge(lookup) %>% group_by(MSOA11CD) %>% summarise(pop=sum(pop)) %>% ungroup()) %>% merge(IMD_MSOA %>% select(MSOA11CD, decile)) %>% mutate(vaxprop=vaccinated/pop) agg_tiff("Outputs/COVIDVaxU18xIMDONS.tiff", units="in", width=10, height=6, res=500) ggplot(vaxdata %>% filter(age!="12-17"), aes(x=vaxrate, y=as.factor(decile), fill=as.factor(decile)))+ geom_col(show.legend=FALSE)+ scale_x_continuous(name="Proportion of age group vaccinated", labels=label_percent(accuracy=1))+ scale_y_discrete(name="IMD decile", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ scale_fill_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ facet_wrap(~age)+ theme_custom()+ labs(title="Child vaccination rates are lowest in deprived areas", subtitle="Proportion of under 18s who have received at least one COVID-19 vaccine dose", caption="Vaccination data from NHS England, population data from ONS\nPlot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDVax1217xIMDONS.tiff", units="in", width=8, height=6, res=500) ggplot(vaxdata %>% filter(age=="12-17"), aes(x=vaxrate, y=as.factor(decile), fill=as.factor(decile)))+ geom_col(show.legend=FALSE)+ scale_x_continuous(name="Proportion of age group vaccinated", labels=label_percent(accuracy=1))+ scale_y_discrete(name="IMD decile", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ scale_fill_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ theme_custom()+ labs(title="Child vaccination rates are lowest in deprived areas", subtitle="Proportion of 12-17 year olds who have received at least one COVID-19 vaccine dose", caption="Vaccination data from NHS England, population data from ONS\nPlot by @VictimOfMaths") dev.off() combined <- vaxdata_MSOA %>% merge(cases_MSOA) %>% mutate(caserate=cases*100000/allpop) agg_tiff("Outputs/COVIDVaxU18xCasesxIMDBW.tiff", units="in", width=9, height=6, res=500) ggplot(combined %>% filter(age=="12-17"), aes(x=caserate, y=vaxprop))+ geom_point(alpha=0.6)+ geom_smooth(method="lm")+ scale_x_continuous(name="Cases per 100,000 in the past week")+ scale_y_continuous(name="Proportion of 12-17 year-olds vaccinated", labels=label_percent(accuracy=1))+ theme_custom()+ labs(title="Areas with higher cases have higher child vaccination rates", subtitle="Association between the latest weekly COVID case rates and the proportion of 12-17 year-olds who have received\nat least one vaccine dose in English neighbourhoods (MSOAs)", caption="Data from NHS England, ONS and coronavirus.data.gov.uk | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDVaxU18xCasesxIMD.tiff", units="in", width=9, height=6, res=500) ggplot(combined %>% filter(age=="12-17"), aes(x=caserate, y=vaxprop, colour=as.factor(decile)))+ geom_point(alpha=0.6)+ scale_x_continuous(name="Cases per 100,000 in the past week")+ scale_y_continuous(name="Proportion of 12-17 year-olds vaccinated", labels=label_percent(accuracy=1))+ scale_colour_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ theme_custom()+ labs(title="Areas with higher cases are more affluent and have higher child vaccination rates", subtitle="Association between the latest weekly COVID case rates and the proportion of 12-17 year-olds\nwho have received at least one vaccine dose, coloured by deprivation decile, in English neighbourhoods (MSOAs)", caption="Data from NHS England, ONS and coronavirus.data.gov.uk | Plot by @VictimOfMaths") dev.off() model <- lm(caserate ~ vaxprop + decile, combined %>% filter(age=="12-17")) af <- anova(model) afss <- af$"Sum Sq" print(cbind(af,PctExp=afss/sum(afss)*100)) url <- "https://api.coronavirus.data.gov.uk/v2/data?areaType=ltla&metric=newCasesBySpecimenDateAgeDemographics&format=csv" temp <- curl_download(url=url, destfile=temp, quiet=FALSE, mode="wb") cases_age <- read.csv(temp) %>% filter(!age %in% c("00_59", "60+", "unassigned")) %>% mutate(date=as.Date(date)) %>% merge(IMD_LTLA, by.x="areaCode", by.y="LAD17CD") %>% group_by(age, decile, date) %>% summarise(cases=sum(cases), pop=sum(pop)) %>% ungroup() %>% mutate(caserate=cases*100000/pop, caserate_roll=roll_mean(caserate, 7, align="center", fill=NA), age=gsub("_", "-", age)) agg_tiff("Outputs/COVIDCasesxAgexIMD.tiff", units="in", width=11, height=8, res=500) ggplot(cases_age %>% filter(date>=as.Date("2021-05-01")), aes(x=date, y=caserate_roll, colour=as.factor(decile)))+ geom_line()+ scale_x_date(name="")+ scale_y_continuous(name="Daily cases per 100,000")+ scale_colour_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ facet_wrap(~age)+ theme_custom()+ labs(title="Cases have risen in less deprived areas in schoolkids and their parents age group", subtitle="7-day rolling average rate of new COVID cases by age and IMD decile, based on average deprivation across each Local Authority", caption="Data from coronavirus.data.gov.uk & ONS | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDCasesxAgexIMDv2.tiff", units="in", width=11, height=8, res=500) ggplot(cases_age %>% filter(date>=as.Date("2021-05-01")), aes(x=date, y=caserate_roll, colour=as.factor(decile)))+ geom_line()+ scale_x_date(name="")+ scale_y_continuous(name="Daily cases per 100,000")+ scale_colour_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ facet_wrap(~age, scales="free_y")+ theme_custom()+ labs(title="Cases have risen in less deprived areas in schoolkids and their parents age group", subtitle="7-day rolling average rate of new COVID cases by age and IMD decile, based on average deprivation across each Local Authority", caption="Data from coronavirus.data.gov.uk & ONS | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDCasesxAgexIMDU20.tiff", units="in", width=11, height=6, res=500) ggplot(cases_age %>% filter(date>=as.Date("2021-05-01") & age %in% c("05-09", "10-14", "15-19")), aes(x=date, y=caserate_roll, colour=as.factor(decile)))+ geom_line()+ scale_x_date(name="")+ scale_y_continuous(name="Daily cases per 100,000")+ scale_colour_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ facet_wrap(~age)+ theme_custom()+ labs(title="Recent peaks in COVID cases in children have been in less deprived areas", subtitle="7-day rolling average rate of new COVID cases by age and IMD decile, based on average deprivation across each Local Authority", caption="Data from coronavirus.data.gov.uk & ONS | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDCasesxAgexIMD2039.tiff", units="in", width=11, height=6, res=500) ggplot(cases_age %>% filter(date>=as.Date("2021-05-01") & age %in% c("20-24", "25-29", "30-34", "35-39")), aes(x=date, y=caserate_roll, colour=as.factor(decile)))+ geom_line()+ scale_x_date(name="")+ scale_y_continuous(name="Daily cases per 100,000")+ scale_colour_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ facet_wrap(~age)+ theme_custom()+ labs(title="The socioeconomic gradient in 20-39 year olds has been more stable", subtitle="7-day rolling average rate of new COVID cases by age and IMD decile, based on average deprivation across each Local Authority", caption="Data from coronavirus.data.gov.uk & ONS | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDCasesxAgexIMD4059.tiff", units="in", width=11, height=6, res=500) ggplot(cases_age %>% filter(date>=as.Date("2021-05-01") & age %in% c("40-44", "45-49", "50-54", "55-59")), aes(x=date, y=caserate_roll, colour=as.factor(decile)))+ geom_line()+ scale_x_date(name="")+ scale_y_continuous(name="Daily cases per 100,000")+ scale_colour_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ facet_wrap(~age)+ theme_custom()+ labs(title="The socioeconomic gradient in 40-59 year olds has reversed", subtitle="7-day rolling average rate of new COVID cases by age and IMD decile, based on average deprivation across each Local Authority", caption="Data from coronavirus.data.gov.uk & ONS | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDCasesxAgexIMD6079.tiff", units="in", width=11, height=6, res=500) ggplot(cases_age %>% filter(date>=as.Date("2021-05-01") & age %in% c("60-64", "65-69", "70-74", "75-79")), aes(x=date, y=caserate_roll, colour=as.factor(decile)))+ geom_line()+ scale_x_date(name="")+ scale_y_continuous(name="Daily cases per 100,000")+ scale_colour_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ facet_wrap(~age)+ theme_custom()+ labs(title="The socioeconomic gradient in 60-79 year olds has reversed", subtitle="7-day rolling average rate of new COVID cases by age and IMD decile, based on average deprivation across each Local Authority", caption="Data from coronavirus.data.gov.uk & ONS | Plot by @VictimOfMaths") dev.off() agg_tiff("Outputs/COVIDCasesxAgexIMD80Plus.tiff", units="in", width=11, height=6, res=500) ggplot(cases_age %>% filter(date>=as.Date("2021-05-01") & age %in% c("80-84", "85-89", "90+")), aes(x=date, y=caserate_roll, colour=as.factor(decile)))+ geom_line()+ scale_x_date(name="")+ scale_y_continuous(name="Daily cases per 100,000")+ scale_colour_paletteer_d("dichromat::BrowntoBlue_10", name="", labels=c("1 - Most deprived","2","3","4","5","6","7","8","9", "10 - least deprived"))+ facet_wrap(~age)+ theme_custom()+ labs(title="The socioeconomic gradient in 80+ year olds has reversed", subtitle="7-day rolling average rate of new COVID cases by age and IMD decile, based on average deprivation across each Local Authority", caption="Data from coronavirus.data.gov.uk & ONS | Plot by @VictimOfMaths") dev.off() agedata <- cases_age %>% group_by(age, date) %>% summarise(cases=sum(cases), pop=sum(pop)) %>% mutate(cases_roll=roll_mean(cases, 7, align="center", fill=NA)) %>% ungroup() %>% mutate(caserate=cases*100000/pop) agg_tiff("Outputs/COVIDCasesxAgeProportion.tiff", units="in", width=11, height=6, res=500) ggplot(agedata %>% filter(date>as.Date("2020-03-01")), aes(x=date, y=cases_roll, fill=age))+ geom_col(position="fill")+ scale_x_date(name="")+ scale_y_continuous(name="Proportion of cases", labels=label_percent(accuracy=1))+ scale_fill_paletteer_d("pals::stepped", name="Age")+ theme_custom()+ labs(title="The shifting age dynamics of the pandemic", subtitle="Proportion of confirmed COVID-19 cases (based on a 7-day rolling average) in England by age group", caption="Data from coronavirus.data.gov.uk | Plot by @VictimOfMaths") dev.off()
st_as_sf = function(x, ...) UseMethod("st_as_sf") st_as_sf.data.frame = function(x, ..., agr = NA_agr_, coords, wkt, dim = "XYZ", remove = TRUE, na.fail = TRUE, sf_column_name = NULL) { if (! missing(wkt)) { if (remove) x[[wkt]] = st_as_sfc(as.character(x[[wkt]])) else x$geometry = st_as_sfc(as.character(x[[wkt]])) } else if (! missing(coords)) { cc = as.data.frame(lapply(x[coords], as.numeric)) if (na.fail && any(is.na(cc))) stop("missing values in coordinates not allowed") classdim = getClassDim(rep(0, length(coords)), length(coords), dim, "POINT") x$geometry = structure( points_rcpp(as.matrix(cc), dim), n_empty = 0L, precision = 0, crs = NA_crs_, bbox = structure( c(xmin = min(cc[[1]], na.rm = TRUE), ymin = min(cc[[2]], na.rm = TRUE), xmax = max(cc[[1]], na.rm = TRUE), ymax = max(cc[[2]], na.rm = TRUE)), class = "bbox"), class = c("sfc_POINT", "sfc" ), names = NULL) if (is.character(coords)) coords = match(coords, names(x)) if (remove) x = x[-coords] } st_sf(x, ..., agr = agr, sf_column_name = sf_column_name) } st_as_sf.sf = function(x, ...) x st_as_sf.sfc = function(x, ...) st_sf(x, ...) st_geometry = function(obj, ...) UseMethod("st_geometry") st_geometry.sf = function(obj, ...) { ret = obj[[attr(obj, "sf_column")]] if (!inherits(ret, "sfc")) stop('attr(obj, "sf_column") does not point to a geometry column.\nDid you rename it, without setting st_geometry(obj) <- "newname"?') ret } st_geometry.sfc = function(obj, ...) obj st_geometry.sfg = function(obj, ...) st_sfc(obj) `st_geometry<-` = function(x, value) UseMethod("st_geometry<-") `st_geometry<-.data.frame` = function(x, value) { stopifnot(inherits(value, "sfc") || is.character(value)) if (inherits(value, "sfc")) stopifnot(nrow(x) == length(value)) if (is.character(value)) st_sf(x, sf_column_name = value) else { a = vapply(x, function(v) inherits(v, "sfc"), TRUE) if (any(a)) { w = which(a) sf_col = attr(x, "sf_column") if (! is.null(sf_col)) x[[ sf_col ]] = value else { if (length(w) > 1) warning("overwriting first sfc column") x[[ which(a)[1L] ]] = value } } else x$geometry = value st_sf(x) } } `st_geometry<-.sf` = function(x, value) { if (! is.null(value)) { stopifnot(is.character(value) || inherits(value, "sfc")) if (inherits(value, "sfc")) stopifnot(nrow(x) == length(value)) } if (!is.null(value) && is.character(value)) { if (!(value %in% names(x))) names(x)[names(x) == attr(x, "sf_column")] = value attr(x, "sf_column") <- value } else x[[attr(x, "sf_column")]] <- value if (is.null(value)) structure(x, sf_column = NULL, agr = NULL, class = setdiff(class(x), "sf")) else x } st_set_geometry = function(x, value) { st_geometry(x) = value x } st_as_sfc.sf = function(x, ...) st_geometry(x) list_column_to_sfc = function(x) { if (is.list(x) && !inherits(x, "data.frame")) { if (inherits(try(y <- st_as_sfc(x), silent = TRUE), "try-error")) x else y } else x } st_sf = function(..., agr = NA_agr_, row.names, stringsAsFactors = sf_stringsAsFactors(), crs, precision, sf_column_name = NULL, check_ring_dir = FALSE, sfc_last = TRUE) { x = list(...) if (length(x) == 1L && (inherits(x[[1L]], "data.frame") || (is.list(x) && !inherits(x[[1L]], "sfc")))) x = x[[1L]] all_sfc_columns = vapply(x, function(x) inherits(x, "sfc"), TRUE) if (! any(all_sfc_columns)) { xlst = lapply(x, list_column_to_sfc) all_sfc_columns = vapply(xlst, function(x) inherits(x, "sfc"), TRUE) if (! any(all_sfc_columns)) stop("no simple features geometry column present") x[all_sfc_columns] = xlst[all_sfc_columns] } all_sfc_columns = which(unlist(all_sfc_columns)) all_sfc_names = if (!is.null(names(x)) && any(nzchar(names(x)[all_sfc_columns]))) names(x)[all_sfc_columns] else { object = as.list(substitute(list(...)))[-1L] arg_nm = sapply(object, function(x) deparse(x)) if (identical(arg_nm, ".")) arg_nm = "geometry" make.names(arg_nm[all_sfc_columns]) } if (! is.null(sf_column_name)) { stopifnot(sf_column_name %in% all_sfc_names) sf_column = match(sf_column_name, all_sfc_names) sfc_name = sf_column_name } else { sf_column = all_sfc_columns[1L] sfc_name = all_sfc_names[1L] } if (missing(row.names)) row.names = seq_along(x[[sf_column]]) df = if (inherits(x, "tbl_df")) x else if (length(x) == 1) data.frame(row.names = row.names) else if (!sfc_last & inherits(x, "data.frame")) x else if (sfc_last && inherits(x, "data.frame")) x[-all_sfc_columns] else cbind(data.frame(row.names = row.names), as.data.frame(x[-all_sfc_columns], stringsAsFactors = stringsAsFactors, optional = TRUE)) if (check_ring_dir) { for (i in seq_along(all_sfc_names)) df[[ all_sfc_names[i] ]] = st_sfc(x[[ all_sfc_columns[i] ]], check_ring_dir = check_ring_dir) } else { for (i in seq_along(all_sfc_names)) df[[ all_sfc_names[i] ]] = x[[ all_sfc_columns[i] ]] } if (! missing(precision)) attr(df[[sfc_name]], "precision") = precision attr(df, "sf_column") = sfc_name if (! inherits(df, "sf")) class(df) = c("sf", class(df)) st_agr(df) = agr if (! missing(crs)) st_crs(df) = crs df } "[.sf" = function(x, i, j, ..., drop = FALSE, op = st_intersects) { nargs = nargs() agr = st_agr(x) if (!missing(i) && (inherits(i, "sf") || inherits(i, "sfc") || inherits(i, "sfg"))) i = lengths(op(x, i, ...)) != 0 sf_column = attr(x, "sf_column") geom = st_geometry(x) if (!missing(i) && nargs > 2) { if (is.character(i)) i = match(i, row.names(x)) geom = geom[i] } class(x) = setdiff(class(x), "sf") x = if (missing(j)) { if (nargs == 2) x[i] else x[i, , drop = drop] } else x[i, j, drop = drop] if (!missing(j)) agr = agr[j] else if (!missing(i) && nargs <= 2) agr = agr[i] if (inherits(x, "sfc")) x else if (! drop) { x[[ sf_column ]] = geom x = st_sf(x, sf_column_name = sf_column, sfc_last = FALSE) st_set_agr(x, agr[match(setdiff(names(x), sf_column), names(agr))]) } else structure(x, class = setdiff(class(x), "sf")) } "$<-.sf" = function(x, i, value) { if (is.null(value) && inherits(x[[i]], "sfc") && ((is.character(i) && i == attr(x, "sf_column")) || (is.integer(i) && names(x)[i] == attr(x, "sf_column")))) st_set_geometry(x, NULL) else { x[[i]] = value x } } "[[<-.sf" = function(x, i, value) { agr = st_agr(x) setting_geom = (i == attr(x, "sf_column")) || inherits(value, "sfc") if (! setting_geom) { ix = if (is.character(i)) which(i == names(x)) else i if (is.null(value)) agr = agr[-ix] else { if (length(ix) == 0 || ix > length(names(x))) agr = st_agr(c(as.character(agr), NA_character_)) else agr[ix] = NA } } x = structure(NextMethod(), class = c("sf", setdiff(class(x), "sf"))) if (! setting_geom) st_agr(x) = agr x } print.sf = function(x, ..., n = getOption("sf_max_print", default = 10)) { geoms = which(vapply(x, function(col) inherits(col, "sfc"), TRUE)) nf = length(x) - length(geoms) app = paste("and", nf, ifelse(nf == 1, "field", "fields")) if (any(!is.na(st_agr(x)))) app = paste0(app, "\n", "Attribute-geometry relationship: ", summarize_agr(x)) if (length(geoms) > 1) app = paste0(app, "\n", "Active geometry column: ", attr(x, "sf_column")) print(st_geometry(x), n = 0, what = "Simple feature collection with", append = app) if (n > 0) { if (inherits(x, "tbl_df")) NextMethod() else { y <- x if (nrow(y) > n) { cat(paste("First", n, "features:\n")) y <- x[1:n, , drop = FALSE] } print.data.frame(y, ...) } } invisible(x) } merge.sf = function(x, y, ...) { if (inherits(y, "sf")) stop("merge on two sf objects not supported") sf_column = attr(x, "sf_column") ret = NextMethod() class(ret) = setdiff(class(ret), "sf") g = ret[[sf_column]] ret[[sf_column]] = NULL st_set_geometry(ret, st_sfc(g)) } as.data.frame.sf = function(x, ...) { class(x) <- setdiff(class(x), "sf") NextMethod() } st_drop_geometry = function(x) { if (!inherits(x, "sf")) stop("st_drop_geometry only works with objects of class sf") st_set_geometry(x, NULL) } transform.sf <- function (`_data`, ...) { st_as_sf(NextMethod(), agr = st_agr(`_data`), sf_column_name = attr(`_data`, "sf_column")) }
HierStraussHard <- local({ HSHpotential <- function(d, tx, tu, par) { r <- par$iradii h <- par$hradii if(!is.factor(tx) || !is.factor(tu)) stop("marks of data and dummy points must be factor variables") lx <- levels(tx) lu <- levels(tu) if(length(lx) != length(lu) || any(lx != lu)) stop("marks of data and dummy points do not have same possible levels") if(!identical(lx, par$types)) stop("data and model do not have the same possible levels of marks") if(!identical(lu, par$types)) stop("dummy points and model do not have the same possible levels of marks") lxname <- make.names(lx, unique=TRUE) uptri <- par$archy$relation & !is.na(r) mark1 <- (lx[row(r)])[uptri] mark2 <- (lx[col(r)])[uptri] mark1name <- (lxname[row(r)])[uptri] mark2name <- (lxname[col(r)])[uptri] vname <- apply(cbind(mark1name,mark2name), 1, paste, collapse="x") vname <- paste("mark", vname, sep="") npairs <- length(vname) z <- array(FALSE, dim=c(dim(d), npairs), dimnames=list(character(0), character(0), vname)) if(length(z) > 0) { rxu <- r[ tx, tu ] str <- (d <= rxu) hxu <- h[ tx, tu ] forbid <- (d < hxu) forbid[is.na(forbid)] <- FALSE value <- str value[forbid] <- -Inf for(i in 1:npairs) { Xsub <- (tx == mark1[i]) Qsub <- (tu == mark2[i]) z[Xsub, Qsub, i] <- value[Xsub, Qsub] } } return(z) } delHSH <- function(which, types, iradii, hradii, archy, ihc) { iradii[which] <- NA if(any(!is.na(iradii))) { return(HierStraussHard(types=types, iradii=iradii, hradii=hradii, archy=archy)) } else if(any(!ihc)) { return(HierHard(types=types, hradii=hradii, archy=archy)) } else return(Poisson()) } BlankHSHobject <- list( name = "Hierarchical Strauss-hard core process", creator = "HierStraussHard", family = "hierpair.family", pot = HSHpotential, par = list(types=NULL, iradii=NULL, hradii=NULL, archy=NULL), parnames = c("possible types", "interaction distances", "hardcore distances", "hierarchical order"), pardesc = c("vector of possible types", "matrix of interaction distances", "matrix of hardcore distances", "hierarchical order"), hasInf = TRUE, selfstart = function(X, self) { types <- self$par$types hradii <- self$par$hradii archy <- self$par$archy if(!is.null(types) && !is.null(hradii) && !is.null(archy)) return(self) if(is.null(types)) types <- levels(marks(X)) if(is.null(archy)) archy <- seq_len(length(types)) if(!inherits(archy, "hierarchicalordering")) archy <- hierarchicalordering(archy, types) if(is.null(hradii)) { marx <- marks(X) d <- nndist(X, by=marx) h <- aggregate(d, by=list(from=marx), min) h <- as.matrix(h[, -1L, drop=FALSE]) m <- table(marx) mm <- outer(m, m, pmin) hradii <- h * mm/(mm+1) dimnames(hradii) <- list(types, types) h[!(archy$relation)] <- NA } HierStraussHard(types=types,hradii=hradii, iradii=self$par$iradii, archy=archy) }, init = function(self) { types <- self$par$types iradii <- self$par$iradii hradii <- self$par$hradii if(!is.null(types)) { if(!is.null(dim(types))) stop(paste("The", sQuote("types"), "argument should be a vector")) if(length(types) == 0) stop(paste("The", sQuote("types"),"argument should be", "either NULL or a vector of all possible types")) if(anyNA(types)) stop("NA's not allowed in types") if(is.factor(types)) { types <- levels(types) } else { types <- levels(factor(types, levels=types)) } nt <- length(types) MultiPair.checkmatrix(iradii, nt, sQuote("iradii"), asymmok=TRUE) if(!is.null(hradii)) MultiPair.checkmatrix(hradii, nt, sQuote("hradii"), asymmok=TRUE) } ina <- is.na(iradii) if(all(ina)) stop(paste("All entries of", sQuote("iradii"), "are NA")) if(!is.null(hradii)) { hna <- is.na(hradii) both <- !ina & !hna if(any(iradii[both] <= hradii[both])) stop("iradii must be larger than hradii") } }, update = NULL, print = function(self) { iradii <- self$par$iradii hradii <- self$par$hradii types <- self$par$types archy <- self$par$archy if(waxlyrical('gory')) splat(nrow(iradii), "types of points") if(!is.null(types) && !is.null(archy)) { if(waxlyrical('space')) { splat("Possible types and ordering:") } else cat("Hierarchy: ") print(archy) } else if(!is.null(types)) { (if(waxlyrical('space')) splat else cat)("Possible types: ") print(types) } else if(waxlyrical('gory')) splat("Possible types:\t not yet determined") splat("Interaction radii:") dig <- getOption("digits") print(hiermat(signif(iradii, dig), archy)) if(!is.null(hradii)) { splat("Hardcore radii:") print(hiermat(signif(hradii, dig), archy)) } else splat("Hardcore radii: not yet determined") invisible(NULL) }, interpret = function(coeffs, self) { typ <- self$par$types ntypes <- length(typ) r <- self$par$iradii h <- self$par$hradii uptri <- self$par$archy$relation & !is.na(r) index1 <- (row(r))[uptri] index2 <- (col(r))[uptri] npairs <- length(index1) gammas <- matrix(NA, ntypes, ntypes) dimnames(gammas) <- list(typ, typ) gammas[ cbind(index1, index2) ] <- exp(coeffs) return(list(param=list(gammas=gammas), inames="interaction parameters gamma_ij", printable=hiermat(dround(gammas), self$par$archy))) }, valid = function(coeffs, self) { iradii <- self$par$iradii hradii <- self$par$hradii gamma <- (self$interpret)(coeffs, self)$param$gammas required <- !is.na(iradii) & self$par$archy$relation if(!all(is.finite(gamma[required]))) return(FALSE) d <- diag(rep(TRUE, nrow(iradii))) activehard <- !is.na(hradii) & (hradii > 0) return(all(gamma[required & d & !activehard] <= 1)) }, project = function(coeffs, self) { gamma <- (self$interpret)(coeffs, self)$param$gammas iradii <- self$par$iradii hradii <- self$par$hradii types <- self$par$types archy <- self$par$archy activehard <- !is.na(hradii) & (hradii > 0) ihc <- !activehard uptri <- archy$relation required <- !is.na(iradii) & uptri offdiag <- !diag(nrow(iradii)) gammavalid <- is.finite(gamma) & (activehard | offdiag | (gamma <= 1)) naughty <- required & !gammavalid if(!any(naughty)) return(NULL) if(spatstat.options("project.fast")) { return(delHSH(naughty, types, iradii, hradii, archy, ihc)) } else { rn <- row(naughty) cn <- col(naughty) ord <- self$par$archy$ordering uptri <- (ord[rn] <= ord[cn]) upn <- uptri & naughty rowidx <- as.vector(rn[upn]) colidx <- as.vector(cn[upn]) mats <- lapply(as.data.frame(rbind(rowidx, colidx)), matrix, ncol=2) inters <- lapply(mats, delHSH, types=types, iradii=iradii, hradii=hradii, archy=archy, ihc=ihc) return(inters) } }, irange = function(self, coeffs=NA, epsilon=0, ...) { r <- self$par$iradii h <- self$par$hradii ractive <- !is.na(r) & self$par$archy$relation hactive <- !is.na(h) & self$par$archy$relation if(any(!is.na(coeffs))) { gamma <- (self$interpret)(coeffs, self)$param$gammas gamma[is.na(gamma)] <- 1 ractive <- ractive & (abs(log(gamma)) > epsilon) } if(!any(c(ractive,hactive))) return(0) else return(max(c(r[ractive],h[hactive]))) }, version=NULL ) class(BlankHSHobject) <- "interact" HierStraussHard <- function(iradii, hradii=NULL, types=NULL, archy=NULL) { if(!is.null(types)) { if(is.null(archy)) archy <- seq_len(length(types)) archy <- hierarchicalordering(archy, types) } iradii[iradii == 0] <- NA out <- instantiate.interact(BlankHSHobject, list(types=types, iradii=iradii, hradii=hradii, archy=archy)) if(!is.null(types)) { dn <- list(types, types) dimnames(out$par$iradii) <- dn if(!is.null(out$par$hradii)) dimnames(out$par$hradii) <- dn } return(out) } HierStraussHard <- intermaker(HierStraussHard, BlankHSHobject) HierStraussHard })
quiet <- function(x) { sink(tempfile()) on.exit(sink()) invisible(force(x)) }
OptRegionTps <- function(X, y, lambda = 0.04, nosim = 1000, alpha = 0.05, LB, UB, triangularRegion = FALSE, vertex1 = NULL, vertex2 = NULL, maximization = TRUE, xlab = "Protein eaten, mg", ylab = "Carbohydrate eaten, mg", outputPDFFile = "CRplot.pdf", outputOptimaFile = "Optima.txt") { k <- dim(X)[2] if ((k > 2) | (k < 2)) stop("Error. Number of factors must equal to 2") if (triangularRegion) { x11p <- vertex1[1] x21 <- vertex1[2] x12 <- vertex2[1] x22 <- vertex2[2] m1 <- x21 / x11p m2 <- x22 / x12 m3 <- (x21 - x22) / (x11p - x12) bintercept <- x22 - m3 * x12 } else { m1 <- 0 m2 <- 0 m3 <- 0 bintercept <- 0 } model <- fields::Tps(X, y, lambda = lambda) out <- fields::Krig.replicates(model) X <- out$xM y <- out$yM model <- fields::Tps(X, y, lambda = lambda) fit <- model$fitted.values nn <- length(y) p <- 3 A <- fields::Krig.Amatrix(model) df <- 2 * sum(diag(A)) - sum(diag(A %*% t(A))) T <- fields::Krig.null.function(model$knots, m = 2) Sigma <- fields::Rad.cov(model$knots, model$knots, p = 2, m = 2) Q <- qr.Q(model$matrices$qr.T, complete = TRUE) F2 <- Q[, (p + 1):nn] M <- solve(t(F2) %*% (Sigma + lambda * diag(nn)) %*% F2) %*% t(F2) w2Hat <- M %*% y MMt <- M %*% t(M) den <- sqrt(diag((diag(nn) - A) %*% (diag(nn) - A))) res <- model$residuals / den w2vectors <- matrix(nrow = nosim, ncol = nn - p) dstar <- matrix(nrow = nosim, ncol = p) w2vectorsStd <- matrix(nrow = nosim, ncol = nn - p) print("Bootstrapping...") for (i in 1:nosim) { indices <- sample(1:nn, replace = TRUE) ystar <- fit + res[indices] modelstar <- fields::Tps(X, ystar, lambda = lambda) w2vectors[i, ] <- M %*% ystar dstar[i, ] <- t(modelstar$d) resstar <- modelstar$residuals / den sigma2star <- norm(resstar) / df Vi <- sigma2star * MMt e <- eigen(Vi, symmetric = TRUE) Ssqrtinv <- solve(e$vectors %*% diag(sqrt(e$values)) %*% t(e$vectors)) w2vectorsStd[i, ] <- Ssqrtinv %*% (w2vectors[i, ] - w2Hat) * sqrt(nn - p) print(i) } deep <- vector(length = nosim) w2vectorsStdMat <- as.matrix(w2vectorsStd) d <- DepthProc::depthTukey(w2vectorsStdMat, w2vectorsStdMat, ndir = 3000) order.d <- order(d) ind.alpha <- alpha * nosim + 1 indices <- order.d[(ind.alpha:nosim)] w2vectors_In <- w2vectors[indices, ] dstar_In <- dstar[indices, ] l <- dim(w2vectors_In) delta1 <- 0.1 * (UB[1] - LB[1]) delta2 <- 0.1 * (UB[2] - LB[2]) X0 <- matrix(nrow = 5, ncol = k) if (triangularRegion) { X0[1, ] <- c(LB[1] + delta1, LB[2] + delta2) X0[2, ] <- vertex1 - c(0, delta2) X0[3, ] <- vertex2 - c(delta1, 0) X0[4, ] <- c(mean(X0[1:3, 1]), mean(X0[1:3, 2])) X0[, 2] <- apply(cbind(X0[, 2], UB[2]), 1, min) X0[, 2] <- apply(cbind(X0[, 2], LB[2]), 1, max) X0[, 1] <- apply(cbind(X0[, 1], UB[1]), 1, min) X0[, 1] <- apply(cbind(X0[, 1], LB[1]), 1, max) noinitial <- 4 numberFeasible <- 4 } else { X0[1, ] <- c(LB[1] + delta1, LB[2] + delta2) X0[2, ] <- c(LB[1] + delta1, UB[2] - delta2) X0[3, ] <- c(UB[1] - delta1, LB[2] + delta2) X0[4, ] <- c(UB[1] - delta1, UB[2] - delta2) X0[5, ] <- c(mean(X0[1:4, 1]), mean(X0[1:4, 2])) noinitial <- 5 numberFeasible <- 5 } xin <- matrix(nrow = l[1], ncol = k) print("Computing optima...") for (m in 1:l[1]) { cCoef <- F2 %*% w2vectors_In[m, ] dCoef <- dstar_In[m, ] best <- 1e50 for (j in 1:numberFeasible) { if (triangularRegion) { local_opts <- list("algorithm" = "NLOPT_LN_COBYLA", "xtol_rel" = 1.0e-3) opts <- list("algorithm" = "NLOPT_LN_AUGLAG", print_level = 0, "local_opts" = local_opts) out <- nloptr::nloptr(X0[j, ], eval_f = computefTps, eval_grad_f = NULL, eval_jac_g_ineq = NULL, lb = LB, ub = UB, eval_g_eq = NULL, eval_g_ineq = constraintsTps, opts = opts, cCoef = cCoef, dCoef = dCoef, maximization = maximization, m1 = m1, m2 = m2, m3 = m3, bintercept = bintercept, knots = model$knots, center = model$transform$x.center, scale = model$transform$x.scale) } else { out <- nloptr::nloptr(X0[j, ], eval_f = computefTps, eval_grad_f = NULL, lb = LB, ub = UB, eval_g_eq = NULL, eval_g_ineq = NULL, opts = list("algorithm" = "NLOPT_LN_COBYLA", print_level = 0, xtol_rel = 1e-03), cCoef = cCoef, dCoef = dCoef, maximization = maximization, m1 = m1, m2 = m2, m3 = m3, bintercept = bintercept, knots = model$knots, center = model$transform$x.center, scale = model$transform$x.scale) } if ((out$objective < best) & (out$status > 0)) { best <- out$objective bestSol <- out$sol bestStatus <- out$status } } xin[m, ] <- bestSol print(c(m, best, xin[m, ], bestStatus)) } pdf(file = outputPDFFile, 5.5, 5.5) coords <- plotConvexHull(xin, LB, UB, xlab, ylab) par(new = TRUE) par(cex.axis = 1.35, cex.lab = 1.5) par(xaxt = "n", yaxt = "n") centroid <- apply(xin, 2, mean) points(centroid[1], centroid[2], col = "red", pch = 19) par(new = TRUE) par(cex.axis = 1.35, cex.lab = 1.5) par(xaxt = "n", yaxt = "n") tpsfit <- fields::Tps(X, y, lambda = lambda) surface <- fields::predictSurface(tpsfit) image(surface, lwd = 2, col = heat.colors(0), cex.axis = 1.35, cex.lab = 1.5, xlim = c(LB[1], UB[1]), ylim = c(LB[2], UB[2])) contour(surface, add = T, drawlabels = T, lwd = 2, cex.axis = 1.35, cex.lab = 1.5, xlim = c(LB[1], UB[1]), ylim = c(LB[2], UB[2])) dev.off() write(t(xin), file = outputOptimaFile, ncolumns = 2) return(list(meanPoint = centroid, xin = xin)) } constraintsTps <- function(x, cCoef, dCoef, maximization, m1, m2, m3, bintercept, knots, center, scale) { z <- vector(length = 3) z[1] <- x[2] - m1 * x[1] z[2] <- m2 * x[1] - x[2] z[3] <- x[2] - bintercept - m3 * x[1] return(z) } plotConvexHull <- function(xin, LB, UB, xlab = "X", ylab = "Y") { plot(0, 0, col = "white", xlim = c(LB[1], UB[1]), ylim = c(LB[2], UB[2]), xlab = xlab, ylab = ylab) hpts_original <- chull(xin) hpts_closed <- c(hpts_original, hpts_original[1]) lines(xin[hpts_closed, ], col = "blue") polygon(xin[hpts_closed, 1], xin[hpts_closed, 2], col = "grey") return(hpts_original) } computefTps <- function(x, cCoef, dCoef, maximization, m1, m2, m3, bintercept, knots, center, scale) { k <- length(x) xscaled <- scale(t(x), center, scale) to <- fields::fields.mkpoly(xscaled, m = 2) Psi <- fields::Rad.cov(xscaled, knots, p = 2, m = 2) f <- to %*% dCoef + Psi %*% cCoef if (maximization) { return(-f) } else { return(f) } }
GMSCDM <- function(dat, msQ, model = "ACDM", s = 1, att.prior=NULL, delta = NULL, control = list()){ if (exists(".Random.seed", .GlobalEnv)) { oldseed <- .GlobalEnv$.Random.seed on.exit(.GlobalEnv$.Random.seed <- oldseed) } else { on.exit(rm(".Random.seed", envir = .GlobalEnv)) } myControl <- list(conv.crit = 0.0001, maxitr = 2000, conv.type=c("ip","mp"),seed=123, lower.p = 1e-4, solver = "auglag") control <- utils::modifyList(myControl,control) set.seed(control$seed) item.no <- msQ[,1] str.no <- msQ[,2] Q <- msQ[,-c(1:2)] N <- nrow(dat) J <- ncol(dat) S <- nrow(Q) K <- ncol(Q) Kj <- rowSums(Q) patt <- attributepattern(K) L <- nrow(patt) sm <- vector("logical",J) for(j in 1:J) sm[j] <- sum(item.no==j)>1 if(is.null(att.prior)){ att.prior <- matrix(rep(1/L, L),ncol = 1) logprior <- matrix(log(att.prior),nrow = L,ncol = 1) } Qjf <- unrestrQ(msQ) Qjf <- Qjf[which(Qjf[,2]==1),] Qj <- Qjf[,-c(1:2)] models <- c("DINA","DINO","rDINA","rDINO","ACDM","LLM","RRUM") model_numeric <- which(model==models) - 2 d <- list() if(is.null(delta)){ for(j in 1:J){ ub <- runif(1,0.75,0.99) lb <- runif(1,0.01,0.25) db <- ub - lb jrows <- which(item.no==j) qj <- apply(Q[jrows,,drop=FALSE],2,max) Kjmax <- which(qj==1) if(model_numeric==-1){ d[[j]] <- c(lb,rep(db,sum(item.no==j))) }else if(model_numeric==0){ d[[j]] <- c(lb,rep(db,sum(item.no==j))) }else if(model_numeric==1){ d[[j]] <- c(lb,db) }else if(model_numeric==2){ d[[j]] <- c(lb,db) }else if(model_numeric==3){ dj <- db/Kj[jrows] dd <- Q[jrows,,drop=FALSE] dd[dd==0] <- NA for(rr in 1:nrow(dd)) dd[rr,] <- dd[rr,]*dj[rr] d[[j]] <- c(lb,apply(dd[,Kjmax,drop=FALSE],2,min,na.rm=TRUE)) }else if(model_numeric==4){ dj <- (qlogis(ub)-qlogis(lb))/Kj[jrows] dd <- Q[jrows,,drop=FALSE] dd[dd==0] <- NA for(rr in 1:nrow(dd)) dd[rr,] <- dd[rr,]*dj[rr] d[[j]] <- c(qlogis(lb),apply(dd[,Kjmax,drop=FALSE],2,min,na.rm=TRUE)) }else if(model_numeric==5){ dj <- (log(ub)-log(lb))/Kj[jrows] dd <- Q[jrows,,drop=FALSE] dd[dd==0] <- NA for(rr in 1:nrow(dd)) dd[rr,] <- dd[rr,]*dj[rr] d[[j]] <- c(log(lb),apply(dd[,Kjmax,drop=FALSE],2,min,na.rm=TRUE)) } } }else{ d <- delta } des <- list() i <- 1 for(j in 1:J){ jrows <- which(item.no==j) qj <- apply(Q[jrows,,drop=FALSE],2,max) Kjmax <- which(qj==1) des1 <- patt[,Kjmax,drop=FALSE] for(ss in str.no[jrows]){ if(model_numeric>2){ red.qjs <- Q[which(item.no==j&str.no==ss),which(qj==1)] des[[i]] <- cbind(1,sweep(des1,2,red.qjs,FUN = "*")) }else if(model_numeric==1){ des[[i]] <- designmatrix(K,model_numeric) des[[i]][which(apply(patt[,which(Q[which(item.no==j&str.no==ss),]==1),drop=FALSE],1,min)==1),2] <- 1 }else if(model_numeric==2){ des[[i]] <- designmatrix(K,model_numeric) des[[i]][which(apply(patt[,which(Q[which(item.no==j&str.no==ss),]==1),drop=FALSE],1,max)==1),2] <- 1 }else if(model_numeric==-1){ if(sm[j]){ des[[i]] <- cbind(1,matrix(0,L,length(jrows))) des[[i]][which(apply(patt[,which(Q[which(item.no==j&str.no==ss),]==1),drop=FALSE],1,min)==1),ss+1] <- 1 }else{ des[[i]] <- designmatrix(K,1) des[[i]][which(apply(patt[,which(Q[which(item.no==j&str.no==ss),]==1),drop=FALSE],1,min)==1),2] <- 1 } }else if(model_numeric==0){ if(sm[j]){ des[[i]] <- cbind(1,matrix(0,L,length(jrows))) des[[i]][which(apply(patt[,which(Q[which(item.no==j&str.no==ss),]==1),drop=FALSE],1,max)==1),ss+1] <- 1 }else{ des[[i]] <- designmatrix(K,2) des[[i]][which(apply(patt[,which(Q[which(item.no==j&str.no==ss),]==1),drop=FALSE],1,max)==1),2] <- 1 } } i <- i+1 } } plc <- d2p(d = d,des = des,msQ = msQ,model = model_numeric,r=s) maxchg <- 10L itr <- 0L parm0 <- list(ip = c(plc), prior = c(exp(logprior)), neg2LL = 0, delt = unlist(d)) dif.parm <- list(ip = 0, prior = 0, neg2LL = 0, delt = 0) while (maxchg > control$conv.crit && itr < control$maxitr) { d0 <- unlist(d) estep <- LikNR_LC(as.matrix(plc), as.matrix(dat), matrix(logprior,ncol = 1), rep(1,N), rep(1,N), 0) dev1 <- estep$LL*(-2) for(j in 1:J){ if(control$solver=="auglag"){ d[[j]] <- alabama::auglag(par = d[[j]],fn=objf,hin = inf,j=j,des=des,msQ=msQ,Nj=estep$N[j,],Rj = estep$R[j,], model=model_numeric,r=s,control.outer = list(trace=FALSE,method="nlminb",kkt2.check=FALSE,eps=1e-6))$par }else if(control$solver=="nloptr"){ message("nloptr is not available") } } plc <- d2p(d = d,des = des,msQ = msQ,model=model_numeric,r=s) logprior <- c(estep$logprior) parm1 <- list(ip = c(plc), prior = c(exp(logprior)), neg2LL = -2*estep$LL, delt = unlist(d)) dif.parm <- list(ip = max(abs(parm1$ip-parm0$ip),na.rm = TRUE), prior = max(abs(parm1$prior-parm0$prior),na.rm = TRUE), neg2LL = parm0$neg2LL-parm1$neg2LL, delt = max(abs(parm1$delt-parm0$delt),na.rm = TRUE)) parm0 <- parm1 itr <- itr + 1 maxchg <- 0 if(any(tolower(control$conv.type)=="ip")) maxchg <- max(maxchg,dif.parm$ip) if(any(tolower(control$conv.type)=="delta")) maxchg <- max(maxchg,dif.parm$delt) if(any(tolower(control$conv.type)=="mp")) maxchg <- max(maxchg,dif.parm$prior) if(any(tolower(control$conv.type)=="neg2ll")) maxchg <- max(maxchg,abs(dif.parm$neg2LL)) cat('\rIteration =',itr,' Max change =',formatC(maxchg,digits = 5, format = "f"), ' Deviance =',formatC(-2*estep$LL,digits = 2, format = "f")) } estep <- LikNR_LC(as.matrix(plc), as.matrix(dat), matrix(logprior,ncol = 1), rep(1,N), rep(1,N), 0) neg2LL <- -2 * estep$LL npar <- length(unlist(d)) + L - 1 AIC <- 2 * npar + neg2LL BIC <- neg2LL + npar * log(N) sIRF <- pjmc <- sprv <- list() for(j in seq_len(J)){ x <- sp(j,d[[j]],des,msQ,model=model_numeric,r=s) sIRF[[j]] <- x$sIRF pjmc[[j]] <- x$pjmc sprv[[j]] <- colSums(c(exp(estep$logprior))*x$pjmc) } item.names <- paste("Item",seq_len(J)) LC.names <- apply(patt,1,paste0,collapse="") sprv <- l2m(sprv) rownames(plc) <- rownames(sprv) <- item.names colnames(plc) <- paste0("P(",LC.names,")") colnames(sprv) <- paste("Strategy",seq_len(max(msQ[,2]))) for(j in seq_len(J)){ rownames(sIRF[[j]]) <- rownames(pjmc[[j]]) <- LC.names colnames(sIRF[[j]]) <- colnames(pjmc[[j]]) <- paste("Strategy",c(msQ[which(msQ[,1]==j),2])) } att <- list(EAP = 1*((exp(estep$logpost) %*% patt) > 0.5000), MLE = patt[apply(estep$loglik,1,which.max.randomtie),], MAP = patt[apply(estep$logpost,1,which.max.randomtie),]) ret <- list(prob=plc,delta=d,att=att,testfit=list(deviance=neg2LL,npar=npar,AIC=AIC,BIC=BIC),sIRF=sIRF,pjmc=pjmc,sprv=sprv) class(ret) <- "GMSCDM" invisible(ret) }
gini.dataProcessed <- function(x) { r <- length(x$yh) t <- 2:r g <- dim(x$Phl)[2] s <- dim(x$Qhlk)[3] g_names <- colnames(x$Phl) s_names <- dimnames(x$Qhlk)[[3]] nhl <- x$Phl nhl[t, ] <- NA nhl[t, ] <- x$Phl[t, ] - x$Phl[t - 1, ] nh <- rowSums(nhl) nl <- colSums(nhl) N <- sum(nl) fl <- nl / N ph <- rowSums(x$Phl) / N ol <- apply(nhl, 2, function (l) min(which(l > 0))) pl_h <- x$Phl / rowSums(x$Phl) wllh <- array(sapply(1:r, function(h) outer(fl, pl_h[h, ])), c(g, g, r)) dimnames(wllh) <- list(l1 = g_names, l2 = g_names, h = 1:r) Shlk <- x$Qhlk Shlk[t, , ] <- NA Shlk[t, , ] <- x$Qhlk[t, , ] - x$Qhlk[t-1, , ] tmp <- Minfhlk <- x$Qhlk tmp[] <- Minfhlk[] <- NA for (k in 1:s) { for (h in 1:r) { for (l in 1:g) { tmp[h, l, k] <- x$Qhlk[h, l, k] / x$Phl[h, l] Minfhlk[h, l, k] <- ifelse( is.nan(tmp[h, l, k]) == TRUE, Shlk[ol[l], l, k] / nhl[ol[l], l], tmp[h, l, k] ) } } } Minfhl <- apply(Minfhlk, c(1, 2), sum) MY <- sum(Minfhl[r, ] %*% x$Phl[r, ]) / sum(x$Phl[r, ]) Mlk <- array(Minfhlk[r, , ], c(g, s)) dimnames(Mlk) <- dimnames(Minfhlk)[-1] tmp <- array( sapply(1:s, function(k) sapply(1:r, function(h) outer(Mlk[, k], Minfhlk[h, , k], "-") / MY ) ), c(g, g, r, s) ) Vllhk <- array( sapply(1:s, function(k) tmp[, , , k] * wllh), c(g, g, r, s) ) dimnames(Vllhk) <- list( l1 = g_names, l2 = g_names, h = 1:r, k = dimnames(x$Qhlk)[[3]] ) flh <- matrix(0, r, g) for (l in 1:g) { flh[, l] <- nhl[, l] / nh } dimnames(flh) <- list(h = 1:r, l = g_names) wll_h <- array(0, c(g, g, r)) for (h in 1:r) { wll_h[ , , h] <- outer(nl / N, flh[h, ], "*") } dimnames(wll_h) <- list(l1 = g_names, l2 = g_names, h = 1:r) Mhlk <- array(0, c(r, g, s)) for (k in 1:s) { Mhlk[ , , k] <- Shlk[ , , k] / nhl } for (h in 1:r) { for (l in 1:g) { Mhlk[h, l, ] <- ifelse(is.nan(Mhlk[h, l, ]) == 1, 0, Mhlk[h, l, ]) } } dimnames(Mhlk) <- list(h = 1:r, l = g_names, k = s_names) Allhk <- array(0, c(g, g, r, s)) for (k in 1:s) { for (h in 1:r) { Allhk[ , , h, k] <- outer(Mlk[ , k], Mhlk[h, , k], "-") / MY * wll_h[ , , h] } } Cllhk <- array(0, c(g, g, r, s)) for (h in 1:r){ Cllhk[ , , h, ] <- Vllhk[ , , h,] * 2 * ph[h] - Allhk[ , , h, ] * nh[h] / N } dimnames(Allhk) <- dimnames(Cllhk) <- list(l1 = g_names, l2 = g_names, h = 1:r, k = s_names) rm(tmp) res <- list( index = "Gini", decomposition = Cllhk, dataProcessed = x ) class(res) <- "decomposition" return(res) }
check_qrng <- function(){ tryCatch( expr = { req <- curl::curl_fetch_memory('https://qrng.anu.edu.au/') req$status_code }, error = function(e){ -1 } ) } getConnection <- function(website, ...) { if (capabilities()["libcurl"]) { url(website, ..., method = "libcurl") } else { curl(website, ...) } } closeConnection <- function(con) { if (capabilities()["libcurl"]) { close(con) } } get_sequence <- function(n = 1, type = "uint8", blocksize = 1) { urlbase <- "https://qrng.anu.edu.au/API/jsonI.php" urltxt <- paste( urlbase, "?length=", format(n, scientific = FALSE), "&type=", format(type, scientific = FALSE), sep = "" ) if (type == "hex16") { urltxt <- paste(urltxt, "&size=", format(blocksize, scientific = FALSE), sep = "") } con <- getConnection(website = urltxt, open = "r") rt <- readLines(con, encoding = "UTF-8") randNum <- as.character(rt) randNum <- fromJSON(randNum) randNum <- randNum$data closeConnection(con) return(randNum) } qrandom <- function(n = 1, type = "uint8", blocksize = 1) { if (!is.numeric(n) || !n %% 1 == 0) { stop("The number 'n' of random numbers to return has to be an integer.") } if (n < 1 || n > 100000) { stop("Random number requests must be between 1 and 100,000 numbers.") } if (!type %in% c("uint8", "uint16", "hex16")) { stop("Type has to be 'uint8', 'uint16' or 'hex16'.") } if (!is.numeric(blocksize) || !blocksize %% 1 == 0) { stop("The variable 'blocksize' has to be an integer.") } if (blocksize < 1 || blocksize > 1024) { stop("The variable 'blocksize' must be between 1 and 1,024.") } if(!curl::has_internet()){ message("No Internet connection! \n") return(invisible(NULL)) } if(!check_qrng() == 200){ message("The ANU Quantum Random Number Generator service is currently not available at [https://qrng.anu.edu.au/index.php]. \n") return(invisible(NULL)) } else{ tmp <- c() count <- n %/% 1024 remain <- n %% 1024 if (count != 0) { progress <- txtProgressBar(min = 0, max = count, style = 3) for (i in 1:count) { tmp <- c(tmp, get_sequence( n = 1024, type = type, blocksize = blocksize )) setTxtProgressBar(progress, i) } if (remain != 0) { tmp <- c(tmp, get_sequence( n = remain, type = type, blocksize = blocksize )) } close(progress) } else{ tmp <- get_sequence(n = n, type = type, blocksize = blocksize) } return(tmp) } } qrandomunif <- function(n = 1, a = 0, b = 1) { if (!is.numeric(n) || !n %% 1 == 0) { stop("The number 'n' of random numbers to return has to be an integer.") } if (n < 1 || n > 100000) { stop("Random number requests must be between 1 and 100,000 numbers.") } if (!is.numeric(a) || !is.numeric(b)) { stop("The parameters 'a' and 'b' must be numeric.") } if (!a < b) { stop("The minimum value 'a' of the distribution has to be less than parameter 'b'.") } if(!curl::has_internet()){ message("No Internet connection! \n") return(invisible(NULL)) } if(!check_qrng() == 200){ message("The ANU Quantum Random Number Generator service is currently not available at [https://qrng.anu.edu.au/index.php]. \n") return(invisible(NULL)) }else{ tmp <- qrandom(n = n, type = "hex16", blocksize = 7) a_tmp <- mpfr(a, base = 10, precBits = 52) b_tmp <- mpfr(b, base = 10, precBits = 52) tmp <- substring(tmp, 2) tmp <- mpfr(tmp, base = 16) tmp <- new("mpfr", unlist(tmp)) urand <- tmp / mpfr("fffffffffffff", base = 16) if (a != 0 || b != 1) { urand <- (b_tmp - a_tmp) * urand + a_tmp } return(as.numeric(urand)) } } qrandomnorm <- function(n = 1, mean = 0, sd = 1, method = "inverse") { if (!is.numeric(n) || !n %% 1 == 0) { stop("The number 'n' of random numbers to return has to be an integer.") } if (n < 1 || n > 100000) { stop("Random number requests must be between 1 and 100,000 numbers.") } if (!is.numeric(mean) || !is.numeric(sd)) { stop("The parameters 'mean' and 'sd' must be numeric.") } if (sd < 0) { stop("The standard deviation 'sd' must not be negative.") } if (!method %in% c("inverse", "polar", "boxmuller")) { stop( "The method for generating true normal random variables has to be 'inverse', 'polar' or 'boxmuller'." ) } if(!curl::has_internet()){ message("No Internet connection! \n") return(invisible(NULL)) } if(!check_qrng() == 200){ message("The ANU Quantum Random Number Generator service is currently not available at [https://qrng.anu.edu.au/index.php]. \n") return(invisible(NULL)) }else{ x <- vector("numeric", n) if (method == "inverse") { tmp <- qrandomunif(n = n) tmp <- qnorm(tmp) x <- sd * tmp + mean } else if (method == "polar") { x <- marsaglia_bray(n = n, mean = mean, sd = sd) } else if (method == "boxmuller") { x <- box_muller(n = n, mean = mean, sd = sd) } return(x) } } marsaglia_bray <- function(n = 1, mean = 0, sd = 1) { x <- vector("numeric", n) i <- 1 count <- 1 cat("Request 1/2:\n") tmp1 <- qrandomunif(n) cat("Request 2/2:\n") tmp2 <- qrandomunif(n) while (i <= n) { if (count > n) { count <- 1 tmp1 <- qrandomunif(n) tmp2 <- qrandomunif(n) } u <- c(tmp1[count], tmp2[count]) v <- 2 * u - 1 w <- sum(v ^ 2) if (w > 0 && w < 1) { y <- sqrt(-2 * log(w) / w) z <- v * y x[i] <- z[1] if ((i + 1) <= n) { x[i + 1] <- z[2] i <- i + 1 } i <- i + 1 } count <- count + 1 } x * sd + mean } box_muller <- function(n = 1, mean = 0, sd = 1) { x <- vector("numeric", n) count <- 1 cat("Request 1/2:\n") tmp1 <- qrandomunif(n) cat("Request 2/2:\n") tmp2 <- qrandomunif(n) i <- 1 while (i <= n) { if (count > n) { count <- 1 tmp1 <- qrandomunif(n) tmp2 <- qrandomunif(n) } u1 <- tmp1[count] u2 <- tmp2[count] if (!u1 == 0) { x[i] <- sqrt(-2 * log(u1)) * cos(2 * pi * u2) if ((i + 1) <= n) { x[i + 1] <- sqrt(-2 * log(u1)) * sin(2 * pi * u2) i <- i + 1 } i <- i + 1 } count <- count + 1 } x * sd + mean }
context("Renaming worksheets.") test_that("Can rename worksheets under all conditions", { tempFile <- file.path(tempdir(), "renaming.xlsx") wb <- createWorkbook() addWorksheet(wb, "sheet 1") addWorksheet(wb, "sheet 2") addWorksheet(wb, "sheet 3") addWorksheet(wb, "sheet 4") addWorksheet(wb, "sheet 5") renameWorksheet(wb, sheet = 2, "THis is SHEET 2") expect_equal(names(wb), c("sheet 1", "THis is SHEET 2", "sheet 3", "sheet 4", "sheet 5")) renameWorksheet(wb, sheet = "THis is SHEET 2", "THis is STILL SHEET 2") expect_equal(names(wb), c("sheet 1", "THis is STILL SHEET 2", "sheet 3", "sheet 4", "sheet 5")) renameWorksheet(wb, sheet = 5, "THis is SHEET 5") expect_equal(names(wb), c("sheet 1", "THis is STILL SHEET 2", "sheet 3", "sheet 4", "THis is SHEET 5")) renameWorksheet(wb, sheet = 5, "THis is STILL SHEET 5") expect_equal(names(wb), c("sheet 1", "THis is STILL SHEET 2", "sheet 3", "sheet 4", "THis is STILL SHEET 5")) renameWorksheet(wb, sheet = 2, "Sheet 2") expect_equal(names(wb), c("sheet 1", "Sheet 2", "sheet 3", "sheet 4", "THis is STILL SHEET 5")) renameWorksheet(wb, sheet = 5, "Sheet 5") expect_equal(names(wb), c("sheet 1", "Sheet 2", "sheet 3", "sheet 4", "Sheet 5")) worksheetOrder(wb) <- c(4,3,2,5,1) saveWorkbook(wb, tempFile, overwrite = TRUE) wb <- loadWorkbook(file = tempFile) renameWorksheet(wb, sheet = 2, "THIS is SHEET 3") wb <- loadWorkbook(tempFile) renameWorksheet(wb, sheet = "Sheet 5", "THIS is NOW SHEET 5") expect_equal(names(wb), c("sheet 4", "sheet 3", "Sheet 2", "THIS is NOW SHEET 5", "sheet 1")) names(wb)[[1]] <- "THIS IS NOW SHEET 4" expect_equal(names(wb), c("THIS IS NOW SHEET 4", "sheet 3", "Sheet 2", "THIS is NOW SHEET 5", "sheet 1")) unlink(tempFile, recursive = TRUE, force = TRUE) })
discreteCounts <- function(x, round.percents=2, name=deparse(substitute(x)), max.values=min(round(2*sqrt(length(x))), round(10*log10(length(x))), 100)){ if (is.data.frame(x)) x <- as.matrix(x) if (is.matrix(x)) { names <- colnames(x) for (j in 1:ncol(x)){ discreteCounts(x[, j], round.percents=round.percents, name=names[j], max.values=max.values) cat("\n") } return(invisible(NULL)) } Count <- table(x) if ((nv <- length(Count)) > max.values) stop("number of unique values of ", name, ", ", nv, ", exceeds maximum, ", max.values) tot <- sum(Count) Percent <- round(100*Count/tot, round.percents) tot.percent <- round(sum(Percent), round.percents) table <- cbind(Count, Percent) table <- rbind(table, c(tot, tot.percent)) rownames(table) <- c(names(Count), "Total") cat("Distribution of", name, "\n") print(table) return(invisible(Count)) }
LL=function(trat, resp, npar="LL.3", ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", ic=FALSE, fill.ic="gray70", alpha.ic=0.5, point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, pointshape = 21, round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("drc") requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) if(npar=="LL.3"){mod=drm(resp~trat,fct=LL.3()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3] e=log(e)} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round) e=round(log(e),round)} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s==frac(%0.3e, 1+e^{%0.3e*(log(%s) %s %0.3e)}) ~~~~~ italic(R^2) == %0.2f", yname.formula, d, b, xname.formula, ifelse(e <= 0, "+", "-"), abs(e), r2) xp=seq(min(trat),max(trat),length.out = 1000) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) } if(npar=="LL.5"){mod=drm(resp~trat,fct=LL.5()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=coef$coefficients[,1][2] d=coef$coefficients[,1][3] e=coef$coefficients[,1][4] f=coef$coefficients[,1][5] e=log(e) dc=d-c} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(coef$coefficients[,1][2],round) d=round(coef$coefficients[,1][3],round) e=round(coef$coefficients[,1][4],round) f=round(coef$coefficients[,1][5],round) e=round(log(e),round) dc=d-c} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s == %0.3e + frac(%0.3e, 1+e^(%0.3e*(log(%s) %s %0.3e))^%0.3e) ~~~~~ italic(R^2) == %0.2f", yname.formula, c, dc, b, xname.formula, ifelse(e <= 0, "+", "-"), abs(e), f, r2) xp=seq(min(trat),max(trat),length.out = 1000) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp)))} if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} if(npar=="LL.4"){mod=drm(resp~trat,fct=LL.4()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=coef$coefficients[,1][2] d=coef$coefficients[,1][3] e=coef$coefficients[,1][4] e=log(e) dc=d-c} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(coef$coefficients[,1][2],round) d=round(coef$coefficients[,1][3],round) e=round(coef$coefficients[,1][4],round) e=round(log(e),round) dc=d-c} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~y == %0.3e + frac(%0.3e, 1+e^{%0.3e*(log(x) %s %0.3e)}) ~~~~~ italic(R^2) == %0.2f", c, dc, b, ifelse(e <= 0, "+", "-"), abs(e), r2) xp=seq(min(trat),max(trat),length.out = 1000) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp)))} if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill="gray")} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill="gray")} if(ic==TRUE){ pred=data.frame(x=xp, y=predict(mod,interval = "confidence",newdata = data.frame(trat=xp))) preditosic=data.frame(x=c(pred$x,pred$x[length(pred$x):1]), y=c(pred$y.Lower,pred$y.Upper[length(pred$x):1])) graph=graph+geom_polygon(data=preditosic,aes(x=x,y),fill=fill.ic,alpha=alpha.ic)} graph=graph+ theme+ geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize)+ scale_color_manual(name="",values=1,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family=fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=5000) result=predict(mod,newdata = data.frame(temp=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(mod) bic=BIC(mod) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, graph) print(graficos) }
timetostratpointcont <- function(x,xdep,ydep){ stopifnot(all(is.finite(x)),all(is.finite(xdep)),all(is.finite(ydep)),is.unsorted(xdep,strictly = TRUE)==FALSE,length(xdep)==length(ydep)) ll=pointtransform(points=x,xdep=xdep,ydep=ydep,direction='time to height',depositionmodel='piecewise linear deposition rate') outlist=list(height=ll$height,age=ll$time) return(outlist) }
print.lba.mle.logit <- function(x, digits = 3L, ...) { cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"), "\n") an <- round(x$A, digits) bn <- round(x$B, digits) cat("\nIdentified mixing parameters:\n\n") print.default(an, ...) cat("\nIdentified latent budget:\n\n") print.default(bn, ...) cat("\nBudget proportions:\n") pkk <- round(x$pk, digits) rownames(pkk) <- c('') print.default(pkk, ...) }
fpol1 <- function(dets,vec,vars,nom,garder=NULL){ n<-length(vec) ux=0 for(i in 1:n){xs=max(dets[vec[i]]) if(xs!=0){ux<-ux+t(t(dets[,vec[i]]/xs))*10^{n+1-i} }else{ux<-ux} } ux<-round(ux,digits=4) uxf<-duplicated(ux) dats1<-data.frame(dets[,c(vec,garder)],ux,uxf) names(dats1)<-c(c(vec,garder),"ux","uxf") ndats1<-dats1[dats1["uxf"]==FALSE,] ndets1<-ndats1[,c(vec,garder,"ux")] names(ndets1)<-c(vec,garder,"ux") vs<-tapply(dets[,vars],ux,sum) id<-as.numeric(names(vs)) tab<-data.frame(id,vs) rownames(tab)<-NULL names(tab)<-c("ux",nom) tab2<-merge(ndets1,tab,by=c("ux","ux")) tab2$ux<-NULL return(tab2) }
NULL efs_create_access_point <- function(ClientToken, Tags = NULL, FileSystemId, PosixUser = NULL, RootDirectory = NULL) { op <- new_operation( name = "CreateAccessPoint", http_method = "POST", http_path = "/2015-02-01/access-points", paginator = list() ) input <- .efs$create_access_point_input(ClientToken = ClientToken, Tags = Tags, FileSystemId = FileSystemId, PosixUser = PosixUser, RootDirectory = RootDirectory) output <- .efs$create_access_point_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$create_access_point <- efs_create_access_point efs_create_file_system <- function(CreationToken, PerformanceMode = NULL, Encrypted = NULL, KmsKeyId = NULL, ThroughputMode = NULL, ProvisionedThroughputInMibps = NULL, Tags = NULL) { op <- new_operation( name = "CreateFileSystem", http_method = "POST", http_path = "/2015-02-01/file-systems", paginator = list() ) input <- .efs$create_file_system_input(CreationToken = CreationToken, PerformanceMode = PerformanceMode, Encrypted = Encrypted, KmsKeyId = KmsKeyId, ThroughputMode = ThroughputMode, ProvisionedThroughputInMibps = ProvisionedThroughputInMibps, Tags = Tags) output <- .efs$create_file_system_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$create_file_system <- efs_create_file_system efs_create_mount_target <- function(FileSystemId, SubnetId, IpAddress = NULL, SecurityGroups = NULL) { op <- new_operation( name = "CreateMountTarget", http_method = "POST", http_path = "/2015-02-01/mount-targets", paginator = list() ) input <- .efs$create_mount_target_input(FileSystemId = FileSystemId, SubnetId = SubnetId, IpAddress = IpAddress, SecurityGroups = SecurityGroups) output <- .efs$create_mount_target_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$create_mount_target <- efs_create_mount_target efs_create_tags <- function(FileSystemId, Tags) { op <- new_operation( name = "CreateTags", http_method = "POST", http_path = "/2015-02-01/create-tags/{FileSystemId}", paginator = list() ) input <- .efs$create_tags_input(FileSystemId = FileSystemId, Tags = Tags) output <- .efs$create_tags_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$create_tags <- efs_create_tags efs_delete_access_point <- function(AccessPointId) { op <- new_operation( name = "DeleteAccessPoint", http_method = "DELETE", http_path = "/2015-02-01/access-points/{AccessPointId}", paginator = list() ) input <- .efs$delete_access_point_input(AccessPointId = AccessPointId) output <- .efs$delete_access_point_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$delete_access_point <- efs_delete_access_point efs_delete_file_system <- function(FileSystemId) { op <- new_operation( name = "DeleteFileSystem", http_method = "DELETE", http_path = "/2015-02-01/file-systems/{FileSystemId}", paginator = list() ) input <- .efs$delete_file_system_input(FileSystemId = FileSystemId) output <- .efs$delete_file_system_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$delete_file_system <- efs_delete_file_system efs_delete_file_system_policy <- function(FileSystemId) { op <- new_operation( name = "DeleteFileSystemPolicy", http_method = "DELETE", http_path = "/2015-02-01/file-systems/{FileSystemId}/policy", paginator = list() ) input <- .efs$delete_file_system_policy_input(FileSystemId = FileSystemId) output <- .efs$delete_file_system_policy_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$delete_file_system_policy <- efs_delete_file_system_policy efs_delete_mount_target <- function(MountTargetId) { op <- new_operation( name = "DeleteMountTarget", http_method = "DELETE", http_path = "/2015-02-01/mount-targets/{MountTargetId}", paginator = list() ) input <- .efs$delete_mount_target_input(MountTargetId = MountTargetId) output <- .efs$delete_mount_target_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$delete_mount_target <- efs_delete_mount_target efs_delete_tags <- function(FileSystemId, TagKeys) { op <- new_operation( name = "DeleteTags", http_method = "POST", http_path = "/2015-02-01/delete-tags/{FileSystemId}", paginator = list() ) input <- .efs$delete_tags_input(FileSystemId = FileSystemId, TagKeys = TagKeys) output <- .efs$delete_tags_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$delete_tags <- efs_delete_tags efs_describe_access_points <- function(MaxResults = NULL, NextToken = NULL, AccessPointId = NULL, FileSystemId = NULL) { op <- new_operation( name = "DescribeAccessPoints", http_method = "GET", http_path = "/2015-02-01/access-points", paginator = list() ) input <- .efs$describe_access_points_input(MaxResults = MaxResults, NextToken = NextToken, AccessPointId = AccessPointId, FileSystemId = FileSystemId) output <- .efs$describe_access_points_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$describe_access_points <- efs_describe_access_points efs_describe_backup_policy <- function(FileSystemId) { op <- new_operation( name = "DescribeBackupPolicy", http_method = "GET", http_path = "/2015-02-01/file-systems/{FileSystemId}/backup-policy", paginator = list() ) input <- .efs$describe_backup_policy_input(FileSystemId = FileSystemId) output <- .efs$describe_backup_policy_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$describe_backup_policy <- efs_describe_backup_policy efs_describe_file_system_policy <- function(FileSystemId) { op <- new_operation( name = "DescribeFileSystemPolicy", http_method = "GET", http_path = "/2015-02-01/file-systems/{FileSystemId}/policy", paginator = list() ) input <- .efs$describe_file_system_policy_input(FileSystemId = FileSystemId) output <- .efs$describe_file_system_policy_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$describe_file_system_policy <- efs_describe_file_system_policy efs_describe_file_systems <- function(MaxItems = NULL, Marker = NULL, CreationToken = NULL, FileSystemId = NULL) { op <- new_operation( name = "DescribeFileSystems", http_method = "GET", http_path = "/2015-02-01/file-systems", paginator = list() ) input <- .efs$describe_file_systems_input(MaxItems = MaxItems, Marker = Marker, CreationToken = CreationToken, FileSystemId = FileSystemId) output <- .efs$describe_file_systems_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$describe_file_systems <- efs_describe_file_systems efs_describe_lifecycle_configuration <- function(FileSystemId) { op <- new_operation( name = "DescribeLifecycleConfiguration", http_method = "GET", http_path = "/2015-02-01/file-systems/{FileSystemId}/lifecycle-configuration", paginator = list() ) input <- .efs$describe_lifecycle_configuration_input(FileSystemId = FileSystemId) output <- .efs$describe_lifecycle_configuration_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$describe_lifecycle_configuration <- efs_describe_lifecycle_configuration efs_describe_mount_target_security_groups <- function(MountTargetId) { op <- new_operation( name = "DescribeMountTargetSecurityGroups", http_method = "GET", http_path = "/2015-02-01/mount-targets/{MountTargetId}/security-groups", paginator = list() ) input <- .efs$describe_mount_target_security_groups_input(MountTargetId = MountTargetId) output <- .efs$describe_mount_target_security_groups_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$describe_mount_target_security_groups <- efs_describe_mount_target_security_groups efs_describe_mount_targets <- function(MaxItems = NULL, Marker = NULL, FileSystemId = NULL, MountTargetId = NULL, AccessPointId = NULL) { op <- new_operation( name = "DescribeMountTargets", http_method = "GET", http_path = "/2015-02-01/mount-targets", paginator = list() ) input <- .efs$describe_mount_targets_input(MaxItems = MaxItems, Marker = Marker, FileSystemId = FileSystemId, MountTargetId = MountTargetId, AccessPointId = AccessPointId) output <- .efs$describe_mount_targets_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$describe_mount_targets <- efs_describe_mount_targets efs_describe_tags <- function(MaxItems = NULL, Marker = NULL, FileSystemId) { op <- new_operation( name = "DescribeTags", http_method = "GET", http_path = "/2015-02-01/tags/{FileSystemId}/", paginator = list() ) input <- .efs$describe_tags_input(MaxItems = MaxItems, Marker = Marker, FileSystemId = FileSystemId) output <- .efs$describe_tags_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$describe_tags <- efs_describe_tags efs_list_tags_for_resource <- function(ResourceId, MaxResults = NULL, NextToken = NULL) { op <- new_operation( name = "ListTagsForResource", http_method = "GET", http_path = "/2015-02-01/resource-tags/{ResourceId}", paginator = list() ) input <- .efs$list_tags_for_resource_input(ResourceId = ResourceId, MaxResults = MaxResults, NextToken = NextToken) output <- .efs$list_tags_for_resource_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$list_tags_for_resource <- efs_list_tags_for_resource efs_modify_mount_target_security_groups <- function(MountTargetId, SecurityGroups = NULL) { op <- new_operation( name = "ModifyMountTargetSecurityGroups", http_method = "PUT", http_path = "/2015-02-01/mount-targets/{MountTargetId}/security-groups", paginator = list() ) input <- .efs$modify_mount_target_security_groups_input(MountTargetId = MountTargetId, SecurityGroups = SecurityGroups) output <- .efs$modify_mount_target_security_groups_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$modify_mount_target_security_groups <- efs_modify_mount_target_security_groups efs_put_backup_policy <- function(FileSystemId, BackupPolicy) { op <- new_operation( name = "PutBackupPolicy", http_method = "PUT", http_path = "/2015-02-01/file-systems/{FileSystemId}/backup-policy", paginator = list() ) input <- .efs$put_backup_policy_input(FileSystemId = FileSystemId, BackupPolicy = BackupPolicy) output <- .efs$put_backup_policy_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$put_backup_policy <- efs_put_backup_policy efs_put_file_system_policy <- function(FileSystemId, Policy, BypassPolicyLockoutSafetyCheck = NULL) { op <- new_operation( name = "PutFileSystemPolicy", http_method = "PUT", http_path = "/2015-02-01/file-systems/{FileSystemId}/policy", paginator = list() ) input <- .efs$put_file_system_policy_input(FileSystemId = FileSystemId, Policy = Policy, BypassPolicyLockoutSafetyCheck = BypassPolicyLockoutSafetyCheck) output <- .efs$put_file_system_policy_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$put_file_system_policy <- efs_put_file_system_policy efs_put_lifecycle_configuration <- function(FileSystemId, LifecyclePolicies) { op <- new_operation( name = "PutLifecycleConfiguration", http_method = "PUT", http_path = "/2015-02-01/file-systems/{FileSystemId}/lifecycle-configuration", paginator = list() ) input <- .efs$put_lifecycle_configuration_input(FileSystemId = FileSystemId, LifecyclePolicies = LifecyclePolicies) output <- .efs$put_lifecycle_configuration_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$put_lifecycle_configuration <- efs_put_lifecycle_configuration efs_tag_resource <- function(ResourceId, Tags) { op <- new_operation( name = "TagResource", http_method = "POST", http_path = "/2015-02-01/resource-tags/{ResourceId}", paginator = list() ) input <- .efs$tag_resource_input(ResourceId = ResourceId, Tags = Tags) output <- .efs$tag_resource_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$tag_resource <- efs_tag_resource efs_untag_resource <- function(ResourceId, TagKeys) { op <- new_operation( name = "UntagResource", http_method = "DELETE", http_path = "/2015-02-01/resource-tags/{ResourceId}", paginator = list() ) input <- .efs$untag_resource_input(ResourceId = ResourceId, TagKeys = TagKeys) output <- .efs$untag_resource_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$untag_resource <- efs_untag_resource efs_update_file_system <- function(FileSystemId, ThroughputMode = NULL, ProvisionedThroughputInMibps = NULL) { op <- new_operation( name = "UpdateFileSystem", http_method = "PUT", http_path = "/2015-02-01/file-systems/{FileSystemId}", paginator = list() ) input <- .efs$update_file_system_input(FileSystemId = FileSystemId, ThroughputMode = ThroughputMode, ProvisionedThroughputInMibps = ProvisionedThroughputInMibps) output <- .efs$update_file_system_output() config <- get_config() svc <- .efs$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .efs$operations$update_file_system <- efs_update_file_system
draw_plot_or <- function(dat, ylim, alpha, pub_bias, prop_sig, pos_sm, pos_me, pos_la, main, cex.pch) { with(dat, plot(x = posi, y = est_cum, type = "p", pch = 16, ylim = ylim, xlim = c(0, 1.05), xaxt = "n", yaxt = "n", bty = "n", xlab = "", cex = cex.pch, cex.lab = par()$cex.lab, ylab = "")) title(main, line = 2.5) mtext("Precision", side = 1, cex = par()$cex.lab, line = 3.8) mtext("Effect size (OR)", side = 2, cex = par()$cex.lab, line = par()$mgp[1]) with(dat[nrow(dat), ], arrows(x0 = posi, y0 = lb_cum, y1 = ub_cum, code = 3, angle = 90, length = 0.1)) with(dat[1:(nrow(dat)-1), ], arrows(x0 = posi, y0 = lb_cum, y1 = ub_cum, code = 3, angle = 90, length = 0.1, col = "gray")) axis(1, at = seq(0, 1, 0.1), cex = par()$cex.axis) axis(2, at = round(seq(ylim[1], ylim[2], length.out = 8), 2), las = 1) if (is.na(pub_bias)) { if (prop_sig > 0.8) { with(dat, points(x = posi, y = pub_est, cex = cex.pch, pch = 8)) } } else if (pub_bias == TRUE) { with(dat, points(x = posi, y = pub_est, cex = cex.pch, pch = 8)) } segments(x0 = pos_la, x1 = pos_la, y0 = par("usr")[3], y1 = par("usr")[4] + strheight("%"), col = "gray", lty = 2, xpd = TRUE) segments(x0 = pos_me, x1 = pos_me, y0 = par("usr")[3], y1 = par("usr")[4] + strheight("%"), col = "gray", lty = 2, xpd = TRUE) segments(x0 = pos_sm, x1 = pos_sm, y0 = par("usr")[3], y1 = par("usr")[4] + strheight("%"), col = "gray", lty = 2, xpd = TRUE) abline(h = dat$est_cum[nrow(dat)], lty = 3) abline(h = 1) text(x = pos_la, y = par("usr")[4] + strheight("%") + (par("usr")[4] + strheight("%"))*0.01, label = "L", cex = par()$cex.lab*1.2, xpd = TRUE, pos = 3) text(x = pos_me, y = par("usr")[4] + strheight("%") + (par("usr")[4] + strheight("%"))*0.01, label = "M", cex = par()$cex.lab*1.2, xpd = TRUE, pos = 3) text(x = pos_sm, y = par("usr")[4] + strheight("%") + (par("usr")[4] + strheight("%"))*0.01, label = "S", cex = par()$cex.lab*1.2, xpd = TRUE, pos = 3) }
missing.person.plot = function(ped_related, missing, id.labels=NULL, available="shaded",marker=NULL, width=c(4,4,1), newdev=TRUE, frametitles=c("H1: POI related", "H2:POI unrelated"), ...) { if(!is.linkdat(ped_related)) stop("Expecting a connected pedigree as H1") miss_internal = internalID(ped_related, missing) if(is.null(id.labels)) { if(!is.null(plotlabs <- ped_related$plot.labels)) { stopifnot(length(plotlabs)==ped_related$nInd) id.labels = plotlabs } else id.labels = ped_related$orig.ids } else if(identical(id.labels, "num")) { id.labels = ped_related$orig.ids id.labels[miss_internal] = "MP" } else id.labels = rep(id.labels, length=ped_related$nInd) labels1 = id.labels misslab = labels1[miss_internal] labels1[miss_internal] = ifelse(misslab=="", "POI", paste(misslab, "= POI")) col1 = ifelse(1:ped_related$nInd == miss_internal, 2, 1) plot1 = list(ped_related, id.labels=labels1, col=col1) labels2 = id.labels plot2 = list(ped_related, id.labels=labels2) s = singleton(id=missing, sex = getSex(ped_related, missing)) if(!is.null(marker)) s = transferMarkerdata(from=ped_related, to=s) plot3 = list(s, id.labels="POI", col=2) plotPedList(list(plot1, plot2, plot3), frames=list(1,2:3), available=available, marker=marker, skip.empty.genotypes=TRUE, frametitles=frametitles, newdev=newdev, ...) } internalID = function(x, orig.ids){ internal_ids = match(orig.ids, x$orig.ids) if (any(is.na(internal_ids))) stop(paste("Indicated ID(s) not among original ID labels:", paste(orig.ids[is.na(internal_ids)], collapse = ","))) internal_ids } getSex = function (x, orig.ids) as.vector(x$pedigree[internalID(x, orig.ids), "SEX"])
UtilAucPROPROC <- function (c1, da){ rho2 <- -(1-c1^2)/(1+c1^2) corr <- diag(2) corr[lower.tri(corr)] <- rho2 corr[upper.tri(corr)] <- rho2 lower <- rep(-Inf,2) upper <- c(-da/sqrt(2),0) mean <- rep(0,2) aucProproc <- pnorm(da/sqrt(2))+2*pmvnorm(lower, upper, mean, corr) return (as.numeric(aucProproc)) }
plot.kerndwd = function(x, color=FALSE, ...) { alpha = x$alpha[-1, ] lambda = x$lambda index = log(lambda) iname = "log lambda" xlab = iname ylab = "coefficients" dotlist = list(...) type = dotlist$type if (is.null(type)) { if (color == FALSE) matplot(index, t(alpha), lty=1, xlab=xlab, ylab=ylab, type="l", pch=500, col=gray.colors(12, start=0.05, end=0.7, gamma=2.2), ...) else matplot(index, t(alpha), lty=1, xlab=xlab, ylab=ylab, type="l", pch=500, ...) } else matplot(index, t(alpha), lty=1, xlab=xlab, ylab=ylab, ...) }
register.knit.print.functions = function(knit.print.opts) { for (opt in knit.print.opts) { if (!is.null(opt$fun)) { for (class in opt$classes) { registerS3method("knit_print", class, opt$fun) } } } } set.knit.print.opts = function(html.data.frame=TRUE,table.max.rows=25, table.max.cols=NULL, round.digits=8, signif.digits=8, show.col.tooltips = TRUE, print.data.frame.fun = NULL, print.matrix.fun=NULL, env=.GlobalEnv, opts=NULL, data.frame.theme = c("code","html","kable","grid","flextable")[1+html.data.frame],word.table.style="Table Simple 1",...) { restore.point("set.knit.print.opts") if (is.null(opts)) { opts = make.knit.print.opts(data.frame.theme=data.frame.theme, ,table.max.rows=table.max.rows, table.max.cols=table.max.cols, round.digits=round.digits, signif.digits=signif.digits, show.col.tooltips = FALSE, print.data.frame.fun = print.data.frame.fun, print.matrix.fun=print.matrix.fun, word.table.style=word.table.style) } register.knit.print.functions(opts) } make.knit.print.opts = function(html.data.frame=TRUE,table.max.rows=25, table.max.cols=NULL, round.digits=8, signif.digits=8, show.col.tooltips = TRUE, print.data.frame.fun = NULL, print.matrix.fun=NULL, data.frame.theme = c("code","html","kable","grid","flextable")[1+html.data.frame], word.table.style="Table Simple 1") { opts = list() restore.point("make.knit.print.opts") if (!is.null(print.data.frame.fun)) { opts[["data.frame"]] = list( fun= print.data.frame.fun, classes=c("data.frame") ) } else { opts[["data.frame"]] = list( fun= function(x, options=NULL, ...) { restore.point("ndnfhdubfdbfbfbh") rtutor.knit_print.data.frame(x,table.max.rows=table.max.rows,table.max.cols=table.max.cols, round.digits=round.digits, signif.digits=signif.digits, show.col.tooltips=show.col.tooltips, options=options, data.frame.theme=data.frame.theme, word.table.style=word.table.style,...) }, classes=c("data.frame","tbl","tbl_df","grouped_df") ) } if (!is.null(print.matrix.fun)) { opts[["matrix"]] = list( fun= print.data.frame.fun, classes=c("matrix") ) } opts } make.knit.print.funs = function(knit.print.opts, parent.env = globalenv()) { env = new.env(parent=parent.env) for (opt in knit.print.opts) { fun.names = paste0("knit_print.",opt$classes) if (!is.null(opt$fun)) { for (fun.name in fun.names) env[[fun.name]] = opt$fun } } as.list(env) } add.htmlwidget.as.shiny <- function(x, outputId=paste0("htmlwidget_output",sample.int(100000,1)), session = getDefaultReactiveDomain(), app=getApp()) { restore.point("add.htmlwidget.as.shiny") widget.name = class(x)[1] outputFun <- function(outputId, width = "100%", height = "400px",...) { htmlwidgets::shinyWidgetOutput(outputId, widget.name, width, height) } env = new.env(parent=globalenv()) env$x = x renderer = htmlwidgets::shinyRenderWidget(quote(x), outputFunction=outputFun, env=env, quoted=TRUE) app$output[[outputId]] = renderer if (!is.null(session)) session$output[[outputId]] = renderer ui = outputFun(outputId) return(ui) } rtutor.knit_print.htmlwidget = function(x,...) { restore.point("rtutor.knit_print.htmlwidget") ps = get.ps() chunk.ind = ps$chunk.ind outputId=paste0("chunk_htmlwidget_",ps$cdt$nali[[chunk.ind]]$name) ui = add.htmlwidget.as.shiny(x, outputId = outputId) ui = add.htmlwidget.as.shiny(x) knit_print.shiny.tag.list(ui) } rtutor.knit_print.shiny.tag.list = function (x, ...) { restore.point("rtutor.knit_print.shiny.tag.list") x <- htmltools:::tagify(x) output <- surroundSingletons(x) deps <- resolveDependencies(htmltool:::findDependencies(x)) content <- htmltool:::takeHeads(output) head_content <- htmltool:::doRenderTags(tagList(content$head)) meta <- if (length(head_content) > 1 || head_content != "") { list(structure(head_content, class = "shiny_head")) } meta <- c(meta, deps) knitr::asis_output(HTML(format(content$ui, indent = FALSE)), meta = meta) } rtutor.knit_print.data.frame = function(x, table.max.rows=25, table.max.cols=NULL, round.digits=8, signif.digits=8, data.frame.theme=c("code","html","kable","grid","flextable")[1], show.col.tooltips=TRUE, col.tooltips=NULL, options=NULL,word.table.style="Table Simple 1", ...) { restore.point("rtutor.knit_print.data.frame") if (is.matrix(x)) x = as.data.frame(x) copy.non.null.fields(dest=environment(), source=options, fields=c("table.max.rows","table.max.cols", "round.digits","signif.digits","data.frame.theme","show.col.tooltips")) if (show.col.tooltips & is.null(col.tooltips) & data.frame.theme=="html") { var.dt = get.ps()$rps$var.dt if (!is.null(var.dt)) { vars = colnames(x) col.tooltips = get.var.descr.dt(vars=vars, var.dt=var.dt)$descr col.tooltips = paste0(vars, ": ", col.tooltips) col.tooltips = sapply(col.tooltips,USE.NAMES = FALSE, function(str) { paste0(strwrap(str, width=30), collapse="\n") }) } } adapt.data = FALSE missing.txt = NULL if (!is.null(table.max.rows)) { if (NROW(x)>table.max.rows) { adapt.data = TRUE missing.txt = paste0("... only ", table.max.rows, " of ", NROW(x), " rows") } } if (!is.null(table.max.cols)) { if (NCOL(x)>table.max.cols) { adapt.data = TRUE if (is.null(missing.txt)) { missing.txt = paste0("... only ", table.max.cols, " of ", NROW(x), " columns") } missing.txt = paste0(missing.txt, " and ", table.max.cols, " of ", NCOL(x), " columns") } } if (adapt.data) { missing.txt = paste0(missing.txt, " shown ...") x = max.size.df(x,table.max.rows, table.max.cols) if (data.frame.theme=="html") { h1 = RTutor:::html.table(x,round.digits=round.digits, signif.digits=signif.digits, col.tooltips=col.tooltips,...) html = c(h1, as.character(p(missing.txt))) return(asis_output(html)) } else if (data.frame.theme == "word") { dat = pretty.df(x,signif.digits = signif.digits, round.digits = round.digits) txt = paste0('```{=openxml}\n',word.xml.table(dat),"\n```\n","\n\n",missing.txt,"") return(asis_output(txt)) } else if (data.frame.theme=="kable") { dat = pretty.df(x,signif.digits = signif.digits, round.digits = round.digits) txt = c(knit_print(kable(dat)),"",missing.txt,"") return(asis_output(txt)) } else if (data.frame.theme == "grid") { dat = pretty.df(x,signif.digits = signif.digits, round.digits = round.digits) library(gridExtra); library(grid) grid.draw(tableGrob(dat, rows=NULL)) return(asis_output(missing.txt)) } else if (data.frame.theme == "flextable") { dat = pretty.df(x,signif.digits = signif.digits, round.digits = round.digits) library(flextable) tab = regulartable(dat) %>% theme_zebra() txt = c(knit_print(tab),"\n\n",missing.txt,"") return(asis_output(txt)) } else { dat = pretty.df(x,signif.digits = signif.digits, round.digits = round.digits) txt = capture.output(print(dat)) txt = c(paste0(txt,collapse="\n"),missing.txt) return(txt) } } else { if (data.frame.theme=="html") { html = RTutor:::html.table(x,round.digits=round.digits, signif.digits=signif.digits, col.tooltips=col.tooltips, ...) return(asis_output(html)) } else if (data.frame.theme == "word") { dat = pretty.df(x,signif.digits = signif.digits, round.digits = round.digits) txt = paste0('```{=openxml}\n',word.xml.table(dat),"\n```\n") return(asis_output(txt)) } else if (data.frame.theme == "kable") { dat = pretty.df(x,signif.digits = signif.digits, round.digits = round.digits) txt = c(knit_print(kable(dat)),"","") return(asis_output(txt)) } else if (data.frame.theme == "grid") { dat = pretty.df(x,signif.digits = signif.digits, round.digits = round.digits) library(gridExtra); library(grid) grid.newpage() grid.draw(tableGrob(dat, rows=NULL)) } else if (data.frame.theme == "flextable") { dat = pretty.df(x,signif.digits = signif.digits, round.digits = round.digits) library(flextable) tab = regulartable(dat) %>% theme_zebra() %>% autofit() return(knit_print(tab)) } else { dat = pretty.df(x,signif.digits = signif.digits, round.digits = round.digits) txt = paste0(capture.output(print(dat)), collapse="\n") return(txt) } } } format.vals = function(vals, signif.digits=NULL, round.digits=NULL) { if (is.numeric(vals)) { if (is.null(signif.digits) & is.null(round.digits)) { return(vals) } else if (!is.null(signif.digits) & is.null(round.digits)) { return(signif(vals, signif.digits)) } else if (is.null(signif.digits) & !is.null(round.digits)) { return(round(vals, signif.digits)) } else { return(signif(round(vals, round.digits), signif.digits)) } } vals } max.size.df = function(x, max.rows=NULL, max.cols=NULL) { if (!is.null(max.rows)) { if (NROW(x)>max.rows) { x = x[1:max.rows,] } } if (!is.null(max.cols)) { if (NCOL(x)>max.cols) { x = x[,1:max.cols] } } x } pretty.df = function(x, signif.digits=NULL, round.digits=NULL, max.rows=NULL, max.cols=NULL) { if (!is.null(max.rows) | ! is.null(max.cols)) x = max.size.df(x, max.rows, max.cols) as.data.frame(lapply(x, format.vals, signif.digits=signif.digits, round.digits=round.digits)) }
.smoothScatterCalcDensity <- function(x, nbin, bandwidth, range.x) { if (!("KernSmooth" %in% loadedNamespaces())) { ns <- try(loadNamespace("KernSmooth")) if (isNamespace(ns)) message("(loaded the KernSmooth namespace)") else stop("panel.smoothScatter() requires the KernSmooth package, but unable to load KernSmooth namespace") } if (length(nbin) == 1) nbin <- c(nbin, nbin) if (!is.numeric(nbin) || (length(nbin)!=2)) stop("'nbin' must be numeric of length 1 or 2") if (missing(bandwidth)) { bandwidth <- diff(apply(x, 2, quantile, probs=c(0.05, 0.95), na.rm=TRUE)) / 25 } else { if(!is.numeric(bandwidth)) stop("'bandwidth' must be numeric") } bandwidth[bandwidth==0] <- 1 if(missing(range.x)) rv <- KernSmooth::bkde2D(x, gridsize=nbin, bandwidth=bandwidth) else rv <- KernSmooth::bkde2D(x, gridsize=nbin, bandwidth=bandwidth, range.x=range.x) rv$bandwidth <- bandwidth return(rv) } panel.smoothScatter <- function (x, y = NULL, nbin = 64, cuts = 255, bandwidth, colramp, nrpoints = 100, transformation = function(x) x^0.25, pch = ".", cex = 1, col="black", range.x, ..., raster = FALSE, subscripts, identifier = "smoothScatter") { if (missing(colramp)) colramp <- colorRampPalette(c("white", " " " " x <- as.numeric(x) y <- as.numeric(y) if (!is.numeric(nrpoints) | (nrpoints < 0) | (length(nrpoints) != 1)) stop("'nrpoints' should be numeric scalar with value >= 0.") xy <- xy.coords(x, y) x <- cbind(xy$x, xy$y)[!(is.na(xy$x) | is.na(xy$y)), , drop = FALSE] if (nrow(x) < 1) return() map <- .smoothScatterCalcDensity(x, nbin, bandwidth, range.x) xm <- map$x1 ym <- map$x2 dens <- map$fhat dens <- array(transformation(dens), dim = dim(dens)) PFUN <- if (raster) panel.levelplot.raster else panel.levelplot PFUN(x = rep(xm, length(ym)), y = rep(ym, each = length(xm)), z = as.numeric(dens), subscripts = TRUE, at = seq(from = 0, to = 1.01 * max(dens), length = cuts + 2), col.regions = colramp(cuts + 1), ..., identifier = identifier) if (nrpoints != 0) { stopifnot(length(xm) == nrow(dens), length(ym) == ncol(dens)) ixm <- round((x[, 1] - xm[1])/(xm[length(xm)] - xm[1]) * (length(xm) - 1)) iym <- round((x[, 2] - ym[1])/(ym[length(ym)] - ym[1]) * (length(ym) - 1)) idens <- dens[1 + iym * length(xm) + ixm] nrpoints <- min(nrow(x), ceiling(nrpoints)) sel <- order(idens, decreasing = FALSE)[1:nrpoints] panel.points(x[sel, 1:2], pch = pch, cex = cex, col = col, identifier = identifier) } }