code
stringlengths
1
13.8M
fixedCoxLassoInf=function(x, y, status, beta, lambda, alpha=.1, type=c("partial"), tol.beta=1e-5, tol.kkt=0.1, gridrange=c(-100,100), bits=NULL, verbose=FALSE, this.call=NULL){ checkargs.xy(x,y) if(is.null(status)) stop("Must supply `status' argument") if( sum(status==0)+sum(status==1)!=length(y)) stop("status vector must have values 0 or 1") if (missing(beta) || is.null(beta)) stop("Must supply the solution beta") if (missing(lambda) || is.null(lambda)) stop("Must supply the tuning parameter value lambda") checkargs.misc(beta=beta,lambda=lambda,alpha=alpha, gridrange=gridrange,tol.beta=tol.beta,tol.kkt=tol.kkt) if (!is.null(bits) && !requireNamespace("Rmpfr",quietly=TRUE)) { warning("Package Rmpfr is not installed, reverting to standard precision") bits = NULL } n=nrow(x) p=ncol(x) nvar=sum(beta!=0) pv=vlo=vup=sd=rep(NA, nvar) ci=tailarea=matrix(NA,nvar,2) m=beta!=0 vars=which(m) if(sum(m)>0){ bhat=beta[beta!=0] sign_bhat=sign(bhat) aaa=coxph(Surv(y,status)~x[,m],init=bhat,iter.max=0) res=residuals(aaa,type="score") if(!is.matrix(res)) res=matrix(res,ncol=1) scor=colSums(res) g=(scor+lambda*sign_bhat)/(2*lambda) if (any(abs(g) > 1+tol.kkt) ) warning(paste("Solution beta does not satisfy the KKT conditions", "(to within specified tolerances)")) MM=vcov(aaa) bbar=(bhat+lambda*MM%*%sign_bhat) A1=-(mydiag(sign_bhat)) b1= -(mydiag(sign_bhat)%*%MM)%*%sign_bhat*lambda temp=max(A1%*%bbar-b1) for(jj in 1:length(bbar)){ vj=rep(0,length(bbar));vj[jj]=sign_bhat[jj] junk=TG.pvalue(bbar, A1, b1, vj,MM) pv[jj] = junk$pv vlo[jj]=junk$vlo vup[jj]=junk$vup sd[jj]=junk$sd junk2=TG.interval(bbar, A1, b1, vj, MM, alpha, flip=(sign_bhat[jj]==-1)) ci[jj,]=junk2$int tailarea[jj,] = junk2$tailarea } fit0=coxph(Surv(y,status)~x[,m]) coef0=fit0$coef se0=sqrt(diag(fit0$var)) zscore0=coef0/se0 out = list(lambda=lambda,pv=pv,ci=ci, tailarea=tailarea,vlo=vlo,vup=vup,sd=sd, vars=vars,alpha=alpha,coef0=coef0,zscore0=zscore0, call=this.call) class(out) = "fixedCoxLassoInf" } return(out) } print.fixedCoxLassoInf <- function(x, tailarea=TRUE, ...) { cat("\nCall:\n") dput(x$call) cat(sprintf("\nStandard deviation of noise (specified or estimated) sigma = %0.3f\n", x$sigma)) cat(sprintf("\nTesting results at lambda = %0.3f, with alpha = %0.3f\n",x$lambda,x$alpha)) cat("",fill=T) tab = cbind(x$vars, round(x$coef0,3), round(x$zscore0,3), round(x$pv,3),round(x$ci,3)) colnames(tab) = c("Var", "Coef", "Z-score", "P-value", "LowConfPt", "UpConfPt") if (tailarea) { tab = cbind(tab,round(x$tailarea,3)) colnames(tab)[(ncol(tab)-1):ncol(tab)] = c("LowTailArea","UpTailArea") } rownames(tab) = rep("",nrow(tab)) print(tab) cat(sprintf("\nNote: coefficients shown are %s regression coefficients\n", ifelse(x$type=="partial","partial","full"))) invisible() }
model <- " y1 ~ y2 + y3 y1 =~ x1 + x2 + x3 y2 =~ x4 + x5 y3 =~ x6 + x7 x1 ~~ x2 " m <- parseModel(model) m identical(m, parseModel(m)) m_incomplete <- m[c("structural", "measurement", "construct_type")] parseModel(m_incomplete) \dontrun{ m_incomplete[c("name_a", "name_b")] <- c("hello world", "hello universe") parseModel(m_incomplete) } \dontrun{ m_incomplete <- m[c("structural", "construct_type")] parseModel(m_incomplete) }
mvregmed.grid.data <- function(fit.lst,lambda.vec){ out<-data.frame(lambda=lambda.vec, do.call(rbind,lapply(fit.lst,function(z) as.data.frame(z[c("converge","iter","df","df.alpha", "df.beta", "df.delta", "df.vary", "bic")])))) return(out) }
firstCommonUpstreamBe <- function(beList=listBe(), uniqueOrg=TRUE){ if(!is.logical(uniqueOrg)){ stop("uniqueOrg should be a logical") } if(!is.atomic(beList) || length(beList)==0){ stop("beList should be a non-empty character vector") } if(!uniqueOrg){ return("Gene") } checkedBe <- match.arg(beList, several.ok=TRUE) notFound <- setdiff(beList, checkedBe) if(length(notFound)>0){ stop(paste( "Could not find the following entities among possible BE:", paste(notFound, collapse=", "), "\nPossible BE: ", paste(listBe(), collapse=", ") )) } if(length(beList)==1){ return(beList) }else{ cql <- 'MATCH (o:BEType)' cid <- 0 for(be in beList){ cid <- cid+1 cql <- c( cql, sprintf( 'MATCH (%s:BEType {value:"%s"})', paste0("be", cid), be ), sprintf( 'MATCH (o)-[:produces*0..]->(%s)', paste0("be", cid) ) ) } cql <- c( cql, 'WITH o, be1', 'MATCH p=shortestPath((o)-[:produces*0..]->(be1))', 'RETURN o.value as be, length(p) as lp', 'ORDER BY lp' ) cqRes <- bedCall( neo2R::cypher, query=neo2R::prepCql(cql) ) return(cqRes[1,1]) } }
NULL NULL fmt_function_signature <- function(x){ paste0("function(", paste(names(formals(x)), collapse = ", "), ")") } fmt_threshold <- function( x, type = "both", log_levels = getOption("lgr.log_levels") ){ assert(all(is.na(x)) || is_integerish(x[!is.na(x)]) || is.character(x)) log_levels = c("off" = 0L, log_levels) if (is.character(x)){ assert(all(x %in% names(log_levels))) x <- unlabel_levels(x, log_levels = log_levels) } impl <- function(.x){ assert((length(.x) == 1L) && (is.na(.x)) || is_integerish(.x)) if (.x %in% log_levels){ .r <- log_levels[which(log_levels == .x)] } else if (is.na(.x)){ .r <- c("all" = NA) } else { return(format(.x)) } if (identical(type, "character")){ return(names(.r)) } paste0(names(.r), " (", .r, ")") } vapply(x, impl, character(1)) }
`Pevid.ind` <- function(alleles, prob, x, u = NULL) { require(combinat) if (!is.numeric(x) || any(is.na(x)) || any(x < 0)) stop("'x' must be a vector of nonnegative integers") x0 <- x x <- round(x) if (any(x != x0)) warning("elements of 'x' have been rounded to integers") if (!is.vector(alleles)) stop("'alleles' must be a vector") if (is.vector(prob) == TRUE) prob <- as.matrix(prob) if (!is.matrix(prob)) stop("'prob' must be a matrix or a vector") n_a <- length(alleles) if (length(union(alleles, alleles)) < n_a) stop("'alleles' must be a vector of distinct elements") if (n_a != dim(prob)[1]) stop("the number of rows of 'prob' should equal to the number of distinct alleles in the mixture") if (!is.numeric(prob) || any(is.na(prob)) || any(prob <= 0) || any(prob >= 1)) stop("all entries of 'prob' must be numbers between 0 and 1") if (any(apply(prob, 2, sum) > 1)) stop("sum of allele proportions in an ethnic group is larger than 1") if (length(x) != dim(prob)[2]) stop("error in the length of 'x' or in the dimension of 'prob'") u <- union(u, u) n_u <- length(u) if (n_u > 0) { if (setequal(intersect(u, alleles), u) == FALSE) stop("'u' must contain only elements from 'alleles'") } G <- length(x) min.x <- trunc(n_u / 2) + n_u %% 2 if (sum(x) == 0 && setequal(u, NULL) == FALSE) stop(gettextf(ngettext(min.x, "there must be at least %d unknown person to carry alleles in 'u'", "there must be at least %d unknown people to carry alleles in 'u'"), min.x)) if (sum(x) > 0 && sum(x) < min.x) stop("not enough unknown contributors") if (n_u > 0) { ind <- rep(NA, n_u) for (k in 1:n_u) ind[k] <- which(alleles == u[k]) } T <- rep(0, n_u + 1) T[1] <- prod(apply(prob, 2, sum)^(2 * x)) if (n_u > 1) { for (skip in 1:(n_u - 1)) { K <- combn(ind, skip) Kcol <- ncol(K) t <- rep(0, Kcol) for (j in 1:Kcol) t[j] <- prod(apply(matrix(prob[ -K[,j], ], ncol = G), 2, sum)^(2 * x)) T[skip + 1] <- (-1)^(skip) * sum(t) } } if (n_u > 0) T[n_u + 1] <- (-1)^(n_u) * prod(apply(matrix(prob[ -ind, ], ncol = G), 2, sum)^(2 * x)) return(sum(T)) }
context("Targets (low level)") test_that("reserved names", { reserved <- c("target_name", ".") expect_equal(sort(reserved), sort(target_reserved_names())) for (i in reserved) { expect_error(make_target(i), "Target name .+ is reserved") } }) test_that("Fake targets", { t <- make_target("a_fake_target", list(type="fake")) expect_is(t, "target_fake") expect_is(t, "target_base") expect_equal(t$type, "fake") expect_equal(t$name, "a_fake_target") expect_equal(t$depends_name, character(0)) expect_equal(t$rule, NULL) expect_equal(t$cleanup_level, "never") expect_equal(t$quiet, FALSE) expect_equal(t$check, "all") t <- make_target("a_fake_target", list()) expect_equal(t$type, "fake") deps <- letters[1:3] t <- make_target("a_fake_target", list(depends=deps)) expect_equal(t$type, "fake") expect_equal(t$depends_name, deps) expect_error(make_target("a_fake_target", list(depends=deps, packages="pkg")), "fake targets may not load packages") }) test_that("Can't do much with fake targets", { t <- make_target("a_fake_target", list(type="fake")) expect_error(target_get(t), "Not something that can be") expect_error(target_set(t), "Not something that can be") }) test_that("Fake targets (invalid)", { expect_error(make_target("fake", list(command="foo()", type="fake")), "fake targets must have a NULL rule") expect_error(make_target("fake", list(target_argument="foo", type="fake")), "Invalid keys: target_argument") expect_error(make_target("fake", list(cleanup_level="tidy", type="fake")), "Unknown fields in fake: cleanup_level") expect_error(make_target("fake", list(other_opt="tidy", type="fake")), "Unknown fields in fake: other_opt") }) test_that("Dependency parsing", { expect_equal(from_yaml_map_list(yaml_load("[]")), list()) expect_equal(from_yaml_map_list(yaml_load("[a, b, c]")), list("a", "b", "c")) expect_equal(from_yaml_map_list(yaml_load("- a\n- b\n- c")), list("a", "b", "c")) expect_equal(from_yaml_map_list(yaml_load("[A: a, b, c]")), list(A="a", "b", "c")) expect_equal(from_yaml_map_list(yaml_load("- A: a\n- b\n- c")), list(A="a", "b", "c")) }) test_that("Object target", { t <- make_target("real", list(command="foo()")) expect_is(t, "target_object") expect_is(t, "target_base") expect_equal(t$type, "object") expect_equal(t$name, "real") expect_equal(t$depends_name, character(0)) expect_equal(t$depends_name, character(0)) expect_equal(t$rule, "foo") expect_equal(t$cleanup_level, "tidy") expect_equal(t$quiet, FALSE) expect_equal(t$check, "all") expect_equal(target_run_fake(t), "real <- foo()") t <- make_target("real", list(command="foo()", quiet=TRUE)) expect_equal(t$quiet, TRUE) t <- make_target("real", list(command="foo()", check="code")) expect_equal(t$check, "code") t <- make_target("real", list(command="foo()", cleanup_level="purge")) expect_equal(t$cleanup_level, "purge") t <- make_target("real", list(command="foo()", depends="a")) expect_equal(t$rule, "foo") expect_equal(t$depends_name, "a") t <- make_target("real", list(command="foo(a)")) expect_equal(t$rule, "foo") expect_equal(t$depends_name, "a") t <- make_target("real", list(command="foo(a, b=c)")) expect_equal(t$rule, "foo") expect_equal(t$depends_name, c("a", "c")) t <- make_target("code.R", list(command="foo()", type="object")) expect_equal(t$type, "object") }) test_that("Object target (invalid)", { expect_error(make_target("foo", "bar"), "While processing target 'foo':") expect_error(make_target("foo", "bar"), "target data must be named") expect_error(make_target("foo", c(name="bar")), "target data must be a list") expect_error(make_target("real", list(type="object")), "Must not have a NULL rule") expect_error(make_target("real", list(command="foo()", target_argument=1)), "Invalid keys: target_argument") expect_error(make_target("real", list(rule="foo")), "Invalid keys: rule") expect_error(make_target("real", list(command="foo()", quiet="quiet")), "quiet must be logical") expect_error(make_target("real", list(command="foo()", quiet=c(TRUE, TRUE))), "quiet must be a scalar") expect_error(make_target("real", list(command="foo()", cleanup_level="purge2")), "cleanup_level must be one") expect_error(make_target("real", list(command="foo()", check="exists2")), "check must be one") expect_error(make_target("real", list(command="foo()", other_opt="tidy")), "Unknown fields in real: other_opt") }) test_that("File targets", { t <- make_target("foo.csv", list(command="foo()")) expect_equal(t$type, "file") expect_is(t, "target_file") expect_is(t, "target_base") expect_equal(t$rule, "foo") expect_equal(t$depends_name, character(0)) expect_null(t$target_argument) expect_equal(target_run_fake(t), "foo()") t <- make_target("foo.csv", list(command="foo(a, b, c)")) expect_equal(t$type, "file") expect_equal(t$rule, "foo") expect_equal(t$depends_name, c("a", "b", "c")) expect_null(t$target_argument) t <- make_target("foo.csv", list(command="foo(a, b, C=c)")) expect_equal(t$type, "file") expect_equal(t$rule, "foo") expect_equal(t$depends_name, c("a", "b", "c")) t <- make_target("foo.csv", list(command="foo(target_name, b, C=c)")) expect_equal(t$type, "file") expect_equal(t$rule, "foo") expect_equal(t$depends_name, c("b", "c")) expect_equal(as.list(t$command[2]), list("foo.csv")) t <- make_target("foo.csv", list(command="foo(name='foo.csv', b, C=c)")) expect_equal(t$type, "file") expect_equal(t$rule, "foo") expect_equal(t$depends_name, c("b", "c")) expect_equal(as.list(t$command[2]), list(name="foo.csv")) }) test_that("Implicit file targets", { expect_error(make_target("code.R", list()), "Must not have a NULL rule") t <- target_new_file_implicit("code.R") expect_equal(t$type, "file") t <- target_new_file_implicit("code.R") expect_equal(t$name, "code.R") expect_equal(t$type, "file") expect_null(t$rule) expect_equal(t$depends_name, character(0)) expect_error(target_build(t), "Can't build implicit target code.R") expect_null(target_run(t, NULL)) expect_null(target_run_fake(t)) expect_warning(t <- target_new_file_implicit("file.csv"), "Creating implicit target for nonexistant") expect_equal(t$name, "file.csv") expect_equal(t$type, "file") expect_null(t$rule) expect_equal(t$depends_name, character(0)) expect_error(target_build(t), "Can't build implicit target file.csv") expect_null(target_run(t)) expect_null(target_run_fake(t)) }) test_that("knitr", { t <- make_target("file.md", list(type="knitr")) expect_is(t, "target_knitr") expect_equal(t$type, "file") expect_equal(t$knitr$input, "file.Rmd") expect_equal(t$knitr$options, list(error=FALSE)) t <- make_target("file.md", list(knitr=TRUE)) expect_is(t, "target_knitr") t <- make_target("file.md", list(knitr=list(input="foo.Rmd"))) expect_equal(t$knitr$input, "foo.Rmd") t <- make_target("file.md", list(knitr=list(auto_figure_prefix=TRUE))) expect_true(t$knitr$auto_figure_prefix) prefix <- "figures/file-" t <- make_target("file.md", list(knitr=list(options=list(fig.path=prefix)))) expect_equal(t$knitr$options$fig.path, prefix) expect_true(t$quiet) expect_true(make_target("file.md", list(quiet=TRUE, type="knitr"))$quiet) expect_false(make_target("file.md", list(quiet=FALSE, type="knitr"))$quiet) expect_equal(t$rule, ".__knitr__") }) test_that("knitr (invalid)", { expect_error(make_target("file.xmd", list(knitr=TRUE)), "Target must end in .md") expect_error(make_target("file.md", list(command="fn()", type="knitr")), "knitr targets must have a NULL rule") expect_error(make_target("file.md", list(command="fn()", knitr=TRUE)), "knitr targets must have a NULL rule") expect_error(make_target("file.md", list(command=c("foo()", "bar(.)"), knitr=TRUE)), "commands must be scalar") expect_error(make_target("file.md", list(quiet="yes please", type="knitr"))$quiet, "quiet must be logical") expect_error(make_target("file.md", list(unknown="opt", type="knitr")), "Unknown fields in file.md") expect_error(make_target("file.md", list(knitr=TRUE, auto_figure_prefix=TRUE)), "Unknown fields in file.md: auto_figure_prefix") dat <- list(knitr=list( options=list(fig.path="foo"), auto_figure_prefix=TRUE)) expect_warning(make_target("file.md", dat), "Ignoring 'auto_figure_prefix'") }) test_that("download", { url <- "http://whatever" t <- make_target("file", list(download=url)) expect_equal(class(t), c("target_download", "target_file", "target_base")) expect_equal(t$download, url) expect_equal(t$check, "exists") expect_equal(t$cleanup_level, "purge") expect_equal(t$type, "file") }) test_that("download (invalid)", { expect_error(make_target("file", list(download=NULL)), "download must be a scalar") expect_error(make_target("file", list(download=character(0))), "download must be a scalar") expect_error(make_target("file", list(download=c("a", "b"))), "download must be a scalar") expect_error(make_target("file", list(download=TRUE)), "download must be character") expect_error(make_target("file", list(download="www.whatever")), "does not look like a") expect_error(make_target("file", list(download="ftp://www.whatever")), "does not look like a") expect_error(make_target("file", list(download="file://www.whatever")), "does not look like a") }) test_that("cleanup", { cleanup() m <- remake("remake_cleanup_hook.yml") t <- m$targets[["clean"]] expect_equal(length(t$depends_name), 2) expect_equal(t$depends_name, c("data.csv", "tidy")) expect_false(file.exists("data.csv")) expect_message(remake_make(m, "clean"), "running post-cleanup hook") expect_true(file.exists("data.csv")) expect_message(remake_make(m, "purge"), "running post-cleanup hook") expect_false(file.exists("data.csv")) cleanup() expect_error(remake("remake_cleanup_error.yml"), "Cleanup target commands must have no arguments") }) test_that("get/set/archive object targets", { cleanup() m <- remake("remake.yml") remake_make(m, "processed") t <- m$targets[["processed"]] expect_is(target_get(t, m$store), "data.frame") dep <- dependency_status(t, m$store) path <- tempfile() dir.create(path) archive_export_target(t, m$store, path) expect_equal(dir(file.path(path, "objects")), c("config", "data", "keys")) expect_equal(dir(file.path(path, "objects", "keys", "objects")), storr::encode64("processed")) expect_equal(readLines(file.path(path, "objects", "keys", "objects", storr::encode64("processed"))), digest::digest(target_get(t, m$store))) st_db <- storr::storr_rds(file.path(path, "objects"), default_namespace="remake_db", mangle_key=TRUE) expect_equal(st_db$list(), t$name) res <- st_db$get(t$name) expect_equal(res[names(res) != "time"], dep[names(dep) != "time"]) expect_gte(as.numeric(dep$time), as.numeric(res$time)) file_remove(path, recursive=TRUE) target_set(t, m$store, "foo") expect_equal(target_get(t, m$store), "foo") remake_remove_target(m, "processed") path <- tempfile() dir.create(path) expect_error(archive_export_target(t, m$store, path), "processed not found in object store") file_remove(path, recursive=TRUE) }) test_that("get/set/archive file targets", { cleanup() m <- remake("remake.yml") remake_make(m, "plot.pdf") t <- m$targets[["plot.pdf"]] expect_equal(target_get(t, m$store), "plot.pdf") dep <- dependency_status(t, m$store) path <- tempfile() dir.create(path) archive_export_target(t, m$store, path) md5 <- function(f) unname(tools::md5sum(f)) expect_equal(dir(file.path(path, "files")), "plot.pdf") expect_equal(md5(file.path(path, "files", "plot.pdf")), md5("plot.pdf")) st_db <- storr::storr_rds(file.path(path, "objects"), default_namespace="remake_db", mangle_key=TRUE) expect_equal(st_db$list(), t$name) res <- st_db$get(t$name) expect_equal(res[names(res) != "time"], dep[names(dep) != "time"]) expect_gte(as.numeric(dep$time), as.numeric(res$time)) file_remove(path, recursive=TRUE) remake_remove_target(m, "plot.pdf") path <- tempfile() dir.create(path) expect_error(archive_export_target(t, m$store, path), "plot.pdf not found in file store") file_remove(path, recursive=TRUE) }) test_that("Error messages", { expect_error(remake("remake_invalid.yml"), "While processing target 'all'") }) test_that("Targets from calls", { t1 <- make_target("a", list(command="foo(b)")) t2 <- make_target("a", list(command=quote(foo(b)))) expect_identical(t1, t2) }) test_that("Extensions", { expect_identical(file_extensions(), tolower(file_extensions())) }) test_that("custom file extensions", { expect_is(make_target("a.phy", list(command="foo()")), "target_object") expect_is(make_target("a.phy", list(command="foo()"), file_extensions="phy"), "target_file") })
select_edges_by_node_id <- function(graph, nodes, set_op = "union") { time_function_start <- Sys.time() fcn_name <- get_calling_fcn() if (graph_object_valid(graph) == FALSE) { emit_error( fcn_name = fcn_name, reasons = "The graph object is not valid") } if (graph_contains_nodes(graph) == FALSE) { emit_error( fcn_name = fcn_name, reasons = "The graph contains no nodes") } if (graph_contains_edges(graph) == FALSE) { emit_error( fcn_name = fcn_name, reasons = "The graph contains no edges") } edges_df <- graph$edges_df edges_selected <- edges_df %>% dplyr::filter(from %in% nodes | to %in% nodes) n_e_select_properties_in <- node_edge_selection_properties(graph = graph) edges_selected <- edges_selected$id edges_prev_selection <- graph$edge_selection$edge if (set_op == "union") { edges_combined <- union(edges_prev_selection, edges_selected) } else if (set_op == "intersect") { edges_combined <- intersect(edges_prev_selection, edges_selected) } else if (set_op == "difference") { edges_combined <- base::setdiff(edges_prev_selection, edges_selected) } edges_combined <- graph$edges_df %>% dplyr::filter(id %in% edges_combined) %>% dplyr::select(id, from, to) %>% dplyr::rename(edge = id) graph$edge_selection <- edges_combined graph$node_selection <- create_empty_nsdf() n_e_select_properties_out <- node_edge_selection_properties(graph = graph) graph$graph_log <- add_action_to_log( graph_log = graph$graph_log, version_id = nrow(graph$graph_log) + 1, function_used = fcn_name, time_modified = time_function_start, duration = graph_function_duration(time_function_start), nodes = nrow(graph$nodes_df), edges = nrow(graph$edges_df)) if (graph$graph_info$write_backups) { save_graph_as_rds(graph = graph) } if (!is.null(graph$graph_info$display_msgs) && graph$graph_info$display_msgs) { if (!n_e_select_properties_in[["node_selection_available"]] & !n_e_select_properties_in[["edge_selection_available"]]) { msg_body <- glue::glue( "created a new selection of \\ {n_e_select_properties_out[['selection_count_str']]}") } else if (n_e_select_properties_in[["node_selection_available"]] | n_e_select_properties_in[["edge_selection_available"]]) { if (n_e_select_properties_in[["edge_selection_available"]]) { msg_body <- glue::glue( "modified an existing selection of\\ {n_e_select_properties_in[['selection_count_str']]}: * {n_e_select_properties_out[['selection_count_str']]}\\ are now in the active selection * used the `{set_op}` set operation") } if (n_e_select_properties_in[["node_selection_available"]]) { msg_body <- glue::glue( "created a new selection of\\ {n_e_select_properties_out[['selection_count_str']]}: * this replaces\\ {n_e_select_properties_in[['selection_count_str']]}\\ in the prior selection") } } emit_message( fcn_name = fcn_name, message_body = msg_body) } graph }
RefSigmaW <- function(sigma,Beta,X,y,delta,tol=0.0001,maxit=100,nitmon) { nit <- 1 repeat{ sigmao <- sigma sigma <- ( RefAve2W(sigmao,Beta,X,y,delta)*sigmao^2/0.5 )^0.5; d <- sigma-sigmao if (nit==maxit | abs(d)<tol) break if(nitmon) cat(nit,sigma,"\n") nit <- nit+1} list(sigma=sigma,nit=nit)}
getData <- function(name='GADM', download=TRUE, path='', ...) { path <- .getDataPath(path) tout <- getOption("timeout") on.exit(options(timeout = tout)) options(timeout = max(600, tout)) if (name=='GADM') { .GADM(..., download=download, path=path) } else if (name=='SRTM') { .SRTM(..., download=download, path=path) } else if (name=='alt') { .raster(..., name=name, download=download, path=path) } else if (name=='worldclim') { .worldclim(..., download=download, path=path) } else if (name=='CMIP5') { .cmip5(..., download=download, path=path) } else if (name=='ISO3') { ccodes()[,c(2,1)] } else if (name=='countries') { .countries(download=download, path=path, ...) } else { stop(name, ' not recognized as a valid name.') } } .download <- function(aurl, filename) { fn <- paste(tempfile(), '.download', sep='') res <- utils::download.file(url=aurl, destfile=fn, quiet = FALSE, mode = "wb", cacheOK = TRUE) if (res == 0) { w <- getOption('warn') on.exit(options('warn' = w)) options('warn'=-1) if (! file.rename(fn, filename) ) { file.copy(fn, filename) file.remove(fn) } } else { stop('could not download the file' ) } } .ISO <- function() { ccodes() } ccodes <- function() { path <- system.file(package="raster") readRDS(file.path(path, "external/countries.rds")) } .getCountry <- function(country='') { country <- toupper(trim(country[1])) cs <- ccodes() cs <- sapply(cs, toupper) cs <- data.frame(cs, stringsAsFactors=FALSE) nc <- nchar(country) if (nc == 3) { if (country %in% cs$ISO3) { return(country) } else { stop('unknown country') } } else if (nc == 2) { if (country %in% cs$ISO2) { i <- which(country==cs$ISO2) return( cs$ISO3[i] ) } else { stop('unknown country') } } else if (country %in% cs[,1]) { i <- which(country==cs[,1]) return( cs$ISO3[i] ) } else if (country %in% cs[,4]) { i <- which(country==cs[,4]) return( cs$ISO3[i] ) } else if (country %in% cs[,5]) { i <- which(country==cs[,5]) return( cs$ISO3[i] ) } else { stop('provide a valid name name or 3 letter ISO country code; you can get a list with "ccodes()"') } } .getDataPath <- function(path) { path <- trim(path) if (path=="") { path <- .dataloc() } else { if (substr(path, nchar(path)-1, nchar(path)) == '//' ) { p <- substr(path, 1, nchar(path)-2) } else if (substr(path, nchar(path), nchar(path)) == '/' | substr(path, nchar(path), nchar(path)) == '\\') { p <- substr(path, 1, nchar(path)-1) } else { p <- path } if (!file.exists(p) & !file.exists(path)) { stop('path does not exist: ', path) } } if (substr(path, nchar(path), nchar(path)) != '/' & substr(path, nchar(path), nchar(path)) != '\\') { path <- paste(path, "/", sep="") } return(path) } .GADM <- function(country, level, download, path, version=3.6, type='sp') { country <- .getCountry(country) if (missing(level)) { stop('provide a "level=" argument; levels can be 0, 1, or 2 for most countries, and higher for some') } if (version > 3) { if (type == 'sf') { filename <- file.path(path, paste0('gadm36_', country, '_', level, "_sf.rds")) } else { filename <- file.path(path, paste0('gadm36_', country, '_', level, "_sp.rds")) } } else { filename <- paste(path, 'GADM_', version, '_', country, '_', level, ".rds", sep="") } if (!file.exists(filename)) { if (download) { baseurl <- paste0("https://biogeo.ucdavis.edu/data/gadm", version) if (version == 2.8) { theurl <- paste(baseurl, '/rds/', country, '_adm', level, ".rds", sep="") } else { if (type == 'sf') { theurl <- paste(baseurl, '/Rsf/gadm36_', country, '_', level, "_sf.rds", sep="") } else { theurl <- paste(baseurl, '/Rsp/gadm36_', country, '_', level, "_sp.rds", sep="") } } .download(theurl, filename) if (!file.exists(filename)) { message("\nCould not download file -- perhaps it does not exist") } } else { message("File not available locally. Use 'download = TRUE'") } } if (file.exists(filename)) { x <- readRDS(filename) if (type != 'sf') { crs(x) <- "+proj=longlat +datum=WGS84" } return(x) } else { return(NULL) } } .countries <- function(download, path, type='sp', ...) { if (type == 'sf') { f <- "countries_gadm36_sf.rds" } else { f <- "countries_gadm36_sp.rds" } filename <- file.path(path, f) if (!file.exists(filename)) { if (download) { theurl <- paste0("https://biogeo.ucdavis.edu/data/gadm3.6/", f) .download(theurl, filename) if (!file.exists(filename)) { message("\nCould not download file -- perhaps it does not exist") } } else { message("File not available locally. Use 'download = TRUE'") } } if (file.exists(filename)) { data <- readRDS(filename) crs(data) <- "+proj=longlat +datum=WGS84" return(data) } } .cmip5 <- function(var, model, rcp, year, res, lon, lat, path, download=TRUE) { if (!res %in% c(0.5, 2.5, 5, 10)) { stop('resolution should be one of: 2.5, 5, 10') } if (res==2.5) { res <- '2_5m' } else if (res == 0.5) { res <- "30s" } else { res <- paste(res, 'm', sep='') } var <- tolower(var[1]) vars <- c('tmin', 'tmax', 'prec', 'bio') stopifnot(var %in% vars) var <- c('tn', 'tx', 'pr', 'bi')[match(var, vars)] model <- toupper(model) models <- c('AC', 'BC', 'CC', 'CE', 'CN', 'GF', 'GD', 'GS', 'HD', 'HG', 'HE', 'IN', 'IP', 'MI', 'MR', 'MC', 'MP', 'MG', 'NO') stopifnot(model %in% models) rcps <- c(26, 45, 60, 85) stopifnot(rcp %in% rcps) stopifnot(year %in% c(50, 70)) m <- matrix(c(0,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,1,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1), ncol=4) i <- m[which(model==models), which(rcp==rcps)] if (!i) { warning('this combination of rcp and model is not available') return(invisible(NULL)) } path <- paste(path, '/cmip5/', res, '/', sep='') dir.create(path, recursive=TRUE, showWarnings=FALSE) zip <- tolower(paste(model, rcp, var, year, '.zip', sep='')) theurl <- paste('https://biogeo.ucdavis.edu/data/climate/cmip5/', res, '/', zip, sep='') zipfile <- paste(path, zip, sep='') if (var == 'bi') { n <- 19 } else { n <- 12 } tifs <- paste(extension(zip, ''), 1:n, '.tif', sep='') files <- paste(path, tifs, sep='') fc <- sum(file.exists(files)) if (fc < n) { if (!file.exists(zipfile)) { if (download) { .download(theurl, zipfile) if (!file.exists(zipfile)) { message("\n Could not download file -- perhaps it does not exist") } } else { message("File not available locally. Use 'download = TRUE'") } } utils::unzip(zipfile, exdir=dirname(zipfile)) } stack(paste(path, tifs, sep='')) } .worldclim <- function(var, res, lon, lat, path, download=TRUE) { if (!res %in% c(0.5, 2.5, 5, 10)) { stop('resolution should be one of: 0.5, 2.5, 5, 10') } if (res==2.5) { res <- '2-5' } stopifnot(var %in% c('tmean', 'tmin', 'tmax', 'prec', 'bio', 'alt')) path <- paste(path, 'wc', res, '/', sep='') dir.create(path, showWarnings=FALSE) if (res==0.5) { lon <- min(180, max(-180, lon)) lat <- min(90, max(-60, lat)) rs <- raster(nrows=5, ncols=12, xmn=-180, xmx=180, ymn=-60, ymx=90 ) row <- rowFromY(rs, lat) - 1 col <- colFromX(rs, lon) - 1 rc <- paste(row, col, sep='') zip <- paste(var, '_', rc, '.zip', sep='') zipfile <- paste(path, zip, sep='') if (var == 'alt') { bilfiles <- paste(var, '_', rc, '.bil', sep='') hdrfiles <- paste(var, '_', rc, '.hdr', sep='') } else if (var != 'bio') { bilfiles <- paste(var, 1:12, '_', rc, '.bil', sep='') hdrfiles <- paste(var, 1:12, '_', rc, '.hdr', sep='') } else { bilfiles <- paste(var, 1:19, '_', rc, '.bil', sep='') hdrfiles <- paste(var, 1:19, '_', rc, '.hdr', sep='') } theurl <- paste('https://biogeo.ucdavis.edu/data/climate/worldclim/1_4/tiles/cur/', zip, sep='') } else { zip <- paste(var, '_', res, 'm_bil.zip', sep='') zipfile <- paste(path, zip, sep='') if (var == 'alt') { bilfiles <- paste(var, '.bil', sep='') hdrfiles <- paste(var, '.hdr', sep='') } else if (var != 'bio') { bilfiles <- paste(var, 1:12, '.bil', sep='') hdrfiles <- paste(var, 1:12, '.hdr', sep='') } else { bilfiles <- paste(var, 1:19, '.bil', sep='') hdrfiles <- paste(var, 1:19, '.hdr', sep='') } theurl <- paste('https://biogeo.ucdavis.edu/data/climate/worldclim/1_4/grid/cur/', zip, sep='') } files <- c(paste(path, bilfiles, sep=''), paste(path, hdrfiles, sep='')) fc <- sum(file.exists(files)) if ( fc < length(files) ) { if (!file.exists(zipfile)) { if (download) { .download(theurl, zipfile) if (!file.exists(zipfile)) { message("\n Could not download file -- perhaps it does not exist") } } else { message("File not available locally. Use 'download = TRUE'") } } utils::unzip(zipfile, exdir=dirname(zipfile)) for (h in paste(path, hdrfiles, sep='')) { x <- readLines(h) x <- c(x[1:14], 'PIXELTYPE SIGNEDINT', x[15:length(x)]) writeLines(x, h) } } if (var == 'alt') { st <- raster(paste(path, bilfiles, sep='')) } else { st <- stack(paste(path, bilfiles, sep='')) } projection(st) <- "+proj=longlat +datum=WGS84" return(st) } .raster <- function(country, name, mask=TRUE, path, download, keepzip=FALSE, ...) { country <- .getCountry(country) path <- .getDataPath(path) if (mask) { mskname <- '_msk_' mskpath <- 'msk_' } else { mskname<-'_' mskpath <- '' } filename <- paste(path, country, mskname, name, ".grd", sep="") if (!file.exists(filename)) { zipfilename <- filename extension(zipfilename) <- '.zip' if (!file.exists(zipfilename)) { if (download) { theurl <- paste("https://biogeo.ucdavis.edu/data/diva/", mskpath, name, "/", country, mskname, name, ".zip", sep="") .download(theurl, zipfilename) if (!file.exists(zipfilename)) { message("\nCould not download file -- perhaps it does not exist") } } else { message("File not available locally. Use 'download = TRUE'") } } ff <- utils::unzip(zipfilename, exdir=dirname(zipfilename)) if (!keepzip) { file.remove(zipfilename) } } if (file.exists(filename)) { rs <- raster(filename) } else { f <- ff[substr(ff, nchar(ff)-3, nchar(ff)) == '.grd'] if (length(f)==0) { warning('something went wrong') return(NULL) } else if (length(f)==1) { rs <- raster(f) } else { rs <- sapply(f, raster) message('returning a list of RasterLayer objects') return(rs) } } projection(rs) <- "+proj=longlat +datum=WGS84" return(rs) } .SRTM <- function(lon, lat, download, path) { stopifnot(lon >= -180 & lon <= 180) stopifnot(lat >= -60 & lat <= 60) rs <- raster(nrows=24, ncols=72, xmn=-180, xmx=180, ymn=-60, ymx=60 ) rowTile <- rowFromY(rs, lat) colTile <- colFromX(rs, lon) if (rowTile < 10) { rowTile <- paste('0', rowTile, sep='') } if (colTile < 10) { colTile <- paste('0', colTile, sep='') } baseurl <- "https://srtm.csi.cgiar.org/wp-content/uploads/files/srtm_5x5/TIFF/" f <- paste0("srtm_", colTile, "_", rowTile, ".zip") zipfilename <- file.path(path, f) tiffilename <- file.path(path, gsub(".zip$", ".tif", f)) if (!file.exists(tiffilename)) { if (!file.exists(zipfilename)) { if (download) { theurl <- paste0(baseurl, f) test <- try (.download(theurl, zipfilename) , silent=TRUE) if (inherits(test, "try-error")) { stop("cannot download the file") } } else {message("file not available locally, use download=TRUE") } } if (file.exists(zipfilename)) { utils::unzip(zipfilename, exdir=dirname(zipfilename)) file.remove(zipfilename) } } if (file.exists(tiffilename)) { rs <- raster(tiffilename) projection(rs) <- "+proj=longlat +datum=WGS84" return(rs) } else { stop('file not found') } }
sign_splits = function(orig.splits, refit.splits, perm.distr, alpha, testtype){ reduced.splits = sort(orig.splits[orig.splits$chg.loss < 0, ]$T.split) final.splits = c() for (ji in 1:length(refit.splits)){ if (testtype == "t-test"){ stat.result = t.test(refit.splits[[ji]], perm.distr[[ji]], alternative = "less")$p.value } else if (testtype == "wilcox"){ stat.result = wilcox.test(refit.splits[[ji]], perm.distr[[ji]], alternative = "less")$p.value } else if (testtype == "ks"){ stat.result = ks.test(refit.splits[[ji]], perm.distr[[ji]], alternative = "greater")$p.value } stat.result = p.adjust(stat.result, method = "BH", n = length(refit.splits)) if (is.numeric(alpha)){ final.splits = rbind(final.splits, data.frame(reduced.splits[ji], stat.result < alpha)) } else if (is.null(alpha)){ final.splits = rbind(final.splits, data.frame(reduced.splits[ji], stat.result)) } } colnames(final.splits) = c("T", "stat_test") rownames(final.splits) = NULL return(final.splits) }
post_success <- function(dat, config) { opts <- config$server_options() response <- NULL if (!is.null(opts)) { remote <- get_remote(opts$name, config) opts <- resolve_env(opts, error = FALSE) slack_url <- opts$slack_url teams_url <- opts$teams_url report_url <- remote$url_report(dat$meta$name, dat$meta$id) response <- list() if (!is.null(slack_url)) { assert_scalar_character(slack_url, "slack_url") data <- slack_data(dat, opts$name, report_url, opts$primary) response$slack <- do_post_success(slack_url, data, "slack") } if (!is.null(teams_url)) { assert_scalar_character(teams_url, "teams_url") data <- teams_data(dat, opts$name, report_url, opts$primary) response$teams <- do_post_success(teams_url, data, "teams") } } response } slack_data <- function(dat, remote_name, report_url, remote_is_primary) { content <- prepare_content(dat, remote_name, report_url, "<{url}|{label}>", escape = FALSE) fields <- list(list(title = "id", value = content$id, short = TRUE)) if (!is.null(dat$git)) { branch <- dat$git$branch %||% "(detached)" sha <- dat$git$sha_short if (!is.null(dat$git$github_url)) { sha <- sprintf("<%s/tree/%s|%s>", dat$git$github_url, sha, sha) } if (!is.null(dat$git$github_url) && !is.null(dat$git$branch)) { branch <- sprintf("<%s/tree/%s|%s>", dat$git$github_url, branch, branch) } fields <- c(fields, list(list(title = "git", value = sprintf("%s@%s", branch, sha), short = TRUE))) } col <- if (remote_is_primary) "good" else "warning" list(username = "orderly", icon_emoji = ":ambulance:", attachments = list(list( title = content$title, text = content$text, color = col, fallback = content$fallback, fields = fields, actions = list(list( name = "link", type = "button", text = ":clipboard: View report", style = "primary", url = report_url))))) } teams_data <- function(dat, remote_name, report_url, remote_is_primary) { content <- prepare_content(dat, remote_name, report_url, "[{label}]({url})", escape = TRUE) facts <- list(list(name = "id:", value = content$id)) if (!is.null(dat$git)) { branch <- dat$git$branch %||% "(detached)" sha <- dat$git$sha_short if (!is.null(dat$git$github_url)) { sha <- sprintf("[%s](%s/tree/%s)", sha, dat$git$github_url, sha) } if (!is.null(dat$git$github_url) && !is.null(dat$git$branch)) { branch <- sprintf("[%s](%s/tree/%s)", branch, dat$git$github_url, branch) } facts <- c(facts, list(list(name = "git:", value = sprintf("%s@%s", branch, sha)))) } col <- if (remote_is_primary) "2EB886" else "DAA038" list( "@type" = "MessageCard", "@context" = "http://schema.org/extensions", summary = content$fallback, themeColor = col, sections = list( list( activityTitle = content$title, activityText = content$text, activityImage = paste0("https://cdn.pixabay.com/photo/2017/", "06/10/07/18/list-2389219_960_720.png") ), list( facts = facts ) ), potentialAction = list( list( "@type" = "OpenUri", name = "View report", targets = list( list( os = "default", uri = report_url ) ) ) ) ) } prepare_content <- function(dat, remote_name, report_url, link_format, escape) { id <- dat$meta$id name <- dat$meta$name elapsed <- format(as.difftime(dat$meta$elapsed, units = "secs"), digits = 2) if (escape) { qname <- sprintf("`%s`", name) } else { qname <- sprintf("'%s'", name) } list( fallback = sprintf("Ran '%s' as '%s'; view at %s", name, id, report_url), title = sprintf("Ran report %s", qname), text = sprintf("on server *%s* in %s", remote_name, elapsed), id = sprintf("`%s`", id) ) } do_post_success <- function(url, data, destination) { if (!requireNamespace("httr", quietly = TRUE)) { message("not sending messages as httr is not available") return(invisible(NULL)) } r <- tryCatch({ r <- httr::POST(url, body = data, encode = "json") httr::stop_for_status(r) r }, error = function(e) { message(sprintf("NOTE: running %s hook failed\n", destination), e$message) NULL }) invisible(r) }
require(sde) k <- NULL theta <- NULL k1 <- NULL theta1 <- NULL sigma.hat <- NULL sigma <- 0.15 pars <- c(0.5, 0.2, sigma) n.sim <- 1000 Delta <- 0.01 set.seed(123) x0 <- rsCIR(n.sim, pars) T <- 100 for(i in 1:n.sim){ X <- sde.sim(X0=x0[i], model="CIR", theta=pars, N=T/Delta, delta=Delta) n <- length(X) I3 <- Delta * sum(1/X[1:(n-1)] + 1/X[2:n])/2 I1 <- log(X[n]/X[1]) + 0.5*sigma^2 * I3 I2 <- X[n] - X[1] I4 <- Delta * sum(X[1:(n-1)] + X[2:n])/2 I5 <- n*Delta k <- c(k, (I1*I5-I2*I3)/(I3*I4-I5^2)) theta <- c(theta, (I1*I4-I2*I5)/(I1*I5-I2*I3)) sigma.est <- sqrt(sum((X[2:n]-X[1:(n-1)])^2/X[1:(n-1)])/(n*Delta)) sigma.hat <- c(sigma.hat, sigma.est) I1 <- log(X[n]/X[1]) + 0.5*sigma.est^2 * I3 k1 <- c(k1, (I1*I5-I2*I3)/(I3*I4-I5^2)) theta1 <- c(theta1, (I1*I4-I2*I5)/(I1*I5-I2*I3)) } cat(sprintf("kappa=%f, theta=%f, sigma=%f : kappa1=%f, theta1=%f\n", mean(k*theta), mean(k), mean(sigma.hat), mean(k1*theta1), mean(k1))) cat(sprintf("SD: kappa=%f, theta=%f, sigma=%f : kappa1=%f, theta1=%f\n", sd(k*theta), sd(k), sd(sigma.hat), sd(k1*theta1), sd(k1))) cat(sprintf("kappa=%f, theta=%f, sigma=%f\n", pars[1], pars[2], pars[3]))
print.clock_calendar <- function(x, ..., max = NULL) { clock_print(x, max) } obj_print_data.clock_calendar <- function(x, ..., max) { if (vec_is_empty(x)) { return(invisible(x)) } x <- max_slice(x, max) out <- format(x) print(out, max = max) invisible(x) } obj_print_footer.clock_calendar <- function(x, ..., max) { clock_print_footer(x, max) } pillar_shaft.clock_calendar <- function(x, ...) { out <- format(x) pillar::new_pillar_shaft_simple(out, align = "left") } ptype2_calendar_and_calendar <- function(x, y, ...) { if (calendar_precision_attribute(x) == calendar_precision_attribute(y)) { x } else { stop_incompatible_type(x, y, ..., details = "Can't combine calendars with different precisions.") } } cast_calendar_to_calendar <- function(x, to, ...) { if (calendar_precision_attribute(x) == calendar_precision_attribute(to)) { x } else { stop_incompatible_cast(x, to, ..., details = "Can't cast between calendars with different precisions.") } } calendar_leap_year <- function(x) { UseMethod("calendar_leap_year") } calendar_leap_year.clock_calendar <- function(x) { stop_clock_unsupported_calendar_op("calendar_leap_year") } calendar_month_factor <- function(x, ..., labels = "en", abbreviate = FALSE) { UseMethod("calendar_month_factor") } calendar_month_factor.clock_calendar <- function(x, ..., labels = "en", abbreviate = FALSE) { stop_clock_unsupported_calendar_op("calendar_month_factor") } calendar_month_factor_impl <- function(x, labels, abbreviate, ...) { check_dots_empty() if (calendar_precision_attribute(x) < PRECISION_MONTH) { abort("`x` must have at least 'month' precision.") } if (is_character(labels)) { labels <- clock_labels_lookup(labels) } if (!is_clock_labels(labels)) { abort("`labels` must be a 'clock_labels' object.") } if (!is_bool(abbreviate)) { abort("`abbreviate` must be `TRUE` or `FALSE`.") } if (abbreviate) { labels <- labels$month_abbrev } else { labels <- labels$month } x <- get_month(x) x <- labels[x] factor(x, levels = labels, ordered = TRUE) } calendar_group <- function(x, precision, ..., n = 1L) { check_dots_empty() precision <- validate_precision_string(precision) if (!calendar_is_valid_precision(x, precision)) { message <- paste0( "`precision` must be a valid precision for a '", calendar_name(x), "'." ) abort(message) } x_precision <- calendar_precision_attribute(x) if (precision > x_precision) { precision <- precision_to_string(precision) x_precision <- precision_to_string(x_precision) message <- paste0( "Can't group at a precision (", precision, ") ", "that is more precise than `x` (", x_precision, ")." ) abort(message) } if (precision > PRECISION_SECOND && x_precision != precision) { precision <- precision_to_string(precision) x_precision <- precision_to_string(x_precision) message <- paste0( "Can't group a subsecond precision `x` (", x_precision, ") ", "by another subsecond precision (", precision, ")." ) abort(message) } UseMethod("calendar_group") } calendar_group.clock_calendar <- function(x, precision, ..., n = 1L) { stop_clock_unsupported_calendar_op("calendar_group") } calendar_group_time <- function(x, n, precision) { if (precision == PRECISION_HOUR) { value <- get_hour(x) value <- group_component0(value, n) x <- set_hour(x, value) return(x) } if (precision == PRECISION_MINUTE) { value <- get_minute(x) value <- group_component0(value, n) x <- set_minute(x, value) return(x) } if (precision == PRECISION_SECOND) { value <- get_second(x) value <- group_component0(value, n) x <- set_second(x, value) return(x) } if (precision == PRECISION_MILLISECOND) { value <- get_millisecond(x) value <- group_component0(value, n) x <- set_millisecond(x, value) return(x) } if (precision == PRECISION_MICROSECOND) { value <- get_microsecond(x) value <- group_component0(value, n) x <- set_microsecond(x, value) return(x) } if (precision == PRECISION_NANOSECOND) { value <- get_nanosecond(x) value <- group_component0(value, n) x <- set_nanosecond(x, value) return(x) } abort("Internal error: Unknown precision.") } group_component0 <- function(x, n) { (x %/% n) * n } group_component1 <- function(x, n) { ((x - 1L) %/% n) * n + 1L } validate_calendar_group_n <- function(n) { n <- vec_cast(n, integer(), x_arg = "n") if (!is_number(n)) { abort("`n` must be a single number.") } if (n <= 0L) { abort("`n` must be a positive number.") } n } calendar_narrow <- function(x, precision) { precision <- validate_precision_string(precision) if (!calendar_is_valid_precision(x, precision)) { message <- paste0( "`precision` must be a valid precision for a '", calendar_name(x), "'." ) abort(message) } x_precision <- calendar_precision_attribute(x) if (precision > x_precision) { precision <- precision_to_string(precision) x_precision <- precision_to_string(x_precision) message <- paste0( "Can't narrow to a precision (", precision, ") ", "that is wider than `x` (", x_precision, ")." ) abort(message) } if (precision > PRECISION_SECOND && x_precision != precision) { precision <- precision_to_string(precision) x_precision <- precision_to_string(x_precision) message <- paste0( "Can't narrow a subsecond precision `x` (", x_precision, ") ", "to another subsecond precision (", precision, ")." ) abort(message) } UseMethod("calendar_narrow") } calendar_narrow.clock_calendar <- function(x, precision) { stop_clock_unsupported_calendar_op("calendar_narrow") } calendar_narrow_time <- function(out_fields, out_precision, x_fields) { if (out_precision >= PRECISION_HOUR) { out_fields[["hour"]] <- x_fields[["hour"]] } if (out_precision >= PRECISION_MINUTE) { out_fields[["minute"]] <- x_fields[["minute"]] } if (out_precision >= PRECISION_SECOND) { out_fields[["second"]] <- x_fields[["second"]] } if (out_precision > PRECISION_SECOND) { out_fields[["subsecond"]] <- x_fields[["subsecond"]] } out_fields } calendar_widen <- function(x, precision) { precision <- validate_precision_string(precision) if (!calendar_is_valid_precision(x, precision)) { message <- paste0( "`precision` must be a valid precision for a '", calendar_name(x), "'." ) abort(message) } x_precision <- calendar_precision_attribute(x) if (x_precision > precision) { precision <- precision_to_string(precision) x_precision <- precision_to_string(x_precision) message <- paste0( "Can't widen to a precision (", precision, ") ", "that is narrower than `x` (", x_precision, ")." ) abort(message) } if (x_precision > PRECISION_SECOND && x_precision != precision) { precision <- precision_to_string(precision) x_precision <- precision_to_string(x_precision) message <- paste0( "Can't widen a subsecond precision `x` (", x_precision, ") ", "to another subsecond precision (", precision, ")." ) abort(message) } UseMethod("calendar_widen") } calendar_widen.clock_calendar <- function(x, precision) { stop_clock_unsupported_calendar_op("calendar_widen") } calendar_widen_time <- function(x, x_precision, precision) { if (precision >= PRECISION_HOUR && x_precision < PRECISION_HOUR) { x <- set_hour(x, 0L) } if (precision >= PRECISION_MINUTE && x_precision < PRECISION_MINUTE) { x <- set_minute(x, 0L) } if (precision >= PRECISION_SECOND && x_precision < PRECISION_SECOND) { x <- set_second(x, 0L) } if (precision == PRECISION_MILLISECOND && x_precision != precision) { x <- set_millisecond(x, 0L) } if (precision == PRECISION_MICROSECOND && x_precision != precision) { x <- set_microsecond(x, 0L) } if (precision == PRECISION_NANOSECOND && x_precision != precision) { x <- set_nanosecond(x, 0L) } x } NULL calendar_start <- function(x, precision) { UseMethod("calendar_start") } calendar_start.clock_calendar <- function(x, precision) { stop_clock_unsupported_calendar_op("calendar_start") } calendar_end <- function(x, precision) { UseMethod("calendar_end") } calendar_end.clock_calendar <- function(x, precision) { stop_clock_unsupported_calendar_op("calendar_end") } calendar_start_end_checks <- function(x, x_precision, precision, which) { if (!calendar_is_valid_precision(x, precision)) { message <- paste0( "`precision` must be a valid precision for a '", calendar_name(x), "'." ) abort(message) } if (x_precision < precision) { precision <- precision_to_string(precision) x_precision <- precision_to_string(x_precision) message <- paste0( "Can't compute the ", which, " of `x` (", x_precision, ") ", "at a more precise precision (", precision, ")." ) abort(message) } if (precision > PRECISION_SECOND && x_precision != precision) { precision <- precision_to_string(precision) x_precision <- precision_to_string(x_precision) message <- paste0( "Can't compute the ", which, " of a subsecond precision `x` (", x_precision, ") ", "at another subsecond precision (", precision, ")." ) abort(message) } invisible(x) } calendar_start_time <- function(x, x_precision, precision) { values <- list( hour = 0L, minute = 0L, second = 0L, millisecond = 0L, microsecond = 0L, nanosecond = 0L ) calendar_start_end_time(x, x_precision, precision, values) } calendar_end_time <- function(x, x_precision, precision) { values <- list( hour = 23L, minute = 59L, second = 59L, millisecond = 999L, microsecond = 999999L, nanosecond = 999999999L ) calendar_start_end_time(x, x_precision, precision, values) } calendar_start_end_time <- function(x, x_precision, precision, values) { if (precision <= PRECISION_DAY && x_precision > PRECISION_DAY) { x <- set_hour(x, values$hour) } if (precision <= PRECISION_HOUR && x_precision > PRECISION_HOUR) { x <- set_minute(x, values$minute) } if (precision <= PRECISION_MINUTE && x_precision > PRECISION_MINUTE) { x <- set_second(x, values$second) } if (precision <= PRECISION_SECOND && x_precision > PRECISION_SECOND) { if (x_precision == PRECISION_MILLISECOND) { x <- set_millisecond(x, values$millisecond) } else if (x_precision == PRECISION_MICROSECOND) { x <- set_microsecond(x, values$microsecond) } else if (x_precision == PRECISION_NANOSECOND) { x <- set_nanosecond(x, values$nanosecond) } } x } NULL calendar_count_between <- function(start, end, precision, ..., n = 1L) { UseMethod("calendar_count_between") } calendar_count_between.clock_calendar <- function(start, end, precision, ..., n = 1L) { check_dots_empty() if (!is_calendar(end)) { abort("`end` must be a <clock_calendar>.") } size <- vec_size_common(start = start, end = end) args <- vec_cast_common(start = start, end = end) args <- vec_recycle_common(!!!args, .size = size) start <- args[[1]] end <- args[[2]] n <- vec_cast(n, integer(), x_arg = "n") if (!is_number(n) || n <= 0L) { abort("`n` must be a single positive integer.") } precision_int <- validate_precision_string(precision) if (calendar_precision_attribute(start) < precision_int) { abort("Precision of inputs must be at least as precise as `precision`.") } args <- calendar_count_between_standardize_precision_n(start, precision, n) precision <- args$precision n <- args$n out <- calendar_count_between_compute(start, end, precision) args <- calendar_count_between_proxy_compare(start, end, precision) start_proxy <- args$start end_proxy <- args$end if (ncol(start_proxy) == 0L) { comparison <- vec_rep(0L, size) } else { comparison <- vec_compare(end_proxy, start_proxy) } adjustment <- vec_rep(-1L, size) adjustment[start > end] <- 1L adjustment[comparison != adjustment] <- 0L out <- out + adjustment if (n != 1L) { out <- out %/% n } out } calendar_count_between_standardize_precision_n <- function(x, precision, n) { UseMethod("calendar_count_between_standardize_precision_n") } calendar_count_between_compute <- function(start, end, precision) { UseMethod("calendar_count_between_compute") } calendar_count_between_proxy_compare <- function(start, end, precision) { UseMethod("calendar_count_between_proxy_compare") } calendar_precision <- function(x) { UseMethod("calendar_precision") } calendar_precision.clock_calendar <- function(x) { precision <- calendar_precision_attribute(x) precision <- precision_to_string(precision) precision } calendar_name <- function(x) { UseMethod("calendar_name") } calendar_is_valid_precision <- function(x, precision) { UseMethod("calendar_is_valid_precision") } calendar_precision_attribute <- function(x) { attr(x, "precision", exact = TRUE) } calendar_require_minimum_precision <- function(x, precision, fn) { if (!calendar_has_minimum_precision(x, precision)) { precision_string <- precision_to_string(precision) msg <- paste0("`", fn, "()` requires a minimum precision of '", precision_string, "'.") abort(msg) } invisible(x) } calendar_has_minimum_precision <- function(x, precision) { calendar_precision_attribute(x) >= precision } calendar_require_precision <- function(x, precision, fn) { if (!calendar_has_precision(x, precision)) { precision_string <- precision_to_string(precision) msg <- paste0("`", fn, "()` requires a precision of '", precision_string, "'.") abort(msg) } invisible(x) } calendar_require_any_of_precisions <- function(x, precisions, fn) { results <- vapply(precisions, calendar_has_precision, FUN.VALUE = logical(1), x = x) if (!any(results)) { precision_string <- precision_to_string(calendar_precision_attribute(x)) msg <- paste0("`", fn, "()` does not support a precision of '", precision_string, "'.") abort(msg) } invisible(x) } calendar_has_precision <- function(x, precision) { calendar_precision_attribute(x) == precision } calendar_validate_subsecond_precision <- function(subsecond_precision) { if (is_null(subsecond_precision)) { abort("If `subsecond` is provided, `subsecond_precision` must be specified.") } subsecond_precision <- validate_precision_string(subsecond_precision, "subsecond_precision") if (!is_valid_subsecond_precision(subsecond_precision)) { abort("`subsecond_precision` must be a valid subsecond precision.") } subsecond_precision } calendar_require_all_valid <- function(x) { if (invalid_any(x)) { message <- paste0( "Conversion from a calendar requires that all dates are valid. ", "Resolve invalid dates by calling `invalid_resolve()`." ) abort(message) } invisible(x) } calendar_ptype_full <- function(x, class) { precision <- calendar_precision_attribute(x) precision <- precision_to_string(precision) paste0(class, "<", precision, ">") } calendar_ptype_abbr <- function(x, abbr) { precision <- calendar_precision_attribute(x) precision <- precision_to_string(precision) precision <- precision_abbr(precision) paste0(abbr, "<", precision, ">") } arith_calendar_and_missing <- function(op, x, y, ...) { switch ( op, "+" = x, stop_incompatible_op(op, x, y, ...) ) } arith_calendar_and_calendar <- function(op, x, y, ..., calendar_minus_calendar_fn) { switch ( op, "-" = calendar_minus_calendar_fn(op, x, y, ...), stop_incompatible_op(op, x, y, ...) ) } arith_calendar_and_duration <- function(op, x, y, ...) { switch ( op, "+" = add_duration(x, y), "-" = add_duration(x, -y), stop_incompatible_op(op, x, y, ...) ) } arith_duration_and_calendar <- function(op, x, y, ...) { switch ( op, "+" = add_duration(y, x, swapped = TRUE), "-" = stop_incompatible_op(op, x, y, details = "Can't subtract a calendar from a duration.", ...), stop_incompatible_op(op, x, y, ...) ) } arith_calendar_and_numeric <- function(op, x, y, ...) { switch ( op, "+" = add_duration(x, duration_helper(y, calendar_precision_attribute(x), retain_names = TRUE)), "-" = add_duration(x, duration_helper(-y, calendar_precision_attribute(x), retain_names = TRUE)), stop_incompatible_op(op, x, y, ...) ) } arith_numeric_and_calendar <- function(op, x, y, ...) { switch ( op, "+" = add_duration(y, duration_helper(x, calendar_precision_attribute(y), retain_names = TRUE), swapped = TRUE), "-" = stop_incompatible_op(op, x, y, details = "Can't subtract a calendar from a duration.", ...), stop_incompatible_op(op, x, y, ...) ) } as_year_month_day.clock_calendar <- function(x) { as_year_month_day(as_sys_time(x)) } as_year_month_weekday.clock_calendar <- function(x) { as_year_month_weekday(as_sys_time(x)) } as_iso_year_week_day.clock_calendar <- function(x) { as_iso_year_week_day(as_sys_time(x)) } as_year_day.clock_calendar <- function(x) { as_year_day(as_sys_time(x)) } as_year_quarter_day.clock_calendar <- function(x, ..., start = NULL) { as_year_quarter_day(as_sys_time(x), ..., start = start) } field_year <- function(x) { out <- field(x, "year") names(out) <- NULL out } field_quarter <- function(x) { field(x, "quarter") } field_month <- function(x) { field(x, "month") } field_week <- function(x) { field(x, "week") } field_day <- function(x) { field(x, "day") } field_hour <- function(x) { field(x, "hour") } field_minute <- function(x) { field(x, "minute") } field_second <- function(x) { field(x, "second") } field_subsecond <- function(x) { field(x, "subsecond") } field_index <- function(x) { field(x, "index") } is_calendar <- function(x) { inherits(x, "clock_calendar") }
seq_vector = function(n) { 1:n }
library(amap) url = 'https://docs.google.com/spreadsheets/d/1PWWoMqE5o3ChwJbpexeeYkW6p4BHL9hubVb1fkKSBgA/edit library(gsheet) data = as.data.frame(gsheet2tbl(url)) str(data) head(data) dim(data) names(data) summary(data) str(data) colnames(data) class(data$Age) apply(data, 2, FUN= class) dim(data) head(data) summary(data) names(data) k1 <- amap::Kmeans(data[,-1],centers=3, iter.max = 200) ?Kmeans k1$centers attributes(k1) k1$size k1$withinss k1$cluster k1$centers k1$cluster[9000:9800] table(k1$cluster) k1$size data_clus_2 <- data[ k1$cluster == 2,] (data_clus_2) mean(data_clus_2$Age) data_clus_2$Cust_id write.csv(data_clus_2[,1], file = "./data/data_clus_2.csv")
add_prefix <- function(prefix) { a <- rstudioapi::getSourceEditorContext() s <- a$selection n <- length(s) if (n == 1L && nchar(s[[1L]]$text) == 0L) { pos <- s[[1L]]$range$start pos[2L] <- 1 rstudioapi::insertText(location = pos, text = prefix) } else { for (i in s) rstudioapi::insertText(location = i$range$start, text = prefix) } } add_multiline_prefix <- function(prefix, as_is = FALSE) { a <- rstudioapi::getSourceEditorContext() content <- strsplit(a$selection[[1]]$text, "\n")[[1]] prefix_content <- iconv(content, "latin1", "ASCII", sub="") prefix_content <- gsub('^["]','',prefix_content) if (as_is) { content <- paste0(prefix, content) } else { content[nzchar(content)] <- paste0( gsub("\\b.*$", "", prefix_content[nzchar(content)], perl = TRUE), prefix, gsub("^\\s*", "", content[nzchar(content)]) ) } if (length(content) > 0) { content <- paste0(content, "\n", collapse = "") } else { content <- "" } rstudioapi::modifyRange( location = a$selection[[1]]$range, text = content, id = a$id ) } enclose <- function(prefix, postfix = prefix) { a <- rstudioapi::getSourceEditorContext() for (s in a$selection) rstudioapi::insertText(location = s$range, text = sprintf("%s%s%s", prefix, s$text, postfix)) }
qcomhd <- function(formula, data, q = c(0.1, 0.25, 0.5, 0.75, 0.9), nboot = 2000, alpha = 0.05, ADJ.CI = TRUE, ...){ if (missing(data)) { mf <- model.frame(formula) } else { mf <- model.frame(formula, data) } cl <- match.call() xy <- split(model.extract(mf, "response"), mf[,2]) faclevels <- names(xy) x <- xy[[1]] y <- xy[[2]] pv=NULL output=matrix(NA,nrow=length(q),ncol=10) dimnames(output)<-list(NULL,c("q","n1","n2","est.1","est.2","est.1_minus_est.2","ci.low","ci.up", "p_crit","p-value")) for(i in 1:length(q)){ output[i,1]=q[i] output[i,2]=length(elimna(x)) output[i,3]=length(elimna(y)) output[i,4]=hd(x,q=q[i]) output[i,5]=hd(y,q=q[i]) output[i,6]=output[i,4]-output[i,5] temp=pb2gen1(x,y,nboot=nboot,est=hd,q=q[i],SEED=FALSE,alpha=alpha,pr=FALSE) output[i,7]=temp$ci[1] output[i,8]=temp$ci[2] output[i,10]=temp$p.value } temp=order(output[,10],decreasing=TRUE) zvec=alpha/c(1:length(q)) output[temp,9]=zvec if(ADJ.CI){ for(i in 1:length(q)){ temp=pb2gen1(x,y,nboot=nboot,est=hd,q=q[i],SEED=FALSE,alpha=output[i,9],pr=FALSE) output[i,7]=temp$ci[1] output[i,8]=temp$ci[2] output[i,10]=temp$p.value } } output <- data.frame(output) output$signif=rep("YES",nrow(output)) temp=order(output[,10],decreasing=TRUE) for(i in 1:nrow(output)){ if(output[temp[i],10]>output[temp[i],9])output$signif[temp[i]]="NO" if(output[temp[i],10]<=output[temp[i],9])break } output <- output[,-ncol(output)] colnames(output) <- c("q", "n1", "n2", "est1", "est2", "est1-est.2", "ci.low", "ci.up", "p.crit", "p.value") result <- list(partable = output, alpha = alpha, call = cl) class(result) <- "robtab" result }
ideo.dist <- function(df, id, ideology, time, adoption){ df2 <- as.data.frame(df) df2$ideo_distance_s <- NA for (i in 1:length(eval(substitute({{ id }}), df2))) { p_time <- data.frame(eval(substitute({{ time }}), df2)[eval(substitute({{ adoption }}), df2)==1 & eval(substitute({{ time }}), df2)<eval(substitute({{ time }}), df2)[i]]) p_ideo <- data.frame(eval(substitute({{ ideology }}), df2)[eval(substitute({{ adoption }}), df2)==1 & eval(substitute({{ time }}), df2)<eval(substitute({{ time }}), df2)[i]]) p_id <- data.frame(eval(substitute({{ id }}), df2)[eval(substitute({{ adoption }}), df2)==1 & eval(substitute({{ time }}), df2)<eval(substitute({{ time }}), df2)[i]]) names(p_id) <- "p_id" names(p_time) <- "p_time" names(p_ideo) <- "p_ideo" scores <- dplyr::bind_cols(p_id,p_time,p_ideo) names(scores) <- c("id","t","ideo") max_time <- {suppressWarnings(max(eval(substitute(t), scores)))} min_time <- {suppressWarnings(min(eval(substitute(t), scores)))} recent_scores <- scores %>% dplyr::filter(t==max_time) older <- scores %>% dplyr::filter(t==min_time) older_scores <- dplyr::setdiff(scores,recent_scores) df2$last_adopter_ideo[i] <- (sum(eval(substitute(ideo), recent_scores))/(length(eval(substitute(ideo), recent_scores)))) df2$allother_adopter_ideo[i] <- (sum(eval(substitute(ideo), older_scores))/(length(eval(substitute(ideo), older_scores)))) } df2$last_adopter_ideo[is.nan(df2$last_adopter_ideo)] <- 0 df2$allother_adopter_ideo[is.nan(df2$allother_adopter_ideo)] <- 0 df2$ideo_distance_s <- abs(((eval(substitute(last_adopter_ideo), df2) + eval(substitute(allother_adopter_ideo), df2))/2) - eval(substitute(ideology), df2)) dfname <- deparse(substitute(df)) pos <- 1 envir = as.environment(pos) assign(dfname, data.frame(df2), envir = envir) }
graphIndexComplexity <- function(g) { if (class(g)[1] != "graphNEL") stop("'g' must be a 'graphNEL' object") stopifnot(.validateGraph(g)) n <- numNodes(g) M <- adjacencyMatrix(g) EV <- as.double(eigen(M, only.values=TRUE)$values) r_max <- max(EV) cr <- (r_max - 2*cos(pi/(n+1))) / ((n-1) - 2*cos(pi/(n+1))) 4 * cr * (1-cr) }
`morisita.horn` <- function(x,y) { aN <- sum(x) bN <- sum(y) da <- sum(x^2)/aN^2 db <- sum(y^2)/bN^2 top <- sum(x*y) mor <- 2*top/((da+db)*aN*bN) return(mor) }
complk_cont <- function(Y,piv,Pi,Mu,Si,k){ sY = dim(Y) n = sY[1] TT = sY[2] if(length(sY)==2) r = 1 else r = sY[3] if(r==1){ if(is.matrix(Y)) Y = array(Y,c(dim(Y),1)) } Phi = array(1,c(n,k,TT)); L = array(0,c(n,k,TT)) for(u in 1:k) Phi[,u,1] = dmvnorm(matrix(Y[,1,],n,r),Mu[,u],Si) L[,,1] = Phi[,,1]%*%diag(piv) for(t in 2:TT){ for(u in 1:k) Phi[,u,t] = dmvnorm(matrix(Y[,t,],n,r),Mu[,u],Si) L[,,t] = Phi[,,t]*(L[,,t-1]%*%Pi[,,t]) } if(n==1) pv = sum(L[1,,TT]) else pv = rowSums(L[,,TT]) lk = sum(log(pv)) out = list(lk=lk,Phi=Phi,L=L,pv=pv) }
"GARI" <- function(ADM,EADM){ n <- nrow(ADM) N <- n-1 tmp <- rep(0,n) for(i in 1:n){ k <- sum(ADM[i,]) tmp[i] <- N + 2*k*(k-N)/N } ECN <- sum(tmp) X <- sum(ADM==EADM) - n gari <- (X- ECN )/( n*(n-1) - ECN ) return( gari ) }
`jadjust.length` <- function (inputdata) { if (is.character(inputdata)) s <- scan(inputdata) else s <- inputdata np <- length(s) pow <- 1 while (2 * pow < np) pow <- 2 * pow new.np <- 2 * pow if (np == new.np) list(signal = s, length = np) else { new.s <- 1:new.np new.s[1:new.np] <- 0 new.s[1:np] <- s list(signal = new.s, length = new.np) } }
context("test-fedregs.R") test_that("We can extract some numbers.", { bad_part <- "800 to end" good_part <- "Part 800 to end" silly_part <- "Part no digits" testthat::expect_error(numextract(bad_part), "Make sure you are providing a valid 'part'.") testthat::expect_error(numextract(silly_part), "Make sure string is a numeric value.") testthat::expect_true(numextract("Part 100 to 200", return = "max") == 200) testthat::expect_true(numextract("Part 100 to 200", return = "min") == 100) testthat::expect_true(numextract("Part 100 to end", return = "max") == Inf) testthat::expect_true(is.numeric(numextract("Part 100 to 200", return = "max"))) testthat::expect_true(is.numeric(numextract("Part 100 to 200", return = "min"))) testthat::expect_true(is.numeric(numextract("Part 100 to end", return = "max"))) }) test_that("We can go all the way", { good_year <- 2012 bad_year <- 1995 na_year <- 1996 good_title_number <- 50 bad_title_number <- 1000 na_title_number <- 1 good_chapter <- 6 bad_chapter <- "BB" good_part <- 648 bad_part <- "DD" testthat::expect_error(cfr_text(bad_year, good_title_number, good_chapter, good_part), "Year must be between 1996 and 2018.\n") testthat::expect_error(cfr_text(good_year, bad_title_number, good_chapter, good_part), "Title must be a numeric value between 1 and 50.\n") testthat::expect_error(cfr_text(good_year, good_title_number, bad_chapter, good_part), "Chapter must be a numeric value, not a Roman Numeral.\n") testthat::expect_error(cfr_text(good_year, good_title_number, good_chapter, bad_part), "Part must be a numeric value.\n") testthat::expect_error(cfr_text(na_year, na_title_number, good_chapter, good_part), sprintf("There aren't any regulations for title %s in %s.\n", na_title_number, na_year)) good_text <- cfr_text(good_year, good_title_number, good_chapter, good_part) testthat::expect_true(all(class(good_text) %in% c("grouped_df", "tbl", "tbl_df", "data.frame") == TRUE)) })
dat <- structure(c(7L, 5L, 8L, 0L), .Dim = c(2L, 2L)) class(dat) <- "table" hyp <- "a:=x[1,1]/c(x[1,1]+x[1,2]); a>.5" res <- gorica(dat, hyp) test_that("contingency table supp 2_3 works", { expect_equivalent(res$fit$gorica_weights, c(0.6146977, 0.3853023), tolerance = .03) })
ubio_classification <- function(...) { .Defunct(msg = "the uBio API is down, for good as far as we know") }
theme_grid <- function(fig, which = c("x", "y"), band_fill_alpha = 1, band_fill_color = "gray", grid_line_alpha = 1, grid_line_cap = "butt", grid_line_color = "black", grid_line_dash = NULL, grid_line_dash_offset = 0, grid_line_join = "miter", grid_line_width = 1, minor_grid_line_alpha = 1, minor_grid_line_cap = "butt", minor_grid_line_color = "black", minor_grid_line_dash = NULL, minor_grid_line_dash_offset = 0, minor_grid_line_join = "miter", minor_grid_line_width = 1, pars = NULL ) { if (is.null(pars)) { specified <- names(as.list(match.call())[-1]) pars <- as.list(environment())[specified] } pars <- pars[names(pars) %in% names(grid_par_validator_map)] pars <- handle_extra_pars(pars, grid_par_validator_map) parnames <- names(pars) if (!is.null(fig$x$modeltype) && fig$x$modeltype == "GridPlot") { for (ii in seq_along(fig$x$spec$figs)) { if ("x" %in% which && fig$x$spec$figs[[ii]]$x$spec$xaxes != FALSE) { if (is.null(fig$x$spec$figs[[ii]]$x$spec$model[["x_grid"]])) fig$x$spec$figs[[ii]] <- fig$x$spec$figs[[ii]] %>% x_axis() for (nm in parnames) fig$x$spec$figs[[ii]]$x$spec$model[["x_grid"]]$attributes[[nm]] <- pars[[nm]] } if ("y" %in% which && fig$x$spec$figs[[ii]]$x$spec$yaxes != FALSE) { if (is.null(fig$x$spec$figs[[ii]]$x$spec$model[["y_grid"]])) fig$x$spec$figs[[ii]] <- fig$x$spec$figs[[ii]] %>% y_axis() for (nm in parnames) fig$x$spec$figs[[ii]]$x$spec$model[["y_grid"]]$attributes[[nm]] <- pars[[nm]] } } } else { if ("x" %in% which && fig$x$spec$xaxes != FALSE) { if (is.null(fig$x$spec$model[["x_grid"]])) fig <- fig %>% x_axis() for (nm in parnames) fig$x$spec$model[["x_grid"]]$attributes[[nm]] <- pars[[nm]] } if ("y" %in% which && fig$x$spec$yaxes != FALSE) { if (is.null(fig$x$spec$model[["y_grid"]])) fig <- fig %>% y_axis() for (nm in parnames) fig$x$spec$model[["y_grid"]]$attributes[[nm]] <- pars[[nm]] } } fig }
act2probrat <- function(act, theta, beta) { 1 / (1 + exp(-theta * (act - beta))) }
crowdingDist4frnt <- function(pop,rnk,rng){ popSize <- nrow(pop); objDim <- length(rng); varNo <- ncol(pop)-1-length(rng); cd <- matrix(Inf,nrow=popSize,ncol=objDim); for (i in 1:length(rnk)){ selectRow <- pop[,ncol(pop)]==i; len <- length(rnk[[i]]); if (len > 2) { for (j in 1:objDim) { originalIdx <- rnk[[i]][order(pop[selectRow,varNo+j])]; cd[originalIdx[2:(len-1)],j] = abs(pop[originalIdx[3:len],varNo+j] - pop[originalIdx[1:(len-2)],varNo+j])/rng[j]; } } } return(cd); }
getHHdata <- function(survey, year, quarter) { if (!checkSurveyOK(survey)) return(FALSE) if (!checkSurveyYearOK(survey, year, checksurvey = FALSE)) return(FALSE) if (!checkSurveyYearQuarterOK(survey, year, quarter, checksurvey = FALSE, checkyear = FALSE)) return(FALSE) url <- sprintf( "https://datras.ices.dk/WebServices/DATRASWebService.asmx/getHHdata?survey=%s&year=%i&quarter=%i", survey, year, quarter) out <- readDatras(url) out <- parseDatras(out) out }
expected <- 2L test(id=1, code={ argv <- structure(list(x = structure(c(1L, 2L, NA), .Label = c("1", "2" ), class = "factor")), .Names = "x") do.call('nlevels', argv); }, o = expected);
complete.mids <- function(data, action = 1L, include = FALSE, mild = FALSE, ...) { if (!is.mids(data)) stop("'data' not of class 'mids'") m <- as.integer(data$m) if (is.numeric(action)) { action <- as.integer(action) idx <- action[action >= 0L & action <= m] if (include && all(idx != 0L)) idx <- c(0L, idx) shape <- ifelse(mild, "mild", "stacked") } else if (is.character(action)) { if (include) idx <- 0L:m else idx <- 1L:m shape <- match.arg(action, c("all", "long", "broad", "repeated", "stacked")) shape <- ifelse(shape == "all" || mild, "mild", shape) } else { stop("'action' not recognized") } mylist <- vector("list", length = length(idx)) for (j in seq_along(idx)) { mylist[[j]] <- single.complete(data$data, data$where, data$imp, idx[j]) } if (shape == "stacked") { return(bind_rows(mylist)) } if (shape == "mild") { names(mylist) <- as.character(idx) class(mylist) <- c("mild", "list") return(mylist) } if (shape == "long") { cmp <- bind_rows(mylist) cmp <- data.frame( .imp = rep(idx, each = nrow(data$data)), .id = rep.int(1L:nrow(data$data), length(idx)), cmp ) if (is.integer(attr(data$data, "row.names"))) { row.names(cmp) <- seq_len(nrow(cmp)) } else { row.names(cmp) <- as.character(seq_len(nrow(cmp))) } return(cmp) } cmp <- bind_cols(mylist) names(cmp) <- paste(rep.int(names(data$data), m), rep.int(idx, rep.int(ncol(data$data), length(idx))), sep = "." ) if (shape == "broad") { return(cmp) } else { return(cmp[, order(rep.int(seq_len(ncol(data$data)), length(idx)))]) } } single.complete <- function(data, where, imp, ell) { if (ell == 0L) { return(data) } if (is.null(where)) { where <- is.na(data) } idx <- seq_len(ncol(data))[apply(where, 2, any)] for (j in idx) { if (is.null(imp[[j]])) { data[where[, j], j] <- NA } else { data[where[, j], j] <- imp[[j]][, ell] } } data }
numMualem <- function(h, scap, pcon = NA) { if(!is.na(pcon)){ q <- pcon[1] r <- pcon[2] }else{ q <- 1 r <- 2 } int1 = pracma::cumtrapz(rev(scap), rev(h^-q)) int2 = max(int1)[1]; mua_num = rev((int1/int2)^r) return(mua_num) }
local({ version <- "0.14.0" project <- getwd() activate <- Sys.getenv("RENV_ACTIVATE_PROJECT") if (!nzchar(activate)) { if (nzchar(Sys.getenv("R_INSTALL_PKG"))) return(FALSE) } if (tolower(activate) %in% c("false", "f", "0")) return(FALSE) if (nzchar(Sys.getenv("RENV_R_INITIALIZING"))) return(invisible(TRUE)) Sys.setenv("RENV_R_INITIALIZING" = "true") on.exit(Sys.unsetenv("RENV_R_INITIALIZING"), add = TRUE) options(renv.consent = TRUE) library(utils, lib.loc = .Library) if ("renv" %in% loadedNamespaces()) { spec <- .getNamespaceInfo(.getNamespace("renv"), "spec") if (identical(spec[["version"]], version)) return(invisible(TRUE)) unloadNamespace("renv") } bootstrap <- function(version, library) { tarball <- tryCatch(renv_bootstrap_download(version), error = identity) if (inherits(tarball, "error")) stop("failed to download renv ", version) status <- tryCatch(renv_bootstrap_install(version, tarball, library), error = identity) if (inherits(status, "error")) stop("failed to install renv ", version) } renv_bootstrap_tests_running <- function() { getOption("renv.tests.running", default = FALSE) } renv_bootstrap_repos <- function() { repos <- Sys.getenv("RENV_CONFIG_REPOS_OVERRIDE", unset = NA) if (!is.na(repos)) return(repos) if (renv_bootstrap_tests_running()) return(getOption("renv.tests.repos")) repos <- getOption("repos") repos[repos == "@CRAN@"] <- getOption( "renv.repos.cran", "https://cloud.r-project.org" ) default <- c(FALLBACK = "https://cloud.r-project.org") extra <- getOption("renv.bootstrap.repos", default = default) repos <- c(repos, extra) dupes <- duplicated(repos) | duplicated(names(repos)) repos[!dupes] } renv_bootstrap_download <- function(version) { nv <- numeric_version(version) components <- unclass(nv)[[1]] methods <- if (length(components) == 4L) { list( renv_bootstrap_download_github ) } else { list( renv_bootstrap_download_cran_latest, renv_bootstrap_download_cran_archive ) } for (method in methods) { path <- tryCatch(method(version), error = identity) if (is.character(path) && file.exists(path)) return(path) } stop("failed to download renv ", version) } renv_bootstrap_download_impl <- function(url, destfile) { mode <- "wb" fixup <- Sys.info()[["sysname"]] == "Windows" && substring(url, 1L, 5L) == "file:" if (fixup) mode <- "w+b" utils::download.file( url = url, destfile = destfile, mode = mode, quiet = TRUE ) } renv_bootstrap_download_cran_latest <- function(version) { spec <- renv_bootstrap_download_cran_latest_find(version) message("* Downloading renv ", version, " ... ", appendLF = FALSE) type <- spec$type repos <- spec$repos info <- tryCatch( utils::download.packages( pkgs = "renv", destdir = tempdir(), repos = repos, type = type, quiet = TRUE ), condition = identity ) if (inherits(info, "condition")) { message("FAILED") return(FALSE) } message("OK (downloaded ", type, ")") info[1, 2] } renv_bootstrap_download_cran_latest_find <- function(version) { binary <- getOption("renv.bootstrap.binary", default = TRUE) && !identical(.Platform$pkgType, "source") && !identical(getOption("pkgType"), "source") && Sys.info()[["sysname"]] %in% c("Darwin", "Windows") types <- c(if (binary) "binary", "source") for (type in types) { for (repos in renv_bootstrap_repos()) { db <- tryCatch( as.data.frame( utils::available.packages(type = type, repos = repos), stringsAsFactors = FALSE ), error = identity ) if (inherits(db, "error")) next entry <- db[db$Package %in% "renv" & db$Version %in% version, ] if (nrow(entry) == 0) next spec <- list(entry = entry, type = type, repos = repos) return(spec) } } fmt <- "renv %s is not available from your declared package repositories" stop(sprintf(fmt, version)) } renv_bootstrap_download_cran_archive <- function(version) { name <- sprintf("renv_%s.tar.gz", version) repos <- renv_bootstrap_repos() urls <- file.path(repos, "src/contrib/Archive/renv", name) destfile <- file.path(tempdir(), name) message("* Downloading renv ", version, " ... ", appendLF = FALSE) for (url in urls) { status <- tryCatch( renv_bootstrap_download_impl(url, destfile), condition = identity ) if (identical(status, 0L)) { message("OK") return(destfile) } } message("FAILED") return(FALSE) } renv_bootstrap_download_github <- function(version) { enabled <- Sys.getenv("RENV_BOOTSTRAP_FROM_GITHUB", unset = "TRUE") if (!identical(enabled, "TRUE")) return(FALSE) pat <- Sys.getenv("GITHUB_PAT") if (nzchar(Sys.which("curl")) && nzchar(pat)) { fmt <- "--location --fail --header \"Authorization: token %s\"" extra <- sprintf(fmt, pat) saved <- options("download.file.method", "download.file.extra") options(download.file.method = "curl", download.file.extra = extra) on.exit(do.call(base::options, saved), add = TRUE) } else if (nzchar(Sys.which("wget")) && nzchar(pat)) { fmt <- "--header=\"Authorization: token %s\"" extra <- sprintf(fmt, pat) saved <- options("download.file.method", "download.file.extra") options(download.file.method = "wget", download.file.extra = extra) on.exit(do.call(base::options, saved), add = TRUE) } message("* Downloading renv ", version, " from GitHub ... ", appendLF = FALSE) url <- file.path("https://api.github.com/repos/rstudio/renv/tarball", version) name <- sprintf("renv_%s.tar.gz", version) destfile <- file.path(tempdir(), name) status <- tryCatch( renv_bootstrap_download_impl(url, destfile), condition = identity ) if (!identical(status, 0L)) { message("FAILED") return(FALSE) } message("OK") return(destfile) } renv_bootstrap_install <- function(version, tarball, library) { message("* Installing renv ", version, " ... ", appendLF = FALSE) dir.create(library, showWarnings = FALSE, recursive = TRUE) bin <- R.home("bin") exe <- if (Sys.info()[["sysname"]] == "Windows") "R.exe" else "R" r <- file.path(bin, exe) args <- c("--vanilla", "CMD", "INSTALL", "-l", shQuote(library), shQuote(tarball)) output <- system2(r, args, stdout = TRUE, stderr = TRUE) message("Done!") status <- attr(output, "status") if (is.numeric(status) && !identical(status, 0L)) { header <- "Error installing renv:" lines <- paste(rep.int("=", nchar(header)), collapse = "") text <- c(header, lines, output) writeLines(text, con = stderr()) } status } renv_bootstrap_platform_prefix <- function() { version <- paste(R.version$major, R.version$minor, sep = ".") prefix <- paste("R", numeric_version(version)[1, 1:2], sep = "-") devel <- identical(R.version[["status"]], "Under development (unstable)") || identical(R.version[["nickname"]], "Unsuffered Consequences") if (devel) prefix <- paste(prefix, R.version[["svn rev"]], sep = "-r") components <- c(prefix, R.version$platform) prefix <- renv_bootstrap_platform_prefix_impl() if (!is.na(prefix) && nzchar(prefix)) components <- c(prefix, components) paste(components, collapse = "/") } renv_bootstrap_platform_prefix_impl <- function() { prefix <- Sys.getenv("RENV_PATHS_PREFIX", unset = NA) if (!is.na(prefix)) return(prefix) auto <- Sys.getenv("RENV_PATHS_PREFIX_AUTO", unset = NA) if (auto %in% c("TRUE", "True", "true", "1")) return(renv_bootstrap_platform_prefix_auto()) "" } renv_bootstrap_platform_prefix_auto <- function() { prefix <- tryCatch(renv_bootstrap_platform_os(), error = identity) if (inherits(prefix, "error") || prefix %in% "unknown") { msg <- paste( "failed to infer current operating system", "please file a bug report at https://github.com/rstudio/renv/issues", sep = "; " ) warning(msg) } prefix } renv_bootstrap_platform_os <- function() { sysinfo <- Sys.info() sysname <- sysinfo[["sysname"]] if (sysname == "Windows") return("windows") else if (sysname == "Darwin") return("macos") for (file in c("/etc/os-release", "/usr/lib/os-release")) if (file.exists(file)) return(renv_bootstrap_platform_os_via_os_release(file, sysinfo)) if (file.exists("/etc/redhat-release")) return(renv_bootstrap_platform_os_via_redhat_release()) "unknown" } renv_bootstrap_platform_os_via_os_release <- function(file, sysinfo) { release <- utils::read.table( file = file, sep = "=", quote = c("\"", "'"), col.names = c("Key", "Value"), comment.char = " stringsAsFactors = FALSE ) vars <- as.list(release$Value) names(vars) <- release$Key os <- tolower(sysinfo[["sysname"]]) id <- "unknown" for (field in c("ID", "ID_LIKE")) { if (field %in% names(vars) && nzchar(vars[[field]])) { id <- vars[[field]] break } } version <- "unknown" for (field in c("UBUNTU_CODENAME", "VERSION_CODENAME", "VERSION_ID", "BUILD_ID")) { if (field %in% names(vars) && nzchar(vars[[field]])) { version <- vars[[field]] break } } paste(c(os, id, version), collapse = "-") } renv_bootstrap_platform_os_via_redhat_release <- function() { contents <- readLines("/etc/redhat-release", warn = FALSE) id <- if (grepl("centos", contents, ignore.case = TRUE)) "centos" else if (grepl("redhat", contents, ignore.case = TRUE)) "redhat" else "unknown" version <- "unknown" parts <- strsplit(contents, "[[:space:]]")[[1L]] for (part in parts) { nv <- tryCatch(numeric_version(part), error = identity) if (inherits(nv, "error")) next version <- nv[1, 1] break } paste(c("linux", id, version), collapse = "-") } renv_bootstrap_library_root_name <- function(project) { asis <- Sys.getenv("RENV_PATHS_LIBRARY_ROOT_ASIS", unset = "FALSE") if (asis) return(basename(project)) id <- substring(renv_bootstrap_hash_text(project), 1L, 8L) paste(basename(project), id, sep = "-") } renv_bootstrap_library_root <- function(project) { path <- Sys.getenv("RENV_PATHS_LIBRARY", unset = NA) if (!is.na(path)) return(path) path <- Sys.getenv("RENV_PATHS_LIBRARY_ROOT", unset = NA) if (!is.na(path)) { name <- renv_bootstrap_library_root_name(project) return(file.path(path, name)) } prefix <- renv_bootstrap_profile_prefix() paste(c(project, prefix, "renv/library"), collapse = "/") } renv_bootstrap_validate_version <- function(version) { loadedversion <- utils::packageDescription("renv", fields = "Version") if (version == loadedversion) return(TRUE) components <- strsplit(loadedversion, "[.-]")[[1]] remote <- if (length(components) == 4L) paste("rstudio/renv", loadedversion, sep = "@") else paste("renv", loadedversion, sep = "@") fmt <- paste( "renv %1$s was loaded from project library, but this project is configured to use renv %2$s.", "Use `renv::record(\"%3$s\")` to record renv %1$s in the lockfile.", "Use `renv::restore(packages = \"renv\")` to install renv %2$s into the project library.", sep = "\n" ) msg <- sprintf(fmt, loadedversion, version, remote) warning(msg, call. = FALSE) FALSE } renv_bootstrap_hash_text <- function(text) { hashfile <- tempfile("renv-hash-") on.exit(unlink(hashfile), add = TRUE) writeLines(text, con = hashfile) tools::md5sum(hashfile) } renv_bootstrap_load <- function(project, libpath, version) { if (!requireNamespace("renv", lib.loc = libpath, quietly = TRUE)) return(FALSE) renv_bootstrap_validate_version(version) renv::load(project) TRUE } renv_bootstrap_profile_load <- function(project) { profile <- Sys.getenv("RENV_PROFILE", unset = NA) if (!is.na(profile) && nzchar(profile)) return(profile) path <- file.path(project, "renv/local/profile") if (!file.exists(path)) return(NULL) contents <- readLines(path, warn = FALSE) if (length(contents) == 0L) return(NULL) profile <- contents[[1L]] if (nzchar(profile)) Sys.setenv(RENV_PROFILE = profile) profile } renv_bootstrap_profile_prefix <- function() { profile <- renv_bootstrap_profile_get() if (!is.null(profile)) return(file.path("renv/profiles", profile)) } renv_bootstrap_profile_get <- function() { profile <- Sys.getenv("RENV_PROFILE", unset = "") renv_bootstrap_profile_normalize(profile) } renv_bootstrap_profile_set <- function(profile) { profile <- renv_bootstrap_profile_normalize(profile) if (is.null(profile)) Sys.unsetenv("RENV_PROFILE") else Sys.setenv(RENV_PROFILE = profile) } renv_bootstrap_profile_normalize <- function(profile) { if (is.null(profile) || profile %in% c("", "default")) return(NULL) profile } renv_bootstrap_profile_load(project) root <- renv_bootstrap_library_root(project) prefix <- renv_bootstrap_platform_prefix() libpath <- file.path(root, prefix) if (renv_bootstrap_load(project, libpath, version)) return(TRUE) prefix <- paste(" postfix <- paste(rep.int("-", 77L - nchar(prefix)), collapse = "") header <- paste(prefix, postfix) message(header) bootstrap(version, libpath) if (!is.na(Sys.getenv("RENV_BOOTSTRAP_INSTALL_ONLY", unset = NA))) return(TRUE) if (requireNamespace("renv", lib.loc = libpath, quietly = TRUE)) { message("* Successfully installed and loaded renv ", version, ".") return(renv::load()) } msg <- c( "Failed to find an renv installation: the project will not be loaded.", "Use `renv::activate()` to re-initialize the project." ) warning(paste(msg, collapse = "\n"), call. = FALSE) })
context("GPModel_combined_GP_grouped_random_effects") sim_rand_unif <- function(n, init_c=0.1){ mod_lcg <- 2^32 sim <- rep(NA, n) sim[1] <- floor(init_c * mod_lcg) for(i in 2:n) sim[i] <- (22695477 * sim[i-1] + 1) %% mod_lcg return(sim / mod_lcg) } n <- 100 d <- 2 coords <- matrix(sim_rand_unif(n=n*d, init_c=0.1), ncol=d) D <- as.matrix(dist(coords)) sigma2_1 <- 1^2 rho <- 0.1 Sigma <- sigma2_1 * exp(-D/rho) + diag(1E-20,n) L <- t(chol(Sigma)) b_1 <- qnorm(sim_rand_unif(n=n, init_c=0.8)) Z_SVC <- matrix(sim_rand_unif(n=n*2, init_c=0.6), ncol=2) colnames(Z_SVC) <- c("var1","var2") b_2 <- qnorm(sim_rand_unif(n=n, init_c=0.17)) b_3 <- qnorm(sim_rand_unif(n=n, init_c=0.42)) m <- 10 group <- rep(1,n) for(i in 1:m) group[((i-1)*n/m+1):(i*n/m)] <- i Z1 <- model.matrix(rep(1,n) ~ factor(group) - 1) b_gr_1 <- qnorm(sim_rand_unif(n=m, init_c=0.56)) n_obs_gr <- n/m group2 <- rep(1,n) for(i in 1:m) group2[(1:n_obs_gr)+n_obs_gr*(i-1)] <- 1:n_obs_gr Z2 <- model.matrix(rep(1,n)~factor(group2)-1) b_gr_2 <- qnorm(sim_rand_unif(n=n_obs_gr, init_c=0.36)) x <- cos((1:n-n/2)^2*5.5*pi/n) Z3 <- diag(x) %*% Z1 b_gr_3 <- qnorm(sim_rand_unif(n=m, init_c=0.5678)) xi <- qnorm(sim_rand_unif(n=n, init_c=0.1)) / 5 X <- cbind(rep(1,n),sin((1:n-n/2)^2*2*pi/n)) beta <- c(2,2) cluster_ids <- c(rep(1,0.4*n),rep(2,0.6*n)) eps <- as.vector(L %*% b_1) + as.vector(Z1 %*% b_gr_1) eps_svc <- as.vector(L %*% b_1 + Z_SVC[,1] * L %*% b_2 + Z_SVC[,2] * L %*% b_3) + Z1 %*% b_gr_1 + Z2 %*% b_gr_2 + Z3 %*% b_gr_3 test_that("Combined Gaussian process and grouped random effects model ", { y <- eps + xi gp_model <- GPModel(gp_coords = coords, cov_function = "exponential", group_data = group) fit(gp_model, y = y, params = list(optimizer_cov = "gradient_descent", std_dev = TRUE, lr_cov = 0.15, use_nesterov_acc = TRUE, acc_rate_cov = 0.8, delta_rel_conv=1E-6)) cov_pars <- c(0.02924971, 0.09509924, 0.61463579, 0.30619763, 1.02189002, 0.25932007, 0.11327419, 0.04276286) expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-6) expect_equal(dim(gp_model$get_cov_pars())[2], 4) expect_equal(dim(gp_model$get_cov_pars())[1], 2) expect_equal(gp_model$get_num_optim_iter(), 33) gp_model <- fitGPModel(gp_coords = coords, cov_function = "exponential", group_data = group, y = y, params = list(optimizer_cov = "fisher_scoring", std_dev = FALSE)) cov_pars <- c(0.02262645, 0.61471473, 1.02446559, 0.11177327) cov_pars_est <- as.vector(gp_model$get_cov_pars()) expect_lt(sum(abs(cov_pars_est-cov_pars)),1E-5) expect_equal(class(cov_pars_est), "numeric") expect_equal(length(cov_pars_est), 4) expect_equal(gp_model$get_num_optim_iter(), 8) gp_model <- fitGPModel(gp_coords = coords, cov_function = "exponential", group_data = group, y = y, params = list(optimizer_cov = "fisher_scoring", std_dev = FALSE)) coord_test <- cbind(c(0.1,0.2,0.7),c(0.9,0.4,0.55)) group_test <- c(1,2,9999) pred <- predict(gp_model, y=y, gp_coords_pred = coord_test, group_data_pred = group_test, predict_cov_mat = TRUE) expected_mu <- c(0.3769074, 0.6779193, 0.1803276) expected_cov <- c(0.619329940, 0.007893047, 0.001356784, 0.007893047, 0.402082274, -0.014950019, 0.001356784, -0.014950019, 1.046082243) expect_lt(sum(abs(pred$mu-expected_mu)),1E-6) expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-6) pred <- predict(gp_model, y=y, gp_coords_pred = coord_test, group_data_pred = group_test, predict_var = TRUE) expect_lt(sum(abs(pred$mu-expected_mu)),1E-6) expect_lt(sum(abs(as.vector(pred$var)-expected_cov[c(1,5,9)])),1E-6) gp_model <- GPModel(gp_coords = coords, cov_function = "exponential", group_data = group) pred <- predict(gp_model, y=y, gp_coords_pred = coord_test, group_data_pred = group_test, cov_pars = c(0.02,1,1.2,0.9), predict_cov_mat = TRUE) expected_mu <- c(0.3995192, 0.6775987, 0.3710522) expected_cov <- c(0.1257410304, 0.0017195802, 0.0007660953, 0.0017195802, 0.0905110441, -0.0028869470, 0.0007660953, -0.0028869470, 1.1680614026) expect_lt(sum(abs(pred$mu-expected_mu)),1E-6) expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-6) nll <- gp_model$neg_log_likelihood(cov_pars=c(0.1,0.9,1.6,0.2),y=y) expect_lt(abs(nll-134.3491913),1E-6) gp_model <- GPModel(gp_coords = coords, cov_function = "exponential", group_data = group) opt <- optim(par=c(0.1,1.5,2,0.2), fn=gp_model$neg_log_likelihood, y=y, method="Nelder-Mead") expect_lt(sum(abs(opt$par-cov_pars)),1E-3) expect_lt(abs(opt$value-(132.4136164)),1E-5) expect_equal(as.integer(opt$counts[1]), 335) }) test_that("Combined GP and grouped random effects model with linear regression term ", { y <- eps + X%*%beta + xi gp_model <- fitGPModel(gp_coords = coords, cov_function = "exponential", group_data = group, y = y, X=X, params = list(optimizer_cov = "fisher_scoring", optimizer_coef = "wls", std_dev = TRUE)) cov_pars <- c(0.02258493, 0.09172947, 0.61704845, 0.30681934, 1.01910740, 0.25561489, 0.11202133, 0.04174140) coef <- c(2.06686646, 0.34643130, 1.92847425, 0.09983966) expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-6) expect_lt(sum(abs(as.vector(gp_model$get_coef())-coef)),1E-6) expect_equal(gp_model$get_num_optim_iter(), 8) coord_test <- cbind(c(0.1,0.2,0.7),c(0.9,0.4,0.55)) group_test <- c(1,2,9999) X_test <- cbind(rep(1,3),c(-0.5,0.2,0.4)) pred <- predict(gp_model, gp_coords_pred = coord_test, group_data_pred = group_test, X_pred = X_test, predict_cov_mat = TRUE) expected_mu <- c(1.442617, 3.129006, 2.946252) expected_cov <- c(0.615200495, 0.007850776, 0.001344528, 0.007850776, 0.399458031, -0.014866034, 0.001344528, -0.014866034, 1.045700453) expect_lt(sum(abs(pred$mu-expected_mu)),1E-5) expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-6) }) test_that("Combined GP and grouped random effects model with random coefficients ", { y <- eps_svc + xi gp_model <- fitGPModel(y = y, gp_coords = coords, cov_function = "exponential", gp_rand_coef_data = Z_SVC, group_data = cbind(group,group2), group_rand_coef_data = x, ind_effect_group_rand_coef = 1, params = list(optimizer_cov = "gradient_descent", std_dev = TRUE, lr_cov = 0.1, use_nesterov_acc = TRUE, acc_rate_cov = 0.5, maxit=10)) expected_values <- c(0.4005820, 0.3111155, 0.4564903, 0.2693683, 1.3819153, 0.7034572, 1.0378165, 0.5916405, 1.3684672, 0.6861339, 0.1854759, 0.1430030, 0.5790945, 0.9748316, 0.2103132, 0.4453663, 0.2639379, 0.8772996, 0.2210313, 0.9282390) expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-expected_values)),1E-6) expect_equal(gp_model$get_num_optim_iter(), 10) gp_model <- GPModel(gp_coords = coords, gp_rand_coef_data = Z_SVC, cov_function = "exponential", group_data = cbind(group,group2), group_rand_coef_data = x, ind_effect_group_rand_coef = 1) coord_test <- cbind(c(0.1,0.2,0.7),c(0.9,0.4,0.55)) Z_SVC_test <- cbind(c(0.1,0.3,0.7),c(0.5,0.2,0.4)) group_data_pred = cbind(c(1,1,7),c(2,1,3)) group_rand_coef_data_pred = c(0,0.1,0.3) pred <- gp_model$predict(y = y, gp_coords_pred = coord_test, gp_rand_coef_data_pred=Z_SVC_test, group_data_pred=group_data_pred, group_rand_coef_data_pred=group_rand_coef_data_pred, cov_pars = c(0.1,0.9,0.8,1.2,1,0.1,0.8,0.15,1.1,0.08), predict_cov_mat = TRUE) expected_mu <- c(0.8657964, 1.5419953, -2.5645509) expected_cov <- c(1.177484599, 0.073515374, 0.030303784, 0.073515374, 0.841043737, 0.004484463, 0.030303784, 0.004484463, 1.011570695) expect_lt(sum(abs(pred$mu-expected_mu)),1E-6) expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-6) gp_model <- fitGPModel(y = y, gp_coords = coords, cov_function = "exponential", gp_rand_coef_data = Z_SVC, group_data = cbind(group,group2), group_rand_coef_data = x, ind_effect_group_rand_coef = 1, params = list(optimizer_cov = "fisher_scoring", std_dev = FALSE, use_nesterov_acc= FALSE, maxit=2)) expected_values <- c(0.6093408, 0.8157278, 1.6016549, 1.2415390,1.7255119, 0.1400087, 1.1872654, 0.1469588, 0.4605333, 0.2635957) expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-expected_values)),1E-6) expect_equal(gp_model$get_num_optim_iter(), 2) nll <- gp_model$neg_log_likelihood(cov_pars=c(0.1,0.9,0.8,1.2,1,0.1,0.8,0.15,1.1,0.08),y=y) expect_lt(abs(nll-182.3674191),1E-5) }) test_that("Combined GP and grouped random effects model with cluster_id's not constant ", { y <- eps + xi gp_model <- fitGPModel(gp_coords = coords, cov_function = "exponential", group_data = group, y = y, cluster_ids = cluster_ids, params = list(optimizer_cov = "fisher_scoring", std_dev = TRUE)) cov_pars <- c(0.005306836, 0.087915468, 0.615012714, 0.315022228, 1.043024690, 0.228236254, 0.113716679, 0.039839629) expect_lt(sum(abs(as.vector(gp_model$get_cov_pars())-cov_pars)),1E-5) expect_equal(gp_model$get_num_optim_iter(), 8) coord_test <- cbind(c(0.1,0.2,0.7),c(0.9,0.4,0.55)) group_data_pred = c(1,1,9999) cluster_ids_pred = c(1,3,1) gp_model <- GPModel(gp_coords = coords, cov_function = "exponential", group_data = group, cluster_ids = cluster_ids) pred <- gp_model$predict(y = y, gp_coords_pred = coord_test, group_data_pred = group_data_pred, cluster_ids_pred = cluster_ids_pred, cov_pars = c(0.1,1.5,1,0.15), predict_cov_mat = TRUE) expected_mu <- c(0.1275193, 0.0000000, 0.5948827) expected_cov <- c(0.76147286, 0.00000000, -0.01260688, 0.00000000, 2.60000000, 0.00000000, -0.01260688, 0.00000000, 2.15607110) expect_lt(sum(abs(pred$mu-expected_mu)),1E-6) expect_lt(sum(abs(as.vector(pred$cov)-expected_cov)),1E-6) }) if(Sys.getenv("GPBOOST_ALL_TESTS") == "GPBOOST_ALL_TESTS"){ test_that("Saving a GPModel and loading from filw works ", { y <- eps + X%*%beta + xi gp_model <- fitGPModel(gp_coords = coords, cov_function = "exponential", group_data = group, y = y, X=X, params = list(optimizer_cov = "fisher_scoring", optimizer_coef = "wls")) coord_test <- cbind(c(0.1,0.2,0.7),c(0.9,0.4,0.55)) group_test <- c(1,2,9999) X_test <- cbind(rep(1,3),c(-0.5,0.2,0.4)) pred <- predict(gp_model, gp_coords_pred = coord_test, group_data_pred = group_test, X_pred = X_test, predict_cov_mat = TRUE) filename <- tempfile(fileext = ".json") saveGPModel(gp_model,filename = filename) rm(gp_model) gp_model_loaded <- loadGPModel(filename = filename) pred_loaded <- predict(gp_model_loaded, gp_coords_pred = coord_test, group_data_pred = group_test, X_pred = X_test, predict_cov_mat = TRUE) expect_equal(pred$mu, pred_loaded$mu) expect_equal(pred$cov, pred_loaded$cov) }) }
sfaLoad<- function (filename){ sfaList<-list() load(file=filename) return(sfaList) } sfaSave<- function (sfaList, filename){ save(sfaList,file=filename) } gaussLoad<- function (filename){ gauss<-list() load(file=filename) return(gauss) } gaussSave<- function (gauss, filename){ save(gauss,file=filename) }
library(magi) library(testthat) context("x-theta sampler") config <- list( nobs = 41, noise = 0.1, kernel = "generalMatern", seed = 123, npostplot = 5, loglikflag = "band", bandsize = 20, hmcSteps = 100, n.iter = 1e3, burninRatio = 0.1, stepSizeFactor = 1 ) VRtrue <- read.csv(system.file("testdata/FN.csv", package="magi")) pram.true <- list( abc=c(0.2,0.2,3), rphi=c(0.9486433, 3.2682434), vphi=c(1.9840824, 1.1185157), sigma=config$noise ) fn.true <- VRtrue[seq(1,401,by=2),] fn.true$time <- seq(0,20,0.1) fn.sim <- fn.true set.seed(config$seed) fn.sim[,1:2] <- fn.sim[,1:2]+rnorm(length(unlist(fn.sim[,1:2])), sd=config$noise) tvec.full <- fn.sim$time fn.sim.all <- fn.sim fn.sim[-seq(1,nrow(fn.sim), length=config$nobs),] <- NaN fn.sim.obs <- fn.sim[seq(1,nrow(fn.sim), length=config$nobs),] tvec.nobs <- fn.sim$time[seq(1,nrow(fn.sim), length=config$nobs)] foo <- outer(tvec.full, t(tvec.full),'-')[,1,] r <- abs(foo) r2 <- r^2 signr <- -sign(foo) foo <- outer(tvec.nobs, t(tvec.nobs),'-')[,1,] r.nobs <- abs(foo) r2.nobs <- r.nobs^2 signr.nobs <- -sign(foo) marlikmap <- list(par = c(2.314, 1.346, 0.622, 2.452, 0.085)) cursigma <- marlikmap$par[5] curCovV <- calCov(marlikmap$par[1:2], r, signr, bandsize=config$bandsize, kerneltype=config$kernel) curCovR <- calCov(marlikmap$par[3:4], r, signr, bandsize=config$bandsize, kerneltype=config$kernel) cursigma <- marlikmap$par[5] curCovV$mu <- as.vector(fn.true[,1]) curCovR$mu <- as.vector(fn.true[,2]) dotmu <- magi:::fODE(pram.true$abc, fn.true[,1:2]) curCovV$dotmu <- as.vector(dotmu[,1]) curCovR$dotmu <- as.vector(dotmu[,2]) xth <- c(fn.true$Vtrue, fn.true$Rtrue, pram.true$abc) rstep <- rep(1e10, length(xth)) foo <- magi:::xthetaSample(data.matrix(fn.sim[,1:2]), list(curCovV, curCovR), cursigma, xth, rstep, config$hmcSteps, F, loglikflag = "usual") test_that("NA should not appear after xthetaSample", { expect_true(all(!is.na(foo$final))) }) rstep <- rep(1e30, length(xth)) foo <- magi:::xthetaSample(data.matrix(fn.sim[,1:2]), list(curCovV, curCovR), cursigma, xth, rstep, config$hmcSteps, T, loglikflag = "usual") test_that("NA should not appear after xthetaSample", { expect_true(all(!is.na(foo$final))) }) rstep <- rep(0.0001, length(xth)) set.seed(234) foo1 <- magi:::xthetaSample(data.matrix(fn.sim[,1:2]), list(curCovV, curCovR), cursigma, xth, rstep, config$hmcSteps, F, loglikflag = "usual") set.seed(234) foo2 <- magi:::xthetaSample(data.matrix(fn.sim[,1:2]), list(curCovV, curCovR), cursigma, xth, rstep, config$hmcSteps, T, loglikflag = "usual") test_that("return trajectory or not does not affect result", { expect_equal(foo1$final, foo2$final) })
Covid19DataHub <- R6::R6Class("Covid19DataHub", inherit = CountryDataClass, public = list( origin = "Covid-19 Data Hub", supported_levels = list("1", "2", "3"), supported_region_names = list( "1" = "country", "2" = "region", "3" = "subregion" ), supported_region_codes = list( "1" = "iso_3166_1_alpha_3", "2" = "iso_code", "3" = "subregion_code" ), level_data_urls = list( "1" = list( "country" = "https://storage.covid19datahub.io/rawdata-1.csv" ), "2" = list( "region" = "https://storage.covid19datahub.io/rawdata-2.csv" ), "3" = list( "subregion" = "https://storage.covid19datahub.io/rawdata-3.csv" ) ), source_data_cols = c("confirmed", "deaths", "recovered", "tested", "hosp"), source_text = "COVID-19 Data Hub", source_url = "https://covid19datahub.io", clean_common = function() { raw_data <- self$data$raw[[names(self$level_data_urls[[self$level]])]] self$data$clean <- raw_data %>% rename( level_1_region_code = .data$iso_alpha_3, level_1_region = .data$administrative_area_level_1, level_2_region_code = .data$iso_alpha_2, level_2_region = .data$administrative_area_level_2, level_3_region_code = .data$iso_numeric, level_3_region = .data$administrative_area_level_3, cases_new = .data$confirmed, deaths_new = .data$deaths, tested_new = .data$tests, recovered_new = .data$recovered, hosp_new = .data$hosp ) %>% mutate( date = ymd(.data$date), cases_new = as.numeric(.data$cases_new), deaths_new = as.numeric(.data$deaths_new), recovered_new = as.numeric(.data$recovered_new), tested_new = as.numeric(.data$tested_new), hosp_new = as.numeric(.data$hosp_new) ) all_levels <- paste0("^level_", self$supported_levels, "_*") keep_levels <- paste0("^level_", seq_len(as.integer(self$level)), "_*") remove_levels <- unlist(map( setdiff(all_levels, keep_levels), ~ { grep(.x, colnames(self$data$clean), value = TRUE) } )) self$data$clean <- self$data$clean %>% select( -all_of(remove_levels) ) } ) )
diff_Chao1bc <- function(ksi, s) { D12 <- ksi[1] f11 <- ksi[2] fp1 <- ksi[3] f1p <- ksi[4] fp2 <- ksi[5] f2p <- ksi[6] if (s == 1){ d <- 1 } else if (s == 2) { d <- f1p * fp1 / (4 * (f2p + 1) * (fp2 + 1)) } else if (s == 3) { d <- f11 * f1p / (4 * (f2p + 1) * (fp2 + 1)) + (2 * fp1 - 1)/ (2 * (fp2 + 1)) } else if (s == 4) { d <- f11 * fp1 / (4 * (f2p + 1) * (fp2 + 1)) + (2 * f1p - 1)/ (2 * (f2p + 1)) } else if (s == 5) { d <- - f11 * f1p * fp1 / (4 * (f2p + 1)) / (fp2 + 1)^2 - fp1 * (fp1 - 1) / 2 / (fp2 + 1)^2 } else if (s == 6) { d <- - f11 * f1p * fp1 / (4 * (fp2 + 1)) / (f2p + 1)^2 - f1p * (f1p - 1) / 2 / (f2p + 1)^2 } else { d <- 0 } return(d) }
mod_clone_tables_ui <- function(id) { ns <- NS(id) tabPanel( title = "Clone Tables", column( width = 12, fluidRow(column(width = 12, h2("Clone Tables"))), fluidRow(column( width = 12, tags$div( align = "left", class = "multicol", checkboxGroupInput( inputId = ns("selected_tables"), label = "Select table(s) to clone", choices = NULL ) ) )), fluidRow(column( width = 12, selectInput( inputId = ns("table_list"), label = "Edit Properties of: ", choices = NULL ) )), fluidRow(column( width = 12, textInput(inputId = ns("new_table_name"), label = "New Table Name") )), fluidRow(column( width = 12, tags$div( align = "left", class = "multicol", checkboxGroupInput(inputId = ns("selected_columns"), label = "Select Columns to clone") ) )), fluidRow(column( width = 12, checkboxInput(inputId = ns("include_data"), label = "Include Data") )), fluidRow(column( width = 12, actionButton(inputId = ns("clone"), label = "Clone") )), br(), br() ) ) } mod_clone_tables_server <- function(input, output, session, conn) { ns <- session$ns info <- reactiveValues( table_name_list = list(), column_list = list(), include_data = list() ) action_clone_tables <- reactiveValues(tables_cloned = NULL) observeEvent(list(conn$active_db, conn$input_sidebar_menu), { if (!is.null(conn$active_db)) { updateCheckboxGroupInput( session = session, inputId = "selected_tables", choices = RSQLite::dbListTables(conn$active_db) ) for (i in RSQLite::dbListTables(conn$active_db)) { info$table_name_list[[i]] = paste0(i, "_copy") info$column_list[[i]] = RSQLite::dbGetQuery(conn$active_db, table_structure_query(i))$name info$include_data[[i]] = TRUE } } }) observeEvent(input$selected_tables, { updateSelectInput( session = session, inputId = "table_list", choices = input$selected_tables ) }) observeEvent(input$table_list, { updateTextInput( session = session, inputId = "new_table_name", value = info$table_name_list[[input$table_list]] ) if (!is.null(conn$active_db)) updateCheckboxGroupInput( session = session, inputId = "selected_columns", choices = RSQLite::dbGetQuery(conn$active_db, table_structure_query(input$table_list))$name, selected = info$column_list[[input$table_list]] ) updateCheckboxInput( session = session, inputId = "include_data", value = info$include_data[[input$table_list]] ) }) observeEvent(input$new_table_name, { info$table_name_list[[input$table_list]] <- input$new_table_name if (!is.null(conn$active_db)) { if (input$new_table_name %in% RSQLite::dbListTables(conn$active_db)) { showNotification( ui = "Table with this name already present in database. Please enter a new name.", duration = 3, type = "error" ) } } }) observeEvent(input$selected_columns, { if (!is.null(input$table_list)) { info$column_list[[input$table_list]] <- input$selected_columns } }, ignoreNULL = FALSE) observeEvent(input$include_data, { info$include_data[[input$table_list]] <- input$include_data }) observeEvent(input$clone, { tryCatch({ if (is.null(input$selected_tables)) { showNotification(ui = "No table selected.", duration = 3, type = "error") } else{ for (i in input$selected_tables) { if (!is.null(info$column_list[[i]])) { if (info$table_name_list[[i]] %in% RSQLite::dbListTables(conn$active_db)) { showNotification( ui = paste0( "Table with name ", info$table_name_list[[i]], " already present in database. This table not cloned." ), duration = 3, type = "error" ) } else{ RSQLite::dbExecute( conn$active_db, clone_query( info$table_name_list[[i]], i, info$column_list[[i]], info$include_data[[i]] ) ) } } else showNotification( ui = paste0( " No columns selected for table ", i, ". This table could not be cloned." ), duration = 10, type = "error" ) } action_clone_tables$tables_cloned <- input$clone showNotification(ui = "Selected tables cloned successfully.", duration = 5, type = "message") updateCheckboxGroupInput( session = session, inputId = "selected_tables", choices = RSQLite::dbListTables(conn$active_db), selected = input$selected_tables ) } }, error = function(err) { showNotification( ui = paste0(err, "Further Tables not cloned."), duration = 10, type = "error" ) }) }) return(action_clone_tables) }
context("images") test_that("returns expected output for public images", { skip_on_cran() imgs <- images() expect_is(imgs, "list") expect_is(imgs[[1]], "image") expect_is(imgs[[1]]$id, "integer") expect_is(imgs[[1]]$name, "character") expect_true(imgs[[1]]$public) }) test_that("fails well with wrong input type to private parameter", { skip_on_cran() expect_error(images(private = "af"), "is not TRUE") }) test_that("works with type parameter", { skip_on_cran() imgs_dist <- images(type = "distribution") imgs_appl <- c(images(type = "application"), images(type = "application", page = 2)) expect_is(imgs_dist, "list") expect_is(imgs_appl, "list") expect_is(imgs_dist[[1]], "image") expect_is(imgs_dist[[1]]$regions, "list") expect_is(imgs_dist[[1]]$regions[[1]], "character") expect_is(imgs_appl[[1]], "image") expect_is(imgs_appl[[1]]$regions, "list") expect_is(imgs_appl[[1]]$regions[[1]], "character") }) test_that("public parameter is defunct", { skip_on_cran() expect_error(images(public = TRUE), "The parameter public has been removed, see private") }) test_that("httr curl options work", { skip_on_cran() library("httr") expect_error(images(config = timeout(seconds = 0.001))) })
.ptime <- proc.time() set.seed(123) demos <- c("Hershey", "Japanese", "lm.glm", "nlm", "plotmath") for(nam in demos) demo(nam, character.only = TRUE) cat("Time elapsed: ", proc.time() - .ptime, "\n")
setClass("mdt", representation(name="character",table="data.frame"), prototype(name="sample multiple decrement table",table=data.frame(x=seq(0,2,1), lx=c(1000,500,200),c1=c(200,200,100),c2=c(300,100,100))) ) setValidity("mdt", function(object){ check<-FALSE namesOfTable<-names(object@table) check1<-is.element("x",namesOfTable) & is.element("lx",namesOfTable) if (!check1) cat("Missing x or lx") check2<-setequal(object@table$x,seq(0,max(object@table$x),by=1)) if (!check2) cat("Check the x sequence") onlyDecrements<-object@table[,setdiff(namesOfTable,c("x","lx"))] check3<-(sum(onlyDecrements)==object@table$lx[1]) if (!check3) cat("Check the lx") check<-check1&check2&check3 return(check) } ) setMethod("initialize", signature(.Object = "mdt"), function (.Object, name,table,...) { if(missing(table)) table=data.frame(x=seq(0,2,1), lx=c(1000,500,200),c1=c(200,200,100),c2=c(300,100,100)) if(missing(name)) name="sample multiple decrement table" table<-.tableSanitizer(decrementDf=table) callNextMethod(.Object=.Object, name =name, table=table,...) } ) setGeneric("getDecrements", function(object) standardGeneric("getDecrements")) setMethod("getDecrements","mdt", function(object) { out<-setdiff(names(object@table),c("x","lx")) return(out) } ) .isProb<-function(prob) { if((prob>1)|(prob<0)) return(FALSE) else return(TRUE) } .tableSanitizer<-function(decrementDf) { out<-decrementDf namesOfTable<-names(decrementDf) decrementIds<-which(!(namesOfTable %in% c("lx","x"))) pureDecrements<-decrementDf[,decrementIds] if(!("lx" %in% namesOfTable)) { lx<-numeric(nrow(decrementDf)) lx[1]<-sum(pureDecrements) for(i in 2:length(lx)) { lx[i]=lx[i-1]-sum(pureDecrements[i-1,]) } out$lx<-lx decrementDf<-out cat("Added lx","\n") } if(!("x" %in% namesOfTable)) { x=seq(from=0,to=(nrow(decrementDf)-1),by=1) out$x<-x decrementDf<-out cat("Added x to the table...","\n") } if(!(min(decrementDf$x)==0)) { x2Complete<-seq(from=0,to=(min(decrementDf$x)-1)) lx2Complete<-numeric(length(x2Complete)) lxLast<-decrementDf$lx[1] for(i in length(lx2Complete):1) { lx2Complete[i]<-lxLast/(1-0.01) lxLast<-lx2Complete[i] } dx2Add<- -diff(c(lx2Complete,decrementDf$lx[1])) decrements2complete<-matrix(0,nrow=length(dx2Add),ncol=ncol(decrementDf), dimnames=list(NULL,c("x","lx",names(decrementDf[,decrementIds])))) decrements2complete[,1]<-x2Complete decrements2complete[,2]<-lx2Complete decrements2complete[,3]<-dx2Add outMatrix<-rbind(decrements2complete,as.matrix(decrementDf)) out<-as.data.frame(outMatrix) rownames(out)<-NULL cat("Added fictional decrement below last x and completed x and lx until zero....","\n") } maxage<-which(out$x==max(out$x)) pureDecrements<-out[,decrementIds] lastCheck<-(rowSums(pureDecrements[maxage,])==out$lx[maxage]) if (!lastCheck) { decrements2complete<-matrix(0,nrow=1,ncol=ncol(decrementDf),dimnames=list(NULL,c("x","lx",names(decrementDf[,decrementIds])))) decrements2complete[1,1]<-max(out$x)+1 decrements2complete[1,2]<-out$lx[1]-sum(out[,decrementIds]) decrements2complete[1,3]<-decrements2complete[1,2] outMatrix<-rbind(out,decrements2complete) out<-as.data.frame(outMatrix) rownames(out)<-NULL cat("Completed the table at top, all decrements on first cause","\n") } invisible(out) } .decr2Probs<-function(decrementDf) { namesOfTable<-names(decrementDf) decrementIds<-which(!(namesOfTable %in% c("lx","x"))) pureDecrements<-decrementDf[,decrementIds] probs<-pureDecrements/decrementDf$lx rownames(probs)<-decrementDf$x invisible(probs) } setMethod("show","mdt", function(object){ cat(paste("Multiple decrements table",object@name),"\n") object@table print(object@table) } ) setMethod("print","mdt", function(x){ cat(paste("Multiple decrements table",x@name),"\n") probs<-.decr2Probs(x@table) print(probs) } ) setAs("mdt","data.frame", function(from){ return(from@table) } ) setMethod("summary", signature(object="mdt"), function (object, ...) { cat("This is Multiple Decrements Table: ",object@name, "\n","Omega age is: ",getOmega(object), "\n", "Stored decrements are: ", getDecrements(object)) } )
htmlNobr <- 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 = 'Nobr', 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')) }
context("waiting for a condition") test_that("waiting for a condition", { s <- Session$new(port = phantom$port) on.exit(s$delete(), add = TRUE) s$go(server$url("/wait-for-1.html")) expect_false(s$executeScript("return $(' expect_true(s$waitFor("$(' expect_true(s$executeScript("return $(' expect_false(s$waitFor("$(' expect_identical( s$waitFor("syntax error"), NA ) expect_true( s$waitFor('"foo" == "foo"') ) })
source('Schelde_pars.R') pHfunction <- function(pH, DIC, TA, SumNH4) return(TA-TA_estimate(pH, DIC, SumNH4)) OSAmodel <- function (tt, state, parms, scenario="B1") { with (as.list(c(state, parms)), { pH <- uniroot (pHfunction, interval = c(6, 10), tol=1e-20, DIC=SumCO2, TA=TA, SumNH4=SumNH4)$root H <- 10^(-pH) * 1e6 CO2 <- H*H/(H*K1CO2 + H*H + K1CO2*K2CO2)*SumCO2 NH3 <- KNH4/(KNH4+H)*SumNH4 NH4 <- SumNH4 - NH3 ECO2 <- KL * (CO2sat - CO2) EO2 <- KL * (O2sat - O2) ENH3 <- KL * (NH3sat - NH3) TO2 <- Transport(O2, O2_up, O2_down) TNO3 <- Transport(NO3, NO3_up, NO3_down) TTA <- Transport(TA, TA_up, TA_down) TSumCO2 <- Transport(SumCO2, SumCO2_up, SumCO2_down) TSumNH4 <- Transport(SumNH4, SumNH4_up, SumNH4_down) if (scenario == "A" && tt > 365) { TOM <- Transport(OM, OM_up_A, OM_down) } else TOM <- Transport(OM, OM_up , OM_down) if (scenario == "B1" && (tt > 360 && tt < 370)) { AddNH4NO3 <- SpillNH4NO3 } else AddNH4NO3 <- 0 if (scenario == "C" && (tt > 360 && tt < 370)) { AddNH3 <- SpillNH3 } else AddNH3 <- 0 ROx <- rOM * OM * (O2/(O2 + ksO2)) ROxCarbon <- ROx * C_Nratio RNit <- rNitri * NH4 * (O2/(O2 + ksO2)) dOM <- TOM - ROx dO2 <- TO2 + EO2 - ROxCarbon - 2*RNit dNO3 <- TNO3 + RNit + AddNH4NO3 dSumCO2 <- TSumCO2 + ECO2 + ROxCarbon dSumNH4 <- TSumNH4 + ENH3 + ROx - RNit + AddNH3 + AddNH4NO3 dTA <- TTA + ENH3 + ROx-2*RNit + AddNH3 return(list(c(dOM, dO2, dNO3, dTA, dSumNH4, dSumCO2), c(pH=pH, CO2=CO2, NH3=NH3, NH4=SumNH4-NH3))) }) } TA_down<- TA_estimate(pH_down, SumCO2_down, SumNH4_down) TA_up <- TA_estimate(pH_up , SumCO2_up , SumNH4_up) TA_ini <- TA_estimate(pH_ini , SumCO2_ini , SumNH4_ini) state <- c(OM=OM_ini, O2=O2_ini, NO3=NO3_ini, TA=TA_ini, SumNH4=SumNH4_ini, SumCO2=SumCO2_ini) times <- c(0, 350:405) outA <- vode(state, times, OSAmodel, phPars, scenario = "A" , hmax = 1) outB <- vode(state, times, OSAmodel, phPars, scenario = "B1", hmax = 1) outC <- vode(state, times, OSAmodel, phPars, scenario = "C" , hmax = 1) par(mfrow = c(3, 4), mar = c(1, 2, 2, 1), oma = c(3, 3, 3, 0)) Selection <- c("pH","TA","SumCO2","O2") plot(outA, mfrow = NULL, xlim = c(350,405), type = "l", xaxt = "n", which = Selection) plot(outB, mfrow = NULL, xlim = c(350,405), type = "l", xaxt = "n", which = Selection) plot(outC, mfrow = NULL, xlim = c(350,405), type = "l", xaxt = "n", which = Selection) mtext(side = 1, outer = TRUE, "time, d", line = 2, cex = 1.2) mtext(side = 2, at = 0.2, outer = TRUE, "Scenario C", line = 1.5, cex = 1.2) mtext(side = 2, at = 0.5, outer = TRUE, "Scenario B", line = 1.5, cex = 1.2) mtext(side = 2, at = 0.8, outer = TRUE, "Scenario A", line = 1.5, cex = 1.2) mtext(side = 3, at = 0.125, outer = TRUE, "pH, -", line = 1, cex = 1.2) mtext(side = 3, at = 0.375, outer = TRUE, "TA, mol/kg", line = 1, cex = 1.2) mtext(side = 3, at = 1-0.375, outer = TRUE, "CO2, mol/kg", line = 1, cex = 1.2) mtext(side = 3, at = 1-0.125, outer = TRUE, "O2, mol/kg", line = 1, cex = 1.2)
JGee1 <- function(formula,id,data,nr,na.action=NULL,family=gaussian(link="identity"), corstr1="independence",Mv=NULL,corstr2="independence", beta_int=NULL,R1=NULL,R2=NULL,scale.fix=FALSE, scale.value=1,maxiter=25,tol=10^-3,silent=FALSE) { call <- match.call() m <- match.call(expand.dots = FALSE) m$family <-m$link <- m$varfun <- m$nr<-m$beta_int <- m$corstr1 <- m$Mv<- m$corstr2 <-m$R1 <- m$R2 <- m$scale.fix <- m$scale.value <- m$maxiter <- m$tol <-m$silent <-NULL if(is.null(m$id)) m$id<-as.name("id") if(!is.null(m$na.action) && m$na.action != "na.omit") { warning("Only 'na.omit' is implemented for gee\ncontinuing with 'na.action=na.omit'") m$na.action <- as.name("na.omit") } m[[1]] <- as.name("model.frame") m <- eval(m, parent.frame()) Terms <- attr(m, "terms") y <- model.extract(m, "response") X<- model.matrix(Terms, m, contrasts) id<-model.extract(m, id) if(is.null(id)) { stop("Id variable not found!") } if(is.null(nr)) { stop("nr variable not found!") } if(length(id) != length(y)) stop("Id and y not same length!") if(!(is.double(X))) X <- as.double(X) if(!(is.double(y))) y <- as.double(y) if(!(is.double(id))) id <- as.double(id) N<-length(unique(id)) nr<-as.integer(nr) K<-ncol(X)-1 xnames <- dimnames(X)[[2]] if(is.null(xnames)) { xnames <- paste("x", 0:K, sep = "") dimnames(X) <- list(NULL, xnames) } avec <- as.integer(unlist(lapply(split(id, id), "length")))/nr maxclsz <-max(avec) maxcl <- maxclsz nt<-avec nobs<-sum(nt)*nr if(missing(family)) family=gaussian(link="identity") if(missing(corstr1)) corstr1="independence" if(missing(corstr2)) corstr2="independence" if(missing(Mv)) Mv<-NULL if(corstr1=="stat_M_dep" && is.null(Mv)) stop("corstr1 is assumed to be 'stat_M_dep' but Mv is not specified!") if(corstr1=="non_stat_M_dep" && is.null(Mv)) stop("corstr1 is assumed to be 'non_stat_M_dep' but Mv is not specified!") if((corstr1!="stat_M_dep" && corstr1!="non_stat_M_dep") && !is.null(Mv)) stop("Mv is specified while corstr1 is assumed to be neither 'stat_M_dep' nor 'non_stat_M_dep'!") if(corstr1=="non_stat_M_dep" && length(unique(nt)) !=1) stop("corstr1 cannot be assumed to be 'non_stat_M_dep' for unbalanced data!") if(corstr1=="unstructured" && length(unique(nt)) !=1) stop("corstr1 cannot be assumed to be 'unstructured' for unbalanced data!") if(missing(R1)) R1<-NULL if(missing(R2)) R2<-NULL if(corstr1!="fixed" && corstr2=="fixed") stop("corstr1 should also be assumed to be 'fixed' when corstr2='fixed'!") if(corstr1=="fixed" && corstr2!="fixed") stop("corstr2 should also be assumed to be 'fixed' when corstr1='fixed'!") if(corstr1=="fixed" && corstr2=="fixed" && is.null(R1) && is.null(R2)) stop("corstr1 and corstr2 are assumed to be 'fixed' but R1 and R2 are not specified!") if(corstr1=="fixed" && corstr2=="fixed" && is.null(R1) && !is.null(R2)) stop("corstr1 and corstr2 are assumed to be 'fixed' but R1 is not specified!") if(corstr1=="fixed" && corstr2=="fixed" && !is.null(R1) && is.null(R2)) stop("corstr1 and corstr2 are assumed to be 'fixed' but R2 is not specified!") if(corstr1!="fixed" && corstr2!="fixed" && !is.null(R1)&& !is.null(R2)) stop("R1 and R2 are specified although corstr1 and corstr2 are not assumed to be 'fixed'!") if(corstr1!="fixed" && corstr2!="fixed" && !is.null(R1)&& is.null(R2)) stop("R1 is specified although corstr1 and corstr2 are not assumed to be 'fixed'!") if(corstr1!="fixed" && corstr2!="fixed" && is.null(R1)&& !is.null(R2)) stop("R2 is specified although corstr1 and corstr2 are not assumed to be 'fixed'!") if(!is.null(R1)) { Rr1 <- nrow(R1) if(Rr1 != ncol(R1)) {stop("R1 is not square!")} else if(Rr1 < maxclsz) {stop("R1 is not big enough to accommodate some clusters!")} else if(Rr1 > maxclsz) {stop("R1 is larger than the maximum cluster!")} } if(!is.null(R2)) { Rr2 <- nrow(R2) if(Rr2 != ncol(R2)) {stop("R2 is not square!")} else if(Rr2 < nr) {stop("R2 is not big enough to accommodate some clusters!")} else if(Rr2 > nr) {stop("R2 is larger than the number of responses!")} } if(missing(scale.fix)) scale.fix=FALSE scale.fix <- as.integer(scale.fix) if(missing(scale.value)) scale.value=1 scale.value<-as.integer(scale.value) if(missing(maxiter)) maxiter<-25 maxiter<-as.integer(maxiter) if(missing(tol)) tol=10^-3 tol=as.double(tol) if(missing(silent)) silent<-FALSE silent<-as.integer(silent) if (is.character(family)) family <- get(family) if (is.function(family)) family <- family() links <- c("identity","log","logit","inverse","probit","cloglog") fams <- c("gaussian","poisson","binomial","Gamma","quasi") varfuns <- c("constant", "mu", "mu(1-mu)", "mu^2") corstrs1 <- c("independence", "fixed", "stat_M_dep", "non_stat_M_dep", "exchangeable", "AR-1", "unstructured") corstrs2 <- c("independence", "fixed", "exchangeable","unstructured") linkv <- as.integer(match(c(family$link), links, -1)) if(linkv < 1) stop("unknown link!") famv <- match(family$family, fams, -1) if(famv < 1) stop("unknown family") if(famv <= 4) varfunv <- famv else varfunv <- match(family$varfun, varfuns, -1) if(varfunv < 1) stop("unknown varfun!") corstrv1 <- as.integer(match(corstr1, corstrs1, -1)) if(corstrv1 < 1) stop("unknown corstr1!") corstrv2 <- as.integer(match(corstr2, corstrs2, -1)) if(corstrv2 < 1) stop("unknown corstr2!") Mv <- as.integer(Mv) if (!is.null(beta_int)) { beta <- matrix(beta_int, nrow = 1) if(ncol(beta) != (K+1)) {stop("Dimension of beta != ncol(X)!")} message("user\'s initial regression estimate") } else { message("running gee to get initial regression estimate") mm <- match.call(expand.dots = FALSE) mm$nr<- mm$R1 <-mm$R2 <- mm$beta_int <- mm$tol <- mm$maxiter <- mm$link <- mm$varfun <-mm$corstr1 <- mm$corstr2 <-mm$Mv <- mm$silent <-mm$scale.fix <- mm$scale.value <- mm$id<- NULL mm[[1]]<-as.name("glm") beta <- eval(mm, parent.frame())$coefficients print(beta) } beta_int=matrix(beta, ncol = 1) beta_new<-beta_int R.fi.hat=mycor_jgee1(N,nr,nt,y,X,family,beta_new,corstr1,Mv,corstr2,maxclsz,R1=R1,R2=R2,scale.fix=scale.fix,scale.value=scale.fix) Rhat=R.fi.hat$Ehat fihat=R.fi.hat$fi S.H.E.val=S_H1(N,nr,nt,y,X,K,family,beta_new,Rhat,fihat) S<-S.H.E.val$S H<-S.H.E.val$H diff<-1 iter<-0 while(iter < maxiter) { beta_old<-beta_new beta_new<-matrix(beta_old)+(ginv(H)%*%S) R.fi.hat=mycor_jgee1(N,nr,nt,y,X,family,beta_new,corstr1,Mv,corstr2,maxclsz,R1,R2,scale.fix,scale.value) Rhat=R.fi.hat$Ehat fihat=R.fi.hat$fi C1hat=R.fi.hat$cor1 C2hat=R.fi.hat$cor2 S.H.E.M.val=S_H1(N,nr,nt,y,X,K,family,beta_new,Rhat,fihat) S<-S.H.E.M.val$S H<-S.H.E.M.val$H M<-S.H.E.M.val$M diff<-sum(abs(beta_old-beta_new)) iter<-iter+1 if (silent==1) cat("iter",iter,"diff",diff,"\n") if (diff <= tol) break } estb=beta_new nv=naive.var<-ginv(H) rv=robust.var<-ginv(H)%*%M%*%ginv(H) final_iter=iter final_diff=diff fit <- list() attr(fit, "class") <- c("JGee1","gee","glm") fit$title <- "JGEE: JOINT GENERALIZED ESTIMATING EQUATIONS FOR CLUSTERED DATA" fit$version <- "Version: 1.0" links <- c("Identity", "Logarithm", "Logit", "Reciprocal", "Probit","Cloglog") varfuns <- c("Gaussian", "Poisson", "Binomial", "Gamma") corstrs1 <- c("Independent", "Fixed", "Stationary M-dependent", "Non-Stationary M-dependent", "Exchangeable", "AR-1", "Unstructured") corstrs2 <- c("Independent", "Fixed","Exchangeable", "Unstructured") fit$model <- list() fit$model$link <- links[linkv] fit$model$varfun <- varfuns[varfunv] fit$model$corstr1 <- corstrs1[corstrv1] if(!is.na(match(c(corstrv1), c(3, 4)))) fit$model$M <- Mv fit$model$corstr2 <- corstrs2[corstrv2] fit$call <- call fit$terms <- Terms fit$formula <- as.vector(attr(Terms, "formula")) fit$nobs <- nobs fit$iterations <- final_iter fit$coefficients <- as.vector(estb) fit$nas <- is.na(fit$coefficients) names(fit$coefficients) <- xnames eta <- as.vector(X %*% fit$coefficients) fit$linear.predictors <- eta mu <- as.vector(family$linkinv(eta)) fit$fitted.values <- mu fit$residuals <- y - mu fit$family <- family fit$y <- as.vector(y) fit$id <- as.vector(id) fit$max.id <- maxcl fit$working.correlation1 <- C1hat[1:maxclsz,1:maxclsz,which(avec==maxclsz)[1]] fit$working.correlation2 <- C2hat fit$working.correlation <- Rhat[1:(maxclsz*nr),1:(maxclsz*nr),which(avec==maxclsz)[1]] fit$scale <- fihat fit$robust.variance <- rv fit$naive.variance <- nv fit$xnames <- xnames fit$error <- final_diff dimnames(fit$robust.variance) <- list(xnames, xnames) dimnames(fit$naive.variance) <- list(xnames, xnames) fit }
smd_test<-function(x, y, paired = c(TRUE, FALSE), auto=TRUE, var = TRUE, normal = TRUE, conf.int = 0.9, mu = 0, swc = 0.5, plot=FALSE) { if (is.character(x) == TRUE || is.factor(x) == TRUE || is.character(y) == TRUE || is.factor(y) == TRUE) { error <- "Sorry, data must be numeric or integer values." stop(error) } if (length(x) < 3 || length(y) < 3) { error <- "Sorry, not enough data." stop(error) } if (missing(paired)) { error <- "Missing Argument: Please specify if data is paired = TRUE/FALSE." stop(error) } if (swc <= 0 ) { error <- "Sorry, the smallest effect size of interest be a positive number" stop(error) } if (length(x) != length(y)) { max.len <- max(length(x), length(y)) x <- c(x, rep(NA, max.len - length(x))) y <- c(y, rep(NA, max.len - length(y))) } if (auto==TRUE){ normal.x<-stats::shapiro.test(x) normal.y<-stats::shapiro.test(y) Normal<-ifelse(normal.x$p.value < .05 || normal.y$p.value < .05, FALSE, TRUE) normlabel<-ifelse(normal.x$p.value < .05 || normal.y$p.value < .05," Skewness Observed"," Normality Observed") equal<-stats::var.test(x,y) variance<-ifelse(equal$p.value < .05, FALSE,TRUE) variance2<-ifelse(equal$p.value < .05, "Unequal Variance","Equal Variance") } if(auto==FALSE){ NormTest <- FALSE VarTest <- FALSE Normal <- normal equal <- var variance <- ifelse(var == FALSE, FALSE, TRUE) variance2 <- ifelse(var == FALSE, "Unequal Variance","Equal Variance") normlabel<-ifelse(normal == FALSE," Skewness Assumed"," Normality Assumed") } length.x <- length(x) - sum(is.na(x)) length.y <- length(y) - sum(is.na(y)) n2 <- length.x + length.y n <- length.x ind.stdr <- sqrt(1 / length.x + 1 / length.y) pair.stdr <- sqrt((sd(x, na.rm = T) ^ 2 + sd(y, na.rm = T) ^ 2) / 2) if (Normal == FALSE) { if (0 %in% x || 0 %in% y) { test <- stats::t.test( log(abs(x + 1)), log(abs(y + 1)), var.equal = variance, paired = paired, conf.level = conf.int, na.action = na.omit, mu = mu ) } else { test <- stats::t.test( log(abs(x)), log(abs(y)), var.equal = variance, paired = paired, conf.level = conf.int, na.action = na.omit, mu = mu ) } estimate <- ifelse( paired == T, unname(test$estimate), (unname(test$estimate[1]) - unname(test$estimate[2])) ) OR <- round(exp(estimate), digits = 2) LL <- round(exp(test$conf.int[1]), digits = 2) UL <- round(exp(test$conf.int[2]), digits = 2) rank <- stats::wilcox.test( x, y, paired = paired, conf.int = T, conf.level = 0.9, na.action = na.omit, correct = F, exact = F ) suppressWarnings(warning(rank)) r <- ifelse(OR < 1, stats::qnorm(rank$p.value / 2) / sqrt(n2), abs(stats::qnorm(rank$p.value / 2) / sqrt(n2))) r.LL <- (exp(2 * ((swc * log((1 + r) / (1 - r) )) + ( stats::qnorm((( 100 - (100 * conf.int) ) / 100 / 2)) / sqrt(n - 3) ))) - 1) / (exp(2 * ((swc * log((1 + r) / (1 - r) )) + ( stats::qnorm((( 100 - (100 * conf.int) ) / 100 / 2)) / sqrt(n - 3) ))) + 1) r.UL <- (exp(2 * ((swc * log((1 + r) / (1 - r) )) - ( stats::qnorm((( 100 - (100 * conf.int) ) / 100 / 2)) / sqrt(n - 3) ))) - 1) / (exp(2 * ((swc * log((1 + r) / (1 - r) )) - ( stats::qnorm((( 100 - (100 * conf.int) ) / 100 / 2)) / sqrt(n - 3) ))) + 1) level <- paste(as.character(100 * conf.int), "%", sep = "") negative <- round(100 * (stats::pnorm((log(0.9) - log(OR)) / abs(log(OR) / stats::qnorm(test$p.value / 2)) )), digits = 1) positive <- round(100 * (1 - stats::pnorm((log(1.11) - log(OR)) / abs(log(OR) / stats::qnorm(test$p.value / 2)) )), digits = 1) trivial <- round((100 - positive - negative), digits = 1) table1 <- matrix(c( round(test$statistic, digits = 5), round(test$parameter, digits = 5), round(test$p.value, digits = 5) ), ncol = 1, byrow = T) rownames(table1) <- c("t", "df", "P value") colnames(table1) <- c("Log-Transformed") table2 <- matrix(c( round(rank$statistic, digits = 3), round(rank$p.value, digits = 3), round(rank$conf.int[1], digits = 3), round(rank$conf.int[2], digits = 3) ), ncol = 1, byrow = T) if (paired == TRUE) { rownames(table2) <- c("V", "P value", paste(level, "CI LL", sep = " "), paste(level, "CI UL", sep = " ")) } else { rownames(table2) <- c("W", "P value", paste(level, "CI LL", sep = " "), paste(level, "CI UL", sep = " ")) } colnames(table2) <- c("Rank-Based") title <- paste(normlabel, variance2, sep = ", ") title2 <- paste(" Method:", test$method, sep = " ") title3 <- paste(" Method:", rank$method, sep = " ") cat(" Mean of ", deparse(substitute(x)), " = ", round(mean(x, na.rm = T), digits = 2), "; ", "Mean of ", deparse(substitute(y)), " = ", round(mean(y, na.rm = T), digits = 2), "\n", sep = "") cat(title, title2, sep = "\n") cat("\n") print(table1) cat("\n") cat(" ", "Factor", " = ", round(OR, digits = 2), "\n", sep = "") cat(" ", level, " CI ", "[", round(LL, digits = 2), ", ", round(UL, digits = 2), "]\n", sep = "") table3 <- matrix( c("Lower", "Trivial", "Higher", negative, trivial, positive), nrow = 2, byrow = T ) rownames(table3) <- c(" ", "MBI (%)") lower <- ifelse(negative < 0.5, "Most Unlikely", ifelse( negative < 5, "Very Unlikely", ifelse( negative < 25, "Unlikely", ifelse( negative < 75, "Possibly", ifelse( negative < 95, "Likely", ifelse( negative < 99, "Most Likely", ifelse(negative >= 99, "Almost Certainly") ) ) ) ) )) trivial2 <- ifelse(trivial < 0.5, "Most Unlikely", ifelse( trivial < 5, "Very Unlikely", ifelse( trivial < 25, "Unlikely", ifelse( trivial < 75, "Possibly", ifelse( trivial < 95, "Likely", ifelse( negative < 99, "Most Likely", ifelse(negative >= 99, "Almost Certainly") ) ) ) ) )) higher <- ifelse(positive < 0.5, "Most Unlikely", ifelse( positive < 5, "Very Unlikely", ifelse( positive < 25, "Unlikely", ifelse( positive < 75, "Possibly", ifelse( positive < 95, "Likely", ifelse( positive < 99, "Most Likely", ifelse(positive >= 99, "Almost Certainly") ) ) ) ) )) colnames(table3) <- c(lower, trivial2, higher) title4 <- (" Magnitude-Based Inference\n") cat("\n") cat(title4, "\n") print(table3) infer <- which.max(table3[2,]) dir <- ifelse(OR < 1, "Decrease.", "Increase.") infer2 <- ifelse(infer == 1, lower, ifelse(infer == 2, trivial2, ifelse(infer == 3, higher))) if (OR < 1) { mag <- ifelse(OR > (1 / 1.5) || infer == 2, "Trivial", ifelse(OR > (1 / 3.5), "Small", ifelse( OR > (1 / 9), "Moderate", ifelse(OR > (1 / 32), "Large", ifelse(OR <= (1 / 32), "Very Large")) ))) } else { mag <- ifelse(abs(OR) < 1.5 || infer == 2, "Trivial", ifelse( abs(OR) < 3.5, "Small", ifelse(abs(OR) < 9, "Moderate", ifelse( abs(OR) < 32, "Large", ifelse(abs(OR) >= 32, "Very Large") )) )) } LogInference <- ifelse(abs(positive) >= 5 && abs(negative) > 5, paste("Inference: Unclear Difference."), paste("Inference:", infer2, mag, dir,sep = " ")) cat(LogInference) cat("\n-----------------------------------------------") cat("\n Nonparametric Inference", title3, sep = "\n") cat("\n") print(table2) cat("\n") cat(" ", "r", " = ", round(r, digits = 2), "\n", sep = "") cat(" ", level, " CI ", "[", round(r.LL, digits = 2), ", ", round(r.UL, digits = 2), "]\n\n", sep = "") positive.r <- round(100 * (1 - stats::pnorm( 0.1, mean = (swc * log((1 + r) / (1 - r))), sd = (1 / sqrt(n - 3)) )), digits = 1) negative.r <- round(100 * (stats::pnorm( -0.1, mean = (swc * log((1 + r) / (1 - r))), sd = (1 / sqrt(n - 3)) )), digits = 1) trivial.r <- round(100 - positive.r - negative.r, digits = 1) lower.r <- ifelse(negative.r < 0.5, "Most Unlikely", ifelse( negative.r < 5, "Very Unlikely", ifelse( negative.r < 25, "Unlikely", ifelse( negative.r < 75, "Possibly", ifelse( negative.r < 95, "Likely", ifelse( negative.r < 99, "Most Likely", ifelse(negative.r >= 99, "Almost Certainly") ) ) ) ) )) trivial2.r <- ifelse(trivial.r < 0.5, "Most Unlikely", ifelse( trivial.r < 5, "Very Unlikely", ifelse( trivial.r < 25, "Unlikely", ifelse( trivial.r < 75, "Possibly", ifelse( trivial.r < 95, "Likely", ifelse( trivial.r < 99, "Most Likely", ifelse(trivial.r >= 99, "Almost Certainly") ) ) ) ) )) higher.r <- ifelse(positive.r < 0.5, "Most Unlikely", ifelse( positive.r < 5, "Very Unlikely", ifelse( positive.r < 25, "Unlikely", ifelse( positive.r < 75, "Possibly", ifelse( positive.r < 95, "Likely", ifelse( positive.r < 99, "Most Likely", ifelse(positive.r >= 99, "Almost Certainly") ) ) ) ) )) table.r <- matrix( c( "Negative", "Trivial", "Positive", negative.r, trivial.r, positive.r ), nrow = 2, byrow = T ) rownames(table.r) <- c(" ", "MBI (%)") colnames(table.r) <- c(lower.r, trivial2.r, higher.r) title.r <- (" Magnitude-Based Inference") cat(title.r, "\n\n") print(table.r) cat("\n") infer.r <- which.max(table.r[2,]) infer3.r <- ifelse(infer.r == 1, lower.r, ifelse(infer.r == 2, trivial2.r, ifelse(infer.r == 3, higher.r))) mag.r <- ifelse(abs(r) < 0.1 || infer.r == 2, "Trivial", ifelse(abs(r) < 0.3, "Small", ifelse( abs(r) < 0.5, "Moderate", ifelse( abs(r) < 0.7, "Large", ifelse(abs(r) < 0.9, "Very Large", ifelse(abs(r) >= 0.9, "Very Large")) ) ))) NonParametricInference <- ifelse(abs(positive.r) >= 5 && abs(negative.r) > 5, paste("Inference: Unclear Difference."), paste("Inference:", infer3.r, mag.r, "Effect Size",sep = " ")) cat(NonParametricInference) invisible(list(or.stat = OR, or.LL = LL, or.UL = UL, r.stat = r, r.LL = r.LL, r.UL = r.UL, t.value = test$statistic[[1]], df = test$parameter[[1]], p.value = test$p.value, mean1 = round(mean(x, na.rm = T), digits = 3), sd1 = round(sd(x, na.rm = T), digits = 3), mean2 = round(mean(y, na.rm = T), digits = 3), sd2 = round(sd(y, na.rm = T), digits = 3), LogmbiNegative = negative, LogmbiTrivial = trivial, LogmbiPositive = positive, mbiNegative.r = negative.r, mbiTrivial.r = trivial.r, mbiPositive.r = positive.r, LogInference=LogInference, NonParametricInference=NonParametricInference)) } else { test <- stats::t.test(x,y, var.equal = variance, paired = paired, conf.level = conf.int, na.action = na.omit, mu = mu) d <- ifelse(paired == T, ((mean(x, na.rm = T) - mean(y, na.rm = T)) / pair.stdr), test$statistic * ind.stdr) LL <- d - (stats::qt((( 100 - (100 * conf.int) ) / 100) / 2, test$parameter)) * abs(d) / stats::qt(test$p.value / 2, test$parameter) UL <- d + (stats::qt((( 100 - (100 * conf.int) ) / 100) / 2, test$parameter)) * abs(d) / stats::qt(test$p.value / 2, test$parameter) if (test$parameter < 30) { d <- d * (1 - (3 / (4 * ( test$parameter - 1 )))) LL <- LL * (1 - (3 / (4 * ( test$parameter - 1 )))) UL <- UL * (1 - (3 / (4 * ( test$parameter - 1 )))) } parameter <- ifelse(test$parameter < 30, "Cohen d Adj", "Cohen d") negative <- round(100 * (ifelse((d--swc) > 0, stats::pt((d--swc) / abs(d) * abs(test$statistic), test$parameter, lower.tail = F ), (1 - stats::pt((-swc - d) / abs(d) * abs(test$statistic), test$parameter, lower.tail = F )) )), digits = 1) positive <- round(100 * (ifelse((d - swc) > 0, (1 - stats::pt((d - swc) / abs(d) * abs(test$statistic), test$parameter, lower.tail = F )), stats::pt((swc - d) / abs(d) * abs(test$statistic), test$parameter, lower.tail = F ) )), digits = 1) trivial <- round((100 - positive - negative), digits = 1) table1 <- matrix(c( round(test$statistic, digits = 3), round(test$parameter, digits = 0), round(test$p.value, digits = 3), round(test$conf.int[1], digits = 3), round(test$conf.int[2], digits = 3) ), ncol = 1, byrow = T) level <- paste(as.character(100 * conf.int), "%", sep = "") rownames(table1) <- c("t", "df", "P value", paste(level, "CI LL", sep = " "), paste(level, "CI UL", sep = " ")) colnames(table1) <- c("Raw Scale") table2 <- matrix( c("Lower", "Trivial", "Higher", negative, trivial, positive), nrow = 2, byrow = T ) rownames(table2) <- c(" ", "MBI (%)") lower <- ifelse(negative < 0.5, "Most Unlikely", ifelse( negative < 5, "Very Unlikely", ifelse( negative < 25, "Unlikely", ifelse( negative < 75, "Possibly", ifelse( negative < 95, "Likely", ifelse( negative < 99, "Most Likely", ifelse(negative >= 99, "Almost Certainly") ) ) ) ) )) trivial2 <- ifelse(trivial < 0.5, "Most Unlikely", ifelse( trivial < 5, "Very Unlikely", ifelse( trivial < 25, "Unlikely", ifelse( trivial < 75, "Possibly", ifelse( trivial < 95, "Likely", ifelse( negative < 99, "Most Likely", ifelse(negative >= 99, "Almost Certainly") ) ) ) ) )) higher <- ifelse(positive < 0.5, "Most Unlikely", ifelse( positive < 5, "Very Unlikely", ifelse( positive < 25, "Unlikely", ifelse( positive < 75, "Possibly", ifelse( positive < 95, "Likely", ifelse( positive < 99, "Most Likely", ifelse(positive >= 99, "Almost Certainly") ) ) ) ) )) colnames(table2) <- c(lower, trivial2, higher) title3 <- (" Magnitude-Based Inference") title <- paste(normlabel, variance2, sep = ", ") title2 <- paste(" Method:", test$method, sep = " ") cat(" Mean of ", deparse(substitute(x)), " = ", round(mean(x, na.rm = T), digits = 2), "; ", "Mean of ", deparse(substitute(y)), " = ", round(mean(y, na.rm = T), digits = 2), "\n", sep = "") cat(title, title2, sep = "\n") cat("\n") print(table1) cat("\n") cat(" ", parameter, " = ", round(d, digits = 2), "\n", sep = "") cat(" ", level, " CI ", "[", round(LL, digits = 2), ", ", round(UL, digits = 2), "]\n\n", sep = "") cat(title3, "\n\n") print(table2) cat("\n") infer <- which.max(table2[2,]) infer2 <- ifelse(infer == 1, lower, ifelse(infer == 2, trivial2, ifelse(infer == 3, higher))) mag <- ifelse(abs(d) < 0.2 || infer == 2, "Trivial", ifelse(abs(d) < 0.6, "Small", ifelse( abs(d) < 1.2, "Moderate", ifelse(abs(d) < 2, "Large", ifelse(abs(d) >= 2, "Very Large")) ))) dir <- ifelse(d < 0, "Decrease.", "Increase.") Inference <- ifelse(abs(positive) >= 5 && abs(negative) > 5, paste("Inference: Unclear Difference."), paste("Inference:", infer2, mag, dir, sep = " ")) cat(Inference) if (plot == TRUE) { plot(NA, ylim = c(0, 1), xlim = c(min(LL, -swc) - max(UL - LL, swc - -swc)/10, max(UL, swc) + max(UL - LL, swc - -swc)/10), bty = "l", yaxt = "n", ylab = "", xlab = "Effect Size") graphics::points(x = d, y = 0.5, pch = 15, cex = 2) graphics::abline(v = swc, lty = 2) graphics::abline(v = -swc, lty = 2) graphics::abline(v = 0, lty = 2, col = "grey") graphics::segments(LL, 0.5, UL, 0.5, lwd = 3) graphics::title(main = paste( "Cohen's d = ", round(d, digits = 3), " \n ", 100 * (conf.int), "% CI [", round(LL, digits = 3), ";", round(UL, digits = 3), "] ", " \n ", "Inference: ", infer2, " ", mag," ", dir, sep = ""), cex.main = 1) } invisible(list( d.stat = d, d.LL = LL, d.UL = UL, t.value = test$statistic[[1]], df = test$parameter[[1]], p.value = test$p.value, conf.int=conf.int, mean1 = round(mean(x, na.rm = T), digits = 3), sd1 = round(sd(x, na.rm = T), digits = 3), mean2 = round(mean(y, na.rm = T), digits = 3), sd2 = round(sd(y, na.rm = T), digits = 3), mbiNegative = negative, mbiTrivial = trivial, mbiPositive = positive, Inference = Inference) ) } }
LoadBeatAmbit <- function(HRVData, RecordName, RecordPath=".", verbose = NULL) { dir=getwd() HRVData = HandleVerboseArgument(HRVData, verbose) VerboseMessage(HRVData$Verbose, paste("Loading beats positions for record:", RecordName)) VerboseMessage(HRVData$Verbose, paste("Path:", RecordPath)) setwd(RecordPath) aux=scan(RecordName,what=character(0),strip.white=TRUE,quiet=TRUE) date=aux[grepl('DateTime',aux)] dateAux=substr(date,11,20) time <- substr(date,22,29) VerboseMessage(HRVData$Verbose, paste("Date: ", dateAux)) VerboseMessage(HRVData$Verbose, paste("Time: ", time)) datetimeinfo = paste(dateAux,time,sep = " ") HRVData$datetime=datetimeinfo BeatPosition=grep('IBI',aux) rawIBI=aux[BeatPosition[1]:BeatPosition[2]] rawIBI[1]=gsub('<IBI>','',rawIBI[1]) rawIBI[length(rawIBI)]=gsub('</IBI>','',rawIBI[length(rawIBI)]) HRVData$Beat$RR=as.numeric(rawIBI) HRVData$Beat$Time=cumsum(HRVData$Beat$RR)/1000 VerboseMessage(HRVData$Verbose, paste("Number of beats:", length(HRVData$Beat$Time)) ) setwd(dir) return(HRVData) }
MYheatmap.2 <- function (x, Rowv = TRUE, Colv = if (symm) "Rowv" else TRUE, distfun = dist, hclustfun = hclust, dendrogram = c("both", "row", "column", "none"), symm = FALSE, scale = c("none", "row", "column"), na.rm = TRUE, revC = identical(Colv, "Rowv"), add.expr, breaks, symbreaks = min(x < 0, na.rm = TRUE) || scale != "none", col = "heat.colors", colsep, rowsep, sepcolor = "white", sepwidth = c(0.05, 0.05), cellnote, notecex = 1, notecol = "cyan", na.color = graphics::par("bg"), trace = c("column", "row", "both", "none"), tracecol = "cyan", hline = stats::median(breaks), vline = stats::median(breaks), linecol = tracecol, margins = c(5, 5), ColSideColors, RowSideColors, cexRow = 0.2 + 1/log10(nr), cexCol = 0.2 + 1/log10(nc), labRow = NULL, labCol = NULL, key = TRUE, keysize = 1.5, density.info = c("histogram", "density", "none"), denscol = tracecol, symkey = min(x < 0, na.rm = TRUE) || symbreaks, densadj = 0.25, main = NULL, xlab = NULL, ylab = NULL, lmat = NULL, lhei = NULL, lwid = NULL, ...) { scale01 <- function(x, low = min(x), high = max(x)) { x <- (x - low)/(high - low) x } retval <- list() scale <- if (symm && missing(scale)) "none" else match.arg(scale) dendrogram <- match.arg(dendrogram) trace <- match.arg(trace) density.info <- match.arg(density.info) if (length(col) == 1 && is.character(col)) col <- get(col, mode = "function") if (!missing(breaks) && (scale != "none")) warning("Using scale=\"row\" or scale=\"column\" when breaks are", "specified can produce unpredictable results.", "Please consider using only one or the other.") if (is.null(Rowv) || is.na(Rowv)) Rowv <- FALSE if (is.null(Colv) || is.na(Colv)) Colv <- FALSE else if (Colv == "Rowv" && !isTRUE(Rowv)) Colv <- FALSE if (length(di <- dim(x)) != 2 || !is.numeric(x)) stop("`x' must be a numeric matrix") nr <- di[1] nc <- di[2] if (nr <= 1 || nc <= 1) stop("`x' must have at least 2 rows and 2 columns") if (!is.numeric(margins) || length(margins) != 2) stop("`margins' must be a numeric vector of length 2") if (missing(cellnote)) cellnote <- matrix("", ncol = ncol(x), nrow = nrow(x)) if (!inherits(Rowv, "dendrogram")) { if (((!isTRUE(Rowv)) || (is.null(Rowv))) && (dendrogram %in% c("both", "row"))) { if (is.logical(Colv) && (Colv)) dendrogram <- "column" else dedrogram <- "none" warning("Discrepancy: Rowv is FALSE, while dendrogram is `", dendrogram, "'. Omitting row dendogram.") } } if (!inherits(Colv, "dendrogram")) { if (((!isTRUE(Colv)) || (is.null(Colv))) && (dendrogram %in% c("both", "column"))) { if (is.logical(Rowv) && (Rowv)) dendrogram <- "row" else dendrogram <- "none" warning("Discrepancy: Colv is FALSE, while dendrogram is `", dendrogram, "'. Omitting column dendogram.") } } if (inherits(Rowv, "dendrogram")) { ddr <- Rowv rowInd <- stats::order.dendrogram(ddr) } else if (is.integer(Rowv)) { hcr <- hclustfun(distfun(x)) ddr <- stats::as.dendrogram(hcr) ddr <- stats::reorder(ddr, Rowv) rowInd <- stats::order.dendrogram(ddr) if (nr != length(rowInd)) stop("row dendrogram ordering gave index of wrong length") } else if (isTRUE(Rowv)) { Rowv <- rowMeans(x, na.rm = na.rm) hcr <- hclustfun(distfun(x)) ddr <- stats::as.dendrogram(hcr) ddr <- stats::reorder(ddr, Rowv) rowInd <- stats::order.dendrogram(ddr) if (nr != length(rowInd)) stop("row dendrogram ordering gave index of wrong length") } else { rowInd <- nr:1 } if (inherits(Colv, "dendrogram")) { ddc <- Colv colInd <- stats::order.dendrogram(ddc) } else if (identical(Colv, "Rowv")) { if (nr != nc) stop("Colv = \"Rowv\" but nrow(x) != ncol(x)") if (exists("ddr")) { ddc <- ddr colInd <- stats::order.dendrogram(ddc) } else colInd <- rowInd } else if (is.integer(Colv)) { hcc <- hclustfun(distfun(if (symm) x else t(x))) ddc <- stats::as.dendrogram(hcc) ddc <- stats::reorder(ddc, Colv) colInd <- stats::order.dendrogram(ddc) if (nc != length(colInd)) stop("column dendrogram ordering gave index of wrong length") } else if (isTRUE(Colv)) { Colv <- colMeans(x, na.rm = na.rm) hcc <- hclustfun(distfun(if (symm) x else t(x))) ddc <- stats::as.dendrogram(hcc) ddc <- stats::reorder(ddc, Colv) colInd <- stats::order.dendrogram(ddc) if (nc != length(colInd)) stop("column dendrogram ordering gave index of wrong length") } else { colInd <- 1:nc } retval$rowInd <- rowInd retval$colInd <- colInd retval$call <- match.call() x <- x[rowInd, colInd] x.unscaled <- x cellnote <- cellnote[rowInd, colInd] if (is.null(labRow)) labRow <- if (is.null(rownames(x))) (1:nr)[rowInd] else rownames(x) else labRow <- labRow[rowInd] if (is.null(labCol)) labCol <- if (is.null(colnames(x))) (1:nc)[colInd] else colnames(x) else labCol <- labCol[colInd] if (scale == "row") { retval$rowMeans <- rm <- rowMeans(x, na.rm = na.rm) x <- sweep(x, 1, rm) retval$rowSDs <- sx <- apply(x, 1, sd, na.rm = na.rm) x <- sweep(x, 1, sx, "/") } else if (scale == "column") { retval$colMeans <- rm <- colMeans(x, na.rm = na.rm) x <- sweep(x, 2, rm) retval$colSDs <- sx <- apply(x, 2, sd, na.rm = na.rm) x <- sweep(x, 2, sx, "/") } if (missing(breaks) || is.null(breaks) || length(breaks) < 1) { if (missing(col) || is.function(col)) breaks <- 16 else breaks <- length(col) + 1 } if (length(breaks) == 1) { if (!symbreaks) breaks <- seq(min(x, na.rm = na.rm), max(x, na.rm = na.rm), length = breaks) else { extreme <- max(abs(x), na.rm = TRUE) breaks <- seq(-extreme, extreme, length = breaks) } } nbr <- length(breaks) ncol <- length(breaks) - 1 if (class(col) == "function") col <- col(ncol) min.breaks <- min(breaks) max.breaks <- max(breaks) x[x < min.breaks] <- min.breaks x[x > max.breaks] <- max.breaks if (missing(lhei) || is.null(lhei)) lhei <- c(keysize, 4) if (missing(lwid) || is.null(lwid)) lwid <- c(keysize, 4) if (missing(lmat) || is.null(lmat)) { lmat <- rbind(4:3, 2:1) if (!missing(ColSideColors)) { if (!is.character(ColSideColors) || length(ColSideColors) != nc) stop("'ColSideColors' must be a character vector of length ncol(x)") lmat <- rbind(lmat[1, ] + 1, c(NA, 1), lmat[2, ] + 1) lhei <- c(lhei[1], 0.2, lhei[2]) } if (!missing(RowSideColors)) { if (!is.character(RowSideColors) || length(RowSideColors) != nr) stop("'RowSideColors' must be a character vector of length nrow(x)") lmat <- cbind(lmat[, 1] + 1, c(rep(NA, nrow(lmat) - 1), 1), lmat[, 2] + 1) lwid <- c(lwid[1], 0.2, lwid[2]) } lmat[is.na(lmat)] <- 0 } if (length(lhei) != nrow(lmat)) stop("lhei must have length = nrow(lmat) = ", nrow(lmat)) if (length(lwid) != ncol(lmat)) stop("lwid must have length = ncol(lmat) =", ncol(lmat)) op <- graphics::par(no.readonly = TRUE) on.exit(graphics::par(op)) graphics::layout(lmat, widths = lwid, heights = lhei, respect = FALSE) if (!missing(RowSideColors)) { graphics::par(mar = c(margins[1], 0, 0, 0.5)) graphics::image(rbind(1:nr), col = RowSideColors[rowInd], axes = FALSE) } if (!missing(ColSideColors)) { graphics::par(mar = c(0.5, 0, 0, margins[2])) graphics::image(cbind(1:nc), col = ColSideColors[colInd], axes = FALSE) } graphics::par(mar = c(margins[1], 0, 0, margins[2])) x <- t(x) cellnote <- t(cellnote) if (revC) { iy <- nr:1 if (exists("ddr")) ddr <- rev(ddr) x <- x[, iy] cellnote <- cellnote[, iy] } else iy <- 1:nr graphics::image(1:nc, 1:nr, x, xlim = 0.5 + c(0, nc), ylim = 0.5 + c(0, nr), axes = FALSE, xlab = "", ylab = "", col = col, breaks = breaks, ...) retval$carpet <- x if (exists("ddr")) retval$rowDendrogram <- ddr if (exists("ddc")) retval$colDendrogram <- ddc retval$breaks <- breaks retval$col <- col if (!invalid(na.color) & any(is.na(x))) { mmat <- ifelse(is.na(x), 1, NA) graphics::image(1:nc, 1:nr, mmat, axes = FALSE, xlab = "", ylab = "", col = na.color, add = TRUE) } graphics::axis(1, 1:nc, labels = labCol, las = 2, line = -0.5, tick = 0, cex.axis = cexCol) if (!is.null(xlab)) graphics::mtext(xlab, side = 1, line = margins[1] - 1.25) graphics::axis(4, iy, labels = labRow, las = 2, line = -0.5, tick = 0, cex.axis = cexRow) if (!is.null(ylab)) graphics::mtext(ylab, side = 4, line = margins[2] - 1.25) if (!missing(add.expr)) eval.parent(substitute(add.expr)) if (!missing(colsep)) for (csep in colsep) graphics::rect(xleft = csep + 0.5, ybottom = rep(0, length(csep)), xright = csep + 0.5 + sepwidth[1], ytop = rep(ncol(x) + 1, csep), lty = 1, lwd = 1, col = sepcolor, border = sepcolor) if (!missing(rowsep)) for (rsep in rowsep) graphics::rect(xleft = 0, ybottom = (ncol(x) + 1 - rsep) - 0.5, xright = nrow(x) + 1, ytop = (ncol(x) + 1 - rsep) - 0.5 - sepwidth[2], lty = 1, lwd = 1, col = sepcolor, border = sepcolor) min.scale <- min(breaks) max.scale <- max(breaks) x.scaled <- scale01(t(x), min.scale, max.scale) if (trace %in% c("both", "column")) { retval$vline <- vline vline.vals <- scale01(vline, min.scale, max.scale) for (i in colInd) { if (!is.null(vline)) { graphics::abline(v = i - 0.5 + vline.vals, col = linecol, lty = 2) } xv <- rep(i, nrow(x.scaled)) + x.scaled[, i] - 0.5 xv <- c(xv[1], xv) yv <- 1:length(xv) - 0.5 graphics::lines(x = xv, y = yv, lwd = 1, col = tracecol, type = "s") } } if (trace %in% c("both", "row")) { retval$hline <- hline hline.vals <- scale01(hline, min.scale, max.scale) for (i in rowInd) { if (!is.null(hline)) { graphics::abline(h = i + hline, col = linecol, lty = 2) } yv <- rep(i, ncol(x.scaled)) + x.scaled[i, ] - 0.5 yv <- rev(c(yv[1], yv)) xv <- length(yv):1 - 0.5 graphics::lines(x = xv, y = yv, lwd = 1, col = tracecol, type = "s") } } if (!missing(cellnote)) graphics::text(x = c(row(cellnote)), y = c(col(cellnote)), labels = c(cellnote), col = notecol, cex = notecex) graphics::par(mar = c(margins[1], 0, 0, 0)) if (dendrogram %in% c("both", "row")) { graphics::plot(ddr, horiz = TRUE, axes = FALSE, yaxs = "i", leaflab = "none") } else graphics::plot.new() graphics::par(mar = c(0, 0, if (!is.null(main)) 5 else 0, margins[2])) if (dendrogram %in% c("both", "column")) { graphics::plot(ddc, axes = FALSE, xaxs = "i", leaflab = "none") } else graphics::plot.new() if (!is.null(main)) graphics::title(main, cex.main = 1.5 * op[["cex.main"]]) if (key) { graphics::par(mar = c(5, 4, 2, 1), cex = 0.75) tmpbreaks <- breaks if (symkey) { max.raw <- max(abs(c(x, breaks)), na.rm = TRUE) min.raw <- -max.raw } else { min.raw <- min(x, na.rm = TRUE) max.raw <- max(x, na.rm = TRUE) } z <- seq(min.raw, max.raw, length = length(col)) graphics::image(z = matrix(z, ncol = 1), col = col, breaks = tmpbreaks, xaxt = "n", yaxt = "n") graphics::par(usr = c(0, 1, 0, 1)) lv <- pretty(breaks) xv <- scale01(as.numeric(lv), min.raw, max.raw) graphics::axis(1, at = xv, labels = lv) if (scale == "row") graphics::mtext(side = 1, "Row Z-Score", line = 2) else if (scale == "column") graphics::mtext(side = 1, "Column Z-Score", line = 2) else graphics::mtext(side = 1, "Value", line = 2) if (density.info == "density") { dens <- stats::density(x, adjust = densadj, na.rm = TRUE) omit <- dens$x < min(breaks) | dens$x > max(breaks) dens$x <- dens$x[-omit] dens$y <- dens$y[-omit] dens$x <- scale01(dens$x, min.raw, max.raw) graphics::lines(dens$x, dens$y/max(dens$y) * 0.95, col = denscol, lwd = 1) graphics::axis(2, at = pretty(dens$y)/max(dens$y) * 0.95, pretty(dens$y)) graphics::title("Color Key\nand Density Plot") graphics::par(cex = 0.5) graphics::mtext(side = 2, "Density", line = 2) } else if (density.info == "histogram") { h <- graphics::hist(x, plot = FALSE, breaks = breaks) hx <- scale01(breaks, min.raw, max.raw) hy <- c(h$counts, h$counts[length(h$counts)]) graphics::lines(hx, hy/max(hy) * 0.95, lwd = 1, type = "s", col = denscol) graphics::axis(2, at = pretty(hy)/max(hy) * 0.95, pretty(hy)) graphics::title("Color Key\nand Histogram") graphics::par(cex = 0.5) graphics::mtext(side = 2, "Count", line = 2) } else graphics::title("Color Key") } else graphics::plot.new() retval$colorTable <- data.frame(low = retval$breaks[-length(retval$breaks)], high = retval$breaks[-1], color = retval$col) invisible(retval) }
"toybase_individual_2016_03"
library(PEcAn.all) library(PEcAn.SIPNET) library(PEcAn.LINKAGES) library(PEcAn.visualization) library(PEcAn.ED2) library(PEcAn.assim.sequential) library(nimble) library(lubridate) library(PEcAn.visualization) library(rgdal) library(ncdf4) setwd('/fs/data2/output//PEcAn_1000009225/') file.copy('/fs/data2/output//PEcAn_1000007999/sda.obs.Rdata',getwd()) setwd('/fs/data2/output//PEcAn_1000008588/') adjustment=TRUE setwd('/fs/data2/output//PEcAn_1000008683/') adjustment=TRUE load("out/sda.initial.runs.Rdata") load("sda.output.Rdata") nt <- length(obs.list$obs.mean) aqq <- array(NA,dim=c(nt,10,10)) t <- length(FORECAST)+1 aqq[t,,]<- solve(enkf.params[[t-1]]$q.bar)*enkf.params[[t-1]]$n bqq<-numeric(nt) bqq[t]<-enkf.params[[t-1]]$n settings <- read.settings("pecan.SDA.xml") obs.list <- load_data_paleon_sda(settings = settings) IC <- NULL status.start("IC") ne <- as.numeric(settings$state.data.assimilation$n.ensemble) state <- as.data.frame(rmvnorm(ne,as.numeric(obs.list$obs.mean[[1]]),(obs.list$obs.cov[[1]]), method = "svd")) colnames(state)<-c('AbvGrndWood','GWBI') IC <- sample.IC.SIPNET(ne, state = state) status.end() if(FALSE){ obs.mean = obs.list$obs.mean obs.cov = obs.list$obs.cov Q = NULL adjustment = TRUE restart=NULL } PEcAn.assim.sequential::sda.enkf(settings, obs.mean = obs.list$obs.mean, obs.cov = obs.list$obs.cov, IC = IC) obmn <- obvn <- list() times.keep <- seq(1,1100,100) for(i in 1:length(times.keep)){ obmn[[i]] <- obs.mean[[times.keep[i]]] obvn[[i]] <- obs.cov[[times.keep[i]]] } names(obmn) <- names(obvn) <- names(obs.mean)[times.keep] obs.mean <- obmn obs.cov <- obvn t1 <- 1 t <- length(obs.list$obs.mean) names.y <- unique(unlist(lapply(obs.list$obs.mean[t1:t], function(x) { names(x) }))) Ybar <- t(sapply(obs.list$obs.mean[t1:t], function(x) { tmp <- rep(NA, length(names.y)) names(tmp) <- names.y mch <- match(names(x), names.y) tmp[mch] <- x[mch] tmp })) YCI <- t(as.matrix(sapply(obs.list$obs.cov[t1:t], function(x) { if (length(x)<2) { rep(NA, length(names.y)) } sqrt(diag(x)) }))) obs.dates <- rownames(Ybar) green <- col2rgb("green") alphagreen <- rgb(green[1], green[2], green[3], 75, max = 255) for(i in 1:length(obs.list$obs.mean[[1]])){ plot(as.Date(obs.dates), as.numeric(Ybar[, i]), type = "l", col = "darkgreen", lwd = 2,ylim=c(0,1),main=colnames(Ybar)[i]) ciEnvelope(as.Date(obs.dates), as.numeric(Ybar[, i]) - as.numeric(YCI[, i]) * 1.96, as.numeric(Ybar[, i]) + as.numeric(YCI[, i]) * 1.96, col = alphagreen) lines(as.Date(obs.dates), as.numeric(Ybar[, i]), type = "l", col = "darkgreen", lwd = 2) }
expected <- eval(parse(text="structure(list(`1` = c(0, 0, 0, 0, 0, 0, 1.48219693752374e-323, 0, 0, 0, 0, 0)), .Names = \"1\")")); test(id=0, code={ argv <- eval(parse(text="list(structure(c(0, 0, 0, 0, 0, 0, 1.48219693752374e-323, 0, 0, 0, 0, 0), .Dim = c(1L, 12L), .Dimnames = list(NULL, c(\"1\", \"1\", \"1\", \"1\", \"1\", \"1\", \"1\", \"1\", \"1\", \"1\", \"1\", \"1\"))), structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = \"1\", class = \"factor\"))")); .Internal(split(argv[[1]], argv[[2]])); }, o=expected);
rdif <- function(x, data, score=NULL, group, focal.name, D=1, alpha=0.05, missing=NA, purify=FALSE, purify.by=c("rdif_rs", "rdif_r", "rdif_s"), max.iter=10, min.resp=NULL, method="MLE", range=c(-4, 4), norm.prior=c(0, 1), nquad=41, weights=NULL, ncore=1, verbose=TRUE) { cl <- match.call() x <- data.frame(x) colnames(x) <- c("id", "cats", "model", paste0("par.", 1:(ncol(x) - 3))) if(ncol(x[, -c(1, 2, 3)]) == 2) { x <- data.frame(x, par.3=NA) } x <- back2df(metalist2(x)) x$model <- as.character(x$model) if(any(x$model %in% c("GRM", "GPCM")) | any(x$cats > 2)) { stop("The current version only supports dichotomous response data.", call.=FALSE) } data <- data.matrix(data) if(!is.na(missing)) { data[data == missing] <- NA } if(!is.null(score)) { if(is.matrix(score) | is.data.frame(score)) { score <- as.numeric(data.matrix(score)) } } else { if(!is.null(min.resp)) { n_resp <- rowSums(!is.na(data)) loc_less <- which(n_resp < min.resp & n_resp > 0) data[loc_less, ] <- NA } score <- est_score(x=x, data=data, D=D, method=method, range=range, norm.prior=norm.prior, nquad=nquad, weights=weights, ncore=ncore)$est.theta } dif_rst <- rdif_one(x=x, data=data, score=score, group=group, focal.name=focal.name, D=D, alpha=alpha) no_purify <- list(dif_stat=NULL, moments=NULL, dif_item=NULL, score=NULL) with_purify <- list(purify.by=NULL, dif_stat=NULL, moments=NULL, dif_item=NULL, n.iter=NULL, score=NULL, complete=NULL) no_purify$dif_stat <- dif_rst$dif_stat no_purify$dif_item <- dif_rst$dif_item no_purify$moments <- data.frame(id=x$id, dif_rst$moments$rdif_r[, c(1, 3)], dif_rst$moments$rdif_s[, c(1, 3)], dif_rst$covariance, stringsAsFactors=FALSE) names(no_purify$moments) <- c("id", "mu.rdif_r", "sigma.rdif_r", "mu.rdif_s", "sigma.rdif_s", "covariance") no_purify$score <- score if(purify) { purify.by <- match.arg(purify.by) dif_item <- NULL dif_stat <- data.frame(id=rep(NA_character_, nrow(x)), rdif_r=NA, z.rdif_r=NA, rdif_s=NA, z.rdif_s=NA, rdif_rs=NA, p.val.rdif_r=NA, p.val.rdif_s=NA, p.val.rdif_rs=NA, n.ref=NA, n.foc=NA, n.total=NA, n.iter=NA, stringsAsFactors=FALSE) mmt_df <- data.frame(id=rep(NA_character_, nrow(x)), mu.rdif_r=NA, sigma.rdif_r=NA, mu.rdif_s=NA, sigma.rdif_s=NA, covariance=NA, n.iter=NA, stringsAsFactors=FALSE) dif_item_tmp <- dif_rst$dif_item[[purify.by]] dif_stat_tmp <- dif_rst$dif_stat mmt_df_tmp <- no_purify$moments x_puri <- x data_puri <- data if(!is.null(dif_item_tmp)) { item_num <- 1:nrow(x) if(max.iter < 1) stop("The maximum iteration (i.e., max.iter) must be greater than 0 when purify = TRUE.", call.=FALSE) if(verbose) { cat("Purification started...", '\n') } for(i in 1:max.iter) { if(verbose) { cat("\r", paste0("Iteration: ", i)) } flag_max <- switch(purify.by, rdif_r=which.max(abs(dif_stat_tmp$z.rdif_r)), rdif_s=which.max(abs(dif_stat_tmp$z.rdif_s)), rdif_rs=which.max(dif_stat_tmp$rdif_rs)) del_item <- item_num[flag_max] dif_item <- c(dif_item, del_item) dif_stat[del_item, 1:12] <- dif_stat_tmp[flag_max, ] dif_stat[del_item, 13] <- i - 1 mmt_df[del_item, 1:6] <- mmt_df_tmp[flag_max, ] mmt_df[del_item, 7] <- i - 1 item_num <- item_num[-flag_max] x_puri <- x_puri[-flag_max, ] data_puri <- data_puri[, -flag_max] if(!is.null(min.resp)) { n_resp <- rowSums(!is.na(data_puri)) loc_less <- which(n_resp < min.resp & n_resp > 0) data_puri[loc_less, ] <- NA } score_puri <- est_score(x=x_puri, data=data_puri, D=D, method=method, range=range, norm.prior=norm.prior, nquad=nquad, weights=weights, ncore=ncore)$est.theta dif_rst_tmp <- rdif_one(x=x_puri, data=data_puri, score=score_puri, group=group, focal.name=focal.name, D=D, alpha=alpha) dif_item_tmp <- dif_rst_tmp$dif_item[[purify.by]] dif_stat_tmp <- dif_rst_tmp$dif_stat mmt_df_tmp <- data.frame(id=dif_rst_tmp$dif_stat$id, dif_rst_tmp$moments$rdif_r[, c(1, 3)], dif_rst_tmp$moments$rdif_s[, c(1, 3)], dif_rst_tmp$covariance, stringsAsFactors=FALSE) names(mmt_df_tmp) <- c("id", "mu.rdif_r", "sigma.rdif_r", "mu.rdif_s", "sigma.rdif_s", "covariance") if(is.null(dif_item_tmp)) { dif_item <- dif_item dif_stat[item_num, 1:12] <- dif_stat_tmp dif_stat[item_num, 13] <- i mmt_df[item_num, 1:6] <- mmt_df_tmp mmt_df[item_num, 7] <- i break } } if(verbose) { cat("", "\n") } n_iter <- i if(max.iter == n_iter & !is.null(dif_item_tmp)) { warning("The iteration reached out the maximum number of iteration before purification is complete.", call.=FALSE) complete <- FALSE dif_item <- c(dif_item, item_num[dif_item_tmp]) dif_stat[item_num, 1:12] <- dif_stat_tmp dif_stat[item_num, 13] <- i mmt_df[item_num, 1:6] <- mmt_df_tmp mmt_df[item_num, 7] <- i } else { complete <- TRUE if(verbose) { cat("Purification is finished.", '\n') } } with_purify$purify.by <- purify.by with_purify$dif_stat <- dif_stat with_purify$moments <- mmt_df with_purify$dif_item <- sort(dif_item) with_purify$n.iter <- n_iter with_purify$score <- score_puri with_purify$complete <- complete } else { with_purify$purify.by <- purify.by with_purify$dif_stat <- cbind(no_purify$dif_stat, n.iter=0) with_purify$moments <- cbind(no_purify$moments, n.iter=0) with_purify$n.iter <- 0 with_purify$complete <- TRUE } } rst <- list(no_purify=no_purify, purify=purify, with_purify=with_purify, alpha=alpha) class(rst) <- "rdif" rst$call <- cl rst } rdif_one <- function(x, data, score, group, focal.name, D=1, alpha=0.05) { meta <- metalist2(x) cats <- x$cats nitem <- nrow(x) loc_ref <- which(group != focal.name) loc_foc <- which(group == focal.name) resp_ref <- data[loc_ref, , drop=FALSE] resp_foc <- data[loc_foc, , drop=FALSE] n_ref <- colSums(!is.na(resp_ref)) n_foc <- colSums(!is.na(resp_foc)) all_miss <- sort(unique(c(which(n_ref == 0), which(n_foc == 0)))) score_ref <- score[loc_ref] score_foc <- score[loc_foc] extscore_ref <- trace(meta=meta, theta=score_ref, D=D)$trace_df extscore_foc <- trace(meta=meta, theta=score_foc, D=D)$trace_df prob_ref <- trace4(meta=meta, theta=score_ref, D=D)$trace prob_foc <- trace4(meta=meta, theta=score_foc, D=D)$trace extscore_ref[is.na(resp_ref)] <- NA extscore_foc[is.na(resp_foc)] <- NA resid_ref <- resp_ref - extscore_ref resid_foc <- resp_foc - extscore_foc rdif_r <- colMeans(resid_foc, na.rm=TRUE) - colMeans(resid_ref, na.rm=TRUE) rdif_s <- colMeans(resid_foc^2, na.rm=TRUE) - colMeans(resid_ref^2, na.rm=TRUE) moments <- resid_moments(p_ref=prob_ref, p_foc=prob_foc, n_ref=n_ref, n_foc=n_foc, resp_ref=resp_ref, resp_foc=resp_foc, cats=cats) moments_rdif_r <- moments$rdif_r moments_rdif_s <- moments$rdif_s covar <- moments$covariance poolsd <- moments$poolsd chisq <- c() for(i in 1:nitem) { if(i %in% all_miss) { chisq[i] <- NaN } else{ cov_mat <- array(NA, c(2, 2)) cov_mat[col(cov_mat) != row(cov_mat)] <- covar[i] diag(cov_mat) <- c(moments_rdif_r[i, 2], moments_rdif_s[i, 2]) mu_vec <- cbind(moments_rdif_r[i, 1], moments_rdif_s[i, 1]) est_mu_vec <- cbind(rdif_r[i], rdif_s[i]) inv_cov <- suppressWarnings(tryCatch({solve(cov_mat, tol=1e-200)}, error = function(e) {NULL})) if(is.null(inv_cov)) { inv_cov <- suppressWarnings(tryCatch({solve(cov_mat + 1e-15, tol=1e-200)}, error = function(e) {NULL})) if(is.null(inv_cov)) { inv_cov <- suppressWarnings(tryCatch({solve(cov_mat + 1e-10, tol=1e-200)}, error = function(e) {NULL})) } } chisq[i] <- as.numeric((est_mu_vec - mu_vec) %*% inv_cov %*% t(est_mu_vec - mu_vec)) } } z_stat_rdif_r <- (rdif_r - moments_rdif_r$mu) / moments_rdif_r$sigma z_stat_rdif_s <- (rdif_s - moments_rdif_s$mu) / moments_rdif_s$sigma pval_rdif_r <- round(2 * stats::pnorm(q=abs(z_stat_rdif_r), mean=0, sd=1, lower.tail=FALSE), 4) pval_rdif_s <- round(2 * stats::pnorm(q=abs(z_stat_rdif_s), mean=0, sd=1, lower.tail=FALSE), 4) pval_rdif_rs <- round(stats::pchisq(chisq, df=2, lower.tail=FALSE), 4) rdif_stats <- list(x=rdif_r, y=rdif_s) n_total <- n_foc + n_ref efs_hedge <- purrr::map2(.x=rdif_stats, .y=poolsd$hedge, .f=function(x, y) {round((x / y) * (1 - (3 / (4 * (n_foc + n_ref) - 9))), 4)}) %>% data.frame() %>% dplyr::rename_all(.f=function(x) c("he_rdif_r", "he_rdif_s")) efs_glass <- purrr::map2(.x=rdif_stats, .y=poolsd$glass, .f=function(x, y) round(x / y, 4)) %>% data.frame() %>% dplyr::rename_all(.f=function(x) c("gl_rdif_r", "gl_rdif_s")) effect_size <- data.frame(id=x$id, efs_hedge, efs_glass, stringsAsFactors=FALSE) stat_df <- data.frame(id=x$id, rdif_r=round(rdif_r, 4), z.rdif_r=round(z_stat_rdif_r, 4), rdif_s=round(rdif_s, 4), z.rdif_s=round(z_stat_rdif_s, 4), rdif_rs=round(chisq, 4), p.val.rdif_r=pval_rdif_r, p.val.rdif_s=pval_rdif_s, p.val.rdif_rs=pval_rdif_rs, n.ref=n_ref, n.foc=n_foc, n.total=n_total, stringsAsFactors=FALSE) rownames(stat_df) <- NULL dif_item_rdif_r <- as.numeric(which(pval_rdif_r <= alpha)) dif_item_rdif_s <- as.numeric(which(pval_rdif_s <= alpha)) dif_item_rdif_rs <- which(pval_rdif_rs <= alpha) if(length(dif_item_rdif_r) == 0) dif_item_rdif_r <- NULL if(length(dif_item_rdif_s) == 0) dif_item_rdif_s <- NULL if(length(dif_item_rdif_rs) == 0) dif_item_rdif_rs <- NULL rst <- list(dif_stat=stat_df, effect_size=effect_size, dif_item=list(rdif_r=dif_item_rdif_r, rdif_s=dif_item_rdif_s, rdif_rs=dif_item_rdif_rs), moments=list(rdif_r=moments_rdif_r, rdif_s=moments_rdif_s), covariance=covar, alpha=alpha) rst } resid_moments <- function(p_ref, p_foc, n_ref, n_foc, resp_ref, resp_foc, cats) { nitem <- length(cats) nrow_ref <- nrow(resp_ref) nrow_foc <- nrow(resp_foc) mu_ref <- purrr::map(.x=1:2, .f=function(x) matrix(NA, nrow=nrow_ref, ncol=nitem)) mu_foc <- purrr::map(.x=1:2, .f=function(x) matrix(NA, nrow=nrow_foc, ncol=nitem)) mu2_ref <- mu_ref mu2_foc <- mu_foc mu_resid3_ref <- matrix(NA, nrow=nrow_ref, ncol=nitem) mu_resid3_foc <- matrix(NA, nrow=nrow_foc, ncol=nitem) for(i in 1:nitem) { Emat_ref <- matrix(0:(cats[i]-1), nrow=nrow_ref, ncol=cats[i], byrow = TRUE) Emat_foc <- matrix(0:(cats[i]-1), nrow=nrow_foc, ncol=cats[i], byrow = TRUE) exp_resid_ref <- Emat_ref - matrix(rowSums(Emat_ref * p_ref[[i]]), nrow=nrow_ref, ncol=cats[i], byrow=FALSE) exp_resid_foc <- Emat_foc - matrix(rowSums(Emat_foc * p_foc[[i]]), nrow=nrow_foc, ncol=cats[i], byrow=FALSE) exp_resid_ref[is.na(resp_ref[, i]), ] <- NA exp_resid_foc[is.na(resp_foc[, i]), ] <- NA value_foc <- value_ref <- vector('list', 2) value_ref[[1]] <- exp_resid_ref value_foc[[1]] <- exp_resid_foc value_ref[[2]] <- exp_resid_ref^2 value_foc[[2]] <- exp_resid_foc^2 resid3_ref <- exp_resid_ref^3 resid3_foc <- exp_resid_foc^3 for(j in 1:2) { mu_ref[[j]][, i] <- rowSums(value_ref[[j]] * p_ref[[i]], na.rm=FALSE) mu2_ref[[j]][, i] <- rowSums((value_ref[[j]])^2 * p_ref[[i]], na.rm=FALSE) mu_foc[[j]][, i] <- rowSums(value_foc[[j]] * p_foc[[i]], na.rm=FALSE) mu2_foc[[j]][, i] <- rowSums((value_foc[[j]])^2 * p_foc[[i]], na.rm=FALSE) } mu_resid3_ref[, i] <- rowSums(resid3_ref * p_ref[[i]], na.rm=FALSE) mu_resid3_foc[, i] <- rowSums(resid3_foc * p_foc[[i]], na.rm=FALSE) } var_ref <- purrr::map2(.x=mu2_ref, .y=mu_ref, .f=function(x, y) x - y^2) var_foc <- purrr::map2(.x=mu2_foc, .y=mu_foc, .f=function(x, y) x - y^2) const_ref <- purrr::map(.x=var_ref, .f=function(x) matrix((1 / n_ref^2), nrow=nrow(x), ncol=ncol(x), byrow=TRUE)) const_foc <- purrr::map(.x=var_foc, .f=function(x) matrix((1 / n_foc^2), nrow=nrow(x), ncol=ncol(x), byrow=TRUE)) var_mu_ref <- purrr::map2(.x=const_ref, .y=var_ref, .f=function(x, y) colSums(x * y, na.rm=TRUE)) var_mu_foc <- purrr::map2(.x=const_foc, .y=var_foc, .f=function(x, y) colSums(x * y, na.rm=TRUE)) mu <- purrr::map2(.x=mu_foc, .y=mu_ref, .f=function(x, y) colMeans(x, na.rm=TRUE) - colMeans(y, na.rm=TRUE)) sigma2 <- purrr::map2(.x=var_mu_foc, .y=var_mu_ref, .f=function(x, y) x + y) sigma <- purrr::map(.x=sigma2, .f=function(x) sqrt(x)) poolsd_hedge <- suppressWarnings(purrr::map2(.x=var_mu_foc, .y=var_mu_ref, .f=function(x, y) { sqrt((x * (n_foc - 1) + y * (n_ref - 1)) / (n_foc + n_foc - 2)) })) poolsd_glass <- suppressWarnings(purrr::map(.x=var_mu_ref, .f=function(x) sqrt(x))) poolsd <- list(hedge=poolsd_hedge, glass=poolsd_glass) covar <- colSums(mu_resid3_foc, na.rm=TRUE) * (1/n_foc^2) + colSums(mu_resid3_ref, na.rm=TRUE) * (1/n_ref^2) rst <- purrr::pmap(.l=list(x=mu, y=sigma2, z=sigma), .f=function(x, y, z) data.frame(mu=x, sigma2=y, sigma=z)) names(rst) <- c("rdif_r", "rdif_s") rst$covariance <- covar rst$poolsd <- poolsd rst }
hist.lengths <- function (x, ..., log = FALSE, zeros.rm = TRUE) { newlen <- x$length + 0 if (zeros.rm & x$zeros) { newlen <- x$length + x$maxcens } args <- list(...) breaks <- "Sturges" if (!is.null(args$breaks)) breaks <- args$breaks include.lowest <- TRUE if (!is.null(args$include.lowest)) include.lowest <- args$include.lowest right <- TRUE if (!is.null(args$right)) right <- args$right res <- tapply(newlen, x$categories, function(Lengths) { if (log) { LogLengths <- log(Lengths) hist(LogLengths, breaks = breaks, include.lowest = include.lowest, right = right, plot = FALSE) } else { hist(Lengths, breaks = breaks, include.lowest = include.lowest, right = right, plot = FALSE) } }) res$direction <- x$direction res$log <- log class(res) <- "hist.lengths" plot <- TRUE if (!is.null(args$plot)) plot <- args$plot if (plot) { plot(res, ...) return(invisible(res)) } if (!plot) return(res) }
if(getRversion() >= "2.15.1") utils::globalVariables("exp2d", package="tgp") "exp2d.Z" <- function(X, sd=0.001) { if(is.null(X)) return(NULL); if(is.null(ncol(X))) X <- matrix(X, ncol=length(X)) if(ncol(X) != 2) stop(paste("X should be a matrix (or data frame) with 2 columns, you have", ncol(X))) Ztrue <- X[,1] * exp(- X[,1]^2 - X[,2]^2) Z <- Ztrue + rnorm(nrow(X),mean=0,sd=sd) return(data.frame(Z=Z,Ztrue=Ztrue)) } "exp2d.rand" <- function(n1=50, n2=30, lh=NULL, dopt=1) { if(n1 < 0 || n2 < 0) { stop("n1 and n2 must be >= 0") } if(!is.null(lh)) { Xcand <- lhs(n1*dopt, rbind(c(-2,2), c(-2,2))) if(dopt > 2) { X <- dopt.gp(n1, NULL, Xcand)$XX } else { X <- Xcand } if(length(n2) == 1) n2 <- rep(ceiling(n2/3), 3) else if(length(n2 != 3)) stop(paste("length of n2 should be 1 or 3, you have", length(n2))) if(length(dopt) != 1 || dopt < 1) stop(paste("dopt should be a scalar >= 1, you have", dopt)) Xcand <- lhs(n2[1]*dopt, rbind(c(2,6), c(-2,2))) Xcand <- rbind(Xcand, lhs(n2[2]*dopt, rbind(c(2,6), c(2,6)))) Xcand <- rbind(Xcand, lhs(n2[3]*dopt, rbind(c(-2,2), c(2,6)))) if(dopt > 2) { X <- rbind(X, dopt.gp(sum(n2), NULL, Xcand)$XX) } else { X <- rbind(X, Xcand) } Zdata <- exp2d.Z(X); Ztrue <- Zdata$Ztrue; Z <- Zdata$Z if(length(lh) == 1) lh <- rep(ceiling(lh/4), 4) else if(length(lh) != 4) stop(paste("length of lh should be 0 (for grid), 1 or 4, you have", length(lh))) XX <- lhs(lh[1]*dopt, rbind(c(-2,2), c(-2,2))) XX <- rbind(XX, lhs(lh[2]*dopt, rbind(c(2,6), c(-2,2)))) XX <- rbind(XX, lhs(lh[3]*dopt, rbind(c(2,6), c(2,6)))) XX <- rbind(XX, lhs(lh[4]*dopt, rbind(c(-2,2), c(2,6)))) if(length(X) > 0 && dopt > 2) { XX <- dopt.gp(sum(lh), X, XX)$XX } ZZdata <- exp2d.Z(XX); ZZtrue <- ZZdata$Ztrue; ZZ <- Zdata$Z } else { if(n1 + n2 >= 441) { stop("n1 + n2 must be <= 441") } if(dopt != 1) { warning("argument dopt != 1 only makes sens when !is.null(lh)") } data(exp2d, envir=environment()); n <- dim(exp2d)[1] si <- (1:n)[1==apply(exp2d[,1:2] <= 2, 1, prod)] s <- c(sample(si, size=n1, replace=FALSE), sample(setdiff(1:n, si), n2, replace=FALSE)) X <- as.matrix(exp2d[s,1:2]); ss <- setdiff(1:n, s) XX <- exp2d[ss, 1:2]; Z <- as.vector(exp2d[s,3]); Ztrue <- as.vector(exp2d[s,4]); ZZ <- as.vector(exp2d[ss,3]); ZZtrue <- as.vector(exp2d[ss,4]); } return(list(X=X, Z=Z, Ztrue=Ztrue, XX=XX, ZZ=ZZ, ZZtrue=ZZtrue)) }
certify <- function(x, ..., allow_null = FALSE, id = NULL, return_id = FALSE) { id <- resolve_id(rlang::enquo(x), id) if (is.null(x)) { if (!allow_null) { stop(backticks(id), " must not be NULL.", call. = FALSE) } else { return(NULL) } } quos <- rlang::enquos(...) for (quo in quos) { condition <- rlang::as_function(rlang::eval_tidy(quo)) satisfied <- condition(x) if (!rlang::is_scalar_logical(satisfied)) stop( "`", rlang::quo_text(quo), "` does not evaluate to a scalar logical for ", backticks(id), ".", call. = FALSE ) if (!satisfied) stop( "Condition `", rlang::quo_text(quo), "` not satisfied for ", backticks(id), ".", call. = FALSE ) } maybe_set_id(x, id, return_id) } gt <- function(l) { force(l) function(x) all(x > l) } gte <- function(l) { force(l) function(x) all(x >= l) } lt <- function(u) { force(u) function(x) all(x < u) } lte <- function(u) { force(u) function(x) all(x <= u) } bounded <- function(l = NULL, u = NULL, incl_lower = TRUE, incl_upper = TRUE) { if (is.null(l) && is.null(u)) stop("At least one of `l` or `u` must be specified.", call. = FALSE) lower_bound <- if (!is.null(l)) { if (incl_lower) gte(l) else gt(l) } else { function() TRUE } upper_bound <- if (!is.null(u)) { if (incl_upper) lte(u) else lt(u) } else { function() TRUE } function(x) lower_bound(x) && upper_bound(x) }
require(rkwarddev) local({ output.dir <- "~/cocor/" overwrite <- TRUE about.node <- rk.XML.about( name="cocor", author=person(given="Birk", family="Diedenhofen", email="[email protected]", role=c("aut","cre")), about=list( desc="Comparison of two correlations based on either dependent or independent groups.", version="1.1-3", date="2016-05-28", url="http://comparingcorrelations.org", license="GPL" ) ) dependencies.node <- rk.XML.dependencies( dependencies=list( rkward.min="0.6.0", rkward.max="", R.min="2.15", R.max="" ) ) var.sel <- rk.XML.varselector("Select data", id.name="vars") raw.data.dep.groups.overlap.var.sel <- rk.XML.varselector("Select data", id.name="raw_data_dep_groups_overlap_var_sel") raw.data.dep.groups.nonoverlap.var.sel <- rk.XML.varselector("Select data", id.name="raw_data_dep_groups_nonoverlap_var_sel") raw.data.indep.groups.var.sel.1 <- rk.XML.varselector("Select data", id.name="raw_data_indep_groups_1_var_sel") raw.data.indep.groups.var.sel.2 <- rk.XML.varselector("Select data", id.name="raw_data_indep_groups_2_var_sel") data.input <- rk.XML.radio("Data input", id.name="data_input", options=list( "Calculate and compare correlations from raw data"=c(val="raw.data"), "Enter correlations manually"=c(val="manual"), "Use correlations stored in single variables"=c(val="variable") ) ) groups <- rk.XML.radio("The two correlations are based on", id.name="groups", options=list( "two independent groups"=c(val="indep"), "two dependent groups (e.g., same group)"=c(val="dep") ) ) correlations <- rk.XML.radio("The two correlations are", id.name="correlations", options=list( "overlapping"=c(val="overlap"), "nonoverlapping"=c(val="nonoverlap") ) ) text.tailed.test <- "Do you want to conduct a one- or two-tailed test?" test.hypothesis.indep.groups <- rk.XML.radio(text.tailed.test, id.name="test_hypothesis_indep_groups", options=list( "Two-tailed: r1.jk is not equal to r2.hm"=c(val="two.sided"), "One-tailed: r1.jk is greater than r2.hm"=c(val="greater"), "One-tailed: r1.jk is less than r2.hm "=c(val="less") ) ) test.hypothesis.indep.groups.null.value <- rk.XML.radio(text.tailed.test, id.name="test_hypothesis_indep_groups_null_value", options=list( "Two-tailed: the difference between r1.jk and r2.hm is not equal to the defined null value"=c(val="two.sided"), "One-tailed: the difference between r1.jk and r2.hm is greater than the defined null value"=c(val="greater"), "One-tailed: the difference between r1.jk and r2.hm is less than the defined null value"=c(val="less") ) ) test.hypothesis.dep.groups.overlap <- rk.XML.radio(text.tailed.test, id.name="test_hypothesis_dep_groups_overlap", options=list( "Two-tailed: r.jk is not equal to r.jh"=c(val="two.sided"), "One-tailed: r.jk is greater than r.jh"=c(val="greater"), "One-tailed: r.jk is less than r.jh"=c(val="less") ) ) test.hypothesis.dep.groups.overlap.null.value <- rk.XML.radio(text.tailed.test, id.name="test_hypothesis_dep_groups_overlap_null_value", options=list( "Two-tailed: the difference between r.jk and r.jh is not equal to the defined null value"=c(val="two.sided"), "One-tailed: the difference between r.jk and r.jh is greater than the defined null value"=c(val="greater"), "One-tailed: the difference between r.jk and r.jh is less than the defined null value"=c(val="less") ) ) test.hypothesis.dep.groups.nonoverlap <- rk.XML.radio(text.tailed.test, id.name="test_hypothesis_dep_groups_nonoverlap", options=list( "Two-tailed: r.jk is not equal to r.hm"=c(val="two.sided"), "One-tailed: r.jk is greater than r.hm"=c(val="greater"), "One-tailed: r.jk is less than r.hm"=c(val="less") ) ) test.hypothesis.dep.groups.nonoverlap.null.value <- rk.XML.radio(text.tailed.test, id.name="test_hypothesis_dep_groups_nonoverlap_null_value", options=list( "Two-tailed: the difference between r.jk and r.hm is not equal to the defined null value"=c(val="two.sided"), "One-tailed: the difference between r.jk and r.hm is greater than the defined null value"=c(val="greater"), "One-tailed: the difference between r.jk and r.hm is less than the defined null value"=c(val="less") ) ) alpha <- rk.XML.spinbox("Alpha level", min=0, max=1, id.name="alpha", initial=.05) alpha.frame <- rk.XML.frame(alpha, label="Please choose an alpha level:") conf.level <- rk.XML.spinbox("Confidence level", min=0, max=1, id.name="conf_int", initial=.95) conf.level.frame <- rk.XML.frame(conf.level, label="Please choose a confidence level:") null.value <- rk.XML.spinbox("Null value", min=-2, max=2, id.name="null_value", initial=0, precision=2) null.value.frame <- rk.XML.frame(rk.XML.text("The null value is the hypothesized difference between the two correlations used for testing the null hypothesis. If the null value is other than 0, only the test by Zou (2007) is available."), null.value, label="Please choose a null value:") text.correlations <- "Please provide the correlations you want to compare:" text.related.correlation <- rk.XML.text("To assess the significance of the difference between the two dependent correlations, you need to provide the correlation between k and h:<br /><br />") text.related.correlations <- rk.XML.text("To assess the significance of the difference between the two dependent correlations, you need to provide additional related correlations:<br /><br />") text.group.size <- "Please indicate the size of your sample:" text.group.sizes <- "Please indicate the size of your samples:" raw.data.indep.groups.1 <- rk.XML.varslot("Raw data set 1 (must be a data.frame)", source=raw.data.indep.groups.var.sel.1, classes=c("data.frame"), id.name="raw_data_indep_groups_1") raw.data.indep.groups.2 <- rk.XML.varslot("Raw data set 2 (must be a data.frame)", source=raw.data.indep.groups.var.sel.2, classes=c("data.frame"), id.name="raw_data_indep_groups_2") raw.data.indep.groups.j <- rk.XML.varslot("Variable j", source=raw.data.indep.groups.var.sel.1, types="number", id.name="raw_data_indep_groups_j") raw.data.indep.groups.k <- rk.XML.varslot("Variable k", source=raw.data.indep.groups.var.sel.1, types="number", id.name="raw_data_indep_groups_k") raw.data.indep.groups.h <- rk.XML.varslot("Variable h", source=raw.data.indep.groups.var.sel.2, types="number", id.name="raw_data_indep_groups_h") raw.data.indep.groups.m <- rk.XML.varslot("Variable m", source=raw.data.indep.groups.var.sel.2, types="number", id.name="raw_data_indep_groups_m") raw.data.indep.groups.col.1 <- rk.XML.col( rk.XML.text("To compare the correlations j ~ k and h ~ m, please provide a data.frame for each correlations and select columns to specify the variables j, k, h, and m.<br />"), raw.data.indep.groups.1.frame <- rk.XML.frame(raw.data.indep.groups.1, raw.data.indep.groups.j, raw.data.indep.groups.k, label="Correlation j ~ k", id.name="raw_data_indep_groups_1_frame"), rk.XML.stretch() ) raw.data.indep.groups.col.2 <- rk.XML.col( raw.data.indep.groups.2.frame <- rk.XML.frame(raw.data.indep.groups.2, raw.data.indep.groups.h, raw.data.indep.groups.m, label="Correlation h ~ m", id.name="raw_data_indep_groups_2_frame"), rk.XML.stretch() ) raw.data.dep.groups.overlap <- rk.XML.varslot("Raw data (must be a data.frame)", source=raw.data.dep.groups.overlap.var.sel, classes=c("data.frame"), id.name="raw_data_dep_groups_overlap") raw.data.dep.groups.overlap.j <- rk.XML.varslot("Variable j", source=raw.data.dep.groups.overlap.var.sel, types="number", id.name="raw_data_dep_groups_overlap_j") raw.data.dep.groups.overlap.k <- rk.XML.varslot("Variable k", source=raw.data.dep.groups.overlap.var.sel, types="number", id.name="raw_data_dep_groups_overlap_k") raw.data.dep.groups.overlap.h <- rk.XML.varslot("Variable h", source=raw.data.dep.groups.overlap.var.sel, types="number", id.name="raw_data_dep_groups_overlap_h") raw.data.dep.groups.overlap.col <- rk.XML.col( rk.XML.text("To compare the correlations j ~ k and j ~ h, please provide a data.frame and select columns to specify the variables j, k, and h.<br />"), raw.data.dep.groups.overlap, raw.data.dep.groups.overlap.frame <- rk.XML.frame(raw.data.dep.groups.overlap.j, raw.data.dep.groups.overlap.k, raw.data.dep.groups.overlap.h, label="Correlations j ~ k and j ~ h", id.name="raw_data_dep_groups_overlap_frame"), rk.XML.stretch() ) raw.data.dep.groups.nonoverlap <- rk.XML.varslot("Raw data (must be a data.frame)", source=raw.data.dep.groups.nonoverlap.var.sel, classes=c("data.frame"), id.name="raw_data_dep_groups_nonoverlap") raw.data.dep.groups.nonoverlap.j <- rk.XML.varslot("Variable j", source=raw.data.dep.groups.nonoverlap.var.sel, types="number", id.name="raw_data_dep_groups_nonoverlap_j") raw.data.dep.groups.nonoverlap.k <- rk.XML.varslot("Variable k", source=raw.data.dep.groups.nonoverlap.var.sel, types="number", id.name="raw_data_dep_groups_nonoverlap_k") raw.data.dep.groups.nonoverlap.h <- rk.XML.varslot("Variable h", source=raw.data.dep.groups.nonoverlap.var.sel, types="number", id.name="raw_data_dep_groups_nonoverlap_h") raw.data.dep.groups.nonoverlap.m <- rk.XML.varslot("Variable m", source=raw.data.dep.groups.nonoverlap.var.sel, types="number", id.name="raw_data_dep_groups_nonoverlap_m") raw.data.dep.groups.nonoverlap.col <- rk.XML.col( rk.XML.text("To compare the correlations j ~ k and h ~ m, please provide a data.frame and select columns to specify the variables j, k, h, and m.<br />"), raw.data.dep.groups.nonoverlap, raw.data.dep.groups.nonoverlap.frame.1 <- rk.XML.frame(raw.data.dep.groups.nonoverlap.j, raw.data.dep.groups.nonoverlap.k, label="Correlation j ~ k", id.name="raw_data_dep_groups_nonoverlap_frame"), raw.data.dep.groups.nonoverlap.frame.2 <- rk.XML.frame(raw.data.dep.groups.nonoverlap.h, raw.data.dep.groups.nonoverlap.m, label="Correlation h ~ m", id.name="raw_data_dep_groups_nonoverlap_frame"), rk.XML.stretch() ) manual.indep.groups.r1.jk <- rk.XML.spinbox("Correlation r1.jk", min=-1, max=1, id.name="manual_indep_groups_r1_jk") manual.indep.groups.r2.hm <- rk.XML.spinbox("Correlation r2.hm", min=-1, max=1, id.name="manual_indep_groups_r2_hm") manual.indep.groups.n1 <- rk.XML.spinbox("Group size n1", min=3, real=FALSE, initial=30, id.name="manual_indep_groups_n1") manual.indep.groups.n2 <- rk.XML.spinbox("Group size n2", min=3, real=FALSE, initial=30, id.name="manual_indep_groups_n2") manual.indep.groups.cor.frame <- rk.XML.frame(manual.indep.groups.r1.jk, manual.indep.groups.r2.hm, label=text.correlations, id.name="manual_indep_groups_cor_frame") manual.indep.groups.group.size.frame <- rk.XML.frame(manual.indep.groups.n1, manual.indep.groups.n2, label=text.group.sizes, id.name="manual_indep_groups_group_size_frame") manual.indep.groups.frame <- rk.XML.frame(manual.indep.groups.cor.frame, manual.indep.groups.group.size.frame, label="", id.name="manual_indep_groups_frame") manual.dep.groups.overlap.r.jk <- rk.XML.spinbox("Correlation j ~ k", min=-1, max=1, id.name="manual_dep_groups_overlap_r_jk") manual.dep.groups.overlap.r.jh <- rk.XML.spinbox("Correlation j ~ h", min=-1, max=1, id.name="manual_dep_groups_overlap_r_jh") manual.dep.groups.overlap.r.kh <- rk.XML.spinbox("Correlation k ~ h", min=-1, max=1, id.name="manual_dep_groups_overlap_r_kh") manual.dep.groups.overlap.n <- rk.XML.spinbox("Group size n", min=3, real=FALSE, initial=30, id.name="manual_dep_groups_overlap_n") manual.dep.groups.overlap.cor.frame <- rk.XML.frame(manual.dep.groups.overlap.r.jk, manual.dep.groups.overlap.r.jh, label=text.correlations, id.name="manual_dep_groups_overlap_cor_frame") manual.dep.groups.overlap.related.cor.frame <- rk.XML.frame(text.related.correlation, manual.dep.groups.overlap.r.kh, id.name="manual_dep_groups_overlap_related_cor_frame") manual.dep.groups.overlap.group.size.frame <- rk.XML.frame(manual.dep.groups.overlap.n, label=text.group.size, id.name="manual_dep_groups_overlap_group_size_frame") manual.dep.groups.overlap.frame <- rk.XML.frame(manual.dep.groups.overlap.cor.frame, manual.dep.groups.overlap.related.cor.frame, manual.dep.groups.overlap.group.size.frame, label="", id.name="manual_dep_groups_overlap_frame") manual.dep.groups.nonoverlap.r.jk <- rk.XML.spinbox("Correlation j ~ k", min=-1, max=1, id.name="manual_dep_groups_nonoverlap_r_jk") manual.dep.groups.nonoverlap.r.hm <- rk.XML.spinbox("Correlation h ~ m", min=-1, max=1, id.name="manual_dep_groups_nonoverlap_r_hm") manual.dep.groups.nonoverlap.r.jh <- rk.XML.spinbox("Correlation j ~ h", min=-1, max=1, id.name="manual_dep_groups_nonoverlap_r_jh") manual.dep.groups.nonoverlap.r.jm <- rk.XML.spinbox("Correlation j ~ m", min=-1, max=1, id.name="manual_dep_groups_nonoverlap_r_jm") manual.dep.groups.nonoverlap.r.kh <- rk.XML.spinbox("Correlation k ~ h", min=-1, max=1, id.name="manual_dep_groups_nonoverlap_r_kh") manual.dep.groups.nonoverlap.r.km <- rk.XML.spinbox("Correlation k ~ m", min=-1, max=1, id.name="manual_dep_groups_nonoverlap_r_km") manual.dep.groups.nonoverlap.n <- rk.XML.spinbox("Group size n", min=3, real=FALSE, initial=30, id.name="manual_dep_groups_nonoverlap_n") manual.dep.groups.nonoverlap.cor.frame <- rk.XML.frame(manual.dep.groups.nonoverlap.r.jk, manual.dep.groups.nonoverlap.r.hm, label=text.correlations, id.name="manual_dep_groups_nonoverlap_cor_frame") manual.dep.groups.nonoverlap.related.cor.frame <- rk.XML.frame(text.related.correlations, manual.dep.groups.nonoverlap.r.jh, manual.dep.groups.nonoverlap.r.jm, manual.dep.groups.nonoverlap.r.kh, manual.dep.groups.nonoverlap.r.km, id.name="manual_dep_groups_nonoverlap_related_cor_frame") manual.dep.groups.nonoverlap.group.size.frame <- rk.XML.frame(manual.dep.groups.nonoverlap.n, label=text.group.size, id.name="manual_dep_groups_nonoverlap_group_size_frame") manual.dep.groups.nonoverlap.frame <- rk.XML.frame(manual.dep.groups.nonoverlap.cor.frame, manual.dep.groups.nonoverlap.related.cor.frame, manual.dep.groups.nonoverlap.group.size.frame, id.name="manual_dep_groups_nonoverlap_frame") variable.indep.groups.r1.jk <- rk.XML.varslot("Correlation r1.jk", source=var.sel, types="number", id.name="variable_indep_groups_r1_jk") variable.indep.groups.r2.hm <- rk.XML.varslot("Correlation r2.hm", source=var.sel, types="number", id.name="variable_indep_groups_r2_hm") variable.indep.groups.n1 <- rk.XML.varslot("Group size n1", source=var.sel, types="number", id.name="variable_indep_groups_n1") variable.indep.groups.n2 <- rk.XML.varslot("Group size n2", source=var.sel, types="number", id.name="variable_indep_groups_n2") variable.indep.groups.cor.frame <- rk.XML.frame(variable.indep.groups.r1.jk, variable.indep.groups.r2.hm, label=text.correlations, id.name="variable_indep_groups_cor_frame") variable.indep.groups.group.size.frame <- rk.XML.frame(variable.indep.groups.n1, variable.indep.groups.n2, label=text.group.sizes, id.name="variable_indep_groups_group_size_frame") variable.indep.groups.frame <- rk.XML.frame(variable.indep.groups.cor.frame, variable.indep.groups.group.size.frame, label="", id.name="variable_indep_groups_frame") variable.dep.groups.overlap.r.jk <- rk.XML.varslot("Correlation j ~ k", source=var.sel, types="number", id.name="variable_dep_groups_overlap_r_jk") variable.dep.groups.overlap.r.jh <- rk.XML.varslot("Correlation j ~ h", source=var.sel, types="number", id.name="variable_dep_groups_overlap_r_jh") variable.dep.groups.overlap.r.kh <- rk.XML.varslot("Correlation k ~ h", source=var.sel, types="number", id.name="variable_dep_groups_overlap_r_kh") variable.dep.groups.overlap.n <- rk.XML.varslot("Group size n", source=var.sel, types="number", id.name="variable_dep_groups_overlap_n") variable.dep.groups.overlap.cor.frame <- rk.XML.frame(variable.dep.groups.overlap.r.jk, variable.dep.groups.overlap.r.jh, label=text.correlations, id.name="variable_dep_groups_overlap_cor_frame") variable.dep.groups.overlap.related.cor.frame <- rk.XML.frame(text.related.correlation, variable.dep.groups.overlap.r.kh, id.name="variable_dep_groups_overlap_related_cor_frame") variable.dep.groups.overlap.group.size.frame <- rk.XML.frame(variable.dep.groups.overlap.n, label=text.group.size, id.name="variable_dep_groups_overlap_group_size_frame") variable.dep.groups.overlap.frame <- rk.XML.frame(variable.dep.groups.overlap.cor.frame, variable.dep.groups.overlap.related.cor.frame, variable.dep.groups.overlap.group.size.frame, label="", id.name="variable_dep_groups_overlap_frame") variable.dep.groups.nonoverlap.r.jk <- rk.XML.varslot("Correlation j ~ k", source=var.sel, types="number", id.name="variable_dep_groups_nonoverlap_r_jk") variable.dep.groups.nonoverlap.r.hm <- rk.XML.varslot("Correlation h ~ m", source=var.sel, types="number", id.name="variable_dep_groups_nonoverlap_r_hm") variable.dep.groups.nonoverlap.r.jh <- rk.XML.varslot("Correlation j ~ h", source=var.sel, types="number", id.name="variable_dep_groups_nonoverlap_r_jh") variable.dep.groups.nonoverlap.r.jm <- rk.XML.varslot("Correlation j ~ m", source=var.sel, types="number", id.name="variable_dep_groups_nonoverlap_r_jm") variable.dep.groups.nonoverlap.r.kh <- rk.XML.varslot("Correlation k ~ h", source=var.sel, types="number", id.name="variable_dep_groups_nonoverlap_r_kh") variable.dep.groups.nonoverlap.r.km <- rk.XML.varslot("Correlation k ~ m", source=var.sel, types="number", id.name="variable_dep_groups_nonoverlap_r_km") variable.dep.groups.nonoverlap.n <- rk.XML.varslot("Group size n", source=var.sel, types="number", id.name="variable_dep_groups_nonoverlap_n") variable.dep.groups.nonoverlap.cor.frame <- rk.XML.frame(variable.dep.groups.nonoverlap.r.jk, variable.dep.groups.nonoverlap.r.hm, label=text.correlations, id.name="variable_dep_groups_nonoverlap_cor_frame") variable.dep.groups.nonoverlap.related.cor.frame <- rk.XML.frame(text.related.correlations, variable.dep.groups.nonoverlap.r.jh, variable.dep.groups.nonoverlap.r.jm, variable.dep.groups.nonoverlap.r.kh, variable.dep.groups.nonoverlap.r.km, id.name="variable_dep_groups_nonoverlap_related_cor_frame") variable.dep.groups.nonoverlap.group.size.frame <- rk.XML.frame(variable.dep.groups.nonoverlap.n, label=text.group.size, id.name="variable_dep_groups_nonoverlap_group_size_frame") variable.dep.groups.nonoverlap.frame <- rk.XML.frame(variable.dep.groups.nonoverlap.cor.frame, variable.dep.groups.nonoverlap.related.cor.frame, variable.dep.groups.nonoverlap.group.size.frame, label="", id.name="variable_dep_groups_nonoverlap_frame") wizard.correlations.page <- rk.XML.page( id.name="wizard_correlations_page", rk.XML.text("Are the two correlations overlapping, i.e., do they have one variable in common?"), correlations, rk.XML.frame(label="Examples", rk.XML.text("Overlapping:<br />Correlation 1: age ~ intelligence<br />Correlation 2: age ~ shoe size<br /><br />These are overlapping correlations because the same variable 'age' is part of both correlations.<br /><br />Nonoverlapping:<br />Correlation 1: age ~ intelligence<br />Correlation 2: body mass index ~ shoe size<br /><br />These are nonoverlapping correlations because no variable is part of both correlations.<br /><br /><br />") ), rk.XML.stretch() ) raw.data.row2 <- rk.XML.row( rk.XML.col(raw.data.indep.groups.var.sel.2), raw.data.indep.groups.col.2 ) manual.and.variable.data.input.col <- rk.XML.col( manual.indep.groups.frame, manual.dep.groups.overlap.frame, manual.dep.groups.nonoverlap.frame, variable.indep.groups.frame, variable.dep.groups.overlap.frame, variable.dep.groups.nonoverlap.frame, rk.XML.stretch() ) wizard <- rk.XML.wizard( label="Comparing correlations", rk.XML.page( rk.XML.text("Are the two correlations based on two independent or on two dependent groups? (If the data were taken from measurements of the same individuals, the groups are dependent.)<br />"), groups, rk.XML.stretch() ), wizard.correlations.page, rk.XML.page( rk.XML.text("Do you want to calculate and compare correlations from raw data, are the correlations already available in single variables, or do you want to type the correlations in manually?"), data.input, rk.XML.stretch() ), rk.XML.page( rk.XML.col( rk.XML.row( rk.XML.col(var.sel,raw.data.indep.groups.var.sel.1,raw.data.dep.groups.overlap.var.sel,raw.data.dep.groups.nonoverlap.var.sel), raw.data.dep.groups.nonoverlap.col, raw.data.dep.groups.overlap.col, raw.data.indep.groups.col.1, manual.and.variable.data.input.col ), raw.data.row2 ) ), rk.XML.page( alpha.frame, conf.level.frame, null.value.frame, rk.XML.stretch() ), rk.XML.page( test.hypothesis.indep.groups, test.hypothesis.dep.groups.overlap, test.hypothesis.dep.groups.nonoverlap, test.hypothesis.indep.groups.null.value, test.hypothesis.dep.groups.overlap.null.value, test.hypothesis.dep.groups.nonoverlap.null.value, rk.XML.stretch() ) ) logic <- rk.XML.logic( raw.data.input.convert <- rk.XML.convert(sources=list(string=data.input), mode=c(equals="raw.data"), id.name="raw_data_input_convert"), manual.input.convert <- rk.XML.convert(sources=list(string=data.input), mode=c(equals="manual"), id.name="manual_input_convert"), variable.input.convert <- rk.XML.convert(sources=list(string=data.input), mode=c(equals="variable"), id.name="variable_input_convert"), indep.groups.convert <- rk.XML.convert(sources=list(string=groups), mode=c(equals="indep"), id.name="indep_groups_convert"), dep.groups.convert <- rk.XML.convert(sources=list(string=groups), mode=c(equals="dep"), id.name="dep_groups_convert"), overlap.correlations.convert <- rk.XML.convert(sources=list(string=correlations), mode=c(equals="overlap"), id.name="overlap_correlations_convert"), nonoverlap.correlations.convert <- rk.XML.convert(sources=list(string=correlations), mode=c(equals="nonoverlap"), id.name="nonoverlap_correlations_convert"), raw.data.indep.groups.1.convert <- rk.XML.convert(sources=list(available=raw.data.indep.groups.1), mode=c(notequals=""), id.name="raw_data_indep_groups_1_convert"), raw.data.indep.groups.2.convert <- rk.XML.convert(sources=list(available=raw.data.indep.groups.2), mode=c(notequals=""), id.name="raw_data_indep_groups_2_convert"), raw.data.dep.groups.overlap.convert <- rk.XML.convert(sources=list(available=raw.data.dep.groups.overlap), mode=c(notequals=""), id.name="raw_data_dep_groups_overlap_convert"), raw.data.dep.groups.nonoverlap.convert <- rk.XML.convert(sources=list(available=raw.data.dep.groups.nonoverlap), mode=c(notequals=""), id.name="raw_data_dep_groups_nonoverlap_convert"), null.value.is.zero.convert <- rk.XML.convert(sources=list(real=null.value), mode=c(min=-0.001, max=0.001), id.name="null_value_is_zero_convert"), null.value.is.greater.than.zero.convert <- rk.XML.convert(sources=list(real=null.value), mode=c(min=0.01, max=2.00), id.name="null_value_is_greater_than_zero_convert"), null.value.is.less.than.zero.convert <- rk.XML.convert(sources=list(real=null.value), mode=c(min=-2.00, max=-0.01), id.name="null_value_is_less_than_zero_convert"), null.value.is.not.zero.convert <- rk.XML.convert(sources=list(null.value.is.less.than.zero.convert, null.value.is.greater.than.zero.convert), mode=c(or=""), id.name="null_value_is_not_zero_convert"), manual.or.variable.input.convert <- rk.XML.convert(sources=list(manual.input.convert, variable.input.convert), mode=c(or=""), id.name="manual_or_variable_input_convert"), dep.groups.and.overlap.correlations.convert <- rk.XML.convert(sources=list(dep.groups.convert, overlap.correlations.convert), mode=c(and=""), id.name="dep_groups_and_overlap_correlations_convert"), dep.groups.and.nonoverlap.correlations.convert <- rk.XML.convert(sources=list(dep.groups.convert, nonoverlap.correlations.convert), mode=c(and=""), id.name="dep_groups_and_nonoverlap_correlations_convert"), indep.groups.and.null.value.is.zero.convert <- rk.XML.convert(sources=list(indep.groups.convert, null.value.is.zero.convert), mode=c(and=""), id.name="indep_groups_and_null_value_is_zero_convert"), dep.groups.and.overlap.correlations.and.null.value.is.zero.convert <- rk.XML.convert(sources=list(dep.groups.convert, overlap.correlations.convert, null.value.is.zero.convert), mode=c(and=""), id.name="dep_groups_and_overlap_correlations_and_null_value_is_zero_convert"), dep.groups.and.nonoverlap.correlations.and.null.value.is.zero.convert <- rk.XML.convert(sources=list(dep.groups.convert, nonoverlap.correlations.convert, null.value.is.zero.convert), mode=c(and=""), id.name="dep_groups_and_nonoverlap_correlations_and_null_value_is_zero_convert"), indep.groups.and.null.value.is.not.zero.convert <- rk.XML.convert(sources=list(indep.groups.convert, null.value.is.not.zero.convert), mode=c(and=""), id.name="indep_groups_and_null_value_is_not_zero_convert"), dep.groups.and.overlap.correlations.and.null.value.is.not.zero.convert <- rk.XML.convert(sources=list(dep.groups.convert, overlap.correlations.convert, null.value.is.not.zero.convert), mode=c(and=""), id.name="dep_groups_and_overlap_correlations_and_null_value_is_not_zero_convert"), dep.groups.and.nonoverlap.correlations.and.null.value.is.not.zero.convert <- rk.XML.convert(sources=list(dep.groups.convert, nonoverlap.correlations.convert, null.value.is.not.zero.convert), mode=c(and=""), id.name="dep_groups_and_nonoverlap_correlations_and_null_value_is_not_zero_convert"), raw.data.and.indep.groups.convert <- rk.XML.convert(sources=list(raw.data.input.convert, indep.groups.convert), mode=c(and=""), id.name="raw_data_and_indep_groups_convert"), raw.data.and.dep.groups.and.nonoverlap.correlations.convert <- rk.XML.convert(sources=list(raw.data.input.convert, dep.groups.convert, nonoverlap.correlations.convert), mode=c(and=""), id.name="raw_data_and_dep_groups_and_nonoverlap_correlations_convert"), raw.data.and.dep.groups.and.overlap.correlations.convert <- rk.XML.convert(sources=list(raw.data.input.convert, dep.groups.convert, overlap.correlations.convert), mode=c(and=""), id.name="raw_data_and_dep_groups_and_overlap_correlations_convert"), manual.and.indep.groups.convert <- rk.XML.convert(sources=list(manual.input.convert, indep.groups.convert), mode=c(and=""), id.name="manual_and_indep_groups_convert"), manual.and.dep.groups.and.nonoverlap.correlations.convert <- rk.XML.convert(sources=list(manual.input.convert, dep.groups.convert, nonoverlap.correlations.convert), mode=c(and=""), id.name="manual_and_dep_groups_and_nonoverlap_correlations_convert"), manual.and.dep.groups.and.overlap.correlations.convert <- rk.XML.convert(sources=list(manual.input.convert, dep.groups.convert, overlap.correlations.convert), mode=c(and=""), id.name="manual_and_dep_groups_and_overlap_correlations_convert"), variable.and.indep.groups.convert <- rk.XML.convert(sources=list(variable.input.convert, indep.groups.convert), mode=c(and=""), id.name="variable_and_indep_groups_convert"), variable.and.dep.groups.and.nonoverlap.correlations.convert <- rk.XML.convert(sources=list(variable.input.convert, dep.groups.convert, nonoverlap.correlations.convert), mode=c(and=""), id.name="variable_and_dep_groups_and_nonoverlap_correlations_convert"), variable.and.dep.groups.and.overlap.correlations.convert <- rk.XML.convert(sources=list(variable.input.convert, dep.groups.convert, overlap.correlations.convert), mode=c(and=""), id.name="variable_and_dep_groups_and_overlap_correlations_convert"), rk.XML.connect(governor=manual.or.variable.input.convert, client=manual.and.variable.data.input.col, set="visible"), rk.XML.connect(governor=manual.and.indep.groups.convert, client=manual.indep.groups.frame, set="visible"), rk.XML.connect(governor=manual.and.dep.groups.and.nonoverlap.correlations.convert, client=manual.dep.groups.nonoverlap.frame, set="visible"), rk.XML.connect(governor=manual.and.dep.groups.and.overlap.correlations.convert, client=manual.dep.groups.overlap.frame, set="visible"), rk.XML.connect(governor=variable.and.indep.groups.convert, client=variable.indep.groups.frame, set="visible"), rk.XML.connect(governor=variable.and.dep.groups.and.nonoverlap.correlations.convert, client=variable.dep.groups.nonoverlap.frame, set="visible"), rk.XML.connect(governor=variable.and.dep.groups.and.overlap.correlations.convert, client=variable.dep.groups.overlap.frame, set="visible"), rk.XML.connect(governor=indep.groups.and.null.value.is.zero.convert, client=test.hypothesis.indep.groups, set="visible"), rk.XML.connect(governor=dep.groups.and.overlap.correlations.and.null.value.is.zero.convert, client=test.hypothesis.dep.groups.overlap, set="visible"), rk.XML.connect(governor=dep.groups.and.nonoverlap.correlations.and.null.value.is.zero.convert, client=test.hypothesis.dep.groups.nonoverlap, set="visible"), rk.XML.connect(governor=indep.groups.and.null.value.is.not.zero.convert, client=test.hypothesis.indep.groups.null.value, set="visible"), rk.XML.connect(governor=dep.groups.and.overlap.correlations.and.null.value.is.not.zero.convert, client=test.hypothesis.dep.groups.overlap.null.value, set="visible"), rk.XML.connect(governor=dep.groups.and.nonoverlap.correlations.and.null.value.is.not.zero.convert, client=test.hypothesis.dep.groups.nonoverlap.null.value, set="visible"), rk.XML.connect(governor=variable.input.convert, client=var.sel, set="visible"), rk.XML.connect(governor=dep.groups.convert, client=wizard.correlations.page, set="visible"), rk.XML.connect(governor=raw.data.and.indep.groups.convert, client=raw.data.indep.groups.var.sel.1, set="visible"), rk.XML.connect(governor=raw.data.and.indep.groups.convert, client=raw.data.row2, set="visible"), rk.XML.connect(governor=raw.data.and.indep.groups.convert, client=raw.data.indep.groups.col.1, set="visible"), rk.XML.connect(governor=raw.data.indep.groups.1.convert, client=raw.data.indep.groups.j, set="enabled"), rk.XML.connect(governor=raw.data.indep.groups.1.convert, client=raw.data.indep.groups.k, set="enabled"), rk.XML.connect(governor=raw.data.indep.groups.2.convert, client=raw.data.indep.groups.h, set="enabled"), rk.XML.connect(governor=raw.data.indep.groups.2.convert, client=raw.data.indep.groups.m, set="enabled"), rk.XML.connect(governor=raw.data.and.dep.groups.and.overlap.correlations.convert, client=raw.data.dep.groups.overlap.var.sel, set="visible"), rk.XML.connect(governor=raw.data.and.dep.groups.and.overlap.correlations.convert, client=raw.data.dep.groups.overlap.col, set="visible"), rk.XML.connect(governor=raw.data.dep.groups.overlap.convert, client=raw.data.dep.groups.overlap.j, set="enabled"), rk.XML.connect(governor=raw.data.dep.groups.overlap.convert, client=raw.data.dep.groups.overlap.k, set="enabled"), rk.XML.connect(governor=raw.data.dep.groups.overlap.convert, client=raw.data.dep.groups.overlap.h, set="enabled"), rk.XML.connect(governor=raw.data.and.dep.groups.and.nonoverlap.correlations.convert, client=raw.data.dep.groups.nonoverlap.var.sel, set="visible"), rk.XML.connect(governor=raw.data.and.dep.groups.and.nonoverlap.correlations.convert, client=raw.data.dep.groups.nonoverlap.col, set="visible"), rk.XML.connect(governor=raw.data.dep.groups.nonoverlap.convert, client=raw.data.dep.groups.nonoverlap.j, set="enabled"), rk.XML.connect(governor=raw.data.dep.groups.nonoverlap.convert, client=raw.data.dep.groups.nonoverlap.k, set="enabled"), rk.XML.connect(governor=raw.data.dep.groups.nonoverlap.convert, client=raw.data.dep.groups.nonoverlap.h, set="enabled"), rk.XML.connect(governor=raw.data.dep.groups.nonoverlap.convert, client=raw.data.dep.groups.nonoverlap.m, set="enabled"), rk.XML.connect(governor=raw.data.and.indep.groups.convert, client=raw.data.indep.groups.1, set="required"), rk.XML.connect(governor=raw.data.and.indep.groups.convert, client=raw.data.indep.groups.2, set="required"), rk.XML.connect(governor=raw.data.and.indep.groups.convert, client=raw.data.indep.groups.j, set="required"), rk.XML.connect(governor=raw.data.and.indep.groups.convert, client=raw.data.indep.groups.k, set="required"), rk.XML.connect(governor=raw.data.and.indep.groups.convert, client=raw.data.indep.groups.h, set="required"), rk.XML.connect(governor=raw.data.and.indep.groups.convert, client=raw.data.indep.groups.m, set="required"), rk.XML.connect(governor=raw.data.and.dep.groups.and.overlap.correlations.convert, client=raw.data.dep.groups.overlap, set="required"), rk.XML.connect(governor=raw.data.and.dep.groups.and.overlap.correlations.convert, client=raw.data.dep.groups.overlap.j, set="required"), rk.XML.connect(governor=raw.data.and.dep.groups.and.overlap.correlations.convert, client=raw.data.dep.groups.overlap.k, set="required"), rk.XML.connect(governor=raw.data.and.dep.groups.and.overlap.correlations.convert, client=raw.data.dep.groups.overlap.h, set="required"), rk.XML.connect(governor=raw.data.and.dep.groups.and.nonoverlap.correlations.convert, client=raw.data.dep.groups.nonoverlap, set="required"), rk.XML.connect(governor=raw.data.and.dep.groups.and.nonoverlap.correlations.convert, client=raw.data.dep.groups.nonoverlap.j, set="required"), rk.XML.connect(governor=raw.data.and.dep.groups.and.nonoverlap.correlations.convert, client=raw.data.dep.groups.nonoverlap.k, set="required"), rk.XML.connect(governor=raw.data.and.dep.groups.and.nonoverlap.correlations.convert, client=raw.data.dep.groups.nonoverlap.h, set="required"), rk.XML.connect(governor=raw.data.and.dep.groups.and.nonoverlap.correlations.convert, client=raw.data.dep.groups.nonoverlap.m, set="required"), rk.XML.connect(governor=variable.and.indep.groups.convert, client=variable.indep.groups.r1.jk, set="required"), rk.XML.connect(governor=variable.and.indep.groups.convert, client=variable.indep.groups.n1, set="required"), rk.XML.connect(governor=variable.and.indep.groups.convert, client=variable.indep.groups.r2.hm, set="required"), rk.XML.connect(governor=variable.and.indep.groups.convert, client=variable.indep.groups.n2, set="required"), rk.XML.connect(governor=variable.and.dep.groups.and.overlap.correlations.convert, client=variable.dep.groups.overlap.r.jk, set="required"), rk.XML.connect(governor=variable.and.dep.groups.and.overlap.correlations.convert, client=variable.dep.groups.overlap.r.jh, set="required"), rk.XML.connect(governor=variable.and.dep.groups.and.overlap.correlations.convert, client=variable.dep.groups.overlap.r.kh, set="required"), rk.XML.connect(governor=variable.and.dep.groups.and.overlap.correlations.convert, client=variable.dep.groups.overlap.n, set="required"), rk.XML.connect(governor=variable.and.dep.groups.and.nonoverlap.correlations.convert, client=variable.dep.groups.nonoverlap.r.jk, set="required"), rk.XML.connect(governor=variable.and.dep.groups.and.nonoverlap.correlations.convert, client=variable.dep.groups.nonoverlap.r.hm, set="required"), rk.XML.connect(governor=variable.and.dep.groups.and.nonoverlap.correlations.convert, client=variable.dep.groups.nonoverlap.r.jh, set="required"), rk.XML.connect(governor=variable.and.dep.groups.and.nonoverlap.correlations.convert, client=variable.dep.groups.nonoverlap.r.jm, set="required"), rk.XML.connect(governor=variable.and.dep.groups.and.nonoverlap.correlations.convert, client=variable.dep.groups.nonoverlap.r.kh, set="required"), rk.XML.connect(governor=variable.and.dep.groups.and.nonoverlap.correlations.convert, client=variable.dep.groups.nonoverlap.r.km, set="required"), rk.XML.connect(governor=variable.and.dep.groups.and.nonoverlap.correlations.convert, client=variable.dep.groups.nonoverlap.n, set="required"), rk.XML.connect(governor="current_object", client=raw.data.indep.groups.1, set="available"), rk.XML.connect(governor="current_object", client=raw.data.indep.groups.2, set="available"), rk.XML.connect(governor="current_object", client=raw.data.dep.groups.overlap, set="available"), rk.XML.connect(governor="current_object", client=raw.data.dep.groups.nonoverlap, set="available"), rk.XML.connect(governor=raw.data.indep.groups.1, client=raw.data.indep.groups.var.sel.1, get="available", set="root"), rk.XML.connect(governor=raw.data.indep.groups.2, client=raw.data.indep.groups.var.sel.2, get="available", set="root"), rk.XML.connect(governor=raw.data.dep.groups.overlap, client=raw.data.dep.groups.overlap.var.sel, get="available", set="root"), rk.XML.connect(governor=raw.data.dep.groups.nonoverlap, client=raw.data.dep.groups.nonoverlap.var.sel, get="available", set="root") ) JS.calc <- rk.paste.JS( jsVar.raw.data.indep.groups.j <- rk.JS.vars(raw.data.indep.groups.j, modifiers="shortname"), jsVar.raw.data.indep.groups.k <- rk.JS.vars(raw.data.indep.groups.k, modifiers="shortname"), jsVar.raw.data.indep.groups.h <- rk.JS.vars(raw.data.indep.groups.h, modifiers="shortname"), jsVar.raw.data.indep.groups.m <- rk.JS.vars(raw.data.indep.groups.m, modifiers="shortname"), ite(id(data.input, " == 'raw.data' && ", groups, " == 'indep'"), echo("result <- cocor(~", jsVar.raw.data.indep.groups.j, " + ", jsVar.raw.data.indep.groups.k, " | ", jsVar.raw.data.indep.groups.h, " + ", jsVar.raw.data.indep.groups.m, ", data=list(", raw.data.indep.groups.1, ",", raw.data.indep.groups.2, ")")), jsVar.raw.data.dep.groups.overlap.j <- rk.JS.vars(raw.data.dep.groups.overlap.j, modifiers="shortname"), jsVar.raw.data.dep.groups.overlap.k <- rk.JS.vars(raw.data.dep.groups.overlap.k, modifiers="shortname"), jsVar.raw.data.dep.groups.overlap.h <- rk.JS.vars(raw.data.dep.groups.overlap.h, modifiers="shortname"), ite(id(data.input, " == 'raw.data' && ", groups, " == 'dep' && ", correlations, " == 'overlap'"), echo("result <- cocor(~", jsVar.raw.data.dep.groups.overlap.j, " + ", jsVar.raw.data.dep.groups.overlap.k, " | ", jsVar.raw.data.dep.groups.overlap.j, " + ", jsVar.raw.data.dep.groups.overlap.h, ", data=", raw.data.dep.groups.overlap)), jsVar.raw.data.dep.groups.nonoverlap.j <- rk.JS.vars(raw.data.dep.groups.nonoverlap.j, modifiers="shortname"), jsVar.raw.data.dep.groups.nonoverlap.k <- rk.JS.vars(raw.data.dep.groups.nonoverlap.k, modifiers="shortname"), jsVar.raw.data.dep.groups.nonoverlap.h <- rk.JS.vars(raw.data.dep.groups.nonoverlap.h, modifiers="shortname"), jsVar.raw.data.dep.groups.nonoverlap.m <- rk.JS.vars(raw.data.dep.groups.nonoverlap.m, modifiers="shortname"), ite(id(data.input, " == 'raw.data' && ", groups, " == 'dep' && ", correlations, " == 'nonoverlap'"), echo("result <- cocor(~", jsVar.raw.data.dep.groups.nonoverlap.j, " + ", jsVar.raw.data.dep.groups.nonoverlap.k, " | ", jsVar.raw.data.dep.groups.nonoverlap.h, " + ", jsVar.raw.data.dep.groups.nonoverlap.m, ", data=", raw.data.dep.groups.nonoverlap)), ite(id(data.input, " == 'manual' && ", groups, " == 'indep'"), echo("result <- cocor.indep.groups(r1.jk=", manual.indep.groups.r1.jk, ", n1=", manual.indep.groups.n1, ", r2.hm=", manual.indep.groups.r2.hm, ", n2=", manual.indep.groups.n2)), ite(id(data.input, " == 'manual' && ", groups, " == 'dep' && ", correlations, " == 'overlap'"), echo("result <- cocor.dep.groups.overlap(r.jk=", manual.dep.groups.overlap.r.jk, ", r.jh=", manual.dep.groups.overlap.r.jh, ", r.kh=", manual.dep.groups.overlap.r.kh, ", n=", manual.dep.groups.overlap.n)), ite(id(data.input, " == 'manual' && ", groups, " == 'dep' && ", correlations, " == 'nonoverlap'"), echo("result <- cocor.dep.groups.nonoverlap(r.jk=", manual.dep.groups.nonoverlap.r.jk, ", r.hm=", manual.dep.groups.nonoverlap.r.hm, ", r.jh=", manual.dep.groups.nonoverlap.r.jh, ", r.jm=", manual.dep.groups.nonoverlap.r.jm, ", r.kh=", manual.dep.groups.nonoverlap.r.kh, ", r.km=", manual.dep.groups.nonoverlap.r.km,", n=", manual.dep.groups.nonoverlap.n)), ite(id(data.input, " == 'variable' && ", groups, " == 'indep'"), echo("result <- cocor.indep.groups(r1.jk=", variable.indep.groups.r1.jk, ", n1=", variable.indep.groups.n1, ", r2.hm=", variable.indep.groups.r2.hm, ", n2=", variable.indep.groups.n2)), ite(id(data.input, " == 'variable' && ", groups, " == 'dep' && ", correlations, " == 'overlap'"), echo("result <- cocor.dep.groups.overlap(r.jk=", variable.dep.groups.overlap.r.jk, ", r.jh=", variable.dep.groups.overlap.r.jh, ", r.kh=", variable.dep.groups.overlap.r.kh, ", n=", variable.dep.groups.overlap.n)), ite(id(data.input, " == 'variable' && ", groups, " == 'dep' && ", correlations, " == 'nonoverlap'"), echo("result <- cocor.dep.groups.nonoverlap(r.jk=", variable.dep.groups.nonoverlap.r.jk, ", r.hm=", variable.dep.groups.nonoverlap.r.hm, ", r.jh=", variable.dep.groups.nonoverlap.r.jh, ", r.jm=", variable.dep.groups.nonoverlap.r.jm, ", r.kh=", variable.dep.groups.nonoverlap.r.kh, ", r.km=", variable.dep.groups.nonoverlap.r.km,", n=", variable.dep.groups.nonoverlap.n)), ite(id(groups, " == 'indep' && ", null.value, " == 0"), echo(", alternative=\"", test.hypothesis.indep.groups, "\"")), ite(id(groups, " == 'indep' && ", null.value, " != 0"), echo(", alternative=\"", test.hypothesis.indep.groups.null.value, "\"")), ite(id(groups, " == 'dep' && ", correlations, " == 'overlap' && ", null.value, " == 0"), echo(", alternative=\"", test.hypothesis.dep.groups.overlap, "\"")), ite(id(groups, " == 'dep' && ", correlations, " == 'overlap' && ", null.value, " != 0"), echo(", alternative=\"", test.hypothesis.dep.groups.overlap.null.value, "\"")), ite(id(groups, " == 'dep' && ", correlations, " == 'nonoverlap' && ", null.value, " == 0"), echo(", alternative=\"", test.hypothesis.dep.groups.nonoverlap, "\"")), ite(id(groups, " == 'dep' && ", correlations, " == 'nonoverlap' && ", null.value, " != 0"), echo(", alternative=\"", test.hypothesis.dep.groups.nonoverlap.null.value, "\"")), ite(id(null.value, " != 0"), echo(", test=\"zou2007\"")), echo(", alpha=", alpha, ", conf.level=", conf.level, ", null.value=", null.value, ")\n"), level=2 ) JS.print <- rk.paste.JS(echo("rk.print(result)\n"), level=2) rkh <- list( summary=rk.rkh.summary(text="Compare two correlation coefficients based on either independent or dependent groups (e.g., same group)."), sections=list( groups=rk.rkh.section(title="Step 1", text="Indicate if the correlations are based on independent or dependent groups."), correlations=rk.rkh.section(title="Step 2", text="If the correlation are based on dependent groups, state whether or not the correlations are overlapping and have one variable in common."), data.input=rk.rkh.section(title="Step 3", text="Choose whether you want to calculate the correlations from raw data, type in the correlation coefficients manually, or retrieve them from existing variables."), data=rk.rkh.section(title="Step 4", text="Enter the data."), test.hypothesis.indep.groups1=rk.rkh.section(title="Step 5", text="Select an alpha level and a confidence level. Specify the null value, i.e., the hypothesized difference between the two correlations used for testing the null hypothesis. If the null value is other than 0, only the test by Zou (2007) is available."), test.hypothesis.indep.groups2=rk.rkh.section(title="Step 6", text="Choose if the test should be one- or two-sided."), code=rk.rkh.section(title="Step 7", text="Copy and paste the generated code to your R script or directly run the code.") ) ) plugin.dir <<- rk.plugin.skeleton( about.node, path=output.dir, provides=c("logic", "wizard"), xml=list(logic=logic, wizard=wizard), rkh=rkh, js=list( require="cocor", results.header="\"Comparing correlations\"", calculate=JS.calc, printout=JS.print ), pluginmap=list(name="Comparing correlations", hierarchy=list("analysis", "correlation")), dependencies=dependencies.node, load=TRUE, overwrite=overwrite ) })
fig_wrap <- function(figs, tag = NULL, prefix = NULL, suffix = NULL, pos = "topleft", x_nudge = 0, y_nudge = 0, nrow = NULL, ncol = NULL, colour = NULL, alpha = NULL, hjust = NULL, vjust = NULL, fontsize = NULL, fontfamily = NULL, fontface = NULL, b_col = NULL, b_size = 1, b_pos = "offset", b_margin = ggplot2::margin(4, 4, 4, 4)) { if (!is.list(figs)) { stop("figs must be a list of figs created by fig().") } num_figs <- length(figs) if (!is.null(tag)) { if (length(tag) > 1) { if (length(tag) != length(figs)) { stop("If providing a tag vector, it must be of equal length to the number of figs.") } } else if (grepl("[[:upper:]]", tag)) { start_let <- grep(tag, LETTERS) tags <- LETTERS[seq(start_let, start_let + num_figs)] } else if (grepl("[[:lower:]]", tag)) { start_let <- grep(tag, letters) tags <- letters[seq(start_let, start_let + num_figs)] } else if (is.numeric(tag)) { tags <- seq(tag, tag + num_figs) } } if (!is.null(tag)) { tags <- paste0(prefix, tags, suffix) } else { tags <- NULL } figs <- lapply(seq_along(figs), function(x) { if (is.null(tags)) { fig <- figs[[x]] } else { fig <- fig_tag( plot = figs[[x]], tag = tags[x], pos = pos, x_nudge = repeat_value(x_nudge, num_figs, int = x), y_nudge = repeat_value(y_nudge, num_figs, int = x), colour = repeat_value(colour, num_figs, int = x), alpha = repeat_value(alpha, num_figs, int = x), hjust = repeat_value(hjust, num_figs, int = x), vjust = repeat_value(vjust, num_figs, int = x), fontsize = repeat_value(fontsize, num_figs, int = x), fontfamily = repeat_value(fontfamily, num_figs, int = x), fontface = repeat_value(fontface, num_figs, int = x) ) } fig <- fig_borders( fig = fig, b_col = repeat_value(b_col, num_figs, int = x), b_pos = repeat_value(b_pos, num_figs, int = x), b_size = repeat_value(b_size, num_figs, int = x) ) if (!is.null(b_margin)) { fig <- fig + ggplot2::theme( plot.margin = b_margin ) } fig }) patchwork::wrap_plots(figs, ncol = ncol, nrow = nrow) }
zipsae <- function(data, vardir, formula, PRECISION = 1e-04, MAXITER = 100 ){ if(missing(data)){ stop("Data argument is missing") } if (length(formula)==0){ stop("Please insert your formula for fitted model") } if (missing(vardir)){ stop("vardir argument is missing") } hasil <- list(estimate = NA, dispersion = list(rse = NA), coefficient = list(lambda = NA, omega = NA ) ) reml <- function(X, Y, vardir, MAXITER){ PRECISION = 1e-04 REML_tmp <- 0 REML_tmp[1] <- mean(vardir) k <- 0 acc <- PRECISION + 1 while ((acc > PRECISION) & (k < MAXITER)) { k <- k + 1 Psi <- 1/(REML_tmp[k] + vardir) PsiXt <- t(Psi * X) Q <- solve(PsiXt %*% X) P <- diag(Psi) - t(PsiXt) %*% Q %*% PsiXt Py <- P %*% Y s <- (-0.5) * sum(diag(P)) + 0.5 * (t(Py) %*% Py) Fis <- 0.5 * sum(diag(P %*% P)) REML_tmp[k + 1] <- REML_tmp[k] + s/Fis acc <- abs((REML_tmp[k + 1] - REML_tmp[k])/REML_tmp[k]) } REML <- max(REML_tmp[k + 1], 0) return(REML) } m_data = model.frame(formula, na.action = na.omit ,data) Xz <- model.matrix(formula, m_data) Xz <- as.numeric(Xz[,-1]) Xnz <- Xz Y <- m_data[, 1] ToOmit <- c() dataLength <- nrow(data) for (i in 1:dataLength) { if (Y[i] == 0) { ToOmit <- c(ToOmit, i) } } if (length(ToOmit) != 0) { Xnz <- Xz[-ToOmit] Ynz <- Y[-ToOmit] vardirNz <- vardir[-ToOmit] }else{ Xnz <- Xz Ynz <- Y vardirNz <- vardir } b.REMLz <- reml(Xz, Y, vardir, MAXITER) a.REMLnz <- reml(Xnz, Ynz, vardirNz, MAXITER) Vnz <- 1/(a.REMLnz + vardirNz) Vz <- 1/(b.REMLz + vardir) Xnz_tmp <- t(Vnz*Xnz) Xz_tmp <- t(Vz*Xz) Qnz <- solve(Xnz_tmp%*%Xnz) Qz <- solve(Xz_tmp%*%Xz) beta.nz <- Qnz%*%Xnz_tmp%*%Ynz beta.z <- Qz%*%Xz_tmp%*%Y X_beta.nz <- Xnz%*%beta.nz X_beta.z <- Xz%*%beta.z residNz <- Ynz - X_beta.nz residZ <- Y - X_beta.z lamda = exp((Xz%*%beta.nz) + as.vector(a.REMLnz*(Vnz%*%residNz))) logit = exp(X_beta.z + as.vector(b.REMLz*(Vz%*%residZ))) omega = (logit/(1 + logit)) delta = 1-omega est <- lamda*delta est - mean(est) -> diff_tmp (diff_tmp)^2 -> diff_tmp_squared sqrt(diff_tmp_squared)/est -> rse_tmp hasil$estimate <- est hasil$dispersion$rse <- rse_tmp hasil$coefficient$lambda <- lamda hasil$coefficient$omega <- omega return(hasil) }
findFeasibleMatrix_targetmean <- function(r,c,p,eps=1e-9,targetmean=0.3){ Lorig <- findFeasibleMatrix(r=r,c=c,p=p,eps=eps) if (mean(Lorig>0)<targetmean){ avgavailable <- mean(p>0) psample <- min(1,(targetmean-mean(Lorig>0))/avgavailable) Adjstart <- matrix(rbinom(length(r)*length(c), size=1, prob=psample*(p>0)), nrow=length(r), ncol=length(c) ) maxsaveval <- pmin(matrix(r/pmax(1,rowSums(Adjstart)),nrow=length(r),ncol=length(c)), matrix(c/pmax(1,colSums(Adjstart)),nrow=length(r),ncol=length(c),byrow=TRUE)) Lstart <- matrix(runif(length(r)*length(c))*maxsaveval,nrow=length(r))*Adjstart Lstart+findFeasibleMatrix(r=r-rowSums(Lstart),c=c-colSums(Lstart),p=p,eps=eps) }else{ warning("Desired mean degree is less than minimal degree that is necessary."); Lorig } } getfeasibleMatr <- function(L,A){ if (min(L,A)<0) stop("L and A must be nonnegative.") if (abs(sum(L)-sum(A))>1e-10) stop("sum(L) different to sum(A).") if (max(A+L)>sum(L)) stop("No feasible matrix exists: max(A+L)>sum(L)") Lorig <- L; Aorig <- A n <- length(L) resall <- matrix(0,nrow=n,ncol=n) while(sum(L)>1e-10&&sum(A)>1e-10){ if (min(ifelse(A>0,A,Inf))<min(ifelse(L>0,L,Inf))){ transp <- TRUE Atmp <- A A <- L L <- Atmp }else{ transp <- FALSE } i <- which.min(ifelse(L>0,L,Inf)) LA <- ifelse(A>0,L+A,0) LA[i] <- Inf o <- order(LA,decreasing=TRUE) L <- L[o] A <- A[o] LA <- LA[o] xi=max(which((LA)[-1]==(LA)[2])) if (xi+1==n) Delta <- min(L[1],xi*(LA)[2]) else Delta <- min(L[1],xi*((LA)[2]-(LA)[2+xi])) res <- matrix(0,nrow=n,ncol=n) res[1,2:(1+xi)]=Delta/xi L[1] <- L[1]-Delta A[2:(1+xi)] <- A[2:(1+xi)]-Delta/xi res[o,o] <- res if (transp)res <- t(res) resall <- resall+res A[o] <- A L[o] <- L if (transp){ Atmp <- A A <- L L <- Atmp } } if (any(abs(rowSums(resall)-Lorig)>1e-9)||any(abs(colSums(resall)-Aorig)>1e-9)){ warning("Discrepancy between intended row/column sums and ", "row/column sums of generated matrix detected. ", "This may only be a numerical issue. ", "Maximum absolute difference between row and column sums: ", max(abs(rowSums(resall)-Lorig),abs(colSums(resall)-Aorig))) } resall }
chainsawSliver = function(downLog, sect, gLog, nSegs = 25, runQuiet = TRUE, ... ) { if(!(is(downLog,'downLog') || !validObject(downLog)) ) stop('***>Invalid "downLog" object passed!') trMat = transfMatrix(downLog@logAngle, coordinates(downLog@location)) trMatInv = solve(trMat) logLen = downLog@logLen buttDiam = downLog@buttDiam topDiam = downLog@topDiam solidType = downLog@solidType halfLen = logLen/2 log = as(gLog, 'matrix') log = cbind(log, rep(1, nrow(log)) ) dn = dimnames(log) log = log %*% trMatInv dimnames(log) = dn log[,'x'] = log[,'x'] + halfLen sect = cbind(sect, rep(1, nrow(sect)) ) sect = sect %*% trMatInv dimnames(sect) = dn sect[,'x'] = sect[,'x'] + halfLen gSect = as(sect[,-3],'gpc.poly') sectArea = rgeos::area.poly(gSect) sectLens = range(sect[,'x']) if(sectLens[1] < 0) sectLens[1] = 0 if(sectLens[2] > logLen) sectLens[2] = logLen boltLen = sectLens[2] - sectLens[1] length = seq(sectLens[1], sectLens[2], len=nSegs) if(!is.null(solidType)) { taper = .StemEnv$wbTaper(buttDiam, topDiam, logLen, nSegs=nSegs, solidType, length) diameter = taper$diameter } else { diameter = taperInterpolate(downLog, 'diameter', length) taper = data.frame(diameter, length) } rad = diameter/2 profile = data.frame( rad = c(-rad, rev(rad)) ) profile$length = c(length, rev(length)) profile = rbind(profile, profile[1,]) np = nrow(profile) rotBolt = profile rotBolt$hc = rep(1, np) rotBolt = as.matrix(rotBolt) trMat = transfMatrix(offset = c(0,-halfLen)) rotBolt = rotBolt %*% trMat trMat = transfMatrix(angle = -pi/2) rotBolt = rotBolt %*% trMat trMat = transfMatrix(downLog@logAngle, offset = coordinates(downLog@location)) rotBolt = rotBolt %*% trMat dimnames(rotBolt) = list(NULL, c('x','y','hc')) gBolt = as(rotBolt[,-3], 'gpc.poly') boltArea = rgeos::area.poly(gBolt) propArea = sectArea/boltArea if(!is.null(solidType)) { boltVol = .StemEnv$wbVolume(buttDiam, topDiam, logLen, solidType, sectLens[2]) - .StemEnv$wbVolume(buttDiam, topDiam, logLen, solidType, sectLens[1]) boltSA = .StemEnv$wbSurfaceArea(buttDiam, topDiam, logLen, solidType, sectLens[1], sectLens[2]) boltCA = .StemEnv$wbCoverageArea(buttDiam, topDiam, logLen, solidType, sectLens[1], sectLens[2]) } else { boltVol = .StemEnv$SmalianVolume(taper)$logVol boltSA = .StemEnv$splineSurfaceArea(taper, sectLens[1], sectLens[2]) boltCA = .StemEnv$splineCoverageArea(taper, sectLens[1], sectLens[2]) } sectVol = propArea*boltVol sectSA = propArea*boltSA sectCA = propArea*boltCA boltBms = boltVol*downLog@conversions['volumeToWeight'] sectBms = propArea*boltBms boltCarbon = boltBms*downLog@conversions['weightToCarbon'] sectCarbon = propArea*boltCarbon if(!runQuiet) { cat('\nPercentage sliver is of bolt area =', propArea*100) cat('\nBolt volume (not expanded) =', boltVol) cat('\nSection/sliver volume (not expanded) =', sectVol) cat('\n') } z = list( rotBolt = rotBolt, boltVol = boltVol, sectVol = sectVol, area = c(propArea=propArea, boltArea=boltArea, sectArea=sectArea), boltLen = boltLen, boltSA = boltSA, sectSA = sectSA, boltCA = boltCA, sectCA = sectCA, boltBms = boltBms, sectBms = sectBms, boltCarbon = boltCarbon, sectCarbon = sectCarbon ) return(z) }
context("graphics") test_that("plot", { testImage <- "/working/base_graphics_test.jpg" jpeg(testImage) plot(runif(10)) dev.off() expect_true(file.exists(testImage)) })
s2_unprojection_filter <- function(handler, projection = s2_projection_plate_carree(), tessellate_tol = Inf) { wk::new_wk_handler( .Call(c_s2_coord_filter_new, handler, projection, TRUE, tessellate_tol), subclass = "s2_coord_filter" ) } s2_projection_filter <- function(handler, projection = s2_projection_plate_carree(), tessellate_tol = Inf) { wk::new_wk_handler( .Call(c_s2_coord_filter_new, handler, projection, FALSE, tessellate_tol), subclass = "s2_coord_filter" ) } s2_projection_plate_carree <- function() { .Call(c_s2_projection_plate_carree) } s2_projection_mercator <- function() { .Call(c_s2_projection_mercator) }
get_all_params(poped.db)
CurtBinomial= function(n, Ac, p=seq(0, 0.5, .01), Plots=TRUE) { q=1-p ASN.full = pbinom(Ac, n+1, p)*((n-Ac)/(n*q)) +(1-pbinom(Ac+1, n+1, p))*((Ac+1)/(n*p)) ASN.full=n*ASN.full ASN.semi = pbinom(Ac, n, p) +(1-pbinom(Ac+1, n+1, p))*((Ac+1)/(n*p)) ASN.semi=n*ASN.semi if(any(p==0)){ ASN.semi[p==0] = n ASN.full[p==0] = n-Ac } results=list(p=p, ASN.semi=ASN.semi, ASN.full=ASN.full, n=n) class(results)="CurtSampPlan" if(Plots){ plot(results) } return(results) }
library(testthat) context("Properties") test_that("construction", { expect_error(Properties$new(cardinality = "c"), "Cardinality must either") expect_equal(Properties$new(cardinality = "a0")$cardinality, "Aleph0") expect_equal(Properties$new(cardinality = "aleph0")$cardinality, "Aleph0") expect_equal(Properties$new(cardinality = "beth0")$cardinality, "Beth0") expect_equal(Properties$new(cardinality = "b20")$cardinality, "Beth20") expect_error(Properties$new(cardinality = "b20a")) expect_error(Properties$new(closure = "not closed")) }) test_that("strprint/print", { expect_equal(class(Properties$new("closed", 5)$strprint()), "list") expect_output(print(Properties$new("closed", 5))) useUnicode(TRUE) expect_equal(Properties$new("closed", 5)$strprint()$cardinality, 5) expect_equal(Properties$new("closed", "a0")$strprint()$cardinality, "\u2135\u2080") expect_equal(Properties$new("closed", "b15")$strprint()$cardinality, "\u2136\u2081\u2085") useUnicode(FALSE) expect_equal(Properties$new("closed", 5)$strprint()$cardinality, 5) expect_equal(Properties$new("closed", "a0")$strprint()$cardinality, "Aleph0") expect_equal(Properties$new("closed", "b15")$strprint()$cardinality, "Beth15") })
normalize_2d = function(x) { x = check_one_attribute(x) x = check_2d(x) return(x) }
context("patch") test_that("Empty patch works",{ x <- data.frame(a=1, b=2) y <- x patch <- diff_data(x,y) expect_equal(patch_data(x, patch), y) }) test_that("Diff changed value works",{ x <- data.frame(a=1, b=2) y <- x y$a <- 10 patch <- diff_data(x,y) expect_equal(patch_data(x, patch), y) }) test_that("Adding row works",{ x <- data.frame(a=1, b=2) y <- rbind(x,x) patch <- diff_data(x,y) expect_equal(patch_data(x, patch), y) }) test_that("Removing row works",{ x <- data.frame(a=1:2, b=2:3) y <- x[1,] patch <- diff_data(x,y) expect_equal(patch_data(x, patch), y) }) test_that("Adding column works",{ x <- data.frame(a=1, b=2) y <- x y$c <- 10 patch <- diff_data(x,y) expect_equal(patch_data(x, patch), y) }) test_that("Removing column works",{ x <- data.frame(a=1, b=2) y <- x y$b <- NULL patch <- diff_data(x,y) expect_equal(patch_data(x, patch), y) }) test_that("Changing a factor works",{ x <- data.frame(a=factor(c("A","B")), b=1:2) y <- x y$a[1] <- "B" patch <- diff_data(x,y) expect_equal(patch_data(x, patch), y) })
`varpart3` <- function (Y, X1, X2, X3, chisquare, permat) { collinwarn <- function(case, mm, m) warning(gettextf("collinearity detected in %s: mm = %d, m = %d", case, mm, m), call. = FALSE) if (inherits(Y, "dist")) { Y <- GowerDblcen(as.matrix(Y^2), na.rm = FALSE) Y <- -Y/2 SS.Y <- sum(diag(Y)) simpleRDA2 <- match.fun(simpleDBRDA) } else { Y <- as.matrix(Y) if (chisquare) { SS.Y <- sum(initCA(Y)^2) simpleRDA2 <- match.fun(simpleCCA) } else { Y <- scale(Y, center = TRUE, scale = FALSE) SS.Y <- sum(Y * Y) } } X1 <- as.matrix(X1) X2 <- as.matrix(X2) X3 <- as.matrix(X3) n <- nrow(Y) n1 <- nrow(X1) n2 <- nrow(X2) n3 <- nrow(X3) p <- ncol(Y) mm1 <- ncol(X1) mm2 <- ncol(X2) mm3 <- ncol(X3) if (n1 != n) stop("Y and X1 do not have the same number of rows") if (n2 != n) stop("Y and X2 do not have the same number of rows") if (n3 != n) stop("Y and X3 do not have the same number of rows") X1 <- scale(X1, center = TRUE, scale = FALSE) X2 <- scale(X2, center = TRUE, scale = FALSE) X3 <- scale(X3, center = TRUE, scale = FALSE) dummy <- simpleRDA2(Y, X1, SS.Y, permat) adfg.ua <- dummy$Rsquare adfg <- dummy$RsquareAdj m1 <- dummy$m if (m1 != mm1) collinwarn("X1", mm1, m1) dummy <- simpleRDA2(Y, X2, SS.Y, permat) bdeg.ua <- dummy$Rsquare bdeg <- dummy$RsquareAdj m2 <- dummy$m if (m2 != mm2) collinwarn("X2", mm2, m2) dummy <- simpleRDA2(Y, X3, SS.Y, permat) cefg.ua <- dummy$Rsquare cefg <- dummy$RsquareAdj m3 <- dummy$m if (m3 != mm3) collinwarn("X3", mm3, m3) mm4 = mm1 + mm2 dummy <- simpleRDA2(Y, cbind(X1, X2), SS.Y, permat) abdefg.ua <- dummy$Rsquare abdefg <- dummy$RsquareAdj m4 <- dummy$m if (m4 != mm4) collinwarn("cbind(X1,X2)", mm4, m4) mm5 = mm1 + mm3 dummy <- simpleRDA2(Y, cbind(X1, X3), SS.Y, permat) acdefg.ua <- dummy$Rsquare acdefg <- dummy$RsquareAdj m5 <- dummy$m if (m5 != mm5) collinwarn("cbind(X1,X3)", mm5, m5) mm6 = mm2 + mm3 dummy <- simpleRDA2(Y, cbind(X2, X3), SS.Y, permat) bcdefg.ua <- dummy$Rsquare bcdefg <- dummy$RsquareAdj m6 <- dummy$m if (m6 != mm6) collinwarn("cbind(X2,X3)", mm6, m6) mm7 = mm1 + mm2 + mm3 dummy <- simpleRDA2(Y, cbind(X1, X2, X3), SS.Y, permat) abcdefg.ua <- dummy$Rsquare abcdefg <- dummy$RsquareAdj m7 <- dummy$m if (m7 != mm7) collinwarn("cbind(X1,X2,X3)", mm7, m7) bigwarning <- NULL if ((m1 + m2) > m4) bigwarning <- c(bigwarning, c("X1, X2")) if ((m1 + m3) > m5) bigwarning <- c(bigwarning, c("X1, X3")) if ((m2 + m3) > m6) bigwarning <- c(bigwarning, c("X2, X3")) if ((m1 + m2 + m3) > m7) bigwarning <- c(bigwarning, c("X1, X2, X3")) Df <- c(m1, m2, m3, m4, m5, m6, m7) fract <- data.frame(Df = Df, R.square = c(adfg.ua, bdeg.ua, cefg.ua, abdefg.ua, acdefg.ua, bcdefg.ua, abcdefg.ua), Adj.R.square = c(adfg, bdeg, cefg, abdefg, acdefg, bcdefg, abcdefg), Testable = rep(TRUE, 7) & Df) rownames(fract) <- c("[a+d+f+g] = X1", "[b+d+e+g] = X2", "[c+e+f+g] = X3", "[a+b+d+e+f+g] = X1+X2", "[a+c+d+e+f+g] = X1+X3", "[b+c+d+e+f+g] = X2+X3", "[a+b+c+d+e+f+g] = All") a <- abcdefg - bcdefg b <- abcdefg - acdefg c <- abcdefg - abdefg d <- acdefg - cefg - a e <- abdefg - adfg - b f <- bcdefg - bdeg - c g <- adfg - a - d - f ma <- m7 - m6 mb <- m7 - m5 mc <- m7 - m4 mad <- m5 - m3 maf <- m4 - m2 mbd <- m6 - m3 mbe <- m4 - m1 mce <- m5 - m1 mcf <- m6 - m2 Df <- c(ma, mb, mc, rep(0, 4), NA) indfract <- data.frame(Df = Df, R.square = rep(NA, 8), Adj.R.square = c(a, b, c, d, e, f, g, 1 - abcdefg), Testable = c(rep(TRUE, 3), rep(FALSE, 5)) & Df) rownames(indfract) <- c("[a] = X1 | X2+X3", "[b] = X2 | X1+X3", "[c] = X3 | X1+X2", "[d]", "[e]", "[f]", "[g]", "[h] = Residuals") Df <- c(mad, maf, mbd, mbe, mce, mcf) contr1 <- data.frame(Df = Df, R.square = rep(NA, 6), Adj.R.square = c(a + d, a + f, b + d, b + e, c + e, c + f), Testable = rep(TRUE, 6) & Df) rownames(contr1) <- c("[a+d] = X1 | X3", "[a+f] = X1 | X2", "[b+d] = X2 | X3", "[b+e] = X2 | X1", "[c+e] = X3 | X1", "[c+f] = X3 | X2") out <- list(fract = fract, indfract = indfract, contr1 = contr1, SS.Y = SS.Y, nsets = 3, bigwarning = bigwarning, n = n1) class(out) <- "varpart234" out }
assertDataCorrectness <- function(data, graphType, config) { validGraphTypes <- c("Area", "AreaLine", "Bar", "BarLine", "Boxplot", "Circular", "Correlation", "Dotplot", "DotLine", "Fish", "Genome", "Heatmap", "Line", "Map", "Meter", "Network", "Pie", "ParallelCoordinates", "Sankey", "Scatter2D", "Scatter3D", "ScatterBubble2D", "Stacked", "StackedPercent", "StackedLine", "StackedPercentLine", "Tree", "Treemap", "TagCloud", "Venn", "Gantt") noDataNecessary <- c("Map") if (is.null(graphType)) stop("graphType cannot be NULL!") if (!(graphType %in% validGraphTypes)) { stop("graphType is invalid, must be one of <", paste(validGraphTypes, collapse = ", "), ">") } if (is.character(data) && graphType != "Network") { if (httr::http_error(data)) { message("Unable to validate URL") } } else if (graphType == "Venn") { vdata <- data if (is.null(vdata)) { if (!("vennData" %in% names(config))) { stop("vennData cannot be NULL!") } else { vdata <- config$vennData } } if (!inherits(vdata, c("data.frame", "matrix", "list"))) { stop("vennData must be a data.frame, matrix, or named list") } if (inherits(vdata, c("list")) & (length(vdata) > 1)) { stop("Venn diagrams do not support multiple datasets") } else if (is.null(vdata[[1]])) { stop("vennData cannot be NULL!") } if (!("vennLegend" %in% names(config)) | !("vennGroups" %in% names(config))) { stop("Venn diagrams must specify both the <vennLegend> and <vennGroups> parameters") } } else if (graphType == "Network") { if (is.character(data)) { if (file.exists(data)) { data <- paste(readLines(data), collapse = '\n') } else if (httr::http_error(data)) { message(data, " may not a valid file location or URL - unable to verify.") } } else { ndata <- NULL edata <- NULL if (!is.null(data)) { if (!("nodeData" %in% names(data)) & !("edgeData" %in% names(data))) { stop("Network diagrams must specify both <nodeData> and <edgeData> as parameters or named data list items") } ndata <- data$nodeData edata <- data$edgeData } else { if (!("nodeData" %in% names(config)) | !("edgeData" %in% names(config))) { stop("Network diagrams must specify both <nodeData> and <edgeData> as parameters or named data list items") } ndata <- config$nodeData edata <- config$edgeData } if (is.null(ndata)) { stop("nodeData cannot be NULL!") } if (is.null(edata)) { stop("edgeData cannot be NULL!") } if (!inherits(ndata, c("data.frame", "matrix", "list"))) { stop("nodeData must be a data.frame or matrix or named list") } if (!inherits(edata, c("data.frame", "matrix", "list"))) { stop("edgeData must be a data.frame or matrix or named list") } } } else if (graphType == "Genome") { message("The Genome graphType is an advanced chart, data is passed as-is to the JS library") } else if (!(graphType %in% noDataNecessary)) { if (is.null(data)) { stop("data cannot be NULL!") } if (!inherits(data, c("data.frame", "matrix", "list"))) { stop("data must be a data.frame, matrix, or named list") } if (inherits(data, c("list"))) { if (length(data) < 1) { stop("data specified as a list must contain at least one item") } precalcBoxplot <- FALSE precalcBarchart <- FALSE if (length(data) > 1 ) { if (is.null(names(data))) { stop("data specified as a list of multiple items must have named elements") } else if (graphType == "Boxplot") { req <- c("iqr1", "qtl1", "median", "qtl3", "iqr3") precalcBoxplot <- (length(intersect(names(data), req)) == 5 || length(intersect(rownames(data), req)) == 5) if (!precalcBoxplot && !("y" %in% names(data))) { stop("data specified as a list of multiple items must contain a <y> element") } } else if (graphType == "Bar") { req <- c("mean", "stdev") precalcBarchart <- (length(intersect(names(data), req)) == 2 || length(intersect(rownames(data), req)) == 2) if (!precalcBarchart && !("y" %in% names(data))) { stop("data specified as a list of multiple items must contain a <y> element") } } else if (!("y" %in% names(data))) { stop("data specified as a list of multiple items must contain a <y> element") } } fail <- vector(mode = "character", length = 0) for (name in names(data)) { if (!inherits(data[[name]], c("data.frame", "matrix"))) { fail <- c(fail, name) } } if (!precalcBoxplot && !precalcBarchart && length(fail) > 0) { stop("data list elements <", paste(fail, collapse = ", "), "> are not data.frame or matrix elements") } } } } assignCanvasXpressColnames <- function(x) { if (is.null(colnames(x))) { names <- paste("V", seq(length = ncol(x)), sep = "") } else { names <- colnames(x) } return(names) } assignCanvasXpressRownames <- function(x) { if (is.null(rownames(x))) { names <- paste("V", seq(length = nrow(x)), sep = "") } else { names <- rownames(x) } return(names) } convertRowsToList <- function(x) { seq_row <- function(x) { seq_len(nrow(x)) } res = lapply(seq_row(x), function(i) stats::setNames(x[i,], NULL)) stats::setNames(res, rownames(x)) } setup_y <- function(data) { y <- NULL if (inherits(data, "list")) { if (length(data) > 1) { y <- lapply(data, as.matrix, dimnames = list()) y$smps <- as.list(assignCanvasXpressColnames(data$y)) y$vars <- as.list(assignCanvasXpressRownames(data$y)) y$data <- y$y y$y <- NULL } else { y <- list(vars = as.list(assignCanvasXpressRownames(data[[1]])), smps = as.list(assignCanvasXpressColnames(data[[1]])), data = as.matrix(data[[1]], dimnames = list())) } } else { y <- list(vars = as.list(assignCanvasXpressRownames(data)), smps = as.list(assignCanvasXpressColnames(data)), data = as.matrix(data, dimnames = list())) } y } setup_x <- function(y_smps, smpAnnot) { x <- NULL if (!is.null(smpAnnot)) { test <- as.list(assignCanvasXpressRownames(smpAnnot)) if (!identical(test, y_smps)) { smpAnnot <- t(smpAnnot) test <- as.list(assignCanvasXpressRownames(smpAnnot)) } if (!identical(test, y_smps)) { stop("Row names in smpAnnot are different from column names in data") } x <- lapply(convertRowsToList(t(smpAnnot)), function(d) if (length(d) > 1) d else list(d)) } x } setup_z <- function(y_vars, varAnnot) { z <- NULL if (!is.null(varAnnot)) { test <- as.list(assignCanvasXpressRownames(varAnnot)) if (!identical(test, y_vars)) { varAnnot <- t(varAnnot) test <- as.list(assignCanvasXpressRownames(varAnnot)) } if (!identical(test, y_vars)) { stop("Row names in varAnnot are different from row names in data") } z <- lapply(convertRowsToList(t(varAnnot)), function(d) if (length(d) > 1) d else list(d)) } z }
cbind.mitml.list <- function(...){ Map(cbind, ...) }
library("simPop") data("ghanaS") seed <- 1234 ghanaP <- simStructure(ghanaS, hid = "hhid", w = "weight", strata = "region", additional = c("age", "sex", "relate"), keep = FALSE) breaks <- c(min(ghanaS$age), seq(6, 18, 2), seq(20, 80, 5), max(ghanaS$age)) ghanaS$ageCat <- cut(ghanaS$age, breaks = breaks, include.lowest = TRUE) ghanaP$ageCat <- cut(ghanaP$age, breaks = breaks, include.lowest = TRUE) basic <- c("ageCat", "sex", "hsize") additional <- c("nation", "ethnic", "religion") ghanaP <- simRelation(ghanaS, ghanaP, hid = "hhid", w = "weight", strata = "region", basic = basic, additional = additional) basic <- c(basic, additional) additional <- c("highest_degree", "occupation") hd14 <- c("bece", "mslc", "ssce", "other", "tech/prof cert") hd18 <- c("hnd", "gce 'a' level", "gce 'o' level", "tech/prof dip", "voc/comm") hd21 <- c("bachelor", "teacher trng a", "teacher trng b") limitHD <- list(ageCat=list("[0,6]" = "none", "(6,8]" = "none", "(8,10]" = "none", "(10,12]" = "none", "(12,14]" = c("none", hd14), "(14,16]" = c("none", hd14), "(16,18]" = c("none", hd14, hd18), "(18,20]" = c("none", hd14, hd18), "(20,25]" = c("none", hd14, hd18, hd21))) o8 <- c("craft and related trades workers", "elementary occupations", "service workers and shop and market sales workers", "skilled agricultural and fishery workers") o18 <- c("armed forces and other security personnel", "clerks", "plant and machine operators and assemblers", "technicians and associate professionals") limitO <- list(ageCat=list("[0,6]" = "none", "(6,8]" =c ("none", o8), "(8,10]" = c("none", o8), "(10,12]" = c("none", o8), "(12,14]" = c("none", o8), "(14,16]" = c("none", o8), "(16,18]" = c("none", o8, o18), "(18,20]" = c("none", o8, o18), "(20,25]" = c("none", o8, o18))) ghanaP <- simCategorical(ghanaS, ghanaP, w = "weight", strata = "region", basic = basic, additional = additional, limit = list(highest_degree = limitHD, occupation = limitO)) breaks <- c(0:10, 15, 20, max(ghanaS$hsize)) labs <- c(1:10, "(11,15]", "(15,20]", "(20,29]") ghanaS$hsizeCat <- cut(ghanaS$hsize, breaks = breaks, labels = labs) ghanaP$hsizeCat <- cut(as.numeric(as.character(ghanaP$hsize)), breaks = breaks, labels = labs) abbRegion <- c("W", "C", "GA", "V", "E", "A", "BA", "N", "UE", "UW") abbHsize <- c(1:10, "15", "20", ">") nam <- c(sex = "Sex", region = "Region", hsizeCat = "Household size") lab <- labeling_border(set_labels = list(region = abbRegion, hsizeCat = abbHsize), set_varnames = nam) spMosaic(c("sex", "region", "hsizeCat"), "weight", ghanaS, ghanaP, labeling = lab) abbEthnic <- c("A", "O", "E", "GD", "Gs", "Gn", "Gm", "M", "MD") abbOccupation <- c("F", "Cl", "Cr", "E", "O", "N", "M", "P", "S", "A", "T") nam <- c(sex = "Sex", ethnic = "Ethnicity", occupation = "Occupation") lab <- labeling_border(set_labels = list(ethnic = abbEthnic, occupation = abbOccupation), set_varnames = nam) spMosaic(c("sex", "ethnic", "occupation"), "weight", ghanaS, ghanaP, labeling = lab) basic <- c(basic, additional) probs <- c(0.05, 0.1, seq(from=0.2, to=0.8, by=0.2), 0.9, 0.95, 0.975, 0.99, 0.995, 0.999) limitI <- list(occupation = list(none = "0")) censorI <- list( "(1.8e+03,2.6e+03]" = list(ageCat = c("[0,6]","(6,8]","(8,10]")), "(2.6e+03,4.16e+03]" = list(ageCat = c("[0,6]", "(6,8]", "(8,10]", "(10,12]", "(12,14]")), "(4.16e+03,7.68e+03]" = list(ageCat = c("[0,6]", "(6,8]", "(8,10]", "(10,12]", "(12,14]")), "(7.68e+03,1.3e+04]" = list(ageCat = c("[0,6]", "(6,8]", "(8,10]", "(10,12]", "(12,14]", "(14,16]")), "(1.3e+04,3.84e+04]" = list(ageCat = c("[0,6]", "(6,8]", "(8,10]", "(10,12]", "(12,14]", "(14,16]", "(16,18]")), "(3.84e+04,1e+06]" = list(ageCat = c("[0,6]", "(6,8]", "(8,10]", "(10,12]", "(12,14]", "(14,16]", "(16,18]", "(18,20]", "(20,25]"), occupation = c("armed forces and other security personnel", "clerks", "elementary occupations"))) ghanaP <- simContinuous(ghanaS, ghanaP, w = "weight", strata = "region", basic = basic, additional = "income", upper = 1000000, probs = probs, limit = limitI, censor = censorI, keep = FALSE) ghanaP$income <- round(ghanaP$income, 2) subset <- which(ghanaS[, "income"] > 0) q <- quantileWt(ghanaS[subset, "income"], ghanaS[subset, "weight"], probs = 0.99) spCdfplot("income", "weight", dataS = ghanaS, dataP = ghanaP, xlim = c(0, q)) spBwplot("income", "weight", dataS = ghanaS, dataP = ghanaP, pch = "|") spBwplot("income", "weight", "region", dataS = ghanaS, dataP = ghanaP, pch = "|", layout = c(1, 10)) spBwplot("income", "weight", "sex", dataS = ghanaS, dataP = ghanaP, pch = "|", layout = c(1, 2)) spBwplot("income", "weight", "ethnic", dataS = ghanaS, dataP = ghanaP, pch = "|", layout = c(1, 9)) spBwplot("income", "weight", "occupation", dataS = ghanaS, dataP = ghanaP, pch = "|", layout = c(1, 11))
calcNullDev <- function(X, y, group, family) { form <- if (any(group==0)) formula(y~X[, group==0]) else formula(y~1) fit <- glm(form, family=family) mean(loss.grpreg(y, predict(fit, type="response"), family)) }
.test.s3methods.rendobase <- function(res.model, input.form, function.std.data, req.df, full.coefs){ input.form <- Formula::as.Formula(input.form) .test.s3methods.basic.structure(res.model=res.model, input.form=input.form, function.std.data=function.std.data, full.coefs=full.coefs) test_that("object structure", { expect_true(all(c("call", "formula", "terms", "coefficients", "names.main.coefs", "fitted.values", "residuals") %in% names(res.model))) expect_s3_class(res.model, "rendo.base") expect_type(res.model$call, "language") expect_s3_class(res.model$formula, "Formula") expect_s3_class(res.model$model, "data.frame") expect_s3_class(res.model$terms, "terms") expect_type(res.model$names.main.coefs, "character") expect_type(res.model$fitted.values, "double") expect_type(res.model$residuals, "double") }) test_that("coef has default = TRUE", { expect_equal(eval(formals(REndo:::coef.rendo.base)[["complete"]]), TRUE) }) test_that("coef with complete=TRUE", { expect_silent(res.cf <- coef(res.model, complete = TRUE)) expect_equal(res.cf, expected = res.model$coefficients) }) test_that("coef with complete=FALSE", { expect_silent(res.cf <- coef(res.model, complete = FALSE)) expect_equal(res.cf, expected = res.model$coefficients[res.model$names.main.coefs]) }) test_that("terms", { expect_silent(terms(res.model)) }) test_that("case.names", { expect_silent(res.cases <- case.names(res.model)) expect_type(res.cases, "character") expect_equal(res.cases, rownames(function.std.data)) expect_length(res.cases, nrow(function.std.data)) }) test_that("summary() - vcov", { expect_silent(res.vcov <- vcov(summary(res.model))) res.attr <- attributes(res.vcov) expect_named(res.attr, c("dim", "dimnames")) expect_length(res.attr$dimnames, 2) expect_equal(res.attr$dim, c(length(coef(res.model)), length(coef(res.model))) ) expect_equal(res.attr$dimnames[[1]], names(coef(res.model))) expect_equal(res.attr$dimnames[[2]], names(coef(res.model))) }) test_that("summary() - coef", { expect_silent(sum.coef <- coef(summary(res.model))) expect_true(ncol(sum.coef) == 4) expect_true(all(colnames(sum.coef) != "")) expect_true(nrow(sum.coef) == length(coef(res.model))) expect_true(all(rownames(sum.coef) == names(coef(res.model)))) }) test_that("Printing methods work", { expect_output(res <- show(res.model), regexp = "Coefficients") expect_null(res) expect_output(res <- print(res.model)) expect_identical(res, res.model) expect_silent(res.sum <- summary(res.model)) expect_output(res <- show(res.sum)) expect_null(res) expect_output(res <- print(res.sum)) expect_equal(res, res.sum) }) }
expected <- eval(parse(text="structure(raw(0), .Dim = c(0L, 0L))")); test(id=0, code={ argv <- eval(parse(text="list(raw(0), 0L, 0L, FALSE, NULL, FALSE, FALSE)")); .Internal(matrix(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]], argv[[6]], argv[[7]])); }, o=expected);
test_that("grey", { withr::local_options(cli.num_colors = 256) expect_true(cli::ansi_has_any(grey()("foobar"))) withr::local_options(cli.num_colors = 1) expect_false(cli::ansi_has_any(grey()("foobar"))) }) test_that("prompt_fancy", { withr::local_options(cli.unicode = FALSE) withr::local_options(cli.num_colors = 1) mockery::stub(prompt_fancy, "devtools_packages", character()) mockery::stub(prompt_fancy, "memory_usage", list(formatted = "194.29 MB")) mockery::stub(prompt_fancy, "ps::ps_loadavg", c(1.31, 1.89, 2.001)) mockery::stub(prompt_fancy, "git_info", "gitinfo") mockery::stub(prompt_fancy, "has_emoji", FALSE) expect_snapshot(prompt_fancy(NULL, NULL, TRUE, TRUE)) mockery::stub(prompt_fancy, "devtools_packages", "mypkg") expect_snapshot(prompt_fancy(NULL, NULL, TRUE, TRUE)) }) test_that("git_info", { mockery::stub(git_info, "git", structure(1, "status" = 10)) expect_equal(git_info(), "") mockery::stub(git_info, "git", structure(1, "status" = 0)) mockery::stub(git_info, "is_git_dir", FALSE) expect_equal(git_info(), "") mockery::stub(git_info, "is_git_dir", TRUE) mockery::stub(git_info, "git_branch", "br") mockery::stub(git_info, "git_dirty", "*") mockery::stub(git_info, "git_arrows", "arr") expect_equal(git_info(), "br*arr") }) test_that("has_emoji", { he <- has_emoji() expect_true(inherits(he, "logical")) expect_equal(length(he), 1) })
context("treeplyr functions work") test_that("treedata can handle matrix/dataframe input", { require(testthat) data(anolis) td <- make.treedata(anolis$phy, anolis$dat, name_column=1) originaldat <- anolis$dat[,-1] rownames(originaldat) <- anolis$dat[,1] jacknife <- sample(1:nrow(anolis$dat), 10, replace=FALSE) td_filtered <- filter(td, SVL > 3.5, island=="Cuba") td_filtered_ <- filter_(td, "SVL > 3.5", "island=='Cuba'") td_selected <- select(td, SVL, ecomorph, island) td_selected_ <- select_(td, "SVL", "ecomorph", "island") td_mutated <- mutate(td, logSVL = log(SVL), discrete_awesome = as.numeric(awesomeness>0)) td_mutated_ <- mutate_(td, logSVL = "log(SVL)", discrete_awesome = "as.numeric(awesomeness>0)") td_reorder <- reorder(td, "postorder") expect_identical(td$dat$SVL[match(anolis$phy$tip.label[jacknife], attributes(td)$tip.label)], originaldat[anolis$phy$tip.label[jacknife], "SVL"]) expect_identical(td_filtered$dat$SVL, originaldat[td_filtered$phy$tip.label, "SVL"]) expect_identical(td_selected$dat$SVL[match(anolis$phy$tip.label[jacknife], attributes(td)$tip.label)], originaldat[anolis$phy$tip.label[jacknife], "SVL"]) expect_identical(td_mutated$dat$SVL[match(anolis$phy$tip.label[jacknife], attributes(td)$tip.label)], originaldat[anolis$phy$tip.label[jacknife], "SVL"]) expect_identical(td_reorder$dat$SVL[match(anolis$phy$tip.label[jacknife], attributes(td)$tip.label)], originaldat[anolis$phy$tip.label[jacknife], "SVL"]) expect_identical(td_selected, td_selected_) expect_identical(td_mutated, td_mutated_) expect_identical(td_filtered, td_filtered_) expect_true(min(filter(td, SVL > 3.5)$dat$SVL) > 3.5) expect_identical(td_filtered$phy$tip.label, td_filtered$phy$tip.label[as.numeric(rownames(td_filtered$dat))]) td_treeply <- treeply(td, geiger::rescale, model="OU", 10) expect_identical(td_treeply$dat$SVL[match(anolis$phy$tip.label[jacknife], attributes(td)$tip.label)], originaldat[anolis$phy$tip.label[jacknife], "SVL"]) expect_identical(td_treeply$phy$edge.length, geiger::rescale(td$phy, "OU", 10)$edge.length) })
confint <- function(object, parm, level = 0.95, ...) UseMethod("confint") format.perc <- function(probs, digits) paste(format(100 * probs, trim = TRUE, scientific = FALSE, digits = digits), "%") confint.lm <- function(object, parm, level = 0.95, ...) { cf <- coef(object) ses <- sqrt(diag(vcov(object))) pnames <- names(ses) if(is.matrix(cf)) cf <- setNames(as.vector(cf), pnames) if(missing(parm)) parm <- pnames else if(is.numeric(parm)) parm <- pnames[parm] a <- (1 - level)/2 a <- c(a, 1 - a) fac <- qt(a, object$df.residual) pct <- format.perc(a, 3) ci <- array(NA_real_, dim = c(length(parm), 2L), dimnames = list(parm, pct)) ci[] <- cf[parm] + ses[parm] %o% fac ci } confint.glm <- function(object, parm, level = 0.95, ...) { if(!requireNamespace("MASS", quietly = TRUE)) stop("package 'MASS' must be installed") confint.glm <- get("confint.glm", asNamespace("MASS"), inherits = FALSE) confint.glm(object, parm, level, ...) } confint.nls <- function(object, parm, level = 0.95, ...) { if(!requireNamespace("MASS", quietly = TRUE)) stop("package 'MASS' must be installed") confint.nls <- get("confint.nls", asNamespace("MASS"), inherits = FALSE) confint.nls(object, parm, level, ...) } confint.default <- function (object, parm, level = 0.95, ...) { cf <- coef(object) pnames <- names(cf) if(missing(parm)) parm <- pnames else if(is.numeric(parm)) parm <- pnames[parm] a <- (1 - level)/2 a <- c(a, 1 - a) pct <- format.perc(a, 3) fac <- qnorm(a) ci <- array(NA, dim = c(length(parm), 2L), dimnames = list(parm, pct)) ses <- sqrt(diag(vcov(object)))[parm] ci[] <- cf[parm] + ses %o% fac ci }
clean_genoprob <- function(object, value_threshold=1e-6, column_threshold=0.01, ind=NULL, cores=1, ...) { if(!is.null(ind)) { probs_sub <- clean_genoprob(subset(object, ind=ind), value_threshold=value_threshold, column_threshold=column_threshold, cores=cores) for(i in seq_along(object)) object[[i]][rownames(probs_sub[[i]]),,] <- probs_sub[[i]] return(object) } attrib <- attributes(object) cores <- setup_cluster(cores) result <- cluster_lapply(cores, seq_along(object), function(i) { this_result <- .clean_genoprob(object[[i]], value_threshold, column_threshold) dimnames(this_result) <- dimnames(object[[i]]) this_result }) for(a in names(attrib)) { attr(result, a) <- attrib[[a]] } result } clean.calc_genoprob <- clean_genoprob
show_available_catalogues <- function(selected_heading = NULL, refresh = FALSE) { if (isFALSE(is.logical(refresh))) { stop("`refresh` must be `TRUE` or `FALSE`.") } if (isFALSE(refresh)) { table_to_use <- abs_lookup_table } else { table_to_use <- scrape_abs_catalogues() } if (!is.null(selected_heading)) { available_catalogues <- filter(table_to_use, .data$heading == selected_heading) } else { available_catalogues <- table_to_use } available_catalogues <- pull(available_catalogues, .data$catalogue) return(available_catalogues) }
iotables_read_tempdir <- function( source = "naio_10_cp1700" ) { validate_source(source) temporary_file <- file.path(tempdir(), paste0(source, '_processed.rds')) if (file.exists(temporary_file)) { readRDS(temporary_file) } }
subsemble <- function(x, y, newx = NULL, family = gaussian(), learner, metalearner = "SL.glm", subsets = 3, subControl = list(), cvControl = list(), learnControl = list(), genControl = list(), id = NULL, obsWeights = NULL, seed = 1, parallel = "seq") { starttime <- Sys.time() runtime <- list() N <- dim(x)[1L] ylim <- range(y) row.names(x) <- 1:N if (is.null(newx)) { newx <- x } subControl <- do.call(".sub_control", subControl) cvControl <- do.call(".cv_control", cvControl) learnControl <- do.call(".learn_control", learnControl) genControl <- do.call(".gen_control", genControl) if (length(unique(y)) != 2) { subControl$stratifyCV = FALSE cvControl$stratifyCV = FALSE } if (is.numeric(subsets) && length(subsets)==1 && subsets%%1==0) { subControl$V <- subsets if (is.numeric(seed)) set.seed(seed) subsets <- CVFolds(N=N, id=NULL, Y=y, cvControl=subControl) } else if (length(subsets)==N) { subsets <- lapply(1:length(unique(subsets)), function(j) which(subsets==j)) names(subsets) <- as.character(seq(length(subsets))) subControl$V <- length(subsets) } else if (is.list(subsets) && identical(seq(N), as.integer(sort(unlist(subsets))))) { subsets <- lapply(subsets, function(ll) as.integer(ll)) names(subsets) <- as.character(seq(length(subsets))) subControl$V <- length(subsets) } else { stop("'subsets' must be either an integer, a vector of subset labels, or a list of index vectors") } J <- subControl$V V <- cvControl$V L <- length(learner) if (J==1) { message("Setting J=1 will fit an ensemble on the full data; this is equivalent to the Super Learner algorithm.") } multilearning <- ifelse(L>1, TRUE, FALSE) if (learnControl$multiType == "divisor" | L==1) { if (J %% L == 0) { learner <- rep(learner, J/L) } else { message("The length of 'learner' must be a divisor of the number of subsets.") } } if (length(metalearner)>1 | !is.character(metalearner)) { stop("The 'metalearner' argument must be a string, specifying the name of a SuperLearner wrapper function.") } if (sum(!sapply(learner, exists))>0) { stop("'learner' function name(s) not found.") } if (!exists(metalearner)) { stop("'metalearner' function name not found.") } if (is.character(family)) family <- get(family, mode = "function", envir = parent.frame()) if (is.function(family)) family <- family() if (is.null(family$family)) { print(family) stop("'family' not recognized") } if (is.null(id)) { id <- seq(N) } else if (length(id)!=N) { stop("If specified, the 'id' argument must be a vector of length nrow(x)") } if (is.null(obsWeights)) { obsWeights <- rep(1, N) } if (inherits(parallel, "character")) { if (!(parallel %in% c("seq","multicore"))) { stop("'parallel' must be either 'seq' or 'multicore' or a snow cluster object") } else if (parallel == "multicore") { ncores <- detectCores() } } else if (!inherits(parallel, "cluster")) { stop("'parallel' must be either 'seq' or 'multicore' or a snow cluster object") } .subCVsplit <- function(idxs, y, cvControl) { folds <- CVFolds(N=length(idxs), id=NULL, Y=y[idxs], cvControl=cvControl) subfolds <- lapply(X=folds, FUN=function(ll) idxs[ll]) return(subfolds) } if (is.numeric(seed)) set.seed(seed) subCVsets <- lapply(X=subsets, FUN=.subCVsplit, y=y, cvControl=cvControl) .subFun <- function(j, v, subCVsets, y, x, family, learner, obsWeights, seed) { idx.train <- setdiff(unlist(subCVsets[[j]]), subCVsets[[j]][[v]]) idx.test <- unlist(lapply(subCVsets, function(ll) ll[[v]]), use.names=FALSE) if (is.numeric(seed)) set.seed(seed) fit <- match.fun(learner[j])(Y=y[idx.train], X=x[idx.train,], newX=x[idx.test,], family=family, obsWeights=obsWeights[idx.train]) if (!is.null(names(fit$pred)) && is.vector(fit$pred)) { if (!identical(as.integer(names(fit$pred)), unlist(sapply(1:J, function(ll) subCVsets[[ll]][[v]], simplify=FALSE)))) { stop("names not identical") } } preds <- as.vector(fit$pred) names(preds) <- as.vector(unlist(sapply(subCVsets, function(ll) ll[[v]], simplify=FALSE))) return(preds) } .cvFun <- function(v, subCVsets, y, xmat, family, learner, obsWeights, seed) { preds <- lapply(X=1:J, FUN=.subFun, v=v, subCVsets=subCVsets, y=y, x=xmat, family=family, learner=learner, obsWeights=obsWeights, seed=seed) return(preds) } .subPreds <- function(j, cvRes) { subRes <- unlist(cvRes[j,]) return(subRes[as.character(seq(length(subRes)))]) } .make_Z_l <- function(V, subCVsets, y, x, family, learner, obsWeights, parallel, seed) { if (inherits(parallel, "cluster")) { cvRes <- parSapply(cl=parallel, X=1:V, FUN=.cvFun, subCVsets=subCVsets, y=y, xmat=x, family=family, learner=learner, obsWeights=obsWeights, seed=seed) } else if (parallel=="multicore") { cl <- makeCluster(min(ncores,V), type="FORK") cvRes <- parSapply(cl=cl, X=1:V, FUN=.cvFun, subCVsets=subCVsets, y=y, xmat=x, family=family, learner=learner, obsWeights=obsWeights, seed=seed) stopCluster(cl) } else { cvRes <- sapply(X=1:V, FUN=.cvFun, subCVsets=subCVsets, y=y, xmat=x, family=family, learner=learner, obsWeights=obsWeights, seed=seed) } if (!inherits(cvRes, "matrix")) { cvRes <- t(as.matrix(cvRes)) } Z <- as.data.frame(sapply(1:J, .subPreds, cvRes=cvRes)) return(Z) } if (multilearning && length(learner)!=length(unique(learner))) { if (!is.null(seed)) warning("Repeating identical learner wrappers in the learning library when the seed is not NULL will cause these sublearners to produce identical submodels (not recommended).") lnames <- learner for (x in learner) { if (sum(learner==x)>1) { for (i in seq(sum(learner==x))) { idxs <- which(learner==x) lnames[idxs[i]] <- paste(learner[idxs[i]], i, sep=".") } } } } else if (multilearning){ lnames <- learner } else { lnames <- unique(learner) } if (multilearning && learnControl$multiType=="crossprod") { multilearner <- sapply(learner, function(ll) list(rep(ll,J))) runtime$cv <- system.time(Z <- do.call("cbind", sapply(X=multilearner, FUN=.make_Z_l, V=V, subCVsets=subCVsets, y=y, x=x, family=family, obsWeights=obsWeights, parallel=parallel, seed=seed, simplify=FALSE)), gcFirst=FALSE) learner <- unlist(multilearner) } else { runtime$cv <- system.time(Z <- .make_Z_l(V=V, subCVsets=subCVsets, y=y, x=x, family=family, learner=learner, obsWeights=obsWeights, seed=seed, parallel=parallel), gcFirst=FALSE) } if (learnControl$multiType=="crossprod") { modnames <- as.vector(sapply(lnames, function(ll) paste(ll, paste("J", seq(J), sep=""), sep="_"))) } else { modnames <- sapply(seq(J), function(i) sprintf("%s_J%s", rep(lnames, J/length(lnames))[i], i)) } names(Z) <- modnames row.names(Z) <- row.names(x) Z[Z < ylim[1]] <- ylim[1] Z[Z > ylim[2]] <- ylim[2] if (is.numeric(seed)) set.seed(seed) runtime$metalearning <- system.time(metafit <- match.fun(metalearner)(Y=y, X=Z, newX=Z, family=family, id=id, obsWeights=obsWeights), gcFirst=FALSE) .fitFun <- function(m, subCVsets, y, x, newx, family, learner, obsWeights, seed) { J <- length(subCVsets) j <- ifelse((m %% J)==0, J, (m %% J)) idx.train <- unlist(subCVsets[[j]]) if (is.numeric(seed)) set.seed(seed) fit <- match.fun(learner[m])(Y=y[idx.train], X=x[idx.train,], newX=newx, family=family, obsWeights=obsWeights[idx.train]) return(fit) } .fitWrapper <- function(m, subCVsets, y, xmat, newx, family, learner, obsWeights, seed) { fittime <- system.time(fit <- .fitFun(m, subCVsets, y, xmat, newx, family, learner, obsWeights, seed), gcFirst=FALSE) return(list(fit=fit, fittime=fittime)) } M <- ncol(Z) if (inherits(parallel, "cluster")) { sublearners <- parSapply(cl=parallel, X=1:M, FUN=.fitWrapper, subCVsets=subCVsets, y=y, xmat=x, newx=newx, family=family, learner=learner, obsWeights=obsWeights, seed=seed, simplify=FALSE) } else if (parallel=="multicore") { cl <- makeCluster(min(ncores,M), type="FORK") sublearners <- parSapply(cl=cl, X=1:M, FUN=.fitWrapper, subCVsets=subCVsets, y=y, xmat=x, newx=newx, family=family, learner=learner, obsWeights=obsWeights, seed=seed, simplify=FALSE) stopCluster(cl) } else { sublearners <- sapply(X=1:M, FUN=.fitWrapper, subCVsets=subCVsets, y=y, xmat=x, newx=newx, family=family, learner=learner, obsWeights=obsWeights, seed=seed, simplify=FALSE) } runtime$sublearning <- lapply(sublearners, function(ll) ll$fittime) names(runtime$sublearning) <- modnames subpred <- do.call("cbind", lapply(sublearners, function(ll) ll$fit$pred)) subpred <- as.data.frame(subpred) names(subpred) <- names(Z) subpred[subpred < ylim[1]] <- ylim[1] subpred[subpred > ylim[2]] <- ylim[2] pred <- predict(metafit$fit, newdata=subpred, family=family) pred[pred < ylim[1]] <- ylim[1] pred[pred > ylim[2]] <- ylim[2] if (genControl$saveFits) { subfits <- lapply(sublearners, function(ll) ll$fit$fit) names(subfits) <- names(Z) } else { subfits = NULL metafit = NULL } runtime$total <- Sys.time() - starttime out <- list(subfits=subfits, metafit=metafit, subpred=subpred, pred=pred, Z=Z, cvRisk=NULL, family=family, subControl=subControl, cvControl=cvControl, learnControl=learnControl, subsets=subsets, subCVsets=subCVsets, ylim=ylim, seed=seed, runtime=runtime) class(out) <- "subsemble" return(out) }
secure_server <- function( server, custom_sign_in_server = NULL, custom_admin_server = NULL, allow_reconnect = FALSE ) { server <- force(server) function(input, output, session) { session$userData$user <- reactiveVal(NULL) if (isTRUE(allow_reconnect) || allow_reconnect == "force") { session$allowReconnect(allow_reconnect) } shiny::observeEvent(input$hashed_cookie, { hashed_cookie <- input$hashed_cookie if (isTRUE(.global_sessions$get_admin_mode())) { session$userData$user(list( session_uid = uuid::UUIDgenerate(), user_uid = "00000000-0000-0000-0000-000000000000", email = "[email protected]", is_admin = TRUE, hashed_cookie = character(0), email_verified = TRUE, roles = NA )) shiny::updateQueryString( queryString = paste0("?page=admin_panel"), session = session, mode = "push" ) return() } query_list <- shiny::getQueryString() page <- query_list$page global_user <- NULL try({ global_user <- .global_sessions$find(hashed_cookie, paste0("server-", page)) }, silent = TRUE) if (is.null(global_user)) { if ((!identical(page, "sign_in")) && isTRUE(.global_sessions$is_auth_required)) { shiny::updateQueryString( queryString = paste0("?page=sign_in"), session = session, mode = "replace" ) session$reload() } else { session$userData$user(NULL) return() } } else { if (identical(query_list$page, "sign_in")) { remove_query_string() session$reload() } if (is.na(global_user$signed_in_as) || !is.null(query_list$page)) { if (!is.na(global_user$signed_in_as)) { .global_sessions$set_signed_in_as( global_user$session_uid, NA, user_uid = global_user$user_uid ) } user_out <- global_user[ c("session_uid", "user_uid", "email", "is_admin", "hashed_cookie", "email_verified", "roles") ] session$userData$user(user_out) } else { signed_in_as_user <- .global_sessions$get_signed_in_as_user(global_user$signed_in_as) signed_in_as_user$session_uid <- global_user$session_uid signed_in_as_user$hashed_cookie <- global_user$hashed_cookie signed_in_as_user$email_verified <- TRUE session$userData$user(signed_in_as_user) } } }, ignoreNULL = TRUE) shiny::observeEvent(session$userData$user(), { query_list <- shiny::getQueryString() hold_user <- session$userData$user() if (isTRUE(hold_user$email_verified) || isFALSE(.global_sessions$is_email_verification_required)) { is_on_admin_page <- if ( isTRUE(.global_sessions$get_admin_mode()) || identical(query_list$page, 'admin_panel')) TRUE else FALSE if (isTRUE(hold_user$is_admin) && isTRUE(is_on_admin_page)) { shiny::callModule( admin_module, "admin" ) if (isTRUE(!is.null(custom_admin_server))) { if (names(formals(custom_admin_server))[[1]] == "id") { custom_admin_server("custom_admin") } else { callModule( custom_admin_server, "custom_admin" ) } } } else if (is.null(query_list$page)) { if (isTRUE(.global_sessions$is_auth_required)) { server(input, output, session) } shiny::callModule( admin_button, "polished" ) shiny::onStop(fun = function() { tryCatch({ .global_sessions$set_inactive( session_uid = hold_user$session_uid, user_uid = hold_user$user_uid ) }, catch = function(err) { print('error setting the session to incative') print(err) }) }) } } else { callModule( verify_email_module, "verify" ) } }, once = TRUE) if (isFALSE(.global_sessions$is_auth_required)) { server(input, output, session) } observeEvent(session$userData$user(), { req(is.null(session$userData$user())) query_list <- shiny::getQueryString() page <- query_list$page if (identical(page, "sign_in")) { if (is.null(custom_sign_in_server)) { shiny::callModule( sign_in_module, "sign_in" ) } else { if (names(formals(custom_sign_in_server))[[1]] == "id") { custom_sign_in_server("sign_in") } else { shiny::callModule( custom_sign_in_server, "sign_in" ) } } } }, ignoreNULL = FALSE, once = TRUE) } }
pack <- function(.data, ..., .names_sep = NULL) { cols <- enquos(...) if (any(names2(cols) == "")) { abort("All elements of `...` must be named") } cols <- map(cols, ~ tidyselect::eval_select(.x, .data)) unpacked <- setdiff(names(.data), unlist(map(cols, names))) unpacked <- .data[unpacked] packed <- map(cols, ~ .data[.x]) if (!is.null(.names_sep)) { packed <- imap(packed, strip_names, names_sep = .names_sep) } packed <- new_data_frame(packed, n = vec_size(.data)) out <- vec_cbind(unpacked, packed) reconstruct_tibble(.data, out) } unpack <- function(data, cols, names_sep = NULL, names_repair = "check_unique") { check_required(cols) cols <- tidyselect::eval_select(enquo(cols), data) size <- vec_size(data) out <- tidyr_new_list(data) cols <- out[cols] cols <- cols[map_lgl(cols, is.data.frame)] cols_names <- names(cols) if (!is.null(names_sep)) { out[cols_names] <- map2( cols, cols_names, rename_with_names_sep, names_sep = names_sep ) } names <- names(out) names[names %in% cols_names] <- "" names(out) <- names out <- df_list(!!!out, .size = size, .name_repair = "minimal") out <- tibble::new_tibble(out, nrow = size) names(out) <- vec_as_names( names = names(out), repair = names_repair, repair_arg = "names_repair" ) reconstruct_tibble(data, out) } rename_with_names_sep <- function(x, outer, names_sep) { inner <- names(x) names <- apply_names_sep(outer, inner, names_sep) set_names(x, names) } strip_names <- function(df, base, names_sep) { base <- vec_paste0(base, names_sep) names <- names(df) has_prefix <- regexpr(base, names, fixed = TRUE) == 1L names[has_prefix] <- substr(names[has_prefix], nchar(base) + 1, nchar(names[has_prefix])) set_names(df, names) }
local({ makeLazyLoadDB <- function(from, filebase, compress = TRUE, ascii = FALSE, variables) { envlist <- function(e) .Internal(getVarsFromFrame(ls(e, all = TRUE), e, FALSE)) envtable <- function() { idx <- 0 envs <- NULL enames <- character(0) find <- function(v, keys, vals) { for (i in seq_along(keys)) if (identical(v, keys[[i]])) return(vals[i]) NULL } getname <- function(e) find(e, envs, enames) getenv <- function(n) find(n, enames, envs) insert <- function(e) { idx <<- idx + 1 name <- paste("env", idx, sep="::") envs <<- c(e, envs) enames <<- c(name, enames) name } list(insert = insert, getenv = getenv, getname = getname) } lazyLoadDBinsertValue <- function(value, file, ascii, compress, hook) .Internal(lazyLoadDBinsertValue(value, file, ascii, compress, hook)) lazyLoadDBinsertListElement <- function(x, i, file, ascii, compress, hook) .Internal(lazyLoadDBinsertValue(x[[i]], file, ascii, compress, hook)) lazyLoadDBinsertVariable <- function(n, e, file, ascii, compress, hook) { x <- .Internal(getVarsFromFrame(n, e, FALSE)) .Internal(lazyLoadDBinsertValue(x[[1L]], file, ascii, compress, hook)) } mapfile <- paste(filebase, "rdx", sep = ".") datafile <- paste(filebase, "rdb", sep = ".") close(file(datafile, "w")) table <- envtable() varenv <- new.env(hash = TRUE) envenv <- new.env(hash = TRUE) envhook <- function(e) { if (is.environment(e)) { name <- table$getname(e) if (is.null(name)) { name <- table$insert(e) data <- list(bindings = envlist(e), enclos = parent.env(e)) key <- lazyLoadDBinsertValue(data, datafile, ascii, compress, envhook) assign(name, key, envir = envenv) } name } } if (is.environment(from)) { if (! missing(variables)) vars <- variables else vars <- ls(from, all = TRUE) } else if (is.list(from)) { vars <- names(from) if (length(vars) != length(from) || any(nchar(vars) == 0)) stop("source list must have names for all elements") } else stop("source must be an environment or a list"); for (i in seq_along(vars)) { if (is.environment(from)) key <- lazyLoadDBinsertVariable(vars[i], from, datafile, ascii, compress, envhook) else key <- lazyLoadDBinsertListElement(from, i, datafile, ascii, compress, envhook) assign(vars[i], key, envir = varenv) } vals <- lapply(vars, get, envir = varenv, inherits = FALSE) names(vals) <- vars rvars <- ls(envenv, all = TRUE) rvals <- lapply(rvars, get, envir = envenv, inherits = FALSE) names(rvals) <- rvars val <- list(variables = vals, references = rvals, compressed = compress) saveRDS(val, mapfile) } omit <- c(".Last.value", ".AutoloadEnv", ".BaseNamespaceEnv", ".Device", ".Devices", ".Machine", ".Options", ".Platform") if (length(search()[search()!="Autoloads"]) != 2) stop("start R with NO packages loaded to create the data base") baseFileBase <- file.path(.Library,"base","R","base") if (file.info(baseFileBase)["size"] < 20000) stop("may already be using lazy loading on base"); basevars <- ls(baseenv(), all.names=TRUE) prims <- basevars[sapply(basevars, function(n) is.primitive(get(n, baseenv())))] basevars <- basevars[! basevars %in% c(omit, prims)] makeLazyLoadDB(baseenv(), baseFileBase, variables = basevars) })
`getsurv` <- function(times,icfit,nonUMLE.method="interpolation"){ ntimes<-length(times) method<-match.arg(nonUMLE.method,c("interpolation","left","right")) getsurvOneStratum<-function(L,R,p){ Sout<-rep(NA,ntimes) mle<-rep(TRUE,ntimes) S<-c(1-cumsum(p)) nonUMLE.func<-switch(method, interpolation=function(i,Time){ if (R[i]==Inf) stop("cannot interpolate when R[i]=Inf") if (i==1){ 1 + ((Time - L[i])/(R[i]-L[i]))*(S[i]-1) } else { S[i-1] + ((Time - L[i])/(R[i]-L[i]))*(S[i]-S[i-1])}}, left=function(i,Time){ ifelse(i<=1,1,S[i-1]) }, right=function(i,Time){ S[i]}) k<-length(p) for (i in 1:ntimes){ if (any(times[i]==R)){ Sout[i]<-S[times[i]==R] } else if (times[i]<=L[1]){ Sout[i]<-1 } else if (times[i]>=R[k]){ Sout[i]<-0 } else { if (times[i]>L[k]){ Sout[i]<-nonUMLE.func(k,times[i]) mle[i]<-FALSE } else { iLup<-min((1:k)[L>=times[i]]) if (R[iLup-1]<=times[i] | L[iLup]==times[i]) Sout[i]<-S[iLup-1] else { Sout[i]<- nonUMLE.func(iLup-1,times[i]) mle[i]<-FALSE } } } } out<-list(S=Sout,times=times,unique.mle=mle,nonUMLE.method=method) out } if (is.null(icfit$strata)){ icfit$strata<-c(length(icfit$pf)) } nstrata<-length(icfit$strata) strata<-icfit$strata cnt<-1 for (i in 1:nstrata){ I<-cnt:(cnt+strata[i]-1) p<-icfit$pf[I] L<-icfit$intmap[1,I] R<-icfit$intmap[2,I] cnt<-cnt+strata[i] if (i==1) OUT<-list(getsurvOneStratum(L,R,p)) else OUT<-c(OUT,list(getsurvOneStratum(L,R,p))) } if (nstrata>1){ strataNames<-names(strata) names(strataNames)<-1:nstrata OUT<-c(OUT,list(strataNames=strataNames)) } OUT }
if(getRversion() >= "2.15.1") utils::globalVariables("output") parse_less <- function(code) { get_v8_console()$call("rlessParse", code, "output") output }
NyeSimilarity <- function (tree1, tree2 = NULL, similarity = TRUE, normalize = FALSE, normalizeMax = !is.logical(normalize), reportMatching = FALSE, diag = TRUE) { unnormalized <- CalculateTreeDistance(NyeSplitSimilarity, tree1, tree2, reportMatching) if (similarity) { InfoInTree <- if (normalizeMax) SplitsInBinaryTree else NSplits if (diag && is.null(tree2)) { unnormalized <- as.matrix(unnormalized) diag(unnormalized) <- InfoInTree(tree1) } NormalizeInfo(unnormalized, tree1, tree2, how = normalize, InfoInTree = InfoInTree, Combine = .MeanOfTwo) } else { unnormalized <- .MaxValue(tree1, tree2, NSplits) - (unnormalized + unnormalized) NormalizeInfo(unnormalized, tree1, tree2, how = normalize, InfoInTree = NSplits, Combine = '+') } } .MeanOfTwo <- function (x, y) (x + y) / 2L NyeSplitSimilarity <- function (splits1, splits2, nTip = attr(splits1, 'nTip'), reportMatching = FALSE) { GeneralizedRF(splits1, splits2, nTip, cpp_jaccard_similarity, k = 1L, allowConflict = TRUE, maximize = TRUE, reportMatching = reportMatching) } JaccardRobinsonFoulds <- function (tree1, tree2 = NULL, k = 1L, allowConflict = TRUE, similarity = FALSE, normalize = FALSE, reportMatching = FALSE) { unnormalized <- CalculateTreeDistance(JaccardSplitSimilarity, tree1, tree2, k = k, allowConflict = allowConflict, reportMatching = reportMatching) * 2L if (!similarity) { unnormalized <- .MaxValue(tree1, tree2, NSplits) - unnormalized } NormalizeInfo(unnormalized, tree1, tree2, how = normalize, InfoInTree = NSplits, Combine = '+') } JaccardSplitSimilarity <- function (splits1, splits2, nTip = attr(splits1, 'nTip'), k = 1L, allowConflict = TRUE, reportMatching = FALSE) { GeneralizedRF(splits1, splits2, nTip, cpp_jaccard_similarity, k = k, allowConflict = allowConflict, maximize = TRUE, reportMatching = reportMatching) }
"ratskin"
gisco_get_lau <- function(year = "2016", epsg = "4326", cache = TRUE, update_cache = FALSE, cache_dir = NULL, verbose = FALSE, country = NULL, gisco_id = NULL) { ext <- "geojson" api_entry <- gsc_api_url( id_giscoR = "lau", year = year, epsg = epsg, resolution = 0, spatialtype = "RG", ext = ext, nuts_level = NULL, level = NULL, verbose = verbose ) filename <- basename(api_entry) if ((!is.null(country) || !is.null(gisco_id)) && cache) { gsc_message(verbose, "Speed up using sf query") if (!is.null(country)) { country <- gsc_helper_countrynames( country, "eurostat" ) } namefileload <- gsc_api_cache( api_entry, filename, cache_dir, update_cache, verbose ) layer <- tools::file_path_sans_ext(basename(namefileload)) q <- paste0( "SELECT * from \"", layer, "\" WHERE" ) where <- NULL if (!is.null(country)) { where <- c(where, paste0( "CNTR_CODE IN (", paste0("'", country, "'", collapse = ", "), ")" )) } if (!is.null(gisco_id)) { where <- c(where, paste0( "GISCO_ID IN (", paste0("'", gisco_id, "'", collapse = ", "), ")" )) } where <- paste(where, collapse = " OR ") q <- paste(q, where) gsc_message(verbose, "Using query:\n ", q) data_sf <- try( suppressWarnings( sf::st_read(namefileload, quiet = !verbose, query = q ) ), silent = TRUE ) if (!inherits(data_sf, "try-error")) { data_sf <- sf::st_make_valid(data_sf) return(data_sf) } update_cache <- FALSE rm(data_sf) gsc_message( TRUE, "\n\nIt was a problem with the query.", "Retrying without country filters\n\n" ) } if (cache) { namefileload <- gsc_api_cache( api_entry, filename, cache_dir, update_cache, verbose ) } else { namefileload <- api_entry } data_sf <- gsc_api_load(namefileload, epsg, ext, cache, verbose) if (!is.null(country) & "CNTR_CODE" %in% names(data_sf)) { country <- gsc_helper_countrynames(country, "eurostat") data_sf <- data_sf[data_sf$CNTR_CODE %in% country, ] } if (!is.null(country) & "CNTR_ID" %in% names(data_sf)) { country <- gsc_helper_countrynames(country, "eurostat") data_sf <- data_sf[data_sf$CNTR_ID %in% country, ] } if (!is.null(gisco_id) & "GISCO_ID" %in% names(data_sf)) { data_sf <- data_sf[data_sf$GISCO_ID %in% gisco_id, ] } return(data_sf) } gisco_get_communes <- function(year = "2016", epsg = "4326", cache = TRUE, update_cache = FALSE, cache_dir = NULL, verbose = FALSE, spatialtype = "RG", country = NULL) { ext <- "geojson" api_entry <- gsc_api_url( id_giscoR = "communes", year = year, epsg = epsg, resolution = 0, spatialtype = spatialtype, ext = ext, nuts_level = NULL, level = NULL, verbose = verbose ) filename <- basename(api_entry) if (cache && !is.null(country)) { gsc_message(verbose, "Speed up using sf query") country <- gsc_helper_countrynames(country, "eurostat") namefileload <- gsc_api_cache( api_entry, filename, cache_dir, update_cache, verbose ) layer <- tools::file_path_sans_ext(basename(namefileload)) q <- paste0( "SELECT * from \"", layer, "\" WHERE CNTR_CODE IN (", paste0("'", country, "'", collapse = ", "), ")" ) gsc_message(verbose, "Using query:\n ", q) data_sf <- try( suppressWarnings( sf::st_read(namefileload, quiet = !verbose, query = q ) ), silent = TRUE ) if (!inherits(data_sf, "try-error")) { data_sf <- sf::st_make_valid(data_sf) return(data_sf) } update_cache <- FALSE rm(data_sf) gsc_message( TRUE, "\n\nIt was a problem with the query.", "Retrying without country filters\n\n" ) } if (cache) { namefileload <- gsc_api_cache( api_entry, filename, cache_dir, update_cache, verbose ) } else { namefileload <- api_entry } data_sf <- gsc_api_load( namefileload, epsg, ext, cache, verbose ) return(data_sf) }
parse_symbols <- function(data) { template <- list( "cost" = as.character, "symbol" = as.character, "colors" = function(x) list(unlist(x)), "cmc" = as.numeric, "loose_variant" = as.character, "english" = as.character, "gatherer_alternates" = function(x) list(unlist(x)), "transposable" = as.logical, "represents_mana" = as.logical, "appears_in_mana_costs" = as.logical, "funny" = as.logical, "svg_uri" = as.character, "colorless" = as.logical, "monocolored" = as.logical, "multicolored" = as.logical ) bind_rows(data, template) }
cleanr::set_cleanr_options(reset = TRUE) path <- system.file("runit_tests", "runit_wrappers.R", package = "cleanr") print(cleanr::check_file_layout(path)) cleanr::get_cleanr_options(flatten_list = FALSE) print(tools::assertCondition(cleanr::check_file_layout(path, max_file_width = 79), c("cleanr", "error", "condition")) ) cleanr::set_cleanr_options(max_file_width = 75, max_file_length = 20) print(tools::assertCondition(cleanr::check_file_layout(path), c("cleanr", "error", "condition")) ) cleanr::set_cleanr_options(reset = TRUE) path <- system.file("source", "R", "checks.R", package = "cleanr") print(cleanr::check_file_layout(path)) print(tools::assertCondition(cleanr::check_file_layout(path, max_file_length = 100), c("cleanr", "error", "condition")) ) print(suppressWarnings(cleanr::check_functions_in_file(path))) print(tools::assertCondition(suppressWarnings(cleanr::check_functions_in_file(path, max_num_arguments = 1)), c("cleanr", "error", "condition")) ) print(suppressWarnings(cleanr::check_file(path))) path <- system.file("runit_tests", package = "cleanr") print(suppressWarnings(cleanr::check_directory(path, check_return = FALSE))) path <- system.file("source", "R", package = "cleanr") cleanr::load_internal_functions("cleanr") print(tools::assertCondition(suppressWarnings(cleanr::check_directory(path)), c("cleanr", "error", "condition")) ) cleanr::set_cleanr_options(reset = TRUE) cleanr::load_internal_functions("cleanr") path <- system.file("source", "R", "wrappers.R", package = "cleanr") r <- tools::assertCondition(cleanr::check_functions_in_file(path, check_return = FALSE), c("cleanr", "error", "condition")) print(r) r <- cleanr::check_functions_in_file(path, check_return = FALSE, max_num_arguments = FALSE) print(r) co <- get_cleanr_options(flatten_list = FALSE) co <- lapply(co, function(x) x == FALSE) options("cleanr" = list(cleanr = co)) get_cleanr_options() path <- system.file("source", "R", package = "cleanr") cleanr::load_internal_functions("cleanr") print(cleanr::check_directory(path))
context("matchSingleIndex") test_that("matchSingleIndex correctly finds matching rows", { ky <- seq(1,10) dta <- as.character(paste("data", ky)) df1 <- data.frame(ky, dta, stringsAsFactors = FALSE) ky <- seq(7,15) dta <- as.character(paste("data", ky)) df2 <- data.frame(ky, dta, stringsAsFactors = FALSE) ky <- seq(7,10) dta <- as.character(paste("data", ky)) dfMtch <- data.frame(ky, dta, stringsAsFactors = FALSE) mtch <- matchSingleIndex(df1, df2, "ky") msgA <- seq(1,6) msgB <- seq(11,15) expect_equal(mtch[[1]][,1], dfMtch[,1]) expect_equal(mtch[[1]][,2], dfMtch[,2]) expect_equal(mtch[[2]][,1], dfMtch[,1]) expect_equal(mtch[[2]][,2], dfMtch[,2]) expect_equal(mtch[[3]][[1]][[1]], msgA) expect_equal(mtch[[3]][[2]][[1]], msgB) })
bdmake <- function(mat1, mat2) { r1 = length(mat1[, 1]) r2 = length(mat2[, 1]) r3 = r1 + r2 res = matrix(rep(0, r3^2), ncol = r3) res[1:r1, 1:r1] = mat1 res[(r1 + 1):r3, (r1 + 1):r3] = mat2 return(res) }
test_that("abbreviate", { txt <- c("euclidean", "maximum", "manhattan", "canberra", "minimum") res <- c("euc", "max", "man", "can" ,"min") names(res) <- txt expect_equal(abbreviate_text(txt, 3), res) txt <- c("euclidean", "maximum", "manhattan", "manhattan", "canberra", "minimum") res <- c("euc", "max", "man", "man", "can", "min") names(res) <- txt expect_equal(abbreviate_text(txt, 3), res) txt <- c("euclidean", "maximum", "manhattan", NA, "canberra", "minimum", "abc", "abc") res <- c("euc", "max", "man", NA, "can", "min", "abc", "abc") names(res) <- txt expect_equal(abbreviate_text(txt, 3), res) txt <- c("ward.D", "ward.D2", "single", "complete", "average", "mcquitty", "median", "centroid") res <- c("ward", "warD", "sin", "com", "ave", "mcq", "med", "cen") names(res) <- txt expect_equal(abbreviate_text(txt, 3), res) res <- c("w", "r", "s", "c", "a", "q", "m", "e") names(res) <- txt expect_equal(abbreviate_text(txt, 0), res) res <- c("set", "ver", "vir") names(res) <- c("setosa", "versicolor", "virginica") expect_equal(abbreviate_text(unique(iris[,5])), res) })
addIdRecords <- function(ids, fullPed, partialPed) { if (length(ids[!all(is.na(ids))]) > 0) { addToPed <- fullPed[is.element(fullPed$id, ids), ] addToPed$sire <- NA addToPed$dam <- NA partialPed <- rbind(partialPed, addToPed, stringsAsFactors = FALSE) } partialPed[!duplicated(partialPed$id), ] }
boolSkip=FALSE TEST_ITERATIONS=2048 MAX_NUMBER_OF_PLAYERS=10 test_that("Check 21.4 - test if bit matrix created for 3 players created is equal to expected (A not specified)" ,{ if(boolSkip){ skip("Test was skipped") } expectedBitMatrix=rbind( c(1,0,0), c(0,1,0), c(0,0,1), c(1,1,0), c(1,0,1), c(0,1,1), c(1,1,1) ) expectedBitMatrix=cbind(expectedBitMatrix,cVal=0) actualBitMatrix=createBitMatrix(n=3) expect_equal(actualBitMatrix, expectedBitMatrix) }) test_that("Check 21.5 - test if bit matrix created for 4 players created is equal to expected (A not specified)" ,{ if(boolSkip){ skip("Test was skipped") } expectedBitMatrix=rbind( c(1,0,0,0), c(0,1,0,0), c(0,0,1,0), c(0,0,0,1), c(1,1,0,0), c(1,0,1,0), c(1,0,0,1), c(0,1,1,0), c(0,1,0,1), c(0,0,1,1), c(1,1,1,0), c(1,1,0,1), c(1,0,1,1), c(0,1,1,1), c(1,1,1,1) ) expectedBitMatrix=cbind(expectedBitMatrix,cVal=0) actualBitMatrix=createBitMatrix(n=4) expect_equal(actualBitMatrix, expectedBitMatrix) }) test_that("Check 21.6 - testing from getPlayersFromBitVector for all possibilities for either 3 or 4 players " ,{ if(boolSkip){ skip("Test was skipped") } expect_equal(getPlayersFromBitVector(bitVector = c(1,0,0,0)),c(1)) expect_equal(getPlayersFromBitVector(bitVector = c(0,1,0,0)),c(2)) expect_equal(getPlayersFromBitVector(bitVector = c(0,0,1,0)),c(3)) expect_equal(getPlayersFromBitVector(bitVector = c(1,1,0,0)),c(1,2)) expect_equal(getPlayersFromBitVector(bitVector = c(1,0,1,0)),c(1,3)) expect_equal(getPlayersFromBitVector(bitVector = c(0,1,1,0)),c(2,3)) expect_equal(getPlayersFromBitVector(bitVector = c(1,1,1,0)),c(1,2,3)) expect_equal(getPlayersFromBitVector(bitVector = c(1,0,0,0,0)),c(1)) expect_equal(getPlayersFromBitVector(bitVector = c(0,1,0,0,0)),c(2)) expect_equal(getPlayersFromBitVector(bitVector = c(0,0,1,0,0)),c(3)) expect_equal(getPlayersFromBitVector(bitVector = c(0,0,0,1,0)),c(4)) expect_equal(getPlayersFromBitVector(bitVector = c(1,1,0,0,0)),c(1,2)) expect_equal(getPlayersFromBitVector(bitVector = c(1,0,1,0,0)),c(1,3)) expect_equal(getPlayersFromBitVector(bitVector = c(1,0,0,1,0)),c(1,4)) expect_equal(getPlayersFromBitVector(bitVector = c(0,1,1,0,0)),c(2,3)) expect_equal(getPlayersFromBitVector(bitVector = c(0,1,0,1,0)),c(2,4)) expect_equal(getPlayersFromBitVector(bitVector = c(0,0,1,1,0)),c(3,4)) expect_equal(getPlayersFromBitVector(bitVector = c(1,1,1,0,0)),c(1,2,3)) expect_equal(getPlayersFromBitVector(bitVector = c(1,1,0,1,0)),c(1,2,4)) expect_equal(getPlayersFromBitVector(bitVector = c(0,1,1,1,0)),c(2,3,4)) expect_equal(getPlayersFromBitVector(bitVector = c(1,1,1,1,0)),c(1,2,3,4)) }) test_that("Check 21.7 - testing from getPlayersFromBitVector for all possibilities for either 3 or 4 players " ,{ if(boolSkip){ skip("Test was skipped") } bm3=createBitMatrix(n=3) bm4=createBitMatrix(n=4) expect_equal(getPlayersFromBMRow(bm3[1,]),c(1)) expect_equal(getPlayersFromBMRow(bm3[2,]),c(2)) expect_equal(getPlayersFromBMRow(bm3[3,]),c(3)) expect_equal(getPlayersFromBMRow(bm3[4,]),c(1,2)) expect_equal(getPlayersFromBMRow(bm3[5,]),c(1,3)) expect_equal(getPlayersFromBMRow(bm3[6,]),c(2,3)) expect_equal(getPlayersFromBMRow(bm3[7,]),c(1,2,3)) expect_equal(getPlayersFromBMRow(bm4[1,]),c(1)) expect_equal(getPlayersFromBMRow(bm4[2,]),c(2)) expect_equal(getPlayersFromBMRow(bm4[3,]),c(3)) expect_equal(getPlayersFromBMRow(bm4[4,]),c(4)) expect_equal(getPlayersFromBMRow(bm4[5,]),c(1,2)) expect_equal(getPlayersFromBMRow(bm4[6,]),c(1,3)) expect_equal(getPlayersFromBMRow(bm4[7,]),c(1,4)) expect_equal(getPlayersFromBMRow(bm4[8,]),c(2,3)) expect_equal(getPlayersFromBMRow(bm4[9,]),c(2,4)) expect_equal(getPlayersFromBMRow(bm4[10,]),c(3,4)) expect_equal(getPlayersFromBMRow(bm4[11,]),c(1,2,3)) expect_equal(getPlayersFromBMRow(bm4[12,]),c(1,2,4)) expect_equal(getPlayersFromBMRow(bm4[13,]),c(1,3,4)) expect_equal(getPlayersFromBMRow(bm4[14,]),c(2,3,4)) expect_equal(getPlayersFromBMRow(bm4[15,]),c(1,2,3,4)) }) test_that("Check 21.8 - test if getPlayersFromBMRow and getPlayersFromIndex achieve equal outcomes when expected to" ,{ if(boolSkip){ skip("Test was skipped") } for(numberOfPlayers in 2:MAX_NUMBER_OF_PLAYERS){ bm=createBitMatrix(numberOfPlayers) numberOfCoalitions=(2^numberOfPlayers)-1 for(i in 1:numberOfCoalitions){ playersFromBMRow=getPlayersFromBMRow(bm[i,]) playersFromIndex=getPlayersFromIndex(n=numberOfPlayers, bitIndex = i) expect_equal(playersFromBMRow, playersFromIndex) } } })
get.max_precision <- function(preds, labels) { DT <- data.table(y_true = labels, y_prob = preds, key = "y_prob") cleaner <- !duplicated(DT[, "y_prob"], fromLast = TRUE) nump <- sum(y_true) DT[, fp_v := cumsum(y_true == 1)] DT[, tp_v := nump - fp_v] DT <- DT[cleaner, ] DT[, prec := tp_v / (tp_v + fp_v)] best_row <- which.max(DT$prec) if (length(best_row) > 0) { return(c(DT$prec[best_row[1]], DT$y_prob[best_row[1]])) } else { return(c(-1, -1)) } }