code
stringlengths
1
13.8M
dob <- function(n, random = TRUE, x = NULL, start = Sys.Date() - 365*15, k = 365*2, by = "1 days", prob = NULL, name = "DOB"){ if (is.null(x)){ x <- seq(start, length = k, by = by) } if (!inherits(x, c("Date", "POSIXct", "POSIXt"))) warning("`x`may not a date vector") out <- sample(x = x, size = n, replace = TRUE, prob = prob) if (!random) out <- sort(out) varname(out, name) } birth <- hijack(dob, name = "Birth" )
varbvsmixupdate <- function (X, sigma, sa, w, xy, d, alpha0, mu0, Xr0, i) { n <- nrow(X) p <- ncol(X) K <- length(w) if (!is.double(X) || !is.matrix(X)) stop("Input X should be a double-precision matrix") if (length(sigma) != 1) stop("Input sigma should be a scalar") if (length(sa) != K) stop("Input sa should have length equal to input w") if (!(length(xy) == p & length(d) == p)) stop("Inputs xy and d should have length = ncol(X)") if (any(c(dim(alpha0),dim(mu0)) != c(p,K,p,K))) stop(paste("Inputs alpha0 and mu0 should be p x K matrices,", "with p = ncol(X) and K = length(w)")) if (length(Xr0) != n) stop("length(Xr0) must be equal to nrow(X)") if (sum(i < 1 | i > p) > 0) stop("Input i contains invalid variable indices") alpha <- t(alpha0) mu <- t(mu0) Xr <- c(Xr0) out <- .Call(C_varbvsmixupdate_Call,X = X,sigma = as.double(sigma), sa = as.double(sa),w = as.double(w),xy = as.double(xy), d = as.double(d),alpha = alpha,mu = mu,Xr = Xr, i = as.integer(i-1),eps = eps) return(list(alpha = t(alpha),mu = t(mu),Xr = Xr)) }
desc2df <- function(desc){ fields <- desc::desc_fields(desc) field_content <- sapply(fields, function(i) desc::desc_get_field(key = i, default = NA, trim_ws = TRUE, file = desc)) mt <- matrix(field_content,nrow = 1,dimnames = list(NULL,fields)) data.frame(mt,check.names = FALSE,stringsAsFactors = FALSE) }
context("f_eval") test_that("first argument must be a function", { expect_error(f_eval(10), "`f` is not a formula") }) test_that("f_eval uses formula's environment", { x <- 10 f <- local({ y <- 100 ~ x + y }) expect_equal(f_eval(f), 110) }) test_that("data needs to be a list", { expect_error(f_eval(~ x, 10), "Do not know how to find data") }) test_that("looks first in `data`", { x <- 10 data <- list(x = 100) expect_equal(f_eval(~ x, data), 100) }) test_that("pronouns resolve ambiguity looks first in `data`", { x <- 10 data <- list(x = 100) expect_equal(f_eval(~ .data$x, data), 100) expect_equal(f_eval(~ .env$x, data), 10) }) test_that("pronouns complain about missing values", { expect_error(f_eval(~ .data$x, list()), "Variable 'x' not found in data") expect_error(f_eval(~ .env$`__`, list()), "Object '__' not found in environment") }) test_that("f_eval does quasiquoting", { x <- 10 expect_equal(f_eval(~ uq(quote(x))), 10) }) test_that("unquoted formulas look in their own env", { f <- function() { n <- 100 ~ n } n <- 10 expect_equal(f_eval(~ uq(f())), 10) }) test_that("unquoted formulas can use data", { f1 <- function() { z <- 100 ~ x + z } f2 <- function() { z <- 100 ~ .data$x + .env$z } z <- 10 expect_equal(f_eval(~ uq(f1()), data = list(x = 1)), 101) expect_equal(f_eval(~ uq(f2()), data = list(x = 1)), 101) }) test_that("f_eval_lhs uses lhs", { f <- 1 ~ 2 expect_equal(f_eval_lhs(f), 1) }) test_that("find data works for NULL, lists, and data frames", { expect_equal(find_data(NULL), list()) expect_equal(find_data(list(x = 1)), list(x = 1)) expect_equal(find_data(mtcars), mtcars) })
bzShiny <- function() { if (!requireNamespace("shiny", quietly = TRUE)) { stop("Shiny needed for this function to work. Please install it.", call. = FALSE) } if (!requireNamespace("shinythemes", quietly = TRUE)) { stop("shinythemes needed for this function to work. Please install it.", call. = FALSE) } if (!requireNamespace("DT", quietly = TRUE)) { stop("DT needed for this function to work. Please install it.", call. = FALSE) } appDir <- system.file("shiny", package = "beanz") if (appDir == "") { stop("Could not find Shiny directory. Try re-installing `beanz`.", call. = FALSE) } shiny::runApp(appDir, display.mode = "normal"); }
test_that("classif_obliqueRF", { requirePackages("obliqueRF", default.method = "load") parset.list = list( list(), list(ntree = 5L, mtry = 2L), list(training_method = "svm") ) old.predicts.list = list() old.probs.list = list() for (i in seq_along(parset.list)) { parset = parset.list[[i]] train = binaryclass.train target = train[, binaryclass.target] target = ifelse(target == binaryclass.task$task.desc$positive, 1, 0) train[, binaryclass.target] = NULL train = as.matrix(train) pars = list(x = train, y = target) pars = c(pars, parset) set.seed(getOption("mlr.debug.seed")) m = do.call(obliqueRF::obliqueRF, pars) binaryclass.test[, binaryclass.target] = NULL p = predict(m, newdata = binaryclass.test) p = as.factor(p) p = as.factor(ifelse(p == 1L, binaryclass.task$task.desc$positive, binaryclass.task$task.desc$negative)) p2 = predict(m, newdata = binaryclass.test, type = "prob") p2 = p2[, colnames(p2) == "1"] old.predicts.list[[i]] = p old.probs.list[[i]] = p2 } testSimpleParsets("classif.obliqueRF", binaryclass.df, binaryclass.target, binaryclass.train.inds, old.predicts.list, parset.list) testProbParsets("classif.obliqueRF", binaryclass.df, binaryclass.target, binaryclass.train.inds, old.probs.list, parset.list) })
fish.1 <- function(data, step1, ano, year.vec, tech.reg, rts, orientation, parallel, mean.x, mean.y, itt, it, shadow) { X1 <- t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$x.vars])) Y1 <- t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$y.vars])) X2 <- if (ano == 1) { t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$x.vars])) } else { t(as.matrix(data[data[, step1$time.var] == year.vec[ano - 1], step1$x.vars])) } Y2 <- if (ano == 1) { t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$y.vars])) } else { t(as.matrix(data[data[, step1$time.var] == year.vec[ano - 1], step1$y.vars])) } if (tech.reg == TRUE) { XREF1 <- X1 YREF1 <- Y1 XREF2 <- X2 YREF2 <- Y2 } else { XREF1 <- t(as.matrix(data[data[, step1$time.var] %in% year.vec[1:(ano)], step1$x.vars])) YREF1 <- t(as.matrix(data[data[, step1$time.var] %in% year.vec[1:(ano)], step1$y.vars])) XREF2 <- if (ano == 1) { t(as.matrix(data[data[, step1$time.var] %in% year.vec[1:(ano)], step1$x.vars])) } else { t(as.matrix(data[data[, step1$time.var] %in% year.vec[1:(ano - 1)], step1$x.vars])) } YREF2 <- if (ano == 1) { t(as.matrix(data[data[, step1$time.var] %in% year.vec[1:(ano)], step1$y.vars])) } else { t(as.matrix(data[data[, step1$time.var] %in% year.vec[1:(ano - 1)], step1$y.vars])) } } P1 <- t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$p.vars])) P2 <- if (ano == 1) { t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$p.vars])) } else { t(as.matrix(data[data[, step1$time.var] == year.vec[ano - 1], step1$p.vars])) } W1 <- t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$w.vars])) W2 <- if (ano == 1) { t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$w.vars])) } else { t(as.matrix(data[data[, step1$time.var] == year.vec[ano - 1], step1$w.vars])) } res2 <- foreach(dmu = 1:length(data[data[, step1$time.var] == year.vec[ano], step1$id.var]), .combine = rbind, .packages = c("lpSolveAPI")) %dopar% { if (nrow(data) > 99 & parallel == FALSE & ((ano-1)*nrow(data[data[, step1$time.var] == year.vec[ano], ])+dmu) %in% itt) { cat(nextElem(it)) flush.console() } P.Qt <- sum(P1[, dmu] * Y1[, dmu]) P.Qs <- sum(P1[, dmu] * Y2[, dmu]) P.Xt <- sum(W1[, dmu] * X1[, dmu]) P.Xs <- sum(W1[, dmu] * X2[, dmu]) L.Qt <- sum(P2[, dmu] * Y1[, dmu]) L.Qs <- sum(P2[, dmu] * Y2[, dmu]) L.Xt <- sum(W2[, dmu] * X1[, dmu]) L.Xs <- sum(W2[, dmu] * X2[, dmu]) Qt <- sqrt(L.Qt * P.Qt) Qs <- sqrt(L.Qs * P.Qs) Xt <- sqrt(L.Xt * P.Xt) Xs <- sqrt(L.Xs * P.Xs) AO <- Qt AI <- Xt TFP <- AO/AI MP <- sqrt(D.tfp(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREF1, YREF = YREF1, PRICESO = P1[, dmu], PRICESI = W1[, dmu], rts) * D.tfp(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREF1, YREF = YREF1, PRICESO = P2[, dmu], PRICESI = W2[, dmu], rts)) TFPE <- TFP/MP TFP2 <- Qs/Xs MP2 <- sqrt(D.tfp(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREF2, YREF = YREF2, PRICESO = P1[, dmu], PRICESI = W1[, dmu], rts) * D.tfp(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREF2, YREF = YREF2, PRICESO = P2[, dmu], PRICESI = W2[, dmu], rts)) TFPE2 <- TFP2/MP2 if (shadow == TRUE) { PO <- DO.shdu(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREF1, YREF = YREF1, rts) PI <- DI.shdu(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREF1, YREF = YREF1, rts) } else { PO <- NULL PI <- NULL } if (orientation == "out") { teseme.OL <- DO.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREF1, YREF = YREF1, PRICESO = P2[, dmu], rts) teseme.OP <- DO.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREF1, YREF = YREF1, PRICESO = P1[, dmu], rts) RAE <- sqrt(teseme.OL["OME"] * teseme.OP["OME"]) RE <- RAE * teseme.OL["OTE"] ROSE <- ((AO/(teseme.OL["OTE"] * RAE))/AI)/MP OSME <- RAE * ROSE RME <- TFPE/teseme.OL["OTE"]/teseme.OL["OSE"] REV <- sum(Y1[, dmu] * mean.y * P1[, dmu]) COST <- sum(X1[, dmu] * mean.x * W1[, dmu]) PROF <- REV/COST P <- REV/AO W <- COST/AI TT <- P/W teseme.O2L <- DO.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREF2, YREF = YREF2, PRICESO = P2[, dmu], rts) names(teseme.O2L) <- c("OTE2", "OSE2","OME2") teseme.O2P <- DO.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREF2, YREF = YREF2, PRICESO = P1[, dmu], rts) names(teseme.O2P) <- c("OTE2", "OSE2","OME2") RAE2 <- sqrt(teseme.O2L["OME2"] * teseme.O2P["OME2"]) RE2 <- RAE2 * teseme.O2L["OTE2"] ROSE2 <- ((Qs/(teseme.O2L["OTE2"] * RAE2))/Xs)/MP2 OSME2 <- RAE2 * ROSE2 RME2 <- TFPE2/teseme.O2L["OTE2"]/teseme.O2L["OSE2"] res1 <- c(REV = REV, COST = COST, PROF = PROF, P = P, W = W, TT = TT, AO = AO, AI = AI, TFP = TFP, MP = MP, TFPE = TFPE, teseme.OL[1:2], RAE = unname(RAE), ROSE = unname(ROSE), OSME = unname(OSME), RME = unname(RME), RE = unname(RE), Qt = Qt, Qs = Qs, Xt = Xt, Xs = Xs, TFP2 = TFP2, MP2 = MP2, TFPE2 = TFPE2, RAE2, ROSE2 = unname(ROSE2), OSME2 = unname(OSME2), RME2 = unname(RME2), RE2 = unname(RE2), PRICEI = PI, PRICEO = PO) } else { if (orientation == "in") { teseme.IL <- DI.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREF1, YREF = YREF1, PRICESI = W2[, dmu], rts) teseme.IP <- DI.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREF1, YREF = YREF1, PRICESI = W1[, dmu], rts) CAE <- sqrt(teseme.IL["IME"] * teseme.IP["IME"]) CE <- CAE * teseme.IL["ITE"] RISE <- (AO/(AI * CAE * teseme.IL["ITE"]))/MP ISME <- CAE * RISE RME <- TFPE/teseme.IL["ITE"]/teseme.IL["ISE"] REV <- sum(Y1[, dmu] * mean.y * P1[, dmu]) COST <- sum(X1[, dmu] * mean.x * W1[, dmu]) PROF <- REV/COST P <- REV/AO W <- COST/AI TT <- P/W teseme.I2L <- DI.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREF2, YREF = YREF2, PRICESI = W2[, dmu], rts) names(teseme.I2L) <- c("ITE2", "ISE2","IME2") teseme.I2P <- DI.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREF2, YREF = YREF2, PRICESI = W1[, dmu], rts) names(teseme.I2P) <- c("ITE2", "ISE2","IME2") CAE2 <- sqrt(teseme.I2L["IME2"] * teseme.I2P["IME2"]) CE2 <- CAE2 * teseme.I2L["ITE2"] RISE2 <- (Qs/(Xs * CAE2 * teseme.I2L["ITE2"]))/MP2 ISME2 <- CAE2 * RISE2 RME2 <- TFPE2/teseme.I2L["ITE2"]/teseme.I2L["ISE2"] res1 <- c(REV = REV, COST = COST, PROF = PROF, P = P, W = W, TT = TT, AO = AO, AI = AI, TFP = TFP, MP = MP, TFPE = TFPE, teseme.IL[1:2], CAE = unname(CAE), RISE = unname(RISE), ISME = unname(ISME), RME = unname(RME), CE = unname(CE), Qt = Qt, Qs = Qs, Xt = Xt, Xs = Xs, TFP2 = TFP2, MP2 = MP2, TFPE2 = TFPE2, CAE2, RISE2 = unname(RISE2), ISME2 = unname(ISME2), RME2 = unname(RME2), CE2 = unname(CE2), PRICEI = PI, PRICEO = PO) } else { teseme.OL <- DO.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREF1, YREF = YREF1, PRICESO = P2[, dmu], rts) teseme.OP <- DO.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREF1, YREF = YREF1, PRICESO = P1[, dmu], rts) RAE <- sqrt(teseme.OL["OME"] * teseme.OP["OME"]) RE <- RAE * teseme.OL["OTE"] ROSE <- ((AO/(teseme.OL["OTE"] * RAE))/AI)/MP OSME <- RAE * ROSE RME <- TFPE/teseme.OL["OTE"]/teseme.OL["OSE"] teseme.IL <- DI.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREF1, YREF = YREF1, PRICESI = W2[, dmu], rts) teseme.IP <- DI.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREF1, YREF = YREF1, PRICESI = W1[, dmu], rts) CAE <- sqrt(teseme.IL["IME"] * teseme.IP["IME"]) CE <- CAE * teseme.IL["ITE"] RISE <- (AO/(AI * CAE * teseme.IL["ITE"]))/MP ISME <- CAE * RISE teseme.OIL <- sqrt(teseme.OL * teseme.IL) names(teseme.OIL)[1:2] <- c("OTE.ITE", "OSE.ISE") RAE.CAE <- sqrt(RAE * CAE) ROSE.RISE <- sqrt(ROSE * RISE) OSME.ISME <- RAE.CAE * ROSE.RISE RE.CE <- sqrt(RE * CE) REV <- sum(Y1[, dmu] * mean.y * P1[, dmu]) COST <- sum(X1[, dmu] * mean.x * W1[, dmu]) PROF <- REV/COST P <- REV/AO W <- COST/AI TT <- P/W teseme.O2L <- DO.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREF2, YREF = YREF2, PRICESO = P2[, dmu], rts) names(teseme.O2L) <- c("OTE2", "OSE2","OME2") teseme.O2P <- DO.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREF2, YREF = YREF2, PRICESO = P1[, dmu], rts) names(teseme.O2P) <- c("OTE2", "OSE2","OME2") RAE2 <- sqrt(teseme.O2L["OME2"] * teseme.O2P["OME2"]) RE2 <- RAE2 * teseme.O2L["OTE2"] ROSE2 <- ((Qs/(teseme.O2L["OTE2"] * RAE2))/Xs)/MP2 OSME2 <- RAE2 * ROSE2 RME2 <- TFPE2/teseme.O2L["OTE2"]/teseme.O2L["OSE2"] teseme.I2L <- DI.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREF2, YREF = YREF2, PRICESI = W2[, dmu], rts) names(teseme.I2L) <- c("ITE2", "ISE2","IME2") teseme.I2P <- DI.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREF2, YREF = YREF2, PRICESI = W1[, dmu], rts) names(teseme.I2P) <- c("ITE2", "ISE2","IME2") CAE2 <- sqrt(teseme.I2L["IME2"] * teseme.I2P["IME2"]) CE2 <- CAE2 * teseme.I2L["ITE2"] RISE2 <- (Qs/(Xs * CAE2 * teseme.I2L["ITE2"]))/MP2 ISME2 <- CAE2 * RISE2 teseme.OI2L <- sqrt(teseme.O2L * teseme.I2L) RE2.CE2 <- sqrt(RE2 * CE2) RAE2.CAE2 <- sqrt(RAE2 * CAE2) ROSE2.RISE2 <- sqrt(ROSE2 * RISE2) OSME2.ISME2 <- RAE2.CAE2 * ROSE2.RISE2 res1 <- c(REV = REV, COST = COST, PROF = PROF, P = P, W = W, TT = TT, AO = AO, AI = AI, TFP = TFP, MP = MP, TFPE = TFPE, teseme.OIL[1:2], RAE.CAE = unname(RAE.CAE), ROSE.RISE = unname(ROSE.RISE), OSME.ISME = unname(OSME.ISME), RME = unname(RME), RE.CE = unname(RE.CE), Qt = Qt, Qs = Qs, Xt = Xt, Xs = Xs, TFP2 = TFP2, MP2 = MP2, TFPE2 = TFPE2, RAE2.CAE2 = unname(RAE2.CAE2), ROSE2.RISE2 = unname(ROSE2.RISE2), OSME2.ISME2 = unname(OSME2.ISME2), RME2 = unname(RME2), RE2.CE2 = unname(RE2.CE2), PRICEI = PI, PRICEO = PO) } } return(res1) } res2 } fish.2 <- function(data, step1, ano, year.vec, rts, orientation, parallel, mean.x, mean.y, itt, it, shadow) { X1 <- t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$x.vars])) Y1 <- t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$y.vars])) X2 <- if (ano == 1) { t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$x.vars])) } else { t(as.matrix(data[data[, step1$time.var] == year.vec[ano - 1], step1$x.vars])) } Y2 <- if (ano == 1) { t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$y.vars])) } else { t(as.matrix(data[data[, step1$time.var] == year.vec[ano - 1], step1$y.vars])) } P1 <- t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$p.vars])) P2 <- if (ano == 1) { t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$p.vars])) } else { t(as.matrix(data[data[, step1$time.var] == year.vec[ano - 1], step1$p.vars])) } W1 <- t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$w.vars])) W2 <- if (ano == 1) { t(as.matrix(data[data[, step1$time.var] == year.vec[ano], step1$w.vars])) } else { t(as.matrix(data[data[, step1$time.var] == year.vec[ano - 1], step1$w.vars])) } XREFs <- t(as.matrix(data[, step1$x.vars])) YREFs <- t(as.matrix(data[, step1$y.vars])) res2 <- foreach(dmu = 1:length(data[data[, step1$time.var] == year.vec[ano], step1$id.var]), .combine = rbind, .packages = c("lpSolveAPI")) %dopar% { if (nrow(data) > 99 & parallel == FALSE & ((ano-1)*nrow(data[data[, step1$time.var] == year.vec[ano], ])+dmu) %in% itt) { cat(nextElem(it)) flush.console() } P.Qt <- sum(P1[, dmu] * Y1[, dmu]) P.Qs <- sum(P1[, dmu] * Y2[, dmu]) P.Xt <- sum(W1[, dmu] * X1[, dmu]) P.Xs <- sum(W1[, dmu] * X2[, dmu]) L.Qt <- sum(P2[, dmu] * Y1[, dmu]) L.Qs <- sum(P2[, dmu] * Y2[, dmu]) L.Xt <- sum(W2[, dmu] * X1[, dmu]) L.Xs <- sum(W2[, dmu] * X2[, dmu]) Qt <- sqrt(L.Qt * P.Qt) Qs <- sqrt(L.Qs * P.Qs) Xt <- sqrt(L.Xt * P.Xt) Xs <- sqrt(L.Xs * P.Xs) AO <- Qt AI <- Xt TFP <- AO/AI MP <- sqrt(D.tfp(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREFs, YREF = YREFs, PRICESO = P1[, dmu], PRICESI = W1[, dmu], rts) * D.tfp(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREFs, YREF = YREFs, PRICESO = P2[, dmu], PRICESI = W2[, dmu], rts)) TFPE <- TFP/MP TFP2 <- Qs/Xs MP2 <- sqrt(D.tfp(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREFs, YREF = YREFs, PRICESO = P1[, dmu], PRICESI = W1[, dmu], rts) * D.tfp(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREFs, YREF = YREFs, PRICESO = P2[, dmu], PRICESI = W2[, dmu], rts)) TFPE2 <- TFP2/MP2 if (shadow == TRUE) { PO <- DO.shdu(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREFs, YREF = YREFs, rts) PI <- DI.shdu(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREFs, YREF = YREFs, rts) } else { PO <- NULL PI <- NULL } if (orientation == "out") { teseme.OL <- DO.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREFs, YREF = YREFs, PRICESO = P2[, dmu], rts) teseme.OP <- DO.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREFs, YREF = YREFs, PRICESO = P1[, dmu], rts) RAE <- sqrt(teseme.OL["OME"] * teseme.OP["OME"]) RE <- RAE * teseme.OL["OTE"] ROSE <- ((AO/(teseme.OL["OTE"] * RAE))/AI)/MP OSME <- RAE * ROSE RME <- TFPE/teseme.OL["OTE"]/teseme.OL["OSE"] REV <- sum(Y1[, dmu] * mean.y * P1[, dmu]) COST <- sum(X1[, dmu] * mean.x * W1[, dmu]) PROF <- REV/COST P <- REV/AO W <- COST/AI TT <- P/W teseme.O2L <- DO.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREFs, YREF = YREFs, PRICESO = P2[, dmu], rts) names(teseme.O2L) <- c("OTE2", "OSE2","OME2") teseme.O2P <- DO.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREFs, YREF = YREFs, PRICESO = P1[, dmu], rts) names(teseme.O2P) <- c("OTE2", "OSE2","OME2") RAE2 <- sqrt(teseme.O2L["OME2"] * teseme.O2P["OME2"]) RE2 <- RAE2 * teseme.O2L["OTE2"] ROSE2 <- ((Qs/(teseme.O2L["OTE2"] * RAE2))/Xs)/MP2 OSME2 <- RAE2 * ROSE2 RME2 <- TFPE2/teseme.O2L["OTE2"]/teseme.O2L["OSE2"] res1 <- c(REV = REV, COST = COST, PROF = PROF, P = P, W = W, TT = TT, AO = AO, AI = AI, TFP = TFP, MP = MP, TFPE = TFPE, teseme.OL[1:2], RAE = unname(RAE), ROSE = unname(ROSE), OSME = unname(OSME), RME = unname(RME), RE = unname(RE), Qt = Qt, Qs = Qs, Xt = Xt, Xs = Xs, TFP2 = TFP2, MP2 = MP2, TFPE2 = TFPE2, RAE2, ROSE2 = unname(ROSE2), OSME2 = unname(OSME2), RME2 = unname(RME2), RE2 = unname(RE2), PRICEI = PI, PRICEO = PO) } else { if (orientation == "in") { teseme.IL <- DI.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREFs, YREF = YREFs, PRICESI = W2[, dmu], rts) teseme.IP <- DI.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREFs, YREF = YREFs, PRICESI = W1[, dmu], rts) CAE <- sqrt(teseme.IL["IME"] * teseme.IP["IME"]) CE <- CAE * teseme.IL["ITE"] RISE <- (AO/(AI * CAE * teseme.IL["ITE"]))/MP ISME <- CAE * RISE RME <- TFPE/teseme.IL["ITE"]/teseme.IL["ISE"] REV <- sum(Y1[, dmu] * mean.y * P1[, dmu]) COST <- sum(X1[, dmu] * mean.x * W1[, dmu]) PROF <- REV/COST P <- REV/AO W <- COST/AI TT <- P/W teseme.I2L <- DI.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREFs, YREF = YREFs, PRICESI = W2[, dmu], rts) names(teseme.I2L) <- c("ITE2", "ISE2","IME2") teseme.I2P <- DI.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREFs, YREF = YREFs, PRICESI = W1[, dmu], rts) names(teseme.I2P) <- c("ITE2", "ISE2","IME2") CAE2 <- sqrt(teseme.I2L["IME2"] * teseme.I2P["IME2"]) CE2 <- CAE2 * teseme.I2L["ITE2"] RISE2 <- (Qs/(Xs * CAE2 * teseme.I2L["ITE2"]))/MP2 ISME2 <- CAE2 * RISE2 RME2 <- TFPE2/teseme.I2L["ITE2"]/teseme.I2L["ISE2"] res1 <- c(REV = REV, COST = COST, PROF = PROF, P = P, W = W, TT = TT, AO = AO, AI = AI, TFP = TFP, MP = MP, TFPE = TFPE, teseme.IL[1:2], CAE = unname(CAE), RISE = unname(RISE), ISME = unname(ISME), RME = unname(RME), CE = unname(CE), Qt = Qt, Qs = Qs, Xt = Xt, Xs = Xs, TFP2 = TFP2, MP2 = MP2, TFPE2 = TFPE2, CAE2, RISE2 = unname(RISE2), ISME2 = unname(ISME2), RME2 = unname(RME2), CE2 = unname(CE2), PRICEI = PI, PRICEO = PO) } else { teseme.OL <- DO.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREFs, YREF = YREFs, PRICESO = P2[, dmu], rts) teseme.OP <- DO.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREFs, YREF = YREFs, PRICESO = P1[, dmu], rts) RAE <- sqrt(teseme.OL["OME"] * teseme.OP["OME"]) RE <- RAE * teseme.OL["OTE"] ROSE <- ((AO/(teseme.OL["OTE"] * RAE))/AI)/MP OSME <- RAE * ROSE RME <- TFPE/teseme.OL["OTE"]/teseme.OL["OSE"] teseme.IL <- DI.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREFs, YREF = YREFs, PRICESI = W2[, dmu], rts) teseme.IP <- DI.teseme(XOBS = X1[, dmu], YOBS = Y1[, dmu], XREF = XREFs, YREF = YREFs, PRICESI = W1[, dmu], rts) CAE <- sqrt(teseme.IL["IME"] * teseme.IP["IME"]) CE <- CAE * teseme.IL["ITE"] RISE <- (AO/(AI * CAE * teseme.IL["ITE"]))/MP ISME <- CAE * RISE teseme.OIL <- sqrt(teseme.OL * teseme.IL) names(teseme.OIL)[1:2] <- c("OTE.ITE", "OSE.ISE") RAE.CAE <- sqrt(RAE * CAE) ROSE.RISE <- sqrt(ROSE * RISE) OSME.ISME <- RAE.CAE * ROSE.RISE RE.CE <- sqrt(RE * CE) REV <- sum(Y1[, dmu] * mean.y * P1[, dmu]) COST <- sum(X1[, dmu] * mean.x * W1[, dmu]) PROF <- REV/COST P <- REV/AO W <- COST/AI TT <- P/W teseme.O2L <- DO.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREFs, YREF = YREFs, PRICESO = P2[, dmu], rts) names(teseme.O2L) <- c("OTE2", "OSE2","OME2") teseme.O2P <- DO.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREFs, YREF = YREFs, PRICESO = P1[, dmu], rts) names(teseme.O2P) <- c("OTE2", "OSE2","OME2") RAE2 <- sqrt(teseme.O2L["OME2"] * teseme.O2P["OME2"]) RE2 <- RAE2 * teseme.O2L["OTE2"] ROSE2 <- ((Qs/(teseme.O2L["OTE2"] * RAE2))/Xs)/MP2 OSME2 <- RAE2 * ROSE2 RME2 <- TFPE2/teseme.O2L["OTE2"]/teseme.O2L["OSE2"] teseme.I2L <- DI.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREFs, YREF = YREFs, PRICESI = W2[, dmu], rts) names(teseme.I2L) <- c("ITE2", "ISE2","IME2") teseme.I2P <- DI.teseme(XOBS = X2[, dmu], YOBS = Y2[, dmu], XREF = XREFs, YREF = YREFs, PRICESI = W1[, dmu], rts) names(teseme.I2P) <- c("ITE2", "ISE2","IME2") CAE2 <- sqrt(teseme.I2L["IME2"] * teseme.I2P["IME2"]) CE2 <- CAE2 * teseme.I2L["ITE2"] RISE2 <- (Qs/(Xs * CAE2 * teseme.I2L["ITE2"]))/MP2 ISME2 <- CAE2 * RISE2 teseme.OI2L <- sqrt(teseme.O2L * teseme.I2L) RE2.CE2 <- sqrt(RE2 * CE2) RAE2.CAE2 <- sqrt(RAE2 * CAE2) ROSE2.RISE2 <- sqrt(ROSE2 * RISE2) OSME2.ISME2 <- RAE2.CAE2 * ROSE2.RISE2 res1 <- c(REV = REV, COST = COST, PROF = PROF, P = P, W = W, TT = TT, AO = AO, AI = AI, TFP = TFP, MP = MP, TFPE = TFPE, teseme.OIL[1:2], RAE.CAE = unname(RAE.CAE), ROSE.RISE = unname(ROSE.RISE), OSME.ISME = unname(OSME.ISME), RME = unname(RME), RE.CE = unname(RE.CE), Qt = Qt, Qs = Qs, Xt = Xt, Xs = Xs, TFP2 = TFP2, MP2 = MP2, TFPE2 = TFPE2, RAE2.CAE2 = unname(RAE2.CAE2), ROSE2.RISE2 = unname(ROSE2.RISE2), OSME2.ISME2 = unname(OSME2.ISME2), RME2 = unname(RME2), RE2.CE2 = unname(RE2.CE2), PRICEI = PI, PRICEO = PO) } } return(res1) } res2 } print.Fisher <- function(x, digits = NULL, ...) { if (is.null(digits)) { digits <- max(3, getOption("digits") - 3) } cat("\nFisher productivity and profitability levels (summary):\n\n") print(summary(x[["Levels"]][-c(1:2)], digits = digits), digits = digits) cat("\n\nFisher productivity and profitability changes (summary):\n\n") print(summary(x[["Changes"]][-c(1:2)], digits = digits), digits = digits) if (!is.null(x[["Shadowp"]])) { cat("\n\nFisher productivity shadow prices (summary):\n\n") print(summary(x[["Shadowp"]][-c(1:2)], digits = digits), digits = digits) } cat("\n") invisible(x) }
whichCondOnLatent <- function( NNarray, firstind.pred=nrow(NNarray)+1 ){ n <- nrow(NNarray) m <- ncol(NNarray)-1 CondOnLatent <- matrix(NA,n,m+1) CondOnLatent[1,1] <- TRUE for(k in 2:n){ latents=rep(0,m) for(ind in 2:(m+1)){ l=NNarray[k,ind] if(!is.na(l) && l<firstind.pred) latents[ind]=sum(is.element(NNarray[k,],NNarray[l,]*CondOnLatent[l,])) } ind=NNarray[k,(which(latents==max(latents)))[1]] CondOnLatent[k, ] <- is.element( NNarray[k,], NNarray[ind,]*CondOnLatent[ind,] ) CondOnLatent[k,NNarray[k,]>=firstind.pred] <- TRUE CondOnLatent[k,1] <- TRUE CondOnLatent[k,is.na(NNarray[k,])] <- NA } return(CondOnLatent) }
pdPgram <- function(X, B, method = c("multitaper", "bartlett"), bias.corr = F, nw = 3) { if(missing(method)){ method <- "multitaper" } method <- match.arg(method, c("multitaper", "bartlett")) d <- ncol(X) n <- nrow(X) if (missing(B)) { B <- d } if(B < d){ warning("The number of tapers 'B' is smaller than the dimension of the time series 'ncol(X)'; the periodogram matrix is not positive definite.") } h <- switch(method, bartlett = matrix(0, 1, 1), multitaper = multitaper::dpss(n, B, nw = nw, returnEigenvalues = F)$v * sqrt(n)) P <- pgram_C(X, B, h, method, F) bias <- ifelse(bias.corr, B * exp(-1/d * sum(digamma(B - (d - 1:d)))), 1) return(list(freq = pi * (0:(dim(P)[3]-1))/dim(P)[3], P = bias * P)) } pdPgram2D <- function(X, B, tf.grid, method = c("dpss", "hermite"), nw = 3, bias.corr = F){ d <- ncol(X) n <- nrow(X) if(missing(method)) { method <- "dpss" } method <- match.arg(method, c("dpss", "hermite")) if (missing(B)) { B <- d } if(B < d){ warning("The number of tapers 'B' is smaller than the dimension of the time series 'ncol(X)'; the periodogram matrix is not positive definite!") } L <- ifelse(missing(tf.grid), 2^round(log2(sqrt(n))), length(tf.grid$time)) m <- 2 * floor(n / (2 * L)) if(missing(tf.grid)){ tf.grid <- list(time = seq(L + 1, n - L - 1, length = L)/n, freq = pi * 0:(m - 1) / m) } bias.corr <-ifelse(isTRUE(bias.corr & B >= d), B * exp(-1/d * sum(digamma(B - (d - 1:d)))), 1) if(method == "dpss"){ h <- multitaper::dpss(m, B, nw, returnEigenvalues = F)$v * sqrt(m) } else if(method == "hermite"){ Hermite <- function(k, t){ res <- numeric(length(t)) for(ti in t){ H <- numeric(k + 1) for(i in 0:k){ H[i + 1] <- (if(i == 0) 1 else if(i == 1) 2 * ti else 2 * ti * H[i] - 2 * (i - 1) * H[i - 1]) } res[which(t == ti)] <- exp(-ti^2 / 2) * H[k + 1] / sqrt(sqrt(pi) * 2^k * factorial(k)) } return(res) } h0 <- sapply(0:(B-1), function(b) Hermite(b, seq(-nw, nw, length = m))) norm.h0 <- sqrt(mean(h0[, 1]^2)) h <- apply(h0, 2, function(h.col) h.col / norm.h0) } Per <- sapply(tf.grid$time, function(ti) { pgram_C(X[round(ti * n) + (-floor(m/2 - 1)):(m / 2), ], B, h, "multitaper", T) }, simplify = "array") return(list(tf.grid = tf.grid, P = bias.corr * aperm(Per, c(1, 2, 4, 3)))) }
groupn <- function(x, y, m=150) { s <- !is.na(x + y) x<-x[s] y<-y[s] i<-order(x) x<-x[i] y<-y[i] n<-length(x) if(n<m) stop("m<number of observations in groupn") start <- 1 end <- m meanx <- NULL meany <- NULL while(end <= n) { meanx <- c(meanx,mean(x[start:end])) meany <- c(meany,mean(y[start:end])) start <- start+m end <- end+m } if(end > n) { meanx <- c(meanx,mean(x[n-m+1:n])) meany <- c(meany,mean(y[n-m+1:n])) } return(list(x=meanx,y=meany)) }
sdc_raster <- function( x , variable , r = 200 , max_risk = 0.95 , min_count = 10 , risk_type = c("external", "internal", "discrete") , ... , field = variable ){ if (!is(r, "Raster")){ if (is.numeric(r) && length(r) < 3 ){ r <- create_raster(x, res = r) } else{ stop("'r' must be either a raster or the size of a raster") } } v <- if (is.character(field)) x[[field]] else field type <- if (is.numeric(v)) { "numeric" } else if (is.logical(v)){ "logical" } else { stop("'variable' is not a numeric or logical.") } risk_type <- if (type == "logical") "discrete" else match.arg(risk_type) l <- list() l$sum <- raster::rasterize(x, r, fun = sum, field = field) l$count <- raster::rasterize(x, r, fun = "count", field = field) l$mean <- l$sum / l$count if (type == "numeric"){ l$max <- raster::rasterize(x, r, fun = max, field = field) l$max2 <- raster::rasterize(x, r, fun = max2, field = field) } value <- raster::brick(l, ...) new_sdc_raster( value, type = type , max_risk = max_risk, min_count = min_count , risk_type = risk_type ) } new_sdc_raster <- function( r , type = c("numeric", "logical") , max_risk , min_count , risk_type , scale = 1 ){ structure( list( value = r, max_risk = max_risk, min_count = min_count, risk_type = risk_type, scale = scale, type = type ), class="sdc_raster") } is_sdc_raster <- function(x, ...){ ("sdc_raster" %in% class(x)) } assert_sdc_raster <- function(x, ...){ if (!is_sdc_raster(x)){ stop("an object of type sdc_raster was expected.") } } print.sdc_raster <- function(x, ...){ cat(x$type, "sdc_raster object: \n" , " resolution:", raster::res(x$value) , ", max_risk:", x$max_risk , ", min_count:", x$min_count , "\n mean sensitivity score [0,1]: ", sensitivity_score(x) ) }
runcodeUI <- function(code = "", type = c("text", "textarea", "ace"), width = NULL, height = NULL, includeShinyjs = NULL, id = NULL) { ns <- shiny::NS(id) if (!missing(includeShinyjs)) { warning("`includeShinyjs` argument is deprecated. You should always make ", "sure to initialize shinyjs using `useShinyjs()`.") } type <- match.arg(type) if (type == "ace") { if (!requireNamespace("shinyAce", quietly = TRUE)) { errMsg("You need to install the 'shinyAce' package in order to use 'shinyAce' editor.") } } placeholder <- "Enter R code" shiny::singleton(shiny::tagList( if (type == "text") shiny::textInput( ns("runcode_expr"), label = NULL, value = code, width = width, placeholder = placeholder ), if (type == "textarea") shiny::textAreaInput( ns("runcode_expr"), label = NULL, value = code, width = width, height = height, placeholder = placeholder ), if (type == "ace") shinyAce::aceEditor(ns("runcode_expr"), mode = 'r', value = code, height = height, theme = "github", fontSize = 16), shiny::actionButton(ns("runcode_run"), "Run", class = "btn-success"), shinyjs::hidden( shiny::div( id = ns("runcode_error"), style = "color: red; font-weight: bold;", shiny::div("Oops, that resulted in an error! Try again."), shiny::div("Error: ", shiny::br(), shiny::tags$i(shiny::span( id = ns("runcode_errorMsg"), style = "margin-left: 10px;"))) ) ) )) } runcodeServer <- function() { parentFrame <- parent.frame(1) session <- getSession() shiny::observeEvent(session$input[['runcode_run']], { shinyjs::hide("runcode_error") tryCatch( shiny::isolate( eval(parse(text = session$input[['runcode_expr']]), envir = parentFrame) ), error = function(err) { shinyjs::html("runcode_errorMsg", as.character(err$message)) shinyjs::show(id = "runcode_error", anim = TRUE, animType = "fade") } ) }) invisible(NULL) }
control_sim_anneal <- function(verbose = TRUE, no_improve = Inf, restart = 8L, radius = c(0.05, 0.15), flip = 3/4, cooling_coef = 0.02, extract = NULL, save_pred = FALSE, time_limit = NA, pkgs = NULL, save_workflow = FALSE, save_history = FALSE, event_level = "first", parallel_over = NULL) { tune::val_class_and_single(verbose, "logical", "control_sim_anneal()") tune::val_class_and_single(save_pred, "logical", "control_sim_anneal()") tune::val_class_and_single(no_improve, c("numeric", "integer"), "control_sim_anneal()") tune::val_class_and_single(restart, c("numeric", "integer"), "control_sim_anneal()") tune::val_class_and_single(flip, "numeric", "control_sim_anneal()") tune::val_class_and_single(cooling_coef, "numeric", "control_sim_anneal()") tune::val_class_or_null(extract, "function", "control_sim_anneal()") tune::val_class_and_single(time_limit, c("logical", "numeric"), "control_sim_anneal()") tune::val_class_or_null(pkgs, "character", "control_sim_anneal()") tune::val_class_and_single(save_workflow, "logical", "control_sim_anneal()") tune::val_class_and_single(save_history, "logical", "control_sim_anneal()") if (!is.null(parallel_over)) { val_parallel_over(parallel_over, "control_sim_anneal()") } if (!is.numeric(radius) | !length(radius) == 2) { rlang::abort("Argument 'radius' should be two numeric values.") } radius <- sort(radius) radius[radius <= 0] <- 0.001 radius[radius >= 1] <- 0.999 flip[flip < 0] <- 0 flip[flip > 1] <- 1 cooling_coef[cooling_coef <= 0] <- 0.0001 if (no_improve < 2) { rlang::abort("'no_improve' should be > 1") } if (restart < 2) { rlang::abort("'restart' should be > 1") } if (!is.infinite(restart) && restart > no_improve) { cli::cli_alert_warning( "Parameter restart is scheduled after {restart} poor iterations but the search will stop after {no_improve}." ) } res <- list( verbose = verbose, no_improve = no_improve, restart = restart, radius = radius, flip = flip, cooling_coef = cooling_coef, extract = extract, save_pred = save_pred, time_limit = time_limit, pkgs = pkgs, save_workflow = save_workflow, save_history = save_history, event_level = event_level, parallel_over = parallel_over ) class(res) <- "control_sim_anneal" res } print.control_sim_anneal <- function(x, ...) { cat("Simulated annealing control object\n") invisible(x) } val_parallel_over <- function(parallel_over, where) { val_class_and_single(parallel_over, "character", where) rlang::arg_match0(parallel_over, c("resamples", "everything"), "parallel_over") invisible(NULL) }
NULL tk_augment_lags <- function(.data, .value, .lags = 1, .names = "auto") { column_expr <- enquo(.value) if (rlang::quo_is_missing(column_expr)) stop(call. = FALSE, "tk_augment_lags(.value) is missing.") UseMethod("tk_augment_lags", .data) } tk_augment_lags.data.frame <- function(.data, .value, .lags = 1, .names = "auto") { col_nms <- names(tidyselect::eval_select(rlang::enquo(.value), .data)) make_call <- function(col, lag_val) { rlang::call2( "lag_vec", x = rlang::sym(col), lag = lag_val, .ns = "timetk" ) } grid <- expand.grid( col = col_nms, lag_val = .lags, stringsAsFactors = FALSE ) calls <- purrr::pmap(.l = list(grid$col, grid$lag_val), make_call) if (any(.names == "auto")) { newname <- paste0(grid$col, "_lag", grid$lag_val) } else { newname <- as.list(.names) } calls <- purrr::set_names(calls, newname) ret <- tibble::as_tibble(dplyr::mutate(.data, !!!calls)) return(ret) } tk_augment_lags.grouped_df <- function(.data, .value, .lags = 1, .names = "auto") { column_expr <- enquo(.value) group_names <- dplyr::group_vars(.data) .data %>% tidyr::nest() %>% dplyr::mutate(nested.col = purrr::map( .x = data, .f = function(df) tk_augment_lags( .data = df, .value = !! enquo(.value), .lags = .lags, .names = .names ) )) %>% dplyr::select(-data) %>% tidyr::unnest(cols = nested.col) %>% dplyr::group_by_at(.vars = group_names) } tk_augment_lags.default <- function(.data, .value, .lags = 1, .names = "auto") { stop(paste0("`tk_augment_lags` has no method for class ", class(data)[[1]])) } tk_augment_leads <- function(.data, .value, .lags = -1, .names = "auto") { column_expr <- enquo(.value) if (rlang::quo_is_missing(column_expr)) stop(call. = FALSE, "tk_augment_leads(.value) is missing.") UseMethod("tk_augment_leads", .data) } tk_augment_leads.data.frame <- function(.data, .value, .lags = -1, .names = "auto") { col_nms <- names(tidyselect::eval_select(rlang::enquo(.value), .data)) make_call <- function(col, lag_val) { rlang::call2( "lag_vec", x = rlang::sym(col), lag = lag_val, .ns = "timetk" ) } grid <- expand.grid( col = col_nms, lag_val = .lags, stringsAsFactors = FALSE ) calls <- purrr::pmap(.l = list(grid$col, grid$lag_val), make_call) if (any(.names == "auto")) { newname <- paste0(grid$col, "_lag", grid$lag_val) %>% stringr::str_replace_all("lag-","lead") } else { newname <- as.list(.names) } calls <- purrr::set_names(calls, newname) ret <- tibble::as_tibble(dplyr::mutate(.data, !!!calls)) return(ret) } tk_augment_leads.grouped_df <- function(.data, .value, .lags = -1, .names = "auto") { column_expr <- enquo(.value) group_names <- dplyr::group_vars(.data) .data %>% tidyr::nest() %>% dplyr::mutate(nested.col = purrr::map( .x = data, .f = function(df) tk_augment_leads( .data = df, .value = !! enquo(.value), .lags = .lags, .names = .names ) )) %>% dplyr::select(-data) %>% tidyr::unnest(cols = nested.col) %>% dplyr::group_by_at(.vars = group_names) } tk_augment_leads.default <- function(.data, .value, .lags = 1, .names = "auto") { stop(paste0("`tk_augment_leads` has no method for class ", class(data)[[1]])) }
setClass( Class = "MacroBetaHirukawaJLNKernel", representation = representation( normalizationConst = "numeric" ), contains = "HirukawaJLNKernel" ) setGeneric ( name = "setNormalizationConstant", def = function(.Object){standardGeneric("setNormalizationConstant")} ) setMethod( f = "setNormalizationConstant", signature = "MacroBetaHirukawaJLNKernel", definition = function(.Object){ f <- function(x,kernel){ density(as(kernel,"HirukawaJLNKernel"),x,scaled=TRUE) } normalizationConst <- integrate(f,lower=0,upper=1,kernel=.Object)$value objectGlobalName <- deparse(substitute(.Object)) .Object@normalizationConst <- normalizationConst assign(objectGlobalName,.Object,envir=parent.frame()) } ) setMethod( f = "density", signature = "MacroBetaHirukawaJLNKernel", definition = function(x,values,scaled = FALSE) { .Object <- x x <- values isMatrix.x <- is.matrix(x) dims <- dim(x) if(!scaled){ x <- getScaledPoints(.Object,x) } if(length(.Object@normalizationConst) == 0){ objectGlobalName <- deparse(substitute(.Object)) setNormalizationConstant(.Object) assign(objectGlobalName,.Object,envir=parent.frame()) } numDataPoints <- length(x) index.nozero <- which(x>=0 & x <=1) x <- x[index.nozero] if(length(x) == 0){ return(rep(0,numDataPoints - length(index.nozero))) } x.indices <- numeric(length(x)) x.densities <- numeric(length(x)) if(length(.Object@densityCache) == length(.Object@dataPointsCache)){ x.indices <- match(x, .Object@dataPointsCache, nomatch=0) if(any(x.indices > 0)){ x.densities[x.indices != 0] <- .Object@densityCache[x.indices[x.indices!=0]] }else{} }else{} x.new <- x[x.indices == 0] x.new.length <- length(x.new) if(x.new.length > 0){ forceDensityCacheTo(.Object,numeric(0)) x.densities[x.indices == 0] <- callNextMethod(.Object, x.new, scaled=TRUE)/.Object@normalizationConst }else{} aux.density <- numeric(numDataPoints) aux.density[index.nozero] <- x.densities x.densities <- aux.density if(isMatrix.x){ dim(x.densities) <- dims } domain.length <- [email protected] - [email protected] if(!scaled){ x.densities <- x.densities/domain.length } return(x.densities) } ) macroBetaHirukawaJLNKernel <- function(dataPoints, b=length(dataPoints)^(-2/5), dataPointsCache=NULL, modified = FALSE, lower.limit=0,upper.limit=1){ dataPoints.scaled <- dataPoints dataPointsCache.scaled <- dataPointsCache if(is.null(dataPointsCache)){ dataPointsCache.scaled <- seq(0,1,0.01) } if(lower.limit!=0 || upper.limit!=1){ dataPoints.scaled <- (dataPoints-lower.limit)/(upper.limit-lower.limit) if(!is.null(dataPointsCache)){ dataPointsCache.scaled <- (dataPointsCache-lower.limit)/(upper.limit-lower.limit) } } kernel <- new(Class="MacroBetaHirukawaJLNKernel",dataPoints = dataPoints.scaled, b = b, dataPointsCache = dataPointsCache.scaled, modified = modified, lower.limit=lower.limit,upper.limit=upper.limit) setNormalizationConstant(kernel) setDensityCache(kernel, densityFunction=NULL) return(kernel) }
setClass('BiclustMethod', representation = representation('VIRTUAL', biclustFunction = 'function')) setGeneric('biclust', function(x,method, ...){standardGeneric('biclust')}) setMethod('biclust', c('matrix','BiclustMethod'), function(x,method, ...) { MYCALL<-match.call() ret<-method@biclustFunction(x,...) ret@Parameters<-c(list(Call=MYCALL,Method=method)) return(ret) }) setMethod('biclust', c('matrix','function'), function(x,method, ...) { method <- method() biclust(x,method, ...) }) setMethod('biclust', c('matrix','character'), function(x,method, ...) { method <- get(method[1], mode="function") biclust(x,method, ...) }) setClass('Biclust', representation = representation( Parameters = 'list', RowxNumber = 'matrix', NumberxCol = 'matrix', Number = 'numeric', info = 'list') ) BiclustResult <- function(mypara, a, b, c, d) { return(new('Biclust', Parameters=mypara, RowxNumber=a, NumberxCol=b, Number=c, info=d)) } setClass('BCBimax', contains = 'BiclustMethod', prototype = prototype( biclustFunction = function(x,minr=2,minc=2,number=100){bimaxbiclust(x,minr,minc,number)})) BCBimax <- function() { return(new('BCBimax')) } setClass('BCrepBimax', contains = 'BiclustMethod', prototype = prototype( biclustFunction = function(x,minr=2,minc=2,number=100,maxc=12){repbimaxbiclust(x,minr,minc,number,maxc)})) BCrepBimax <- function() { return(new('BCrepBimax')) } setClass('BCXmotifs', contains = 'BiclustMethod', prototype = prototype( biclustFunction = function(x,ns=10,nd=10,sd=5,alpha=0.05,number=10){xmotifbiclust(x,ns,nd,sd,alpha,number)})) BCXmotifs <- function() { return(new('BCXmotifs')) } setClass('BCCC', contains = 'BiclustMethod', prototype = prototype( biclustFunction = function(x,delta=1.0,alpha=1.5,number=100){ccbiclust(x,delta,alpha,number)})) BCCC <- function() { return(new('BCCC')) } setClass('BCSpectral', contains = 'BiclustMethod', prototype = prototype( biclustFunction = function(x,normalization="log",numberOfEigenvalues=3,minr=2, minc=2, withinVar=1) {spectral(x,normalization, numberOfEigenvalues, minr, minc, withinVar)})) BCSpectral <- function() { return(new('BCSpectral')) } setClass('BCPlaid', contains = 'BiclustMethod', prototype = prototype( biclustFunction = function(x, cluster="b", fit.model= ~ m + a + b, background=TRUE, background.layer=NA, background.df=1, row.release=0.7,col.release=0.7,shuffle=3, back.fit=2,max.layers=10,iter.startup=5,iter.layer=30, verbose=TRUE) {plaid(x, cluster, fit.model, background, background.layer, background.df, row.release, col.release, shuffle, back.fit, max.layers, iter.startup, iter.layer, verbose) })) BCPlaid <- function() { return(new('BCPlaid')) } setClass('BCQuest', contains = 'BiclustMethod', prototype = prototype( biclustFunction = function(x,ns=10,nd=10,sd=5,alpha=0.05,number=10){questmotif(x,ns,nd,sd,alpha,number)})) BCQuest <- function() { return(new('BCQuest')) } setClass('BCQuestord', contains = 'BiclustMethod', prototype = prototype( biclustFunction = function(x,d=1,ns=10,nd=10,sd=5,alpha=0.05,number=10){questordmotif(x,d,ns,nd,sd,alpha,number)})) BCQuestord <- function() { return(new('BCQuestord')) } setClass('BCQuestmet', contains = 'BiclustMethod', prototype = prototype( biclustFunction = function(x,quant=0.25,vari=1,ns=10,nd=10,sd=5,alpha=0.05,number=10){questmetmotif(x,quant,vari,ns,nd,sd,alpha,number)})) BCQuestmet <- function() { return(new('BCQuestmet')) } setMethod("show", "Biclust", function(object) { cat("\nAn object of class",class(object),"\n\n") cat("call:", deparse(object@Parameters$Call,0.75*getOption("width")), sep="\n\t") n<-object@Number n<-min(c(n,5)) if(n>1) { cat("\nNumber of Clusters found: ",object@Number, "\n") cat("\nFirst ",n," Cluster sizes:\n") rowcolsizes<-rbind(colSums(object@RowxNumber[,1:n]),rowSums(object@NumberxCol[1:n,])) rownames(rowcolsizes)<-c("Number of Rows:","Number of Columns:") colnames(rowcolsizes)<-paste("BC", 1:n) print(rowcolsizes) } else { if(n==1) cat("\nThere was one cluster found with\n ",sum(object@RowxNumber[,1]), "Rows and ", sum(object@NumberxCol), "columns") if(n==0) cat("\nThere was no cluster found") } cat("\n\n") }) setGeneric("summary") setMethod("summary", "Biclust", function(object) { cat("\nAn object of class",class(object),"\n\n") cat("call:", deparse(object@Parameters$Call,0.75*getOption("width")), sep="\n\t") n<-object@Number if(n>1) { cat("\nNumber of Clusters found: ",object@Number, "\n") cat("\nCluster sizes:\n") rowcolsizes<-rbind(colSums(object@RowxNumber[,1:n]),rowSums(object@NumberxCol[1:n,])) rownames(rowcolsizes)<-c("Number of Rows:","Number of Columns:") colnames(rowcolsizes)<-paste("BC", 1:n) print(rowcolsizes) } else { if(n==1) cat("\nThere was one cluster found with\n ",sum(object@RowxNumber[,1]), "Rows and ", sum(object@NumberxCol), "columns") if(n==0) cat("\nThere was no cluster found") } cat("\n\n") })
library(knitr) showMessage <- FALSE showWarning <- TRUE set_alias(w = "fig.width", h = "fig.height", res = "results") opts_chunk$set(comment = " tidy = FALSE, cache = FALSE, echo = TRUE, fig.width = 7, fig.height = 7, fig.path = "man/figures") regmedint:::calc_myreg_mreg_linear_yreg_linear_est regmedint:::calc_myreg_mreg_linear_yreg_linear_se regmedint:::calc_myreg_mreg_linear_yreg_logistic_est regmedint:::calc_myreg_mreg_linear_yreg_logistic_se regmedint:::calc_myreg_mreg_logistic_yreg_linear_est regmedint:::calc_myreg_mreg_logistic_yreg_linear_se regmedint:::calc_myreg_mreg_logistic_yreg_logistic_est regmedint:::calc_myreg_mreg_logistic_yreg_logistic_se
label_value_map <- c("hide" = "labelHide", "show" = "labelShow", "show_unread" = "labelSHowIfUnread", NULL ) name_map <- c( "user_id" = "userId", "search" = "q", "num_results" = "maxResults", "add_labels" = "addLabelIds", "remove_labels" = "removeLabelIds", "page_token" = "pageToken", "include_spam_trash" = "includeSpamTrash", "start_history_id" = "startHistoryId", "label_list_visibility" = "labelListVisibility", "message_list_visibility" = "messageListVisibility", "upload_type" = "uploadType", "label_ids" = "labelIds", NULL ) rename <- function(...) { args <- dots(...) arg_names <- names(args) missing <- if (is.null(arg_names)) { rep(TRUE, length(args)) } else { !nzchar(arg_names) } arg_names[missing] <- vapply(args[missing], deparse, character(1)) to_rename <- arg_names %in% names(name_map) arg_names[to_rename] <- name_map[arg_names[to_rename]] vals <- list(...) names(vals) <- arg_names vals } not_null <- function(x){ Filter(Negate(is.null), x) } gmail_path <- function(user, ...) { paste("https://www.googleapis.com/gmail/v1/users", user, paste0(unlist(list(...)), collapse = "/"), sep = "/") } gmail_upload_path <- function(user, ...) { paste("https://www.googleapis.com/upload/gmail/v1/users", user, paste0(list(...), collapse = "/"), sep = "/") } mark_utf8 <- function(x) { if (length(x)) { Encoding(x) <- "UTF-8" } x } base64url_decode_to_char <- function(x) { mark_utf8(rawToChar(base64decode(gsub("_", "/", gsub("-", "+", x))))) } base64url_decode <- function(x) { base64decode(gsub("_", "/", gsub("-", "+", x))) } base64url_encode <- function(x) { gsub("/", "_", gsub("\\+", "-", base64encode(charToRaw(as.character(x))))) } debug <- function(...){ args <- dots(...) base::message(sprintf(paste0(args, "=%s", collapse=" "), ...)) } dots <- function (...) { eval(substitute(alist(...))) } page_and_trim <- function(type, user_id, num_results, ...){ num_results <- num_results %||% 100 itr <- function(...){ req <- GET(gmail_path(user_id, type), query = not_null(rename(...)), gm_token()) stop_for_status(req) content(req, "parsed") } counts <- function(res) { vapply(lapply(res, `[[`, type), length, integer(1)) } trim <- function(res, amount) { if(is.null(amount)){ return(res) } num <- counts(res) count <- 0 itr <- 0 while(count < amount && itr <= length(num)){ itr <- itr + 1 count <- count + num[itr] } remain <- amount - count if(itr > length(res)){ res } else { res[[itr]][[type]] <- res[[itr]][[type]][1:(num[itr] + remain)] res[1:itr] } } res <- itr(...) all_results <- list(res) page_token <- res[["nextPageToken"]] while(sum(counts(all_results)) < num_results && !is.null(page_token)){ res <- itr(..., page_token = page_token) page_token <- res[["nextPageToken"]] all_results[[length(all_results) + 1]] <- res } structure(trim(all_results, num_results), class=paste0("gmail_", type)) } ord <- function(x) { strtoi(charToRaw(x), 16L) } chr <- function(x) { rawToChar(as.raw(x)) } substitute_regex <- function(data, pattern, fun, ...) { match <- gregexpr(pattern, ..., data) regmatches(data, match) <- lapply(regmatches(data, match), function(x) { if(length(x) > 0) { vapply(x, function(xx) paste0(fun(xx), collapse=""), character(1)) } else { x } }) data } "%||%" <- function(x, y){ if(is.null(x)){ y } else { x } } "%|||%" <- function(x, y){ if(is.null(x)){ x } else { y } } encode_base64 <- function(x, line_length = 76L, newline = "\r\n") { if (length(x) == 0) { return(x) } if(is.raw(x)) { base64encode(x, 76L, newline) } else { base64encode(charToRaw(x), 76L, "\r\n") } } exists_list <- function(data, x){ if(is.character(x)){ return(exists(x, data)) } return(length(data) >= x && !is.null(data[[x]])) } "%==%" <- function(x, y) { identical(x, y) } "%!=%" <- function(x, y) { !identical(x, y) } p <- function(...) paste(sep="", collapse="", ...) vcapply <- function(...) vapply(..., FUN.VALUE = character(1)) vlapply <- function(...) vapply(..., FUN.VALUE = logical(1)) vnapply <- function(...) vapply(..., FUN.VALUE = numeric(1)) isFALSE <- function(x) { is.logical(x) && length(x) == 1L && !is.na(x) && !x }
cat("\014") rm(list = ls()) setwd("~/git/of_dollars_and_data") source(file.path(paste0(getwd(),"/header.R"))) library(scales) library(readxl) library(lubridate) library(stringr) library(tidyRSS) library(tidyverse) folder_name <- "xxxx_pull_rss_feed" out_path <- paste0(exportdir, folder_name) dir.create(file.path(paste0(out_path)), showWarnings = FALSE) df <- tidyfeed( "https://ofdollarsanddata.com/feed" ) to_export <- df %>% select(item_title, item_link, item_description, item_pub_date, item_category) %>% mutate(pub_date = as.Date(item_pub_date)) %>% arrange(pub_date) %>% mutate(post_num = row_number()) %>% rename(title = item_title, link = item_link, description = item_description, category = item_category) %>% select(post_num, pub_date, title, link, description) export_to_excel(to_export, outfile = paste0(out_path, "/all_posts.xlsx"), sheetname = "raw", new_file = 1, fancy_formatting = 0)
makeRLearner.surv.gamboost = function() { makeRLearnerSurv( cl = "surv.gamboost", package = c("!survival", "mboost"), par.set = makeParamSet( makeDiscreteLearnerParam(id = "baselearner", values = c("bbs", "bols", "btree")), makeIntegerLearnerParam(id = "dfbase", default = 4L), makeNumericLearnerParam(id = "offset"), makeDiscreteLearnerParam(id = "family", default = "CoxPH", values = c("CoxPH", "Weibull", "Loglog", "Lognormal", "Gehan", "custom.family")), makeNumericVectorLearnerParam(id = "nuirange", default = c(0, 100), requires = quote(family %in% c("Weibull", "Loglog", "Lognormal"))), makeUntypedLearnerParam(id = "custom.family.definition", requires = quote(family == "custom.family")), makeIntegerLearnerParam(id = "mstop", default = 100L, lower = 1L), makeNumericLearnerParam(id = "nu", default = 0.1, lower = 0, upper = 1), makeDiscreteLearnerParam(id = "risk", values = c("inbag", "oobag", "none")), makeLogicalLearnerParam(id = "stopintern", default = FALSE), makeLogicalLearnerParam(id = "trace", default = FALSE, tunable = FALSE) ), par.vals = list( family = "CoxPH" ), properties = c("numerics", "factors", "ordered", "weights"), name = "Gradient boosting with smooth components", short.name = "gamboost", note = "`family` has been set to `CoxPH()` by default.", callees = c("gamboost", "mboost_fit", "boost_control", "CoxPH", "Weibull", "Loglog", "Lognormal", "Gehan") ) } trainLearner.surv.gamboost = function(.learner, .task, .subset, .weights = NULL, nuirange = c(0, 100), family, custom.family.definition, mstop, nu, risk, stopintern, trace, ...) { requirePackages("mboost", why = "argument 'baselearner' requires package", suppress.warnings = TRUE) ctrl = learnerArgsToControl(mboost::boost_control, mstop, nu, risk, trace, stopintern) family = switch(family, CoxPH = mboost::CoxPH(), Weibull = mboost::Weibull(nuirange = nuirange), Loglog = mboost::Loglog(nuirange = nuirange), Lognormal = mboost::Lognormal(nuirange = nuirange), Gehan = mboost::Gehan(), custom.family = custom.family.definition ) f = getTaskFormula(.task) data = getTaskData(.task, subset = .subset, recode.target = "surv") if (is.null(.weights)) { model = mboost::gamboost(f, data = data, control = ctrl, family = family, ...) } else { model = mboost::gamboost(f, data = getTaskData(.task, subset = .subset, recode.target = "surv"), control = ctrl, weights = .weights, family = family, ...) } } predictLearner.surv.gamboost = function(.learner, .model, .newdata, ...) { predict(.model$learner.model, newdata = .newdata, type = "link") }
.onLoad<-function(libname, pkgname){ utils::globalVariables(c("abhalf0","abhalf1","ab","key"),"AATtools") registerS3method("print",class="aat_splithalf",method=print.aat_splithalf) registerS3method("plot",class="aat_splithalf",method=plot.aat_splithalf) registerS3method("print",class="aat_bootstrap",method=print.aat_bootstrap) registerS3method("plot",class="aat_bootstrap",method=plot.aat_bootstrap) registerS3method("print",class="qreliability",method=print.qreliability) registerS3method("plot",class="qreliability",method=plot.qreliability) if (r_check_limit_cores()) { num_workers <- 2L } else { num_workers <- max(parallel::detectCores()-1,1) } options(AATtools.workers=num_workers) } r_check_limit_cores <- function() { Rcheck <- tolower(Sys.getenv("_R_CHECK_LIMIT_CORES_", "")) return((nchar(Rcheck[1]) > 0) & (Rcheck != "false")) } aat_splithalf<-function(ds,subjvar,pullvar,targetvar=NULL,rtvar,iters, algorithm=c("aat_doublemeandiff","aat_doublemediandiff", "aat_dscore","aat_dscore_multiblock", "aat_regression","aat_standardregression", "aat_doublemedianquotient","aat_doublemeanquotient", "aat_singlemeandiff","aat_singlemediandiff"), trialdropfunc=c("prune_nothing","trial_prune_3SD","trial_prune_SD_dropcases","trial_recode_SD", "trial_prune_percent_subject","trial_prune_percent_sample"), errortrialfunc=c("prune_nothing","error_replace_blockmeanplus","error_prune_dropcases"), casedropfunc=c("prune_nothing","case_prune_3SD"),plot=TRUE,include.raw=FALSE,parallel=TRUE, ...){ packs<-c("magrittr","dplyr","AATtools") args<-list(...) algorithm<-ifelse(is.function(algorithm),deparse(substitute(algorithm)),match.arg(algorithm)) if(!(algorithm %in% c("aat_singlemeandiff","aat_singlemediandiff","aat_regression","aat_standardregression")) & is.null(targetvar)){ stop("Argument targetvar missing but required for algorithm!") } trialdropfunc<-ifelse(is.function(trialdropfunc),deparse(substitute(trialdropfunc)),match.arg(trialdropfunc)) casedropfunc<-ifelse(is.function(casedropfunc),deparse(substitute(casedropfunc)),match.arg(casedropfunc)) errortrialfunc<-ifelse(is.function(errortrialfunc),deparse(substitute(errortrialfunc)),match.arg(errortrialfunc)) if(errortrialfunc=="error_replace_blockmeanplus"){ stopifnot(!is.null(args$blockvar),!is.null(args$errorvar)) if(is.null(args$errorbonus)){ args$errorbonus<- 0.6 } if(is.null(args$blockvar)){ args$blockvar<- 0 } if(is.null(args$errorvar)){ args$errorvar<- 0 } } stopifnot(!(algorithm=="aat_dscore_multiblock" & is.null(args$blockvar))) if(algorithm %in% c("aat_regression","aat_standardregression")){ if(!("formula" %in% names(args))){ args$formula<-as.formula(paste0(rtvar,"~",pullvar,"*",targetvar)) warning("No formula provided. Defaulting to formula ",form2char(args$formula)) }else if(is.character(args$formula)){ args$formula<-as.formula(args$formula) } if(!("aatterm" %in% names(args))){ args$aatterm<-paste0(pullvar,":",targetvar) warning("No AAT-term provided. Defaulting to AAT-term ",args$aatterm) } } ds<-do.call(aat_preparedata,c(list(ds=ds,subjvar=subjvar,pullvar=pullvar,targetvar=targetvar,rtvar=rtvar),args)) if(parallel){ `%dofunc%` <- `%dopar%` hasCluster<-getDoParRegistered() if(!hasCluster){ cluster<-makeCluster(getOption("AATtools.workers")) registerDoParallel(cluster) on.exit(unregisterDoParallel(cluster)) } }else{ `%dofunc%` <- `%do%` } results<- foreach(iter = seq_len(iters), .packages=packs) %dofunc% { if(is.null(targetvar)){ iterds<-ds%>%group_by(!! sym(subjvar), !! sym(pullvar))%>% mutate(key=sample(n())%%2)%>%ungroup() }else{ iterds<-ds%>%group_by(!! sym(subjvar), !! sym(pullvar), !! sym(targetvar))%>% mutate(key=sample(n())%%2)%>%ungroup() } iterds<-do.call(trialdropfunc,c(args,list(ds=iterds,subjvar=subjvar,rtvar=rtvar))) iterds<-do.call(errortrialfunc,c(args,list(ds=iterds,subjvar=subjvar,rtvar=rtvar))) iterds<-drop_empty_cases(iterds,subjvar) half0set<-iterds%>%filter(key==0) half1set<-iterds%>%filter(key==1) abds<-merge( do.call(algorithm,c(list(ds=half0set,subjvar=subjvar,pullvar=pullvar, targetvar=targetvar,rtvar=rtvar),args)), do.call(algorithm,c(list(ds=half1set,subjvar=subjvar,pullvar=pullvar, targetvar=targetvar,rtvar=rtvar),args)), by=subjvar,suffixes=c("half0","half1")) abds<-do.call(casedropfunc,list(ds=abds)) currcorr<-cor(abds$abhalf0,abds$abhalf1,use="complete.obs") list(corr=currcorr,abds=abds,rawdata=iterds) } cors<-sapply(results,FUN=function(x){x$corr}) ordering<-order(cors) cors<-cors[ordering] avg_n<-mean(sapply(results,function(x){ sum(!is.na(x$abds$abhalf0) & !is.na(x$abds$abhalf1)) })) output<-list(rsplithalf=mean(cors), lowerci=cors[round(iters*0.025)], upperci=cors[round(iters*0.975)], pval=r2p(mean(cors),avg_n), rSB=SpearmanBrown(mean(cors)), pval_rSB=r2p(SpearmanBrown(mean(cors)),avg_n), avg_n=avg_n, parameters=c(list(ds=ds, subjvar=subjvar, pullvar=pullvar, targetvar=targetvar, rtvar=rtvar, iters=iters, algorithm=algorithm, trialdropfunc=trialdropfunc, errortrialfunc=errortrialfunc, casedropfunc=casedropfunc), args), itercors=cors, iterdata=lapply(results,function(x){ x$abds })[ordering]) %>% structure(class = "aat_splithalf") if(include.raw){ output$rawiterdata<-lapply(results,function(x){ x$rawdata })[ordering] } if(plot){ plot(output) } return(output) } print.aat_splithalf<-function(x,...){ cat("\nr = ",format(x$rsplithalf, digits=2), ", p = ",format(x$pval,digits=3), "\nSpearman-Brown-corrected r = ",format(x$rSB,digits=2),", p = ",format(x$pval_rSB,digits=3), "\n95%CI = [", format(x$lowerci,digits=2), ", ", format(x$upperci,digits=2),"]\n", sep="") } plot.aat_splithalf<-function(x,type=c("median","minimum","maximum","random"),...){ type<-match.arg(type) if(type=="median"){ title<-"Split-half Scatterplot for Iteration with Median Reliability" idx<-ceiling(x$parameters$iters/2) }else if(type=="minimum"){ title<-"Split-half Scatterplot for Iteration with the Lowest Reliability" idx<-1 }else if(type=="maximum"){ title<-"Split-half Scatterplot for Iteration with the Highest Reliability" idx<-x$parameters$iters }else if(type=="random"){ title<-"Split-half Scatterplot for Random Iteration" idx<-sample(1:x$parameters$iters,1) } abds<-x$iterdata[[idx]] plot(abds$abhalf0,abds$abhalf1,pch=20,main= paste0(title, "\n(r = ", round(x$itercors[idx],digits=2),")"), xlab="Half 1 computed bias",ylab="Half 2 computed bias") text(abds$abhalf0,abds$abhalf1,abds[,1],cex= 0.7, pos=3, offset=0.3) } NULL prune_nothing<-function(ds,...){ ds } trial_prune_percent_subject<-function(ds,subjvar,rtvar,lowerpercent=.01,upperpercent=.99,...){ ds %>% group_by(!!sym(subjvar)) %>% mutate(percentile=rank(!!sym(rtvar))/n()) %>% filter(.data$percentile > lowerpercent & .data$percentile< upperpercent) %>% ungroup() } trial_prune_percent_sample<-function(ds,rtvar,lowerpercent=.01,upperpercent=.99,...){ ds %>% mutate(percentile=rank(!!sym(rtvar))/n()) %>% filter(.data$percentile > lowerpercent & .data$percentile< upperpercent) } trial_prune_3SD<-function(ds,subjvar,rtvar,...){ ds %>% group_by(!!sym(subjvar)) %>% filter(abs(scale(!!sym(rtvar))) <3) %>% ungroup() } trial_prune_SD_dropcases<-function(ds,subjvar,rtvar,trialsd=3,maxoutliers=.15,...){ ds %>% group_by(!!sym(subjvar)) %>% mutate(is.ol=as.numeric(abs(scale(!!sym(rtvar))) >=3),avg.ol=mean(.data$is.ol)) %>% ungroup %>% filter(.data$is.ol==0 & .data$avg.ol<maxoutliers) } trial_recode_SD<-function(ds,subjvar,rtvar,trialsd=3,...){ dsa<- ds %>% group_by(!!sym(subjvar)) %>% mutate(ol.z.score=scale(!!sym(rtvar)), ol.type=(.data$ol.z.score >= trialsd) - (.data$ol.z.score <= -trialsd), is.ol=abs(.data$ol.type), ol.max.rt=mean(!!sym(rtvar))+sd(!!sym(rtvar))*trialsd, ol.min.rt=mean(!!sym(rtvar))-sd(!!sym(rtvar))*trialsd) dsa[which(dsa$is.ol!=0),rtvar]<-ifelse(dsa[which(dsa$is.ol!=0),]$ol.type==1, dsa[which(dsa$is.ol!=0),]$ol.max.rt, dsa[which(dsa$is.ol!=0),]$ol.min.rt) dsa %>% dplyr::select(-.data$ol.type,-.data$ol.max.rt,-.data$ol.min.rt,-.data$ol.z.score) } case_prune_3SD<-function(ds,...){ dplyr::filter(ds,(abhalf0 < mean(abhalf0,na.rm=TRUE)+3*sd(abhalf0,na.rm=TRUE) & abhalf0 > mean(abhalf0,na.rm=TRUE)-3*sd(abhalf0,na.rm=TRUE)) & (abhalf1 < mean(abhalf1,na.rm=TRUE)+3*sd(abhalf1,na.rm=TRUE) & abhalf1 > mean(abhalf1,na.rm=TRUE)-3*sd(abhalf1,na.rm=TRUE))) } error_replace_blockmeanplus<-function(ds,subjvar,rtvar,blockvar,errorvar,errorbonus, ...){ if(!("is.ol" %in% colnames(ds))){ ds$is.ol<-0; } ds%<>%group_by(!!sym(subjvar),!!sym(blockvar), key)%>% mutate(newrt=mean((!!sym(rtvar))[!(!!sym(errorvar)) & .data$is.ol==0])+errorbonus)%>%ungroup() ds[ds[,errorvar]==1,rtvar]<-ds[ds[,errorvar]==1,]$newrt dplyr::select(ds,-.data$newrt) } error_prune_dropcases<-function(ds,subjvar, errorvar, maxerrors = .15, ...){ ds%>%group_by(!!sym(subjvar), key)%>% filter(mean(!!sym(errorvar))<maxerrors & !!sym(errorvar) == FALSE) } NULL aat_doublemeandiff<-function(ds,subjvar,pullvar,targetvar,rtvar,...){ group_by(ds,!!sym(subjvar)) %>% summarise(ab=(mean(subset(!!sym(rtvar),!!sym(pullvar)==0 & !!sym(targetvar) == 1),na.rm=TRUE) - mean(subset(!!sym(rtvar),!!sym(pullvar)==1 & !!sym(targetvar) == 1),na.rm=TRUE)) - (mean(subset(!!sym(rtvar),!!sym(pullvar)==0 & !!sym(targetvar) == 0),na.rm=TRUE) - mean(subset(!!sym(rtvar),!!sym(pullvar)==1 & !!sym(targetvar) == 0),na.rm=TRUE))) } aat_doublemediandiff<-function(ds,subjvar,pullvar,targetvar,rtvar,...){ group_by(ds,!!sym(subjvar)) %>% summarise(ab=(median(subset(!!sym(rtvar),!!sym(pullvar)==0 & !!sym(targetvar) == 1),na.rm=TRUE) - median(subset(!!sym(rtvar),!!sym(pullvar)==1 & !!sym(targetvar) == 1),na.rm=TRUE)) - (median(subset(!!sym(rtvar),!!sym(pullvar)==0 & !!sym(targetvar) == 0),na.rm=TRUE) - median(subset(!!sym(rtvar),!!sym(pullvar)==1 & !!sym(targetvar) == 0),na.rm=TRUE))) } aat_dscore<-function(ds,subjvar,pullvar,targetvar,rtvar,...){ group_by(ds,!!sym(subjvar)) %>% summarise(ab=((mean(subset(!!sym(rtvar),!!sym(pullvar)==0 & !!sym(targetvar) == 1),na.rm=TRUE) - mean(subset(!!sym(rtvar),!!sym(pullvar)==1 & !!sym(targetvar) == 1),na.rm=TRUE)) - (mean(subset(!!sym(rtvar),!!sym(pullvar)==0 & !!sym(targetvar) == 0),na.rm=TRUE) - mean(subset(!!sym(rtvar),!!sym(pullvar)==1 & !!sym(targetvar) == 0),na.rm=TRUE))) / sd(!!sym(rtvar),na.rm=TRUE)) } aat_dscore_multiblock<-function(ds,subjvar,pullvar,targetvar,rtvar,blockvar,...){ ds %>% mutate(.blockset = floor((!!sym(blockvar) - min(!!sym(blockvar)))/2) ) %>% group_by(!!sym(subjvar),.data$.blockset) %>% summarise(ab=((mean(subset(!!sym(rtvar),!!sym(pullvar)==0 & !!sym(targetvar) == 1),na.rm=TRUE) - mean(subset(!!sym(rtvar),!!sym(pullvar)==1 & !!sym(targetvar) == 1),na.rm=TRUE)) - (mean(subset(!!sym(rtvar),!!sym(pullvar)==0 & !!sym(targetvar) == 0),na.rm=TRUE) - mean(subset(!!sym(rtvar),!!sym(pullvar)==1 & !!sym(targetvar) == 0),na.rm=TRUE))) / sd(!!sym(rtvar),na.rm=TRUE)) %>% group_by(!!sym(subjvar)) %>% summarise(ab=mean(ab,na.rm=TRUE)) } aat_regression<-function(ds,subjvar,formula,aatterm,...){ output<-data.frame(pp=unique(ds[[subjvar]]),ab=NA,var=NA) for(i in seq_len(nrow(output))){ mod<-coef(summary(lm(formula,data=ds[ds[[subjvar]]==output[i,"pp"],]))) if(aatterm %in% rownames(mod)){ output[i,"ab"]<- -mod[rownames(mod)==aatterm,1] output[i,"var"]<- mod[rownames(mod)==aatterm,2] } } colnames(output)[colnames(output)=="pp"]<-subjvar return(output) } aat_standardregression<-function(ds,subjvar,formula,aatterm,...){ output<-data.frame(pp=unique(ds[[subjvar]]),ab=NA,var=NA) for(i in seq_len(nrow(output))){ mod<-coef(summary(lm(formula,data=ds[ds[[subjvar]]==output[i,"pp"],]))) if(aatterm %in% rownames(mod)){ output[i,"ab"]<- -mod[rownames(mod)==aatterm,1] output[i,"var"]<- mod[rownames(mod)==aatterm,2] } } colnames(output)[colnames(output)=="pp"]<-subjvar output$ab<-output$ab/output$var return(output) } aat_doublemedianquotient<-function(ds,subjvar,pullvar,targetvar,rtvar,...){ group_by(ds,!!sym(subjvar)) %>% summarise(ab=log(median(subset(!!sym(rtvar),!!sym(pullvar)==0 & !!sym(targetvar) == 1),na.rm=TRUE) / median(subset(!!sym(rtvar),!!sym(pullvar)==1 & !!sym(targetvar) == 1),na.rm=TRUE)) - log(median(subset(!!sym(rtvar),!!sym(pullvar)==0 & !!sym(targetvar) == 0),na.rm=TRUE) / median(subset(!!sym(rtvar),!!sym(pullvar)==1 & !!sym(targetvar) == 0),na.rm=TRUE))) } aat_doublemeanquotient<-function(ds,subjvar,pullvar,targetvar,rtvar,...){ group_by(ds,!!sym(subjvar)) %>% summarise(ab=log(mean(subset(!!sym(rtvar),!!sym(pullvar)==0 & !!sym(targetvar) == 1),na.rm=TRUE) / mean(subset(!!sym(rtvar),!!sym(pullvar)==1 & !!sym(targetvar) == 1),na.rm=TRUE)) - log(mean(subset(!!sym(rtvar),!!sym(pullvar)==0 & !!sym(targetvar) == 0),na.rm=TRUE) / mean(subset(!!sym(rtvar),!!sym(pullvar)==1 & !!sym(targetvar) == 0),na.rm=TRUE))) } aat_singlemeandiff<-function(ds,subjvar,pullvar,rtvar,...){ group_by(ds,!!sym(subjvar))%>% summarise(ab=mean(subset(!!sym(rtvar),!!sym(pullvar)==1)) - mean(subset(!!sym(rtvar),!!sym(pullvar)==0))) } aat_singlemediandiff<-function(ds,subjvar,pullvar,rtvar,...){ group_by(ds,!!sym(subjvar))%>% summarise(ab=median(subset(!!sym(rtvar),!!sym(pullvar)==1)) - median(subset(!!sym(rtvar),!!sym(pullvar)==0))) } aat_bootstrap<-function(ds,subjvar,pullvar,targetvar=NULL,rtvar,iters, algorithm=c("aat_doublemeandiff","aat_doublemediandiff", "aat_dscore","aat_dscore_multiblock", "aat_regression","aat_standardregression", "aat_doublemeanquotient","aat_doublemedianquotient", "aat_singlemeandiff","aat_singlemediandiff"), trialdropfunc=c("prune_nothing","trial_prune_3SD","trial_prune_SD_dropcases","trial_recode_SD", "trial_prune_percent_subject","trial_prune_percent_sample"), errortrialfunc=c("prune_nothing","error_replace_blockmeanplus","error_prune_dropcases"), plot=TRUE,include.raw=FALSE,parallel=TRUE,...){ packs<-c("magrittr","dplyr","AATtools") args<-list(...) algorithm<-ifelse(is.function(algorithm),deparse(substitute(algorithm)),match.arg(algorithm)) if(!(algorithm %in% c("aat_singlemeandiff","aat_singlemediandiff","aat_regression","aat_standardregression")) & is.null(targetvar)){ stop("Argument targetvar missing but required for algorithm!") } trialdropfunc<-ifelse(is.function(trialdropfunc),deparse(substitute(trialdropfunc)),match.arg(trialdropfunc)) errortrialfunc<-ifelse(is.function(errortrialfunc),deparse(substitute(errortrialfunc)),match.arg(errortrialfunc)) if(errortrialfunc=="error_replace_blockmeanplus"){ stopifnot(!is.null(args$blockvar),!is.null(args$errorvar)) if(is.null(args$errorbonus)){ args$errorbonus<- 0.6 } if(is.null(args$blockvar)){ args$blockvar<- 0 } if(is.null(args$errorvar)){ args$errorvar<- 0 } } stopifnot(!(algorithm=="aat_dscore_multiblock" & is.null(args$blockvar))) if(algorithm %in% c("aat_regression","aat_standardregression")){ if(!("formula" %in% names(args))){ args$formula<-as.formula(paste0(rtvar,"~",pullvar,"*",targetvar)) warning("No formula provided. Defaulting to formula ",form2char(args$formula)) }else if(is.character(args$formula)){ args$formula<-as.formula(args$formula) } if(!("aatterm" %in% names(args))){ args$aatterm<-paste0(pullvar,":",targetvar) warning("No AAT-term provided. Defaulting to AAT-term ",args$aatterm) } } ds<-do.call(aat_preparedata,c(list(ds=ds,subjvar=subjvar,pullvar=pullvar,targetvar=targetvar,rtvar=rtvar),args)) %>% mutate(key=1) if(parallel){ `%dofunc%` <- `%dopar%` hasCluster<-getDoParRegistered() if(!hasCluster){ cluster<-makeCluster(getOption("AATtools.workers")) registerDoParallel(cluster) on.exit(unregisterDoParallel(cluster)) } }else{ `%dofunc%` <- `%do%` } results<- foreach(iter = seq_len(iters), .packages=packs, .combine=cbind) %dofunc% { iterds<-ds %>% group_by(!!sym(subjvar), !!sym(pullvar), !!sym(targetvar)) %>% sample_n(size=n(),replace=TRUE) %>% ungroup() iterds<-do.call(trialdropfunc,list(ds=iterds,subjvar=subjvar,rtvar=rtvar)) iterds<-do.call(errortrialfunc,list(ds=iterds,subjvar=subjvar,rtvar=rtvar, blockvar=args$blockvar,errorvar=args$errorvar, errorbonus=args$errorbonus)) abds<-do.call(algorithm,c(list(ds=iterds,subjvar=subjvar,pullvar=pullvar, targetvar=targetvar,rtvar=rtvar),args)) outvar<-abds$ab names(outvar)<-abds[[subjvar]] outvar } statset<-data.frame(ppidx=rownames(results), bias=rowMeans(results,na.rm=TRUE), var=apply(results,MARGIN = 1,FUN=var,na.rm=TRUE), lowerci=apply(results,MARGIN=1,FUN=function(x){quantile(x,0.025,na.rm=TRUE)}), upperci=apply(results,MARGIN=1,FUN=function(x){quantile(x,0.975,na.rm=TRUE)}), stringsAsFactors=F) statset$ci<-statset$upperci-statset$lowerci bv<-var(statset$bias,na.rm=TRUE) wv<-mean(statset$var,na.rm=TRUE) q<-(bv-wv)/(bv+wv) output<-list(bias=statset, reliability=q, parameters=c(list(ds=ds, subjvar=subjvar, pullvar=pullvar, targetvar=targetvar, rtvar=rtvar, iters=iters, algorithm=algorithm, trialdropfunc=trialdropfunc, errortrialfunc=errortrialfunc),args)) %>% structure(class = "aat_bootstrap") if(include.raw){ output$iterdata<-results } if(plot){ plot(output) } return(output) } print.aat_bootstrap<-function(x,...){ cat("Bootstrapped bias scores and confidence intervals", "\nMean bias score: ", mean(x$bias$bias,na.rm=TRUE), "\nMean confidence interval: ",mean(x$bias$ci,na.rm=TRUE), "\nreliability: q = ",mean(x$bias$bias,na.rm=TRUE), "\nNumber of iterations: ",x$parameters$iters,sep="") } plot.aat_bootstrap <- function(x,...){ statset<-x$bias statset<-statset[!is.na(statset$bias) & !is.na(statset$upperci) & !is.na(statset$lowerci),] rank<-rank(statset$bias) wideness<-max(statset$upperci) - min(statset$lowerci) plot(x=statset$bias,y=rank,xlim=c(min(statset$lowerci)-0.01*wideness,max(statset$upperci)+0.01*wideness), xlab="Bias score",main=paste0("Individual bias scores with 95%CI", "\nEstimated reliability: q = ",x$reliability)) segments(x0=statset$lowerci,x1=statset$bias-0.005*wideness,y0=rank,y1=rank) segments(x0=statset$bias+0.005*wideness,x1=statset$upperci,y0=rank,y1=rank) abline(v=0) } aat_compute<-function(ds,subjvar,pullvar,targetvar=NULL,rtvar, algorithm=c("aat_doublemeandiff","aat_doublemediandiff", "aat_dscore","aat_dscore_multiblock", "aat_regression","aat_standardregression", "aat_doublemeanquotient","aat_doublemedianquotient", "aat_singlemeandiff","aat_singlemediandiff"), trialdropfunc=c("prune_nothing","trial_prune_3SD","trial_prune_SD_dropcases","trial_recode_SD", "trial_prune_percent_subject","trial_prune_percent_sample"), errortrialfunc=c("prune_nothing","error_replace_blockmeanplus","error_prune_dropcases"), ...){ args<-list(...) algorithm<-ifelse(is.function(algorithm),deparse(substitute(algorithm)),match.arg(algorithm)) if(!(algorithm %in% c("aat_singlemeandiff","aat_singlemediandiff","aat_regression","aat_standardregression")) & is.null(targetvar)){ stop("Argument targetvar missing but required for algorithm!") } trialdropfunc<-ifelse(is.function(trialdropfunc),deparse(substitute(trialdropfunc)),match.arg(trialdropfunc)) errortrialfunc<-ifelse(is.function(errortrialfunc),deparse(substitute(errortrialfunc)),match.arg(errortrialfunc)) if(errortrialfunc=="error_replace_blockmeanplus"){ stopifnot(!is.null(args$blockvar),!is.null(args$errorvar)) if(is.null(args$errorbonus)){ args$errorbonus<- 0.6 } if(is.null(args$blockvar)){ args$blockvar<- 0 } if(is.null(args$errorvar)){ args$errorvar<- 0 } } stopifnot(!(algorithm=="aat_dscore_multiblock" & is.null(args$blockvar))) if(algorithm %in% c("aat_regression","aat_standardregression")){ if(!("formula" %in% names(args))){ args$formula<-as.formula(paste0(rtvar,"~",pullvar,"*",targetvar)) warning("No formula provided. Defaulting to formula ",form2char(args$formula)) }else if(is.character(args$formula)){ args$formula<-as.formula(args$formula) } if(!("aatterm" %in% names(args))){ args$aatterm<-paste0(pullvar,":",targetvar) warning("No AAT-term provided. Defaulting to AAT-term ",args$aatterm) } } ds<-do.call(aat_preparedata,c(list(ds=ds,subjvar=subjvar,pullvar=pullvar,targetvar=targetvar,rtvar=rtvar),args)) %>% mutate(key=1) iterds<-do.call(trialdropfunc,list(ds=ds,subjvar=subjvar,rtvar=rtvar)) iterds<-do.call(errortrialfunc,list(ds=ds,subjvar=subjvar,rtvar=rtvar, blockvar=args$blockvar,errorvar=args$errorvar, errorbonus=args$errorbonus)) abds<-do.call(algorithm,c(list(ds=ds,subjvar=subjvar,pullvar=pullvar, targetvar=targetvar,rtvar=rtvar),args)) abds <- merge(x=abds,by=subjvar,all=TRUE,y=iterds %>% group_by(!!sym(subjvar)) %>% summarise(trials=n())) return(abds) } q_reliability<-function(ds,subjvar,formula,aatterm=NA){ cols<-c(subjvar,as.character(attr(terms(formula),"variables"))[-1]) stopifnot(all(cols %in% colnames(ds))) ds<-ds[apply(!is.na(ds[,cols]),MARGIN=1,FUN=all),] if(aatterm=="1"){ aatterm<-NA } coefs<-data.frame(pp=unique(ds[[subjvar]]),ab=NA,var=NA) for(u in 1:nrow(coefs)){ iterset<-ds[ds[[subjvar]]==coefs[u,]$pp,] mod<-lm(formula,data=iterset) coefs[u,]$ab <- -coef(mod)[ifelse(is.na(aatterm),length(coef(mod)),aatterm)] coefs[u,]$var <- (diag(vcov(mod)))[ifelse(is.na(aatterm),length(coef(mod)),aatterm)] } bv<-var(coefs$ab,na.rm=TRUE) wv<-mean(coefs$var,na.rm=TRUE) q<-(bv-wv)/(bv+wv) return(structure(list(q=q,coefs=coefs),class="qreliability")) } print.qreliability<-function(x,...){ cat("q = ",x$q,"\n",sep="") } plot.qreliability<-function(x,...){ bv<-var(x$coefs$ab,na.rm=TRUE) / nrow(x$coefs)*1.96 *2 wv<-mean(x$coefs$var,na.rm=TRUE) / nrow(x$coefs)*1.96 *2 plotset<-data.frame(x=mean(x$coefs$ab) + cos(0:100 / 100 * 2*pi)*bv * 1/2*sqrt(2) - sin(0:100 / 100 * 2*pi)*wv * 1/2*sqrt(2), y=mean(x$coefs$ab) + cos(0:100 / 100 * 2*pi)*bv * 1/2*sqrt(2) + sin(0:100 / 100 * 2*pi)*wv * 1/2*sqrt(2)) plot(plotset$x,plotset$y,type="l",main=paste0("Reliability\n","q = ",round(x$q,digits=2)),xlab="Participants' scores",ylab="Participants' scores") points(x$coefs$ab,x$coefs$ab) dispval<-(bv+wv)/100 plotset<-data.frame(xstart=c(x$coefs$ab+dispval,x$coefs$ab-dispval), ystart=c(x$coefs$ab-dispval,x$coefs$ab+dispval), xend=c(x$coefs$ab+sqrt(x$coefs$var) *1/2*sqrt(2), x$coefs$ab-sqrt(x$coefs$var) *1/2*sqrt(2)), yend=c(x$coefs$ab-sqrt(x$coefs$var) *1/2*sqrt(2), x$coefs$ab+sqrt(x$coefs$var) *1/2*sqrt(2))) segments(plotset$xstart,plotset$ystart,plotset$xend,plotset$yend) } SpearmanBrown<-function(corr,ntests=2,fix.negative=c("nullify","bilateral","none")){ fix.negative<-match.arg(fix.negative) if(fix.negative=="bilateral"){ s<-sign(corr) corr<-abs(corr) sb<-ntests*corr / (1+(ntests-1)*corr) return(s*sb) }else{ sb<-ntests*corr / (1+(ntests-1)*corr) if(fix.negative=="nullify"){ return(ifelse(sb<0,0,sb)) }else{ return(sb) } } } r2p<-function(corr,n){ t<- (corr*sqrt(n-2))/(1-corr^2) 2*pt(abs(t),n-2,lower.tail=FALSE) } aat_preparedata<-function(ds,subjvar,pullvar,targetvar=NULL,rtvar,...){ args<-list(...) cols<-c(subjvar,pullvar,targetvar,rtvar,args$errorvar,args$blockvar) if("formula" %in% names(args)){ formterms <- args$formula %>% as.formula() %>% terms() %>% attr("variables") %>% as.character() formterms <- formterms[-1] if(any(!(formterms %in% colnames(ds)))){ stop("Formula term(s) ",paste(formterms[!(formterms %in% colnames(ds))],collapse=", ")," missing from dataset") } cols <- c(cols,formterms) } stopifnot(all(cols %in% colnames(ds))) ds<-ds[,cols] ds[[subjvar]]%<>%as.factor() if(is.logical(ds[,pullvar])){ warning("Recoded ",pullvar," from logical to numeric. Please make sure that FALSE ", "represents push trials and TRUE represents pull trials") ds[,pullvar]%<>%as.numeric() } if(is.factor(ds[,pullvar])){ warning("Recoded ",pullvar," from factor to numeric. Please make sure that ", levels(ds[,pullvar])[1], " represents push trials and ",levels(ds[,pullvar])[2], " represents pull trials") ds[,pullvar]<-as.numeric(ds[,pullvar])-1 } if(!is.null(targetvar)){ if(is.logical(ds[,targetvar])){ warning("Recoded ",targetvar," from logical to numeric. Please make sure that FALSE ", "represents control/neutral stimuli and TRUE represents target stimuli") ds[,targetvar]%<>%as.numeric() } if(is.factor(ds[,targetvar])){ warning("Recoded ",targetvar," from factor to numeric. Please make sure that ", levels(ds[,targetvar])[1], " represents control/neutral stimuli and ",levels(ds[,targetvar])[2], " represents target stimuli") ds[,targetvar]<-as.numeric(ds[,targetvar])-1 } } rmindices <- ds[,cols] %>% lapply(FUN=is.na) %>% as.data.frame %>% apply(MARGIN=1,FUN=any) %>% which if(length(rmindices)>0){ ds<-ds[-rmindices,] warning("Removed ",length(rmindices)," rows due to presence of NA in critical variable(s)") } return(ds) } val_between<-function(x,lb,ub){x>lb & x<ub} drop_empty_cases<-function(iterds,subjvar){ iterds%>%group_by(!!sym(subjvar))%>%filter(val_between(mean(key),0,1)) } form2char<-function(x){ if(is.character(x)){ return(x) } fs<-as.character(x) fs<-paste(fs[2],fs[1],fs[3]) return(fs) } is.formula <- function(x){ inherits(x,"formula") } unregisterDoParallel <- function(cluster) { stopCluster(cluster) registerDoSEQ() }
PRISMA_flowdiagram <- function (data, interactive = FALSE, previous = TRUE, other = TRUE, fontsize = 7, font = 'Helvetica', title_colour = 'Goldenrod1', greybox_colour = 'Gainsboro', main_colour = 'Black', arrow_colour = 'Black', arrow_head = 'normal', arrow_tail = 'none', side_boxes = TRUE) { for(var in seq_len(length(data))) { assign(names(data)[var], data[[var]]) } dbr_excluded[,1] <- stringr::str_wrap(dbr_excluded[,1], width = 35) other_excluded[,1] <- stringr::str_wrap(other_excluded[,1], width = 35) if(stringr::str_count(paste(dbr_excluded[,1], collapse = "\n"), "\n") > 3){ dbr_excludedh <- 3.5 - ((stringr::str_count(paste(dbr_excluded[,1], collapse = "\n"), "\n")-4)/9) } else { dbr_excludedh <- 3.5 } if(nrow(other_excluded) > 3){ other_excludedh <- 3.5 - ((nrow(other_excluded)-4)/9) } else { other_excludedh <- 3.5 } if (is.na(previous_studies) == TRUE && is.na(previous_reports) == TRUE) { previous <- FALSE } if(previous == TRUE){ xstart <- 0 ystart <- 0 A <- paste0("A [label = '', pos='",xstart+1,",",ystart+0,"!', tooltip = '']") Aedge <- paste0("subgraph cluster0 { edge [color = White, arrowhead = none, arrowtail = none] 1->2; edge [color = ", arrow_colour, ", arrowhead = none, arrowtail = ", arrow_tail, "] 2->A; edge [color = ", arrow_colour, ", arrowhead = ", arrow_head, ", arrowtail = none, constraint = FALSE] A->19; }") bottomedge <- paste0("edge [color = ", arrow_colour, ", arrowhead = ", arrow_head, ", arrowtail = ", arrow_tail, "] 12->19;\n") h_adj1 <- 0 h_adj2 <- 0 if(is.na(previous_studies) == TRUE) { cond_prevstud <- '' } else { cond_prevstud <- stringr::str_wrap(paste0(previous_studies_text, " (n = ", previous_studies, ")"), width = 40) } if(is.na(previous_reports) == TRUE) { cond_prevrep <- '' } else { cond_prevrep <- paste0(stringr::str_wrap(previous_reports_text, width = 40), "\n(n = ", previous_reports, ')') } if (is.na(previous_studies) == TRUE || is.na(previous_reports) == TRUE) { dbl_br <- '' } else { dbl_br <- "\n\n" } previous_nodes <- paste0("node [shape = box, fontsize = ", fontsize,", fontname = ", font, ", color = ", greybox_colour, "] 1 [label = '", previous_text, "', style = 'rounded,filled', width = 3.5, height = 0.5, pos='",xstart+1,",",ystart+8.25,"!', tooltip = '", tooltips[1], "'] node [shape = box, fontname = ", font, ", color = ", greybox_colour, "] 2 [label = '",paste0(cond_prevstud, dbl_br, cond_prevrep), "', style = 'filled', width = 3.5, height = 0.5, pos='",xstart+1,",",ystart+7,"!', tooltip = '", tooltips[2], "']") finalnode <- paste0(" node [shape = box, fontname = ", font, ", color = ", greybox_colour, "] 19 [label = '",paste0(stringr::str_wrap(paste0(total_studies_text, " (n = ", total_studies, ")"), width = 33), "\n", stringr::str_wrap(paste0(total_reports_text, " (n = ", total_reports, ')'), width = 33)), "', style = 'filled', width = 3.5, height = 0.5, pos='",xstart+5,",",ystart+0,"!', tooltip = '", tooltips[19], "']") prev_rank1 <- "{rank = same; A; 19}" prevnode1 <- "1; " prevnode2 <- "2; " } else { xstart <- -3.5 ystart <- 0 A <- "" Aedge <- "" bottomedge <- "" previous_nodes <- "" finalnode <- "" h_adj1 <- 0.63 h_adj2 <- 1.4 prev_rank1 <- "" prevnode1 <- "" prevnode2 <- "" } if(side_boxes == TRUE){ sidebox <- paste0("node [shape = box, fontsize = ", fontsize,", fontname = ", font, ", color = ", title_colour, " ] identification [color = LightSteelBlue2, label=' ', style = 'filled,rounded', pos='",-1.4,",",ystart+7,"!', width = 0.4, height = 1.5, tooltip = '", tooltips[20], "']; screening [color = LightSteelBlue2, label=' ', style = 'filled,rounded', pos='",-1.4,",",ystart+4.5,"!', width = 0.4, height = 2.5, tooltip = '", tooltips[21], "']; included [color = LightSteelBlue2, label=' ', style = 'filled,rounded', pos='",-1.4,",",h_adj1+0.87,"!', width = 0.4, height = ",2.5-h_adj2,", tooltip = '", tooltips[22], "'];\n ") } else { sidebox <- "" } if (is.na(website_results) == TRUE && is.na(organisation_results) == TRUE && is.na(citations_results) == TRUE) { other <- FALSE } if(other == TRUE){ if (is.data.frame(other_excluded) == TRUE){ other_excluded_data <- paste0(':', paste(paste('\n', other_excluded[,1], ' (n = ', other_excluded[,2], ')', sep = ''), collapse = '')) } else { other_excluded_data <- paste0('\n', '(n = ', other_excluded, ')') } B <- paste0("B [label = '', pos='",xstart+13,",",ystart+1.5,"!', tooltip = '']") if (is.na(website_results) == FALSE) { cond_websites <- paste0(website_results_text, " (n = ", website_results, ')\n') } else { cond_websites <- '' } if (is.na(organisation_results) == FALSE) { cond_organisation <- paste0(organisation_results_text, " (n = ", organisation_results, ')\n') } else { cond_organisation <- '' } if (is.na(citations_results) == FALSE) { cond_citation <- paste0(citations_results_text, " (n = ", citations_results, ')') } else { cond_citation <- '' } cluster2 <- paste0("subgraph cluster2 { edge [color = White, arrowhead = none, arrowtail = none] 13->14; edge [color = ", arrow_colour, ", arrowhead = ", arrow_head, ", arrowtail = ", arrow_tail, "] 14->15; 15->16; 15->17; 17->18; edge [color = ", arrow_colour, ", arrowhead = none, arrowtail = ", arrow_tail, "] 17->B; edge [color = ", arrow_colour, ", arrowhead = ", arrow_head, ", arrowtail = none, constraint = FALSE] B->12; }") othernodes <- paste0("node [shape = box, fontname = ", font, ", color = ", greybox_colour, "] 13 [label = '", other_text, "', style = 'rounded,filled', width = 7.5, height = 0.5, pos='",xstart+15,",",ystart+8.25,"!', tooltip = '", tooltips[5], "'] node [shape = box, fontname = ", font, ", color = ", greybox_colour, "] 14 [label = '", paste0('Records identified from:\n', cond_websites, cond_organisation, cond_citation), "', style = 'filled', width = 3.5, height = 0.5, pos='",xstart+13,",",ystart+7,"!', tooltip = '", tooltips[6], "'] node [shape = box, fontname = ", font, ", color = ", greybox_colour, "] 15 [label = '", paste0(other_sought_reports_text, '\n(n = ', other_sought_reports, ')'), "', style = 'filled', width = 3.5, height = 0.5, pos='",xstart+13,",",ystart+4.5,"!', tooltip = '", tooltips[12], "'] node [shape = box, fontname = ", font, ", color = ", greybox_colour, "] 16 [label = '", paste0(other_notretrieved_reports_text,'\n(n = ', other_notretrieved_reports, ')'), "', style = 'filled', width = 3.5, height = 0.5, pos='",xstart+17,",",ystart+4.5,"!', tooltip = '", tooltips[13], "'] node [shape = box, fontname = ", font, ", color = ", greybox_colour, "] 17 [label = '", paste0(other_assessed_text, '\n(n = ', other_assessed, ')'),"', style = 'filled', width = 3.5, height = 0.5, pos='",xstart+13,",",ystart+3.5,"!', tooltip = '", tooltips[16], "'] node [shape = box, fontname = ", font, ", color = ", greybox_colour, "] 18 [label = '", paste0(other_excluded_text, other_excluded_data), "', style = 'filled', width = 3.5, height = 0.5, pos='",xstart+17,",",ystart+other_excludedh,"!', tooltip = '", tooltips[17], "']\n ") extraedges <- "16->18;" othernode13 <- "; 13" othernode14 <- "; 14" othernode1516 <- "; 15; 16" othernode1718 <- "; 17; 18" othernodeB <- "; B" } else { B <- "" cluster2 <- "" othernodes <- "" extraedges <- "" optnodesother <- "" othernode13 <- "" othernode14 <- "" othernode1516 <- "" othernode1718 <- "" othernodeB <- "" } if (any(!grepl("\\D", dbr_excluded)) == FALSE){ dbr_excluded_data <- paste0(':', paste(paste('\n', dbr_excluded[,1], ' (n = ', dbr_excluded[,2], ')', sep = ''), collapse = '')) } else { dbr_excluded_data <- paste0('\n', '(n = ', dbr_excluded, ')') } if (is.na(database_results) == FALSE) { cond_database <- paste0(database_results_text, ' (n = ', database_results, ')\n') } else { cond_database <- '' } if (is.na(register_results) == FALSE) { cond_register <- paste0(register_results_text, ' (n = ', register_results, ')') } else { cond_register <- '' } if (is.na(duplicates) == FALSE) { cond_duplicates <- paste0(stringr::str_wrap(paste0(duplicates_text, ' (n = ', duplicates, ')'), width = 42), '\n') } else { cond_duplicates <- '' } if (is.na(excluded_automatic) == FALSE) { cond_automatic <- paste0(stringr::str_wrap(paste0(excluded_automatic_text, ' (n = ', excluded_automatic, ')'), width = 42), '\n') } else { cond_automatic <- '' } if (is.na(excluded_other) == FALSE) { cond_exclother <- paste0(stringr::str_wrap(paste0(excluded_other_text, ' (n = ', excluded_other, ')'), width = 42)) } else { cond_exclother <- '' } if (is.na(duplicates) == TRUE && is.na(excluded_automatic) == TRUE && is.na(excluded_other) == TRUE) { cond_duplicates <- paste0('(n = 0)') } if(is.na(new_studies) == FALSE) { cond_newstud <- paste0(stringr::str_wrap(new_studies_text, width = 40), '\n(n = ', new_studies, ')\n') } else { cond_newstud <- '' } if(is.na(new_reports) == FALSE) { cond_newreports <- paste0(stringr::str_wrap(new_reports_text, width = 40), '\n(n = ', new_reports, ')') } else { cond_newreports <- '' } x <- DiagrammeR::grViz( paste0("digraph TD { graph[splines=ortho, layout=neato, tooltip = 'Click the boxes for further information', outputorder=edgesfirst]", sidebox, previous_nodes," node [shape = box, fontsize = ", fontsize,", fontname = ", font, ", color = ", title_colour, "] 3 [label = '", newstud_text, "', style = 'rounded,filled', width = 7.5, height = 0.5, pos='",xstart+7,",",ystart+8.25,"!', tooltip = '", tooltips[3], "'] node [shape = box, fontname = ", font, ", color = ", main_colour, "] 4 [label = '", paste0('Records identified from:\n', cond_database, cond_register), "', width = 3.5, height = 0.5, height = 0.5, pos='",xstart+5,",",ystart+7,"!', tooltip = '", tooltips[4], "'] node [shape = box, fontname = ", font, ", color = ", main_colour, "] 5 [label = '", paste0('Records removed before screening:\n', cond_duplicates, cond_automatic, cond_exclother), "', width = 3.5, height = 0.5, pos='",xstart+9,",",ystart+7,"!', tooltip = '", tooltips[7], "'] node [shape = box, fontname = ", font, ", color = ", main_colour, "] 6 [label = '", paste0(records_screened_text, '\n(n = ', records_screened, ')'), "', width = 3.5, height = 0.5, height = 0.5, pos='",xstart+5,",",ystart+5.5,"!', tooltip = '", tooltips[8], "'] node [shape = box, fontname = ", font, ", color = ", main_colour, "] 7 [label = '", paste0(records_excluded_text, '\n(n = ', records_excluded, ')'), "', width = 3.5, height = 0.5, pos='",xstart+9,",",ystart+5.5,"!', tooltip = '", tooltips[9], "'] node [shape = box, fontname = ", font, ", color = ", main_colour, "] 8 [label = '", paste0(dbr_sought_reports_text, '\n(n = ', dbr_sought_reports, ')'), "', width = 3.5, height = 0.5, height = 0.5, pos='",xstart+5,",",ystart+4.5,"!', tooltip = '", tooltips[10], "'] node [shape = box, fontname = ", font, ", color = ", main_colour, "] 9 [label = '", paste0(dbr_notretrieved_reports_text, '\n(n = ', dbr_notretrieved_reports, ')'), "', width = 3.5, height = 0.5, pos='",xstart+9,",",ystart+4.5,"!', tooltip = '", tooltips[11], "'] node [shape = box, fontname = ", font, ", color = ", main_colour, "] 10 [label = '", paste0(dbr_assessed_text, '\n(n = ', dbr_assessed, ')'), "', width = 3.5, height = 0.5, pos='",xstart+5,",",ystart+3.5,"!', tooltip = '", tooltips[14], "'] node [shape = box, fontname = ", font, ", color = ", main_colour, ", fillcolor = White, style = filled] 11 [label = '", paste0(dbr_excluded_text, dbr_excluded_data), "', width = 3.5, height = 0.5, pos='",xstart+9,",",ystart+dbr_excludedh,"!', tooltip = '", tooltips[15], "'] node [shape = box, fontname = ", font, ", color = ", main_colour, ", fillcolor = '', style = solid] 12 [label = '", paste0(cond_newstud, cond_newreports), "', width = 3.5, height = 0.5, pos='",xstart+5,",",ystart+1.5,"!', tooltip = '", tooltips[18], "'] ",othernodes, finalnode," node [shape = square, width = 0, color=White]\n", A," ",B," ", Aedge," node [shape = square, width = 0, style=invis] C [label = '', width = 3.5, height = 0.5, pos='",xstart+9,",",ystart+3.5,"!', tooltip = ''] subgraph cluster1 { edge [style = invis] 3->4; 3->5; edge [color = ", arrow_colour, ", arrowhead = ", arrow_head, ", arrowtail = ", arrow_tail, ", style = filled] 4->5; 4->6; 6->7; 6->8; 8->9; 8->10; 10->C; 10->12; edge [style = invis] 5->7; 7->9; 9->11; ",extraedges," } ",cluster2," ", bottomedge,"\n\n", prev_rank1,"\n", "{rank = same; ",prevnode1,"3",othernode13,"} {rank = same; ",prevnode2,"4; 5",othernode14,"} {rank = same; 6; 7} {rank = same; 8; 9",othernode1516,"} {rank = same; 10; 11",othernode1718,"} {rank = same; 12",othernodeB,"} } ") ) if (side_boxes == TRUE) { x <- PRISMA_insert_js_(x, identification_text = identification_text,screening_text = screening_text,included_text = included_text) } if (interactive == TRUE) { x <- PRISMA_interactive_(x, urls, previous = previous, other = other) } return(x) } PRISMA_data <- function(data){ previous_studies <- scales::comma(as.numeric(data[grep('previous_studies', data[,1]),]$n)) previous_reports <- scales::comma(as.numeric(data[grep('previous_reports', data[,1]),]$n)) register_results <- scales::comma(as.numeric(data[grep('register_results', data[,1]),]$n)) database_results <- scales::comma(as.numeric(data[grep('database_results', data[,1]),]$n)) website_results <- scales::comma(as.numeric(data[grep('website_results', data[,1]),]$n)) organisation_results <- scales::comma(as.numeric(data[grep('organisation_results', data[,1]),]$n)) citations_results <- scales::comma(as.numeric(data[grep('citations_results', data[,1]),]$n)) duplicates <- scales::comma(as.numeric(data[grep('duplicates', data[,1]),]$n)) excluded_automatic <- scales::comma(as.numeric(data[grep('excluded_automatic', data[,1]),]$n)) excluded_other <- scales::comma(as.numeric(data[grep('excluded_other', data[,1]),]$n)) records_screened <- scales::comma(as.numeric(data[grep('records_screened', data[,1]),]$n)) records_excluded <- scales::comma(as.numeric(data[grep('records_excluded', data[,1]),]$n)) dbr_sought_reports <- scales::comma(as.numeric(data[grep('dbr_sought_reports', data[,1]),]$n)) dbr_notretrieved_reports <- scales::comma(as.numeric(data[grep('dbr_notretrieved_reports', data[,1]),]$n)) other_sought_reports <- scales::comma(as.numeric(data[grep('other_sought_reports', data[,1]),]$n)) other_notretrieved_reports <- scales::comma(as.numeric(data[grep('other_notretrieved_reports', data[,1]),]$n)) dbr_assessed <- scales::comma(as.numeric(data[grep('dbr_assessed', data[,1]),]$n)) dbr_excluded <- data.frame(reason = gsub(",.*$", "", unlist(strsplit(as.character(data[grep('dbr_excluded', data[,1]),]$n), split = '; '))), n = gsub(".*,", "", unlist(strsplit(as.character(data[grep('dbr_excluded', data[,1]),]$n), split = '; ')))) other_assessed <- scales::comma(as.numeric(data[grep('other_assessed', data[,1]),]$n)) other_excluded <- data.frame(reason = gsub(",.*$", "", unlist(strsplit(as.character(data[grep('other_excluded', data[,1]),]$n), split = '; '))), n = gsub(".*,", "", unlist(strsplit(as.character(data[grep('other_excluded', data[,1]),]$n), split = '; ')))) new_studies <- scales::comma(as.numeric(data[grep('new_studies', data[,1]),]$n)) new_reports <- scales::comma(as.numeric(data[grep('new_reports', data[,1]),]$n)) total_studies <- scales::comma(as.numeric(data[grep('total_studies', data[,1]),]$n)) total_reports <- scales::comma(as.numeric(data[grep('total_reports', data[,1]),]$n)) tooltips <- stats::na.omit(data$tooltips) urls <- data.frame(box = data[!duplicated(data$box), ]$box, url = data[!duplicated(data$box), ]$url) previous_text <- data[grep('prevstud', data[,3]),]$boxtext newstud_text <- data[grep('newstud', data[,3]),]$boxtext other_text <- data[grep('othstud', data[,3]),]$boxtext previous_studies_text <- data[grep('previous_studies', data[,1]),]$boxtext previous_reports_text <- data[grep('previous_reports', data[,1]),]$boxtext register_results_text <- data[grep('register_results', data[,1]),]$boxtext database_results_text <- data[grep('database_results', data[,1]),]$boxtext website_results_text <- data[grep('website_results', data[,1]),]$boxtext organisation_results_text <- data[grep('organisation_results', data[,1]),]$boxtext citations_results_text <- data[grep('citations_results', data[,1]),]$boxtext duplicates_text <- data[grep('duplicates', data[,1]),]$boxtext excluded_automatic_text <- data[grep('excluded_automatic', data[,1]),]$boxtext excluded_other_text <- data[grep('excluded_other', data[,1]),]$boxtext records_screened_text <- data[grep('records_screened', data[,1]),]$boxtext records_excluded_text <- data[grep('records_excluded', data[,1]),]$boxtext dbr_sought_reports_text <- data[grep('dbr_sought_reports', data[,1]),]$boxtext dbr_notretrieved_reports_text <- data[grep('dbr_notretrieved_reports', data[,1]),]$boxtext other_sought_reports_text <- data[grep('other_sought_reports', data[,1]),]$boxtext other_notretrieved_reports_text <- data[grep('other_notretrieved_reports', data[,1]),]$boxtext dbr_assessed_text <- data[grep('dbr_assessed', data[,1]),]$boxtext dbr_excluded_text <- data[grep('dbr_excluded', data[,1]),]$boxtext other_assessed_text <- data[grep('other_assessed', data[,1]),]$boxtext other_excluded_text <- data[grep('other_excluded', data[,1]),]$boxtext new_studies_text <- data[grep('new_studies', data[,1]),]$boxtext new_reports_text <- data[grep('new_reports', data[,1]),]$boxtext total_studies_text <- data[grep('total_studies', data[,1]),]$boxtext total_reports_text <- data[grep('total_reports', data[,1]),]$boxtext identification_text <- data[grep('identification', data[,1]),]$boxtext screening_text <- data[grep('screening', data[,1]),]$boxtext included_text <- data[grep('included', data[,1]),]$boxtext x <- list(previous_studies = previous_studies, previous_reports = previous_reports, register_results = register_results, database_results = database_results, website_results = website_results, organisation_results = organisation_results, citations_results = citations_results, duplicates = duplicates, excluded_automatic = excluded_automatic, excluded_other = excluded_other, records_screened = records_screened, records_excluded = records_excluded, dbr_sought_reports = dbr_sought_reports, dbr_notretrieved_reports = dbr_notretrieved_reports, other_sought_reports = other_sought_reports, other_notretrieved_reports = other_notretrieved_reports, dbr_assessed = dbr_assessed, dbr_excluded = dbr_excluded, other_assessed = other_assessed, other_excluded = other_excluded, new_studies = new_studies, new_reports = new_reports, total_studies = total_studies, total_reports = total_reports, previous_text = previous_text, newstud_text = newstud_text, other_text = other_text, previous_studies_text = previous_studies_text, previous_reports_text = previous_reports_text, register_results_text = register_results_text, database_results_text = database_results_text, website_results_text = website_results_text, organisation_results_text = organisation_results_text, citations_results_text = citations_results_text, duplicates_text = duplicates_text, excluded_automatic_text = excluded_automatic_text, excluded_other_text = excluded_other_text, records_screened_text = records_screened_text, records_excluded_text = records_excluded_text, dbr_sought_reports_text = dbr_sought_reports_text, dbr_notretrieved_reports_text = dbr_notretrieved_reports_text, other_sought_reports_text = other_sought_reports_text, other_notretrieved_reports_text = other_notretrieved_reports_text, dbr_assessed_text = dbr_assessed_text, dbr_excluded_text = dbr_excluded_text, other_assessed_text = other_assessed_text, other_excluded_text = other_excluded_text, new_studies_text = new_studies_text, new_reports_text = new_reports_text, total_studies_text = total_studies_text, total_reports_text = total_reports_text, identification_text = identification_text, screening_text = screening_text, included_text = included_text, tooltips = tooltips, urls = urls) return(x) } PRISMA_save <- function(plotobj, filename = 'PRISMA2020_flowdiagram.html', filetype = NA, overwrite = FALSE){ if (!file.exists(filename) | overwrite == TRUE ) { format_real <- PRISMA_calc_filetype_(filename, filetype) switch( format_real, "HTML" = { tmp_html <- tempfile(pattern = "PRISMA2020_", tmpdir = tempdir(), fileext = ".html" ) htmlwidgets::saveWidget(plotobj, file=tmp_html, title = tools::file_path_sans_ext(filename)) if (!(file.copy(tmp_html, filename, overwrite = TRUE))){ stop("Error saving HTML") } file.remove(tmp_html) }, "PDF" = { tmp_svg <- PRISMA_gen_tmp_svg_(plotobj) rsvg::rsvg_pdf(tmp_svg, filename) file.remove(tmp_svg) }, "PNG" = { tmp_svg <- PRISMA_gen_tmp_svg_(plotobj) rsvg::rsvg_png(tmp_svg, filename) file.remove(tmp_svg) }, "SVG" = { tmp_svg <- PRISMA_gen_tmp_svg_(plotobj) if (!(file.copy(tmp_svg, filename, overwrite = TRUE))){ stop("Error saving SVG") } file.remove(tmp_svg) }, "PS" = { tmp_svg <- PRISMA_gen_tmp_svg_(plotobj) rsvg::rsvg_ps(tmp_svg, filename) file.remove(tmp_svg) }, "WEBP" = { tmp_svg <- PRISMA_gen_tmp_svg_(plotobj) rsvg::rsvg_webp(tmp_svg, filename) file.remove(tmp_svg) }, stop("Please choose one of the supported file types") ) return(tools::file_path_as_absolute(filename)) } else { stop("File exists, please set overwite = TRUE to overwrite") } } sr_flow_interactive <- function(plot, urls, previous, other) { .Deprecated("PRISMA_interactive_") return(PRISMA_interactive_(plot, urls, previous, other)) } read_PRISMAdata <- function(data){ .Deprecated("PRISMA_data") return(PRISMA_data(data)) }
library(hamcrest) expected <- c(0x1.b5f3b62ep-12 + -0x1.2p-52i, -0x1p-43 + -0x1.bfd78p-47i, -0x1.4p-43 + -0x1.ee0b6b8b4ce8p-53i, -0x1.8p-43 + 0x1.6027fe8p-46i, -0x1.4p-43 + -0x1.23d14p-46i, -0x1.6p-43 + -0x1.13b48p-47i, -0x1.8p-43 + -0x1.ab7fa4a3a599p-48i, -0x1.ap-43 + 0x1.7aa006p-48i, -0x1.6p-43 + 0x1.1cp-47i, -0x1.ap-43 + 0x1.b1ec4p-46i, -0x1.ap-43 + 0x1.e3b7d251d2cc6p-47i, -0x1p-42 + 0x1.a7d7fe8p-46i, -0x1.8p-43 + 0x1.cfd14p-46i, -0x1.8p-43 + 0x1.bdd9cp-46i, -0x1.9p-43 + -0x1.e0ff49474b318p-49i, -0x1.08p-42 + 0x1.43f8018p-46i, -0x1.cp-43 + -0x1.d6edbb471b4p-49i, -0x1.ap-43 + 0x1.f9ccc2a09db8fp-47i, -0x1.9p-43 + 0x1.99aab472ce754p-47i, -0x1.bp-43 + 0x1.91cba2f1f0bf8p-48i, -0x1.a8p-43 + -0x1.a12c9672b36b8p-49i, -0x1.4p-43 + 0x1.25086b3b68f97p-46i, -0x1.38p-43 + 0x1.511d1ec1b15e6p-46i, -0x1.98p-43 + 0x1.4a706cbc0dffp-46i, -0x1.3p-43 + 0x1.fe150ae172296p-46i, -0x1.48p-43 + 0x1.e8ebe77822e68p-49i, -0x1.48p-43 + 0x1.a11d62dc8fa08p-48i, -0x1.58p-43 + 0x1.7b50d6f95d0ep-47i, -0x1.cp-44 + 0x1.293d34bc5d814p-46i, -0x1.08p-43 + 0x1.6721ca13d9998p-46i, -0x1.dp-44 + 0x1.da9c6a315a048p-47i, -0x1.18p-43 + 0x1.b9ddf7ed300cp-46i, -0x1.58p-44 + 0x1.6ep-48i, -0x1.28p-44 + 0x1.40144p-46i, -0x1p-44 + 0x1.5c23e928e9664p-46i, -0x1.b8p-44 + 0x1.6027fe8p-46i, -0x1.7p-45 + 0x1.985d8p-47i, -0x1.08p-44 + 0x1.2625cp-46i, -0x1.8p-47 + 0x1.0a402dae2d33ap-47i, -0x1.6p-44 + -0x1.0abff4p-49i, 0x1p-48 + 0x1.cep-46i, -0x1.2p-45 + -0x1.e13cp-50i, -0x1p-47 + -0x1.3c482dae2d338p-47i, -0x1.08p-44 + -0x1.e028018p-46i, -0x1p-46 + -0x1.42ecp-50i, -0x1.8p-47 + 0x1.05d9cp-46i, 0x1.5p-45 + -0x1.083fd251d2cc8p-47i, -0x1.2p-46 + -0x1.e03ff4p-49i, 0x1.6p-45 + -0x1.7844912e393p-47i, 0x1.cp-46 + -0x1.6cbde1504edc8p-46i, 0x1.cp-45 + -0x1.748d87e7946e3p-46i, 0x1p-49 + -0x1.c845d778f85fcp-47i, 0x1.38p-44 + -0x1.237ced31a9929p-46i, 0x1.6p-45 + -0x1.0179d676d1f2ep-47i, 0x1.2p-44 + -0x1.2adcf113842adp-46i, 0x1.6p-45 + -0x1.37a069bc0dfefp-46i, 0x1.ap-44 + 0x1.17abd47a375aap-48i, 0x1.1p-44 + -0x1.0289f9de08b9ap-47i, 0x1.7p-45 + -0x1.791f0ccaa2378p-47i, 0x1.4p-46 + -0x1.ddf86e7cae87p-46i, 0x1.18p-44 + 0x1.2cca968744fd8p-47i, 0x1.8p-45 + 0x1.5c91b5ec26668p-46i, 0x1.38p-44 + -0x1.ac703b53fe758p-49i, 0x1.1p-45 + 0x1.f09058967fap-49i, 0x1.58p-44 + 0x1.e1c41b2ca998p-49i, 0x1.08p-44 + 0x1.8c131850649c8p-47i, 0x1.8p-45 + 0x1.3b9a408654548p-49i, 0x1.8p-48 + 0x1.81df134781558p-47i, 0x1.38p-44 + 0x1.a5163fcdde501p-47i, 0x0p+0 + 0x1.91899ec79217p-49i, 0x1.6p-45 + 0x1.dbcb85115dd24p-48i, -0x1p-48 + 0x1.0655999a47087p-46i, 0x1.8p-45 + 0x1.1b961c7b1fccep-46i, -0x1p-47 + 0x1.5cc68c6a1d34p-52i, -0x1p-48 + 0x1.2d5e75601b06p-48i, -0x1.6p-45 + -0x1.c5d55aedad8ap-49i, -0x1.8p-47 + 0x1.ea4abbcca0f5ep-47i, -0x1.8p-45 + 0x1.5204c47f35806p-47i, -0x1.8p-47 + -0x1.2ceeae8e1da6cp-48i, -0x1.6p-44 + 0x1.e9e1279f020a4p-48i, -0x1p-47 + 0x1.0117ba8bd4407p-46i, -0x1.6p-44 + -0x1.0775cee69f63cp-48i, -0x1p-44 + -0x1.6cdd7660051ccp-46i, -0x1.cp-44 + -0x1.d06b30cac4892p-46i, -0x1.4p-44 + -0x1.c8e71bec74ab6p-47i, -0x1.bp-44 + -0x1.0de147da1cfe4p-47i, -0x1.bp-44 + -0x1.2dac8a865b5ep-47i, -0x1.2p-43 + -0x1.9dc07886b928p-50i, -0x1.bp-44 + 0x1.d14e81bccfad8p-50i, -0x1.38p-43 + 0x1.1f0a4c2da151p-46i, -0x1.4p-43 + 0x1.97f1c6585a14p-51i, -0x1.7p-43 + -0x1.dbb6869568f54p-46i, -0x1.ep-44 + 0x1.1a5db2b68e56p-50i, -0x1.3p-43 + 0x1.21e93d9fdb629p-47i, -0x1.2p-43 + 0x1.e0d41cdeb63c4p-48i, -0x1.6p-43 + -0x1.74e9a5a485204p-47i, -0x1.08p-43 + 0x1.9b8p-46i, -0x1.28p-43 + 0x1.80288p-47i, -0x1.4p-43 + 0x1.7847d251d2cc6p-47i, -0x1.ap-43 + -0x1.fd8018p-50i, -0x1.1p-43 + 0x1.ec2ecp-46i, -0x1.5p-43 + 0x1.d625cp-46i, -0x1.fp-44 + 0x1.7a900b6b8b4cep-45i, -0x1.b8p-43 + 0x1.8ea8018p-46i, -0x1.1p-43 + 0x1.a7p-45i, -0x1.5p-43 + 0x1.50f62p-45i, -0x1.5p-43 + 0x1.80edf49474b32p-45i, -0x1.88p-43 + 0x1.0bebff4p-45i, -0x1.2p-43 + 0x1.87e8ap-45i, -0x1.1p-43 + 0x1.eeecep-45i, -0x1.cp-44 + 0x1.51f00b6b8b4cep-45i, -0x1.7p-43 + 0x1.a1fc00cp-45i, 0x1.b5f3b62ebp-12 + 0x1.f1eedbb471b4p-45i, 0x1.3b2bdc4182p-9 + 0x1.01a10f57d891cp-45i, 0x1.cfafe661d8p-9 + 0x1.7db93c0c35c8ep-45i, 0x1.51ac7f6d9p-8 + 0x1.7dee8a21c1e81p-45i, 0x1.e6e1cd89e8p-8 + 0x1.9e4189672b36cp-45i, 0x1.5b7dcde688p-7 + 0x1.77a18a624b835p-45i, 0x1.eb0aaa19a4p-7 + 0x1.629187763deaap-45i, 0x1.5777d87e9e8p-6 + 0x1.542fcb21f9008p-45i, 0x1.dbac4485ap-6 + 0x1.417abd47a375ap-44i, 0x1.46147c1676cp-5 + 0x1.23aec0c43ee8dp-44i, 0x1.ba94fa486f8p-5 + 0x1.41b83ccd57722p-45i, 0x1.2957aa9046p-4 + 0x1.2103c8c1a8bc8p-45i, 0x1.8b865d80dfp-4 + 0x1.36654b43a27ecp-46i, 0x1.0688de37468p-3 + 0x1.39236bd84ccdp-47i, 0x1.5906d0327e8p-3 + -0x1.d58e076a7fcebp-46i, 0x1.be42585c5fp-3 + -0x1.90f6fa769806p-45i, 0x1.1dc9625ee09p-2 + -0x1.448p-46i, 0x1.6a7ce95d731p-2 + 0x1.20144p-46i, 0x1.c755a49a442p-2 + -0x1.01ee0b6b8b4cep-45i, 0x1.1b3bac03b65p-1 + -0x1.6fec00cp-45i, 0x1.5cfe4eb721ep-1 + 0x1.b85d8p-47i, 0x1.a9f0262ee58p-1 + -0x1.3b48p-51i, 0x1.017901281cdp+0 + -0x1.d5bfd251d2cc6p-47i, 0x1.345d391225cp+0 + -0x1.a157fe8p-46i, 0x1.6de3f144b3bp+0 + 0x1.0ep-46i, 0x1.aeabe12f1bdp+0 + 0x1.63d88p-47i, 0x1.f5f0a7af74cp+0 + -0x1.87120b6b8b4cep-45i, 0x1.21e0dedd06b4p+1 + -0x1.ac1400cp-45i, 0x1.4be4c95ef044p+1 + -0x1.8176p-49i, 0x1.78d12cfffaccp+1 + -0x1.044c8p-47i, 0x1.a85f5245eddcp+1 + -0x1.7e0ff49474b32p-45i, 0x1.d9dc9a0ed23cp+1 + -0x1.3e03ff4p-45i, 0x1.067768d2ba94p+2 + -0x1.f5bb6ed1c6dp-47i, 0x1.20c0da0e840ep+2 + -0x1.06333d5f62471p-47i, 0x1.3b7f22585588p+2 + -0x1.999552e34c62bp-45i, 0x1.563af94a2b08p+2 + -0x1.cdc68ba1c1e81p-45i, 0x1.70b8053a7ce2p+2 + -0x1.d0964b3959b5cp-48i, 0x1.8aed3e69d434p+2 + -0x1.f5ef29892e0d2p-47i, 0x1.a4e00dc509a2p+2 + -0x1.1bb8b84f93a86p-44i, 0x1.be2d35c8bbdp+2 + -0x1.3d63e4d0fc804p-44i, 0x1.d7215b1c126cp+2 + -0x1.81eaf51e8dd6ap-46i, 0x1.efc77a94f117p+2 + -0x1.017141887dd1ap-45i, 0x1.0423832949768p+3 + -0x1.55ee29d23706p-44i, 0x1.1089937023fcp+3 + -0x1.6095e520d45e4p-44i, 0x1.1d507969bbab8p+3 + -0x1.56c2cb43a27ecp-46i, 0x1.2aa894658c8ap+3 + -0x1.6c6f1af613334p-45i, 0x1.3910ceae45de8p+3 + -0x1.54ac72b9d4bf7p-44i, 0x1.48c98d917c398p+3 + -0x1.61888204b3fdp-44i, 0x1.5a680d785e3ap+3 + -0x1.848p-46i, 0x1.6e45dc6d1825p+3 + -0x1.9febcp-46i, 0x1.84fe491bb4cbp+3 + -0x1.30f705b5c5a67p-44i, 0x1.9f18405b74e84p+3 + -0x1.37f6006p-44i, 0x1.bd12661de752p+3 + 0x1.30bbp-48i, 0x1.dfb35d71a7fbp+3 + -0x1.73b48p-47i, 0x1.03b4c5f8dcd59p+4 + -0x1.e56ff49474b32p-45i, 0x1.1a707f8d56388p+4 + -0x1.0455ffap-44i, 0x1.343b2e7a8e948p+4 + 0x1.4ep-46i, 0x1.514a98718e3c8p+4 + -0x1.709ep-49i, 0x1.71da3fc34bbfbp+4 + -0x1.e7120b6b8b4cep-45i, 0x1.961b0e980426p+4 + -0x1.1a0a006p-44i, 0x1.be2262d49baa2p+4 + 0x1.afa28p-47i, 0x1.e9f672392cbcp+4 + -0x1.72264p-46i, 0x1.0cc07ff1f05b5p+5 + -0x1.0307fa4a3a599p-44i, 0x1.26621df3f70d2p+5 + -0x1.2b01ffap-44i, 0x1.41d784514b0b8p+5 + 0x1.8f76dda38dap-48i, 0x1.5f0b49f1c29cfp+5 + -0x1.32f785413b72p-48i, 0x1.7de96a527d132p+5 + -0x1.8a46c3f3ca372p-45i, 0x1.9e5f919c0762cp+5 + -0x1.9d08baef1f0cp-44i, 0x1.c041be647954bp+5 + 0x1.3c8312ce566d7p-46i, 0x1.e38b266615464p+5 + -0x1.50bceb3b68f97p-46i, 0x1.0411f99b86e28p+6 + -0x1.7eb73c44e10abp-44i, 0x1.16ef5c4bd6c2ep+6 + -0x1.79e81a6f037fcp-44i, 0x1.2a5bc001a44d4p+6 + -0x1.50a8570b914acp-49i, 0x1.3e505fa1cc6c1p+6 + -0x1.20a27e77822e7p-45i, 0x1.52c4a7adcb5f4p+6 + -0x1.4f23e1995446fp-44i, 0x1.67b8dca7f0849p+6 + -0x1.5b7e1b9f2ba1cp-44i, 0x1.7d2141bca95ep+6 + -0x1.4cd5a5e2ec0ap-49i, 0x1.92fc6ac2ab07ap+6 + -0x1.f1b72509eccccp-45i, 0x1.a94769567b34ap+6 + -0x1.a56381da9ff3bp-44i, 0x1.bff8c965cac14p+6 + -0x1.c87b7d3b4c03p-44i, 0x1.d707bfe5f4c06p+6 + -0x1.729c41b2ca998p-45i, 0x1.ee6d2a0a9dbfap+6 + -0x1.f2f0861419272p-45i, 0x1.030d4c9eacd74p+7 + -0x1.bbcadd6fbdef9p-44i, 0x1.0f006166c8ep+7 + -0x1.0c13f19478156p-43i, 0x1.1b068b2a71ee4p+7 + -0x1.7a2d9fe6ef28p-46i, 0x1.2711d7ec45748p+7 + -0x1.e2f2d9ec79217p-45i, 0x1.331bd8e6d9e24p+7 + -0x1.732cace58a904p-44i, 0x1.3f167737dde99p+7 + -0x1.e24165a691c22p-44i, 0x1.4af47cb0b1da8p+7 + -0x1.ff961c7b1fccep-46i, 0x1.56abf17acbefcp+7 + -0x1.10cd4d18d43a6p-45i, 0x1.62360030ee81bp+7 + -0x1.89e7f2c18cfd4p-44i, 0x1.6d88061522dp+7 + -0x1.ade555e89293bp-44i, 0x1.789c0ec279932p+7 + -0x1.582dde6507afp-50i, 0x1.836b9689d23fep+7 + -0x1.ad4ee23f9ac03p-46i, 0x1.8df3d59c8725bp+7 + -0x1.f682135725b16p-45i, 0x1.9831c3a3512a1p+7 + -0x1.b9442373e0414p-45i, 0x1.a2234e9b48d8ep+7 + 0x1.1259ad44c9dfp-47i, 0x1.abc673b2ae749p+7 + -0x1.88ab934b74dc4p-47i, 0x1.b517da64506e9p+7 + -0x1.3cbbea9696371p-45i, 0x1.be157974bb25cp+7 + -0x1.b3577ede218b9p-45i, 0x1.c6b985252cb7ep+7 + 0x1.f0a1a16635eb4p-48i, 0x1.cf1e2e32e9234p+7 + 0x1.2202f4c7c0e4p-47i, 0x1.d720c864d2cd1p+7 + -0x1.0377be9cb7ca2p-45i, 0x1.dea78df0dec3ap+7 + -0x1.1450c7bfde1bep-44i, 0x1.e5baafc499608p+7 + -0x1.c1d5a4b1d1504p-47i, 0x1.ec4fbb64578f8p+7 + -0x1.933d493e625d8p-48i, 0x1.f25edb00beea4p+7 + -0x1.5e186e623d803p-45i, 0x1.f7df8aecfab1ep+7 + -0x1.d47c51389cfe6p-45i, 0x1.fccca1fe2ce8ap+7 + -0x1.7e56e3655bc5cp-47i, 0x1.00925a9cea3b8p+8 + -0x1.215885541d3f2p-45i, 0x1.02763c5eaba0dp+8 + -0x1.4ecc4e8329c54p-45i, 0x1.04161a30b842fp+8 + -0x1.7473cf54d756p-44i, 0x1.05783b0164834p+8 + -0x1.124p-45i, 0x1.06a8bdd5ce45fp+8 + -0x1.7ff5ep-45i, 0x1.07b76baaabd38p+8 + -0x1.e1ee0b6b8b4cep-45i, 0x1.08b592e977706p+8 + -0x1.27f6006p-44i, 0x1.09b742783b0f8p+8 + -0x1.89e8ap-45i, 0x1.0ad3cdebcf238p+8 + -0x1.54ed2p-45i, 0x1.0c262640ee446p+8 + -0x1.656ff49474b32p-45i, 0x1.0dc7bf1839982p+8 + -0x1.0c55ffap-44i, 0x1.0fd3320176ddbp+8 + -0x1.99p-45i, 0x1.12618f3288964p+8 + -0x1.2f09ep-45i, 0x1.1588f0068631ap+8 + -0x1.7f120b6b8b4cep-45i, 0x1.195a90d5dc6eap+8 + -0x1.d41400cp-45i, 0x1.1de35e34ea612p+8 + -0x1.78176p-45i, 0x1.232753e9fad98p+8 + -0x1.91132p-45i, 0x1.292422e5a7c52p+8 + -0x1.6e0ff49474b32p-45i, 0x1.2fcb9e7f4769fp+8 + -0x1.1e03ff4p-45i, 0x1.37077bee97fe4p+8 + -0x1.5c2248971c98p-46i, 0x1.3eb4e16296c9bp+8 + -0x1.3cbde1504edc8p-46i, 0x1.46a790a434d9ep+8 + -0x1.12361f9e51b8cp-48i, 0x1.4ea9bad873588p+8 + -0x1.108baef1f0bf8p-48i, 0x1.567b74906c9e7p+8 + -0x1.837ced31a9929p-46i, 0x1.5dd95e2241c5ep+8 + -0x1.42f3aceda3e5bp-48i, 0x1.647a345f704f5p+8 + 0x1.8a461dd8f7aa6p-47i, 0x1.6a1561d19d327p+8 + 0x1.50bf2c87e4022p-47i, 0x1.6e62c37cf97d6p+8 + -0x1.742a15c2e452bp-47i, 0x1.7120061bc71cdp+8 + 0x1.075d81887dd1ap-45i, 0x1.7213b156ea157p+8 + 0x1.8370799aaee44p-46i, 0x1.711123e442084p+8 + 0x1.a103c8c1a8bc8p-45i, 0x1.6df954387f7acp+8 + -0x1.93356978bb028p-47i, 0x1.68bd00a80595cp+8 + 0x1.c91b5ec266678p-50i, 0x1.615bff31f275bp+8 + 0x1.aa71f89580315p-46i, 0x1.57e7e76ed505ep+8 + 0x1.6f09058967fap-45i, 0x1.4c835a74b4e66p+8 + -0x1.2p-52i, 0x1.3f5eb500bb71bp+8 + 0x1.20144p-46i, 0x1.30b65a1751838p+8 + 0x1.fe11f49474b32p-45i, 0x1.20d2b60347169p+8 + 0x1.5809ffap-44i, 0x1.0ffdbc43adc42p+8 + -0x1.23d14p-46i, 0x1.fd0e4a173f6d6p+7 + 0x1.7625cp-46i, 0x1.d981b9f23cdaep+7 + 0x1.654805b5c5a67p-44i, 0x1.b5e94c11c4b26p+7 + 0x1.97aa006p-44i, 0x1.92cf7a35dbacp+7 + -0x1.b9p-45i, 0x1.70b2310c54316p+7 + -0x1.384fp-48i, 0x1.4ff7de9072822p+7 + 0x1.78edf49474b32p-45i, 0x1.30f7ddc4eb079p+7 + 0x1.69f5ffap-44i, 0x1.13ef45775141cp+7 + -0x1.0c0bbp-44i, 0x1.f20f49689336p+6 + -0x1.0899p-48i, 0x1.c0b31ba9caf8cp+6 + 0x1.e1f00b6b8b4cep-45i, 0x1.93d52d6760f86p+6 + 0x1.a1fc00cp-45i, 0x1.6b63580a3aeecp+6 + -0x1.1d6edbb471b4p-45i, 0x1.47353e3d5ca2p+6 + -0x1.03199eafb1238p-46i, 0x1.271137d6d4372p+6 + 0x1.666aad1cb39d5p-45i, 0x1.0ab22a2e2b8dp+6 + 0x1.991cba2f1f0cp-44i, 0x1.e3a07a64c4a6ap+5 + -0x1.1a12c9672b36cp-45i, 0x1.b82262b006f9p+5 + -0x1.b5ef29892e0d2p-47i, 0x1.9255f164aca64p+5 + 0x1.a88e8f60d8af3p-45i, 0x1.71a252cb6c29ap+5 + 0x1.529c1b2f037fcp-44i, 0x1.556c768d7bc73p+5 + -0x1.01eaf51e8dd6ap-46i, 0x1.3d218c32a752ap+5 + 0x1.1e8ebe77822e6p-45i, 0x1.28507ad0ad1dp+5 + 0x1.b423ac5b91f41p-45i, 0x1.16875800bc2ccp+5 + 0x1.6f6a1adf2ba1cp-44i, 0x1.075ae8dc889f8p+5 + -0x1.ad85968744fd8p-47i, 0x1.f4dfe76e91965p+4 + 0x1.3390e509eccccp-45i, 0x1.dee63d9c5253dp+4 + 0x1.f6a71a8c56812p-45i, 0x1.cc3b783271f67p+4 + 0x1.6e777dfb4c03p-44i, 0x1.bc595cff66c92p+4 + 0x1.b7p-47i, 0x1.aecc0a8f4cb68p+4 + 0x1.c0144p-46i, 0x1.a320fd615882p+4 + 0x1.6e11f49474b32p-45i, 0x1.99013c83fd002p+4 + 0x1.1809ffap-44i, 0x1.8f6d2d1ce4cfep+4 + 0x1.85d8p-51i, 0x1.8725fe60e365p+4 + 0x1.312ep-49i, 0x1.802db58570acdp+4 + 0x1.852016d71699dp-46i, 0x1.798039f89d2a6p+4 + 0x1.4f5400cp-45i, 0x1.73046e9192c0fp+4 + -0x1.52p-46i, 0x1.6c88cf0bdd697p+4 + 0x1.03d88p-47i, 0x1.65fca3473ca68p+4 + 0x1.00edf49474b32p-45i, 0x1.5f4e90a28df2p+4 + 0x1.87ebff4p-45i, 0x1.587f76744b1bp+4 + 0x1.c7a28p-47i, 0x1.5187aa6999a0dp+4 + 0x1.ebb38p-47i, 0x1.4a79ae8ddc216p+4 + 0x1.45f00b6b8b4cep-45i, 0x1.4379a8b5c56fp+4 + 0x1.71fc00cp-45i, 0x1.3c9e9dcb97d07p+4 + 0x1.63ddb768e368p-46i, 0x1.360e6d52a1489p+4 + 0x1.09a10f57d891cp-45i, 0x1.30007a7d398a7p+4 + 0x1.25b93c0c35c8ep-45i, 0x1.2aab287f87488p+4 + 0x1.adee8a21c1e81p-45i, 0x1.263fc31dd19acp+4 + 0x1.0e4189672b36cp-45i, 0x1.22ebe0602bfb5p+4 + 0x1.3f4314c497069p-46i, 0x1.20dcfd5d1b09p+4 + 0x1.6a9187763deaap-45i, 0x1.203a268c2b84dp+4 + 0x1.242fcb21f9008p-45i, 0x1.2116f71a7f7f8p+4 + 0x1.45eaf51e8dd6ap-46i, 0x1.2383b7a80b0e7p+4 + 0x1.febb0310fba33p-46i, 0x1.277c92942fc88p+4 + 0x1.a1b83ccd57722p-45i, 0x1.2cee09daf976bp+4 + 0x1.0881e460d45e4p-44i, 0x1.33b2b28fc30bap+4 + 0x1.0b32a5a1d13f6p-45i, 0x1.3b9fdada66d1p+4 + 0x1.6e48daf613334p-45i, 0x1.447b68e7f9b18p+4 + 0x1.e538fc4ac018ap-45i, 0x1.4dff65bd3ce74p+4 + 0x1.5f09058967fap-45i, 0x1.57e1b89f181dap+4 + 0x1.1e1c41b2ca998p-45i, 0x1.61cdb44a79c2p+4 + 0x1.c6098c28324e4p-46i, 0x1.6b7ad90335dfp+4 + 0x1.13b9a40865454p-45i, 0x1.749f38df7ed3ep+4 + 0x1.81df134781558p-47i, 0x1.7cf6b1463afe8p+4 + 0x1.a5163fcdde501p-47i, 0x1.8448c354bae4ep+4 + 0x1.91899ec79217p-49i, 0x1.8a6d1f1e20f25p+4 + -0x1.121a3d775116ep-47i, 0x1.8f44ad8464ac1p+4 + 0x1.95666691c21cp-52i, 0x1.92baf7fd3c9fp+4 + 0x1.b961c7b1fccep-50i, 0x1.94cffca5fc892p+4 + 0x1.5cc68c6a1d34p-52i, 0x1.9590944a2886dp+4 + 0x1.2d5e75601b06p-48i, 0x1.951c6ad4218f3p+4 + 0x1.8e8aa944949d8p-47i, 0x1.93a34a6bb4c6fp+4 + -0x1.0adaa219af851p-46i, 0x1.91584dda5ae08p+4 + -0x1.56fd9dc0653fdp-46i, 0x1.8e7cbcf23a513p+4 + -0x1.2ceeae8e1da6cp-48i, 0x1.8b4cdad6f9702p+4 + -0x1.0b0f6c307efaep-47i, 0x1.8814afb4bf2b2p+4 + -0x1.fdd08ae8577f2p-47i, 0x1.8522dece1696ap+4 + -0x1.0775cee69f63cp-48i, 0x1.82b5d7a2d69ep+4 + -0x1.b375d9801473p-48i, 0x1.810c0c96a6ea4p+4 + -0x1.d06b30cac4892p-46i, 0x1.806260beadb8cp+4 + 0x1.b8c7209c5aa5p-50i, 0x1.80dcfdcf817f3p+4 + -0x1.86f0a3ed0e7f2p-46i, 0x1.8293ff864e72bp+4 + -0x1.96d645432dafp-46i, 0x1.85a1ef89c3c9cp+4 + -0x1.9dc07886b928p-50i, 0x1.89fcc6dfd7f8bp+4 + 0x1.1d14e81bccfaep-46i, 0x1.8f98f87b5d227p+4 + -0x1.e0f5b3d25eafp-46i, 0x1.965c712e607cp+4 + 0x1.97f1c6585a14p-51i, 0x1.9e1ad6059e52ap+4 + 0x1.2449796a970acp-46i, 0x1.a6a30ce594486p+4 + 0x1.08d2ed95b472bp-45i, 0x1.afbe3598abdcep+4 + 0x1.21e93d9fdb629p-47i, 0x1.b9341ad4aad64p+4 + 0x1.e0d41cdeb63c4p-48i, 0x1.c2d635b60753p+4 + 0x1.458b2d2dbd6fep-46i, 0x1.cd00cdd2c3285p+4 + 0x1.9b8p-46i, 0x1.d6d64db77fd1dp+4 + 0x1.80288p-47i, 0x1.e072e3c25a384p+4 + 0x1.7847d251d2cc6p-47i, 0x1.ea04a9adbb01p+4 + -0x1.fd8018p-50i, 0x1.f3b14bb895ccap+4 + 0x1.ec2ecp-46i, 0x1.fdb7fcaefb7cap+4 + -0x1.4ed2p-49i, 0x1.042b0fdd10816p+5 + -0x1.0adfe928e9663p-46i, 0x1.0a0aa74420f2ep+5 + -0x1.c55ffap-48i, 0x1.10c9e2674d6a5p+5 + 0x1.4ep-46i, 0x1.18c02b37e8405p+5 + -0x1.5e13cp-46i, 0x1.225171a81495dp+5 + -0x1.fc482dae2d338p-47i, 0x1.2dfdc77a5b6c6p+5 + -0x1.e828018p-46i, 0x1.3c41ba3f06a42p+5 + 0x1.0fd14p-46i, 0x1.4d99a157780a9p+5 + -0x1.11132p-45i, 0x1.628edc738aec2p+5 + -0x1.5c1fe928e9664p-46i, 0x1.7baf36476ed67p+5 + -0x1.2f01ffap-44i, 0x1.9993507b29e1ap+5 + -0x1.c2248971c98p-50i, 0x1.bcc0c460ff1fcp+5 + -0x1.fcbde1504edc8p-46i, 0x1.e5baed702f51ep+5 + -0x1.412361f9e51b9p-44i, 0x1.0a7e42835fa8p+6 + -0x1.c108baef1f0cp-44i, 0x1.2578dad3520dap+6 + -0x1.86f9da6353252p-47i, 0x1.43f8d4aa429c2p+6 + -0x1.885e759db47cbp-45i, 0x1.661857912828p+6 + -0x1.4eb73c44e10abp-44i, 0x1.8be9f8237df0ap+6 + -0x1.d5e81a6f037fcp-44i, 0x1.b567de52de1ccp+6 + -0x1.7d0a8570b914bp-45i, 0x1.e27ad7867096p+6 + -0x1.5c513f3bc1173p-44i, 0x1.097aca29e240ep+7 + -0x1.5f23e1995446fp-44i, 0x1.2346cf3668a05p+7 + -0x1.37bf0dcf95d0ep-43i, 0x1.3e70495a20dfap+7 + -0x1.93356978bb028p-47i, 0x1.5ab9fe38ee056p+7 + -0x1.b1b72509eccccp-45i, 0x1.77d9257d4fc6ap+7 + -0x1.d58e076a7fcebp-46i, 0x1.95775cb5e36cp+7 + -0x1.90f6fa769806p-45i, 0x1.b333ec884390ap+7 + 0x1.77p-47i, 0x1.d0a5d095a0afap+7 + -0x1.6ff5ep-45i, 0x1.ed5e40dcba921p+7 + -0x1.01ee0b6b8b4cep-45i, 0x1.0475d2ce1c6dcp+8 + -0x1.6fec00cp-45i, 0x1.116e6af22c74fp+8 + 0x1.b85d8p-47i, 0x1.1d62153dcf118p+8 + -0x1.3b48p-51i, 0x1.281de038e8477p+8 + -0x1.eadfe928e9663p-46i, 0x1.31742428d2b7cp+8 + -0x1.50abff4p-45i, 0x1.393cf4da0d136p+8 + -0x1.e4p-47i, 0x1.3f5971a633dd5p+8 + -0x1.2709ep-45i, 0x1.43b20a7eb93e8p+8 + -0x1.c482dae2d33ap-51i, 0x1.4638bf2b91718p+8 + -0x1.5828018p-46i, 0x1.46e895d2e5924p+8 + -0x1.302ecp-46i, 0x1.45c5ddd714a86p+8 + -0x1.01132p-45i, 0x1.42dd79b430fe4p+8 + -0x1.f07fa4a3a598cp-48i, 0x1.3e43d2edd2ba4p+8 + 0x1.03f8018p-46i, 0x1.38146321ec1c1p+8 + 0x1.0a44912e393p-47i, 0x1.306f80015d6dp+8 + 0x1.f39985413b71ep-48i, 0x1.277a5787d994p+8 + 0x1.666aad1cb39d5p-45i, 0x1.1d5d39d9e71a8p+8 + 0x1.591cba2f1f0cp-44i, 0x1.1242419921c1cp+8 + -0x1.e84b259cacdaep-47i, 0x1.06549635857c9p+8 + 0x1.2284359db47ccp-45i, 0x1.f37ede7ef291bp+7 + 0x1.044747b06c57ap-44i, 0x1.d9588ba79ea8cp+7 + 0x1.629c1b2f037fcp-44i, 0x1.be864b99294f6p+7 + -0x1.81eaf51e8dd6ap-46i, 0x1.a35384ef1183cp+7 + 0x1.f475f3bc11734p-48i, 0x1.8806154c7ed84p+7 + 0x1.0a11d62dc8fap-44i, 0x1.6cddbd3efed6ep+7 + 0x1.7f6a1adf2ba1cp-44i, 0x1.521391d00f96ep+7 + -0x1.56c2cb43a27ecp-46i, 0x1.37da350481f72p+7 + 0x1.a721ca13d9998p-46i, 0x1.1e5eb8319e5a6p+7 + 0x1.4b538d462b409p-44i, 0x1.05c5f7b0a15eap+7 + 0x1.be777dfb4c03p-44i, 0x1.dc5d94015117cp+6 + 0x1.77p-47i, 0x1.af6703a675f38p+6 + 0x1.500a2p-45i, 0x1.84d018e76aa48p+6 + 0x1.5f08fa4a3a599p-44i, 0x1.5cb63ead5bea4p+6 + 0x1.1404ffdp-43i, 0x1.372d453c7ebfap+6 + 0x1.185d8p-47i, 0x1.144024afc50e6p+6 + 0x1.e312ep-45i, 0x1.e7e31660d9234p+5 + 0x1.654805b5c5a67p-44i, 0x1.ac7adb5fc81acp+5 + 0x1.f3aa006p-44i, 0x1.7631090823aacp+5 + 0x1.b8p-48i, 0x1.44e3920bfddc5p+5 + 0x1.a8f62p-45i, 0x1.18662c72e2834p+5 + 0x1.9c76fa4a3a599p-44i, 0x1.e10748a1e3cbp+4 + 0x1.e5f5ffap-44i, 0x1.99fe9aabc9022p+4 + 0x1.4be8ap-45i, 0x1.5b2c7dcc99bd6p+4 + 0x1.f6ecep-45i, 0x1.23fd3fef1bcbep+4 + 0x1.a4f805b5c5a67p-44i, 0x1.e70490d63c16ep+3 + 0x1.c4fe006p-44i, 0x1.93dbd2330bafcp+3 + 0x1.83ddb768e368p-46i, 0x1.4cb491d09b964p+3 + 0x1.d9a10f57d891cp-45i, 0x1.0ffae169c8fcp+3 + 0x1.4adc9e061ae47p-44i, 0x1.b9350741d3f2p+2 + 0x1.7af74510e0f4p-44i, 0x1.631221f4a9008p+2 + 0x1.1e4189672b36cp-45i, 0x1.1bddcdf0e012p+2 + 0x1.a7a18a624b834p-45i, 0x1.c2903a00b709p+1 + 0x1.5948c3bb1ef55p-44i, 0x1.62ef78737874p+1 + 0x1.1e17e590fc804p-44i, 0x1.15d2e5be475fp+1 + 0x1.6bd5ea3d1bad5p-47i, 0x1.b0dc58eac6bcp+0 + 0x1.febb0310fba33p-46i, 0x1.50485575f8bap+0 + 0x1.e1b83ccd57722p-45i, 0x1.053c0e56e86cp+0 + 0x1.9903c8c1a8bc8p-45i, 0x1.9acc5917940cp-1 + 0x1.59952d0e89fbp-48i, 0x1.4afb42c3627cp-1 + 0x1.0e48daf613334p-45i, 0x1.162a3b1be07cp-1 + 0x1.5538fc4ac018ap-45i, 0x1.ec5291f7f5d8p-2 + 0x1.4f09058967fap-45i, 0x1.d2bbd826136p-2 + -0x1.29c41b2ca998p-49i, 0x1.db73a8c9ea28p-2 + 0x1.b43de7af9b638p-47i, 0x1.00cc517c2d8p-1 + 0x1.90d48a410841cp-46i, 0x1.229bfca84fep-1 + 0x1.df60735c3f554p-46i, 0x1.510acc33c1c8p-1 + -0x1.745b3fcdde5p-47i, 0x1.8e2830366de8p-1 + 0x1.d0d261386de9p-49i, 0x1.d75fd76bf198p-1 + 0x1.334d4c69d5bfp-46i, 0x1.16a7569e5e68p+0 + 0x1.edf4d2cb71efp-47i, 0x1.478da29aa9ap+0 + -0x1.ff2c38f63f99cp-47i, 0x1.7de13ea2458p+0 + -0x1.219a9a31a874dp-46i, 0x1.b9bd5b48a2e8p+0 + 0x1.586034f9cc0aep-46i, 0x1.fb19c4faffacp+0 + 0x1.c86aa85db5b14p-46i, 0x1.202595e77ee6p+1 + -0x1.9582dde6507afp-46i, 0x1.442dec2ba71ep+1 + -0x1.5a9dc47f35806p-47i, 0x1.690f4321075cp+1 + 0x1.25f7b2a3693aap-47i, 0x1.8e1a21c3c23cp+1 + -0x1.728846e7c0828p-46i, 0x1.b28ad12f975cp+1 + -0x1.76d3295d9b108p-46i, 0x1.d58f84c9bcd4p+1 + -0x1.88ab934b74dc4p-47i, 0x1.f64fd74c6d9cp+1 + -0x1.e5df54b4b1b88p-48i, 0x1.09faa1f308abp+2 + -0x1.9abbf6f10c5c8p-48i, 0x1.16da145c25d3p+2 + -0x1.83d797a672853p-46i, 0x1.216a66c30369p+2 + -0x1.777f42ce0fc7p-45i, 0x1.295df0471ccap+2 + -0x1.86ef7d396f944p-46i, 0x1.2e78eeecd24fp+2 + -0x1.450c7bfde1be8p-48i, 0x1.30947182e82cp+2 + -0x1.3075692c74541p-45i, 0x1.2fa04509bf9cp+2 + -0x1.e4cf524f98976p-46i, 0x1.2ba3c3895ebdp+2 + -0x1.7861b988f600cp-47i, 0x1.24bd75f143fp+2 + -0x1.51f144e273f98p-47i, 0x1.1b218f938d0dp+2 + -0x1.bf2b71b2ade2ep-46i, 0x1.0f175e2d267ap+2 + -0x1.215885541d3f2p-45i, 0x1.00f5db67e65p+2 + -0x1.9d989d06538a8p-46i, 0x1.e23f359acaf8p+1 + 0x1.718615651541p-49i, 0x1.bffcb0336c8p+1 + -0x1.49p-47i, 0x1.9bfcda565f48p+1 + -0x1.ffafp-48i, 0x1.7714e8d5bc54p+1 + 0x1.3c23e928e9663p-46i, 0x1.520ea9fdd164p+1 + 0x1.809ffap-48i, 0x1.2da1d4c60174p+1 + -0x1.13d14p-46i, 0x1.0a6ed4e8da5p+1 + -0x1.53b48p-47i, 0x1.d1f6744dbb38p+0 + 0x1.6a402dae2d33ap-47i, 0x1.935fa2b7a9e8p+0 + 0x1.4ea8018p-46i, 0x1.59b0a2aaf1fp+0 + 0x1.9cp-47i, 0x1.2548db3917p+0 + 0x1.43d88p-47i, 0x1.eca8400c8f3p-1 + 0x1.01dbe928e9664p-46i, 0x1.99a1bdaffc6p-1 + 0x1.d7d7fe8p-46i, 0x1.512edb130f3p-1 + 0x1.fa28p-51i, 0x1.12c3c77def3p-1 + 0x1.bbb38p-47i, 0x1.bb4fec45f68p-2 + 0x1.23e016d71699cp-46i, 0x1.620a1bb23d4p-2 + 0x1.87f003p-47i, 0x1.17e8bf76a76p-2 + -0x1.b844912e393p-47i, 0x1.b629ce7c978p-3 + -0x1.797bc2a09db8fp-47i, 0x1.5381b8cd66cp-3 + 0x1.db93c0c35c8e8p-49i, 0x1.046d0cab6e4p-3 + 0x1.dee8a21c1e81p-49i, 0x1.8b865d80ep-4 + -0x1.be7698d4c948p-53i, 0x1.2957aa9048p-4 + 0x1.7a18a624b834ap-49i, 0x1.ba94fa4872p-5 + 0x1.8a461dd8f7aa6p-47i, 0x1.46147c167ap-5 + 0x1.50bf2c87e4022p-47i, 0x1.dbac4485a6p-6 + 0x1.8bd5ea3d1bad5p-47i, 0x1.5777d87ea4p-6 + 0x1.d760621f7466p-51i, 0x1.eb0aaa19a8p-7 + 0x1.06e0f3355dc88p-47i, 0x1.5b7dcde69p-7 + 0x1.420791835179p-46i, 0x1.e6e1cd8ap-8 + 0x1.b32a5a1d13f6p-49i, 0x1.51ac7f6dap-8 + 0x1.1c91b5ec26668p-46i, 0x1.cfafe661ep-9 + 0x1.54e3f12b0062ap-47i, 0x1.3b2bdc418p-9 + 0x1.bc2416259fe8p-47i) assertThat(stats:::fft(z=c(69.3960931829029+0i, -38.2557511320866-12.2364435179003i, 9.3835792339577-22.7010573579115i, -24.9437262575059+36.0881842085867i, 22.9873743364522-6.9221233646368i, 4.70702798330528-0.09131853561383i, -3.4855516101682-15.8796448346085i, -13.8986579566687+7.7320785340451i, 7.44752212944896+6.42760175696428i, 1.72908760355909+0.81688745432433i, 4.42888131358119-7.23651733808099i, -7.69923704294959+1.60001750650117i, 2.38866206897461+1.28040305352333i, -0.38958076795512+2.0975825545369i, 2.90803087954275-2.66831958880578i, -2.84126830760458+0.47798485129404i, 0.975237148082374-0.18218806207258i, -0.409794969359215+0.959529481803594i, 0.779509821970734-0.98005318226616i, -0.723824938214022+0.425358451166908i, 0.282581346601006-0.326053039186713i, -0.205848933770649+0.460494979364222i, 0.247823826200259-0.317480414508844i, -0.129419056476597+0.132699636634662i, 0.0098884221077766-0.0985489733438956i, -0.018072589058847+0.108507065688675i, 0.0508044326451802-0.0542855530621947i, -0.0278330142612114+0.015106247866356i, 0.0096897149751812-0.0227580427286841i, -0.0129285026530165+0.0285687927756497i, 0.0146265174333508-0.0188710107415458i, -0.00669657489162954+0.00831936619701322i, 0.00036765394066355-0.00667597675878766i, -0.0010056939153399+0.00574537981266003i, 0.00133227007774275-0.00240175244934385i, -9.8894965440534e-05+6.41203451664861e-04i, -1.2919584017544e-04-2.59058828512148e-04i, -1.6307793343093e-05-2.42455851311312e-04i, -7.8808726334273e-05+2.17949868939393e-04i, -1.11253292039305e-04-7.5015881448416e-05i, 6.69645252783494e-06+9.27376389138338e-06i, 7.240174126264e-06+2.59830201072588e-04i, 9.697507869713e-06-1.42594623843933e-04i, 3.63481770226044e-04+2.39995591208501e-04i, -2.4670600000839e-04-7.02034425099486e-04i, -6.8182006730356e-05+4.5573463425159e-04i, -5.5843436067622e-05-9.32699502362776e-05i, -9.53496135729914e-05-8.3957163898485e-05i, 2.18085334498443e-04+3.88411128375809e-04i, -1.15930331703352e-04-3.60192893557337e-04i, 3.07466964959034e-04+1.89022806868514e-04i, -4.07399462569602e-04-3.44114312294043e-04i, 1.29594211457982e-04+2.60150063136343e-04i, 2.28456228866351e-06+4.82028027595587e-06i, -1.59054399190015e-04-1.11892314172853e-04i, 3.26594532362735e-04+3.25876250661426e-04i, -1.98303374622467e-04-4.2927300978421e-04i, 1.92066390268526e-04+1.92281083647876e-04i, -3.03997684704762e-04-1.54552796418383e-04i, 8.05407580616925e-05+8.17295659379743e-05i, 1.00022233730219e-04+1.26214512020815e-04i, -2.8466374796913e-04-9.8369416851841e-05i, 5.48293708057053e-04+9.2768070466783e-05i, -5.01697700866666e-04-1.88371188926097e-04i, 2.81035589717271e-04+8.5110365275581e-05i, -1.41592805107969e-04-3.16020975334e-07i, -6.05011232296863e-05+1.4216236489355e-06i, 2.49008350897009e-04+2.85293360384e-07i, -2.90438270386603e-04-8.102944481311e-06i, 2.56487385854016e-04-7.2027325815379e-05i, -2.83067738556283e-04+5.619849315054e-05i, 1.60577603830794e-04+3.1828521096639e-05i, -1.18163386856337e-05-3.0916896569967e-06i, -1.16969550799418e-04+3.4173361762774e-05i, 3.99052524319294e-04-1.751306697862e-05i, -4.09628155306663e-04-1.15701319111755e-04i, 2.20719598036708e-04-1.18351234184033e-04i, -2.7857785535465e-04+2.24031572335762e-04i, 1.25221493332754e-04-2.461713148731e-05i, 4.97025842365178e-05+1.25910091765866e-05i, -7.11489126519355e-05+9.91580438900807e-05i, 3.39086553461404e-04-2.06338519829023e-04i, -4.16038947053962e-04-1.8486304359853e-05i, 1.62260106956536e-04+2.3895934188363e-05i, -9.5495045173889e-05+6.9303745845167e-05i, -9.42134371046282e-06+3.6086492514285e-06i, 1.40574966589056e-04-2.1320931404431e-05i, -9.4605318292829e-05+1.32603987897436e-04i, 1.640766953179e-04-3.38383368220357e-04i, -2.76243028603656e-04+2.17800281330818e-04i, 1.16263062229284e-04-4.5510617529242e-05i, -8.0098354344113e-06+2.88354723060882e-05i, -4.11159900759657e-05+8.49423930815997e-05i, 1.85646229724583e-04-1.11713820620961e-04i, -1.23110429712048e-04+3.1015266958208e-05i, 5.4399418853481e-05-2.16977842657198e-04i, -2.07756284442269e-04+2.56542648530852e-04i, 1.19581075269616e-04-7.3948370945046e-05i, 9.1423088022767e-06-1.98624543488594e-05i, -6.930029404274e-06+2.17452962700862e-04i, 1.00606683949571e-04-3.30407352353339e-04i, -2.8161927165487e-05+1.74858570900621e-04i, -1.27710138213451e-04-1.7668846114196e-04i, 2.6362077451921e-05+1.71875999016256e-04i, 1.19488694392029e-05-2.46774479204664e-05i, 2.01961069108116e-05-4.25145239272444e-05i, 4.6594110741322e-05+1.55662816668247e-04i, -7.382766335867e-06-3.2671891568907e-04i, -8.5242767600085e-05+2.41625259519031e-04i, -7.449253941858e-06-1.07334108866029e-04i, 3.75997999256947e-05+8.44643556069968e-05i, 4.2736376417741e-06+6.2936194320836e-05i, 4.3677703565514e-05-1.7851326966109e-04i, 8.8026752171604e-05+1.30492634314949e-04i, -2.46736610979001e-04-2.48272062836803e-04i, 9.0621574444782e-05+2.42597931742966e-04i, -2.83927539977572e-05-3.6742368000898e-05i, 1.29313326552962e-05+8.479775668911e-07i, 9.05313667232827e-05+8.61629571155001e-05i, 8.429851107456e-06-1.79840063893996e-04i, 4.480935702866e-06+3.87002677104214e-05i, -2.00254174281824e-04-8.4845502693082e-05i, 1.12942187986762e-04+1.62215861673319e-04i, -7.1716580329834e-06-3.5359876394281e-05i, -1.88890265482971e-05-5.808482848191e-07i, 1.07797352994744e-04+8.1622637471267e-05i, -2.922148200663e-05-2.39583562617863e-04i, -3.7883986374378e-05+1.33983823222083e-04i, -1.10536265052674e-04-4.7712256546727e-05i, 9.42979517554801e-05+7.85794708915315e-05i, -5.439611603687e-07-1.2692009086834e-06i, -2.61442946141423e-05-1.32810689313002e-05i, 1.737646905958e-04+2.0666217278295e-05i, -2.07155346179823e-04-1.81268727446554e-04i, 5.9289822231747e-05+1.29176964989802e-04i, -7.80434681212893e-05+1.66615525367578e-05i, 5.64069628144653e-05+6.321429186975e-07i, 4.84048796416383e-05+2.51274610972347e-05i, -4.23064864606567e-05-1.36094344943618e-05i, 1.1537360018261e-04-7.9906249864792e-05i, -2.02411330429303e-04-8.988885736843e-06i, 1.01327699430121e-04+6.8733974915757e-05i, -3.72473396971622e-05-8.660774147174e-07i, -6.51880785501584e-06+2.56041664872258e-06i, 1.11549112216042e-04-1.1196567534859e-05i, -1.29267445813345e-04-1.060193609492e-05i, 1.00530048673151e-04-6.9161215365144e-05i, -1.49922899225587e-04+1.02930570218184e-04i, 1.15271943446401e-04-2.9198801598725e-05i, -1.95823935866016e-05+2.161272953281e-06i, -1.76702563377537e-05+2.58073203559952e-05i, 9.248583169792e-05-9.36313696537008e-05i, -1.31966781528097e-04+5.4989953155343e-05i, 3.23456107225922e-05-6.01922253019832e-05i, -2.9051551407322e-05+1.02731173836465e-04i, 4.79824935680419e-05-3.11918343030065e-05i, 8.80403169460255e-06+2.35262383940408e-06i, -2.08047621728233e-05+2.7336193114101e-06i, 8.64930674391062e-05-9.0686561826063e-05i, -1.73812032015692e-04+6.4157225927183e-05i, 9.11897114878611e-05-1.79430307570414e-05i, -2.15322932257995e-05+5.38788745828886e-05i, 1.01305779012919e-05-2.12862009247272e-05i, 3.63073403671419e-05-3.68739994685092e-05i, -3.33668812344773e-05+4.32722617958086e-05i, 6.43972355624e-06-1.05056947694726e-04i, -6.9788400121405e-05+1.28486393305376e-04i, 6.9545890580116e-05-5.6197340304384e-05i, -6.1325016314917e-06+2.09269640125448e-05i, 2.264510196169e-06+1.640651562504e-05i, 4.14275518033267e-05-8.42446741723665e-05i, -8.93154942756449e-05+3.2041554996961e-05i, 1.19966611311344e-05-3.30183746242459e-05i, -1.6859707817117e-05+1.27968138734547e-04i, 5.55672304678694e-05-8.90979208118088e-05i, -7.31268006750303e-06+9.59950921839247e-06i, 1.08090342336289e-05+4.97901892949552e-05i, -6.746377147926e-06-1.68505168151103e-04i, -4.4491743054138e-05+1.62229670009177e-04i, -2.46850991978608e-05-7.90146298810716e-05i, 7.28313222469443e-05+6.83783021307915e-05i, -2.54938209121841e-05-3.64294026409139e-05i, -6.31043772629802e-06-9.367630376959e-06i, 4.63232014125699e-05+3.268718236227e-06i, -8.7970256539373e-05-4.65132771927244e-05i, 2.23017617743377e-05+7.92088086538067e-05i, 1.96008495986947e-05-2.29466995667736e-05i, 1.31419377249024e-05+4.779643772288e-07i, -3.64222598947742e-06-4.52006210999592e-06i, 6.4201848006117e-06-4.55426230053285e-05i, -2.66106430644642e-05+3.17902704282662e-05i, -5.57735125974381e-05-4.76936703814926e-05i, 6.424270785645e-05+1.28674567794444e-04i, -1.20594351986293e-05-7.64347812505893e-05i, 1.94402482032863e-05+1.7214691779166e-06i, 3.19136695790415e-05+3.8611132175019e-06i, -6.3603182791951e-05-5.70553495795772e-05i, 5.6973684853036e-06+2.77385222396069e-05i, -5.5957890083399e-05+2.54680801072852e-05i, 9.06692958759324e-05+3.47480785690129e-05i, -2.95469548934397e-05-4.60685129750324e-05i, 6.2022120309855e-07+1.1196919549013e-06i, 3.59285784545173e-05-3.351936988113e-07i, -8.47015633077469e-05-3.34027991203412e-05i, 4.12287799831452e-05+4.02211206121932e-05i, -2.10409284033625e-05+1.6870711844863e-05i, 4.8128847527245e-05-1.33824320989922e-05i, -2.31531321208878e-05-1.44584750705137e-05i, -8.5662421526936e-06-2.02571287466675e-05i, 2.32086839866531e-05+5.0675277371307e-06i, -1.07560911469618e-04+1.6910233979145e-05i, 1.16263040220051e-04+3.0705595530842e-05i, -3.72307812858108e-05-9.4449676166697e-06i, 2.23593816284055e-05-3.44941745449408e-05i, 1.11583108847153e-06-6.1736735235985e-07i, -3.66876865001586e-05-6.9537129122563e-06i, -1.05931382051046e-05-1.38429114541474e-05i, -2.77335003326531e-05+6.49686826555037e-05i, 7.71189155901708e-05-5.469586035753e-07i, -2.07927616363336e-05-2.98193771972745e-05i, 3.2925041497615e-07-6.86891850628453e-06i, 2.41178577818788e-05-1.94997533138036e-05i, -7.61200781954183e-05-9.271875765247e-06i, 1.05189231649673e-05+1.95590188201399e-05i, 2.5339027864314e-06+6.6875005597912e-05i, 5.25640775825936e-05-5.44974519865998e-05i, -2.5213784061404e-05-1.3686488179067e-06i, 2.6203310495145e-08+4.28516558220407e-07i, 1.77211633848084e-05-3.61639885254017e-05i, -7.84797773009858e-05+3.21395442597451e-05i, 4.99534391606712e-05+2.8342623811298e-06i, -5.7384799417244e-06+3.10201289519941e-05i, 1.60426848885318e-05-4.36891759807049e-05i, -8.38481909947796e-06+9.07340411227866e-06i, -4.1396517935036e-07+8.11762728870538e-06i, -2.70782939337911e-05-4.3783546120977e-05i, 6.4481245808405e-06+7.22421232685004e-05i, 2.712853213057e-05-2.67743199234726e-05i, -4.5767545412495e-06-1.42530056634947e-05i, -1.53725469352065e-05-7.3633804703231e-06i, -8.7469688505443e-07-6.38927457928574e-06i, -1.0346360393484e-05+2.73987760125244e-05i, -2.9957414478543e-05-1.38299870919499e-05i, 6.65832954871261e-05+4.64292538449082e-05i, -1.92907769106975e-05-4.14977658984447e-05i, 3.1837345521297e-06-1.71773201508029e-05i, -9.11110689257541e-06+6.70440009461078e-06i, -1.41280517410479e-05-8.2882767539091e-06i, -2.69960952041783e-05+1.43307439864998e-05i, 1.83898287640272e-05+2.54648501758252e-05i, 3.52651309861207e-05+3.1927937155075e-06i, -1.3887174617391e-05-3.59810345972462e-05i, -8.73535586811686e-06+4.55622206340091e-06i, 1.10518223925989e-06-3.89561245818612e-06i, -2.62625327895873e-05-1.0411283317755e-06i, 1.14245349674882e-05+2.82837067409459e-05i, 1.36668960887387e-05+0i, 1.14245349674687e-05-2.82837067409538e-05i, -2.62625327895845e-05+1.0411283318462e-06i, 1.10518223928771e-06+3.89561245832759e-06i, -8.7353558680447e-06-4.55622206330555e-06i, -1.38871746172898e-05+3.5981034597067e-05i, 3.52651309859845e-05-3.1927937154017e-06i, 1.83898287638254e-05-2.54648501756504e-05i, -2.69960952040343e-05-1.43307439864165e-05i, -1.41280517406988e-05+8.2882767537262e-06i, -9.11110689260429e-06-6.70440009457155e-06i, 3.1837345520993e-06+1.71773201509284e-05i, -1.92907769107954e-05+4.1497765898623e-05i, 6.6583295487152e-05-4.64292538448711e-05i, -2.99574144785291e-05+1.38299870918897e-05i, -1.03463603934818e-05-2.73987760127e-05i, -8.7469688510595e-07+6.38927457936109e-06i, -1.53725469352064e-05+7.3633804703235e-06i, -4.5767545412255e-06+1.42530056634523e-05i, 2.71285321305486e-05+2.67743199233569e-05i, 6.4481245807602e-06-7.22421232684321e-05i, -2.70782939338022e-05+4.37835461210546e-05i, -4.1396517933736e-07-8.11762728865895e-06i, -8.3848190995973e-06-9.07340411231837e-06i, 1.60426848885415e-05+4.36891759807906e-05i, -5.7384799417001e-06-3.10201289520224e-05i, 4.99534391606412e-05-2.8342623811109e-06i, -7.8479777301312e-05-3.21395442598902e-05i, 1.77211633847642e-05+3.61639885253878e-05i, 2.6203310524841e-08-4.28516558221737e-07i, -2.52137840614596e-05+1.368648818013e-06i, 5.25640775826321e-05+5.44974519863069e-05i, 2.5339027864312e-06-6.68750055979119e-05i, 1.05189231649741e-05-1.95590188201921e-05i, -7.61200781951269e-05+9.2718757653483e-06i, 2.41178577817547e-05+1.94997533136637e-05i, 3.2925041497275e-07+6.86891850628003e-06i, -2.07927616362624e-05+2.98193771971964e-05i, 7.71189155902853e-05+5.469586037686e-07i, -2.77335003325778e-05-6.49686826556062e-05i, -1.05931382050887e-05+1.38429114541227e-05i, -3.66876865001181e-05+6.9537129121533e-06i, 1.11583108850155e-06+6.1736735239748e-07i, 2.2359381628418e-05+3.44941745449002e-05i, -3.72307812857648e-05+9.444967616667e-06i, 1.16263040220174e-04-3.0705595530848e-05i, -1.0756091146962e-04-1.6910233979146e-05i, 2.32086839865703e-05-5.0675277370818e-06i, -8.5662421526827e-06+2.02571287466417e-05i, -2.31531321206882e-05+1.44584750704878e-05i, 4.81288475272646e-05+1.33824320990017e-05i, -2.10409284033808e-05-1.68707118448639e-05i, 4.12287799831129e-05-4.02211206121674e-05i, -8.4701563307747e-05+3.34027991205007e-05i, 3.59285784545131e-05+3.351936989102e-07i, 6.2022120303367e-07-1.11969195482896e-06i, -2.95469548934383e-05+4.60685129749785e-05i, 9.0669295876231e-05-3.4748078568922e-05i, -5.59578900833569e-05-2.54680801072878e-05i, 5.6973684853293e-06-2.77385222396578e-05i, -6.3603182792124e-05+5.70553495795631e-05i, 3.19136695793765e-05-3.8611132169289e-06i, 1.94402482033801e-05-1.7214691780168e-06i, -1.2059435198654e-05+7.6434781251088e-05i, 6.424270785645e-05-1.28674567794444e-04i, -5.57735125971619e-05+4.76936703815061e-05i, -2.6610643064358e-05-3.17902704281959e-05i, 6.420184800483e-06+4.55426230052427e-05i, -3.64222598972343e-06+4.52006210979987e-06i, 1.31419377248699e-05-4.779643772505e-07i, 1.96008495986777e-05+2.29466995667838e-05i, 2.23017617744241e-05-7.92088086539633e-05i, -8.79702565393434e-05+4.65132771926699e-05i, 4.63232014125603e-05-3.2687182361833e-06i, -6.31043772630626e-06+9.3676303768629e-06i, -2.54938209120189e-05+3.64294026406821e-05i, 7.28313222466949e-05-6.83783021308971e-05i, -2.46850991977952e-05+7.90146298811971e-05i, -4.4491743054487e-05-1.62229670009248e-04i, -6.746377148077e-06+1.6850516815118e-04i, 1.08090342336254e-05-4.97901892949389e-05i, -7.31268006734795e-06-9.59950921831283e-06i, 5.55672304679099e-05+8.90979208117965e-05i, -1.685970781712e-05-1.27968138734566e-04i, 1.19966611311267e-05+3.30183746242111e-05i, -8.9315494275582e-05-3.20415549968512e-05i, 4.14275518034311e-05+8.42446741725442e-05i, 2.2645101961001e-06-1.640651562517e-05i, -6.1325016314994e-06-2.09269640125701e-05i, 6.95458905801788e-05+5.61973403045186e-05i, -6.9788400121502e-05-1.28486393305798e-04i, 6.439723556071e-06+1.05056947694626e-04i, -3.33668812344374e-05-4.32722617958804e-05i, 3.63073403673065e-05+3.68739994687764e-05i, 1.01305779013014e-05+2.12862009246096e-05i, -2.15322932258926e-05-5.38788745825922e-05i, 9.1189711487861e-05+1.79430307570416e-05i, -1.73812032015594e-04-6.4157225927475e-05i, 8.64930674389113e-05+9.06865618261193e-05i, -2.08047621728268e-05-2.7336193114189e-06i, 8.8040316943969e-06-2.35262383934004e-06i, 4.79824935682228e-05+3.11918343029748e-05i, -2.9051551407389e-05-1.02731173836367e-04i, 3.23456107226858e-05+6.01922253021511e-05i, -1.31966781528177e-04-5.4989953155339e-05i, 9.24858316977875e-05+9.36313696535922e-05i, -1.76702563379011e-05-2.58073203561612e-05i, -1.95823935866094e-05-2.1612729533339e-06i, 1.15271943446492e-04+2.919880159883e-05i, -1.49922899225936e-04-1.0293057021846e-04i, 1.00530048673048e-04+6.9161215365144e-05i, -1.29267445813234e-04+1.0601936094904e-05i, 1.11549112215975e-04+1.1196567534984e-05i, -6.51880785549784e-06-2.56041664904472e-06i, -3.72473396969553e-05+8.660774148307e-07i, 1.01327699429953e-04-6.8733974915847e-05i, -2.02411330428947e-04+8.98888573711e-06i, 1.15373600182492e-04+7.9906249864164e-05i, -4.23064864605137e-05+1.36094344944107e-05i, 4.8404879641728e-05-2.51274610969749e-05i, 5.64069628146799e-05-6.321429184571e-07i, -7.80434681213573e-05-1.66615525371351e-05i, 5.9289822231944e-05-1.291769649894e-04i, -2.07155346180601e-04+1.81268727445199e-04i, 1.73764690596054e-04-2.0666217277728e-05i, -2.61442946143351e-05+1.32810689312735e-05i, -5.4396116037073e-07+1.26920090897087e-06i, 9.42979517546625e-05-7.85794708926977e-05i, -1.10536265052674e-04+4.7712256546727e-05i, -3.7883986374138e-05-1.33983823221385e-04i, -2.9221482005609e-05+2.39583562616857e-04i, 1.07797352994597e-04-8.16226374716e-05i, -1.88890265482146e-05+5.808482850567e-07i, -7.1716580330554e-06+3.53598763948802e-05i, 1.12942187987432e-04-1.62215861673216e-04i, -2.00254174282296e-04+8.4845502692614e-05i, 4.4809357030119e-06-3.87002677104351e-05i, 8.429851106484e-06+1.7984006389408e-04i, 9.05313667236024e-05-8.61629571152934e-05i, 1.29313326555757e-05-8.479775672033e-07i, -2.83927539977386e-05+3.67423680010493e-05i, 9.06215744446e-05-2.42597931743301e-04i, -2.46736610979028e-04+2.48272062837083e-04i, 8.8026752171707e-05-1.30492634315283e-04i, 4.3677703565626e-05+1.78513269660922e-04i, 4.2736376414915e-06-6.29361943207091e-05i, 3.75997999259449e-05-8.44643556066096e-05i, -7.449253941849e-06+1.07334108865635e-04i, -8.5242767599639e-05-2.41625259518787e-04i, -7.382766335989e-06+3.26718915688942e-04i, 4.6594110741277e-05-1.55662816667999e-04i, 2.01961069108244e-05+4.25145239270625e-05i, 1.19488694393129e-05+2.46774479207435e-05i, 2.6362077451929e-05-1.71875999016069e-04i, -1.27710138213439e-04+1.76688461141935e-04i, -2.8161927165277e-05-1.74858570900978e-04i, 1.00606683949105e-04+3.30407352353265e-04i, -6.930029404666e-06-2.1745296270027e-04i, 9.142308801876e-06+1.98624543487035e-05i, 1.19581075269797e-04+7.3948370944289e-05i, -2.07756284442269e-04-2.56542648530852e-04i, 5.4399418853421e-05+2.16977842656999e-04i, -1.23110429711828e-04-3.1015266957996e-05i, 1.85646229724241e-04+1.1171382061997e-04i, -4.11159900759469e-05-8.49423930813482e-05i, -8.009835434655e-06-2.88354723058374e-05i, 1.16263062229276e-04+4.5510617529538e-05i, -2.76243028603553e-04-2.17800281331026e-04i, 1.64076695317838e-04+3.38383368220451e-04i, -9.4605318292916e-05-1.32603987897139e-04i, 1.40574966588803e-04+2.13209314045e-05i, -9.4213437103991e-06-3.60864925220696e-06i, -9.54950451739699e-05-6.93037458451769e-05i, 1.62260106956755e-04-2.3895934188226e-05i, -4.16038947054204e-04+1.8486304360324e-05i, 3.39086553462037e-04+2.06338519828348e-04i, -7.11489126519663e-05-9.91580438901237e-05i, 4.97025842367039e-05-1.259100917621e-05i, 1.25221493332384e-04+2.4617131487212e-05i, -2.78577855353327e-04-2.24031572335793e-04i, 2.20719598036603e-04+1.18351234183994e-04i, -4.0962815530568e-04+1.15701319112298e-04i, 3.99052524318921e-04+1.7513066978835e-05i, -1.16969550798978e-04-3.4173361763128e-05i, -1.18163386859273e-05+3.0916896568246e-06i, 1.60577603830921e-04-3.1828521096094e-05i, -2.83067738556701e-04-5.6198493150721e-05i, 2.5648738585368e-04+7.2027325815155e-05i, -2.90438270386488e-04+8.102944480991e-06i, 2.49008350896436e-04-2.85293358712e-07i, -6.05011232291451e-05-1.4216236495478e-06i, -1.41592805107824e-04+3.16020975035e-07i, 2.81035589717271e-04-8.5110365275581e-05i, -5.0169770086639e-04+1.88371188926119e-04i, 5.4829370805581e-04-9.2768070466831e-05i, -2.84663747968552e-04+9.8369416850622e-05i, 1.00022233729375e-04-1.26214512020439e-04i, 8.05407580627519e-05-8.17295659384904e-05i, -3.03997684704544e-04+1.54552796418049e-04i, 1.92066390268216e-04-1.92281083648198e-04i, -1.98303374622324e-04+4.29273009783997e-04i, 3.26594532362916e-04-3.25876250660222e-04i, -1.59054399190116e-04+1.11892314172907e-04i, 2.28456228823985e-06-4.82028027601457e-06i, 1.29594211458474e-04-2.60150063136933e-04i, -4.073994625703e-04+3.44114312295818e-04i, 3.07466964959516e-04-1.89022806868881e-04i, -1.15930331703741e-04+3.60192893557518e-04i, 2.18085334498547e-04-3.88411128375995e-04i, -9.53496135726216e-05+8.39571638988239e-05i, -5.58434360676845e-05+9.32699502365398e-05i, -6.8182006731091e-05-4.55734634252176e-04i, -2.46706000008312e-04+7.02034425099294e-04i, 3.63481770226185e-04-2.39995591208063e-04i, 9.697507869729e-06+1.42594623843863e-04i, 7.240174125203e-06-2.59830201072346e-04i, 6.69645252805372e-06-9.2737638917572e-06i, -1.11253292039012e-04+7.5015881448822e-05i, -7.8808726334565e-05-2.17949868939455e-04i, -1.6307793344343e-05+2.4245585131119e-04i, -1.29195840175096e-04+2.59058828511326e-04i, -9.8894965439964e-05-6.41203451664509e-04i, 0.0013322700777426+0.00240175244934319i, -0.00100569391534063-0.0057453798126606i, 0.00036765394066356+0.00667597675878766i, -0.00669657489162757-0.0083193661970128i, 0.0146265174333495+0.018871010741545i, -0.0129285026530171-0.028568792775649i, 0.0096897149751807+0.0227580427286832i, -0.0278330142612102-0.0151062478663562i, 0.0508044326451796+0.0542855530621939i, -0.018072589058848-0.108507065688674i, 0.0098884221077766+0.0985489733438949i, -0.129419056476596-0.132699636634663i, 0.247823826200259+0.317480414508844i, -0.205848933770651-0.460494979364221i, 0.282581346601006+0.326053039186713i, -0.723824938214021-0.425358451166909i, 0.779509821970735+0.98005318226616i, -0.409794969359216-0.959529481803594i, 0.975237148082374+0.18218806207258i, -2.84126830760457-0.47798485129404i, 2.90803087954274+2.66831958880578i, -0.38958076795512-2.0975825545369i, 2.38866206897461-1.28040305352333i, -7.69923704294959-1.60001750650118i, 4.42888131358119+7.23651733808099i, 1.72908760355909-0.81688745432433i, 7.44752212944895-6.42760175696428i, -13.8986579566687-7.7320785340451i, -3.4855516101682+15.8796448346085i, 4.70702798330529+0.09131853561384i, 22.9873743364522+6.9221233646368i, -24.9437262575059-36.0881842085867i, 9.3835792339577+22.7010573579115i, -38.2557511320866+12.2364435179003i)) , identicalTo( expected, tol = 1e-6 ) )
if (getRversion() >= '2.15.1') utils::globalVariables( c('N', '.', 'copies') ) is_id <- function(dt, by, verbose = TRUE, return_report = FALSE) { if (!(is.data.table(dt))) { dt <- as.data.table(dt) } else { dt <- data.table::copy(dt) } m <- dt[, .(copies =.N), by = mget(by)] is_id <- m[, mean(copies)] == 1 if (verbose) { cli::cli_h3("Duplicates in terms of {.code {by}}") d <- freq_table(m, "copies") print(d[]) cli::cli_rule(right = "End of {.field is_id()} report") } if (isFALSE(return_report)) { return(is_id) } else { return(m) } }
"boa.pardesc" <- function() { return(.boa.pardesc) }
gfunction.bet2.cc <- function(para, map, ref, Delta, delta, ncase, nctrl, xi, pr){ nmodel <- length(map$bet) g.bet2 <- list() n <- nrow(ref) const <- list() for(i in 1:nmodel){ id <- c(alp.index.cc(map, i), map$bet[[i]]) gam <- para[id] rx <- as.matrix(ref[, names(gam), drop = FALSE]) rho.i <- ncase[i, i] / nctrl[i, i] const[[i]] <- -rx * (delta[, i] * (1 - rho.i * delta[, i]) * (1 + rho.i * Delta) / (1 + rho.i * delta[, i])^3) } nlam <- max(map$lam) offset <- max(map$the) foo <- function(j, l){ paste0(j,'-',l) } for(i in 1:nmodel){ id.a <- alp.index.cc(map, i) id.b <- map$bet[[i]] id <- c(id.a, id.b) for(j in id.b){ fxj <- ref[, names(para)[j]] tmp <- const[[i]] * fxj for(l in id.b){ if(l < j){ next } fxl <- ref[, names(para)[l]] gt <- matrix(0, nrow = n, ncol = nlam - 1) gt[, id - offset] <- tmp * fxl g.bet2[[foo(j,l)]] <- t(gt %*% xi) %*% pr } } } g.bet2 }
RVI_func <- function(ID, DXcontrol, covariates=NULL, resp.range, EP, data) { resp.names <- names(data)[resp.range] resp.data <- data.frame(data[,resp.range]) colnames(resp.data) <- resp.names control.idx <- rownames(subset(data,eval(parse(text=DXcontrol)))) i.norm.data <- data.frame(ID=data[,which(names(data)==ID)]) if(is.null(covariates)==T){ for (i in 1:ncol(resp.data)) { formula <- stats::as.formula(paste(resp.names[i], ' ~ ', 1)) model <- stats::lm(formula, na.action=stats::na.exclude, data=data) model.residuals <- stats::resid(model) i.norm.residuals <- stats::qnorm((rank(model.residuals, na.last = "keep")) / (sum(!is.na(model.residuals))+1)) i.norm.data <- cbind(i.norm.data,i.norm.residuals) } colnames(i.norm.data) <- c(ID,resp.names) } else{ for (i in 1:ncol(resp.data)) { formula <- stats::as.formula(paste(resp.names[i], ' ~ ', paste(covariates, collapse = "+"))) model <- stats::lm(formula,na.action=stats::na.exclude, data=data) model.residuals <- stats::resid(model) i.norm.residuals <- stats::qnorm((rank(model.residuals, na.last = "keep")) / (sum(!is.na(model.residuals))+1)) i.norm.data <- cbind(i.norm.data,i.norm.residuals) } colnames(i.norm.data) <- c(ID,resp.names) } z.norm.data <- data.frame(ID=data[,which(names(data)==ID)]) for (i in 2:ncol(i.norm.data)) { inorm.control.mean <- mean(i.norm.data[control.idx,i]) inorm.control.sd <- stats::sd(i.norm.data[control.idx,i]) z.norm.residuals <- (i.norm.data[,i] - inorm.control.mean)/inorm.control.sd z.norm.data <- cbind(z.norm.data,z.norm.residuals) } colnames(z.norm.data) <- c(ID,resp.names) RVI.data <- data.frame(ID=data[,which(names(data)==ID)],RVI=NA) for (i in 1:nrow(z.norm.data)) { RVI.data$RVI[i] <- stats::cor(unlist(z.norm.data[i,2:(length(resp.range)+1)]), EP, use = "complete.obs") RVI.data$EDP[i] <- sum(unlist(z.norm.data[i,2:(length(resp.range)+1)])*EP, na.rm = TRUE) } out <- list() out$i.norm.resid <- i.norm.data out$z.norm.resid <- z.norm.data out$RVI <- RVI.data return (out) }
expected <- eval(parse(text="c(\"structure(list(Sex = structure(c(2L, 2L, 1L, 1L, 2L, 2L), .Label = c(\\\"Female\\\", \", \"\\\"Male\\\"), class = \\\"factor\\\"), age = c(15, 20, 10, 12, 2, 4), Subject = structure(c(2L, \", \"2L, 1L, 1L, 3L, 3L), .Label = c(\\\"F30\\\", \\\"M01\\\", \\\"M04\\\"), class = \\\"factor\\\")), .Names = c(\\\"Sex\\\", \", \"\\\"age\\\", \\\"Subject\\\"), row.names = c(NA, -6L), class = \\\"data.frame\\\")\")")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(Sex = structure(c(2L, 2L, 1L, 1L, 2L, 2L), .Label = c(\"Female\", \"Male\"), class = \"factor\"), age = c(15, 20, 10, 12, 2, 4), Subject = structure(c(2L, 2L, 1L, 1L, 3L, 3L), .Label = c(\"F30\", \"M01\", \"M04\"), class = \"factor\")), .Names = c(\"Sex\", \"age\", \"Subject\"), row.names = c(NA, -6L), class = \"data.frame\"), 60L, FALSE, 69, -1L)")); .Internal(deparse(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]])); }, o=expected);
library("infercnv") infercnv_obj = CreateInfercnvObject(raw_counts_matrix="../oligodendroglioma_expression_downsampled.counts.matrix", annotations_file="../oligodendroglioma_annotations_downsampled.txt", delim="\t", gene_order_file="../gencode_downsampled.txt", ref_group_names=c("Microglia/Macrophage","Oligodendrocytes (non-malignant)")) out_dir="output_dir_use_zscores" infercnv_obj = infercnv::run(infercnv_obj, cutoff=1, out_dir=out_dir, cluster_by_groups=T, plot_steps=T, use_zscores=T, include.spike=T )
filterStream <- function(file.name=NULL, track=NULL, follow=NULL, locations=NULL, language=NULL, timeout=0, tweets=NULL, oauth=NULL, verbose=TRUE) { open.in.memory <- FALSE if (all(is.null(c(track,follow,language,locations)))) { stop("No filter parameter was specified. At least one is necessary. See ?filterStream for more information about this error.") } if (all(is.null(c(track,follow,locations))) & !is.null(language)){ stop("Language parameter can only be used in combination with other filter parameters.") } if ((missing(file.name)||is.character(file.name)==FALSE)){ stop("The file where the tweets will be stored was not named properly.") } if (timeout<0||is.numeric(timeout)==FALSE||length(timeout)>1){ stop("The specified time out was not properly formatted.") } if (is.null(oauth)) { stop("No authentication method was provided. Please use an OAuth token.") } if (!is.null(oauth)){ if (is.list(oauth)){ oauth <- createOAuthToken(consumerKey=oauth$consumer_key, consumerSecret=oauth$consumer_secret, accessToken=oauth$access_token, accessTokenSecret=oauth$access_token_secret) } if (!inherits(oauth, "OAuth")) { stop("oauth argument must be of class OAuth") } if (!oauth$handshakeComplete) { stop("Oauth needs to complete its handshake. See ?filterStream.") } } params <- buildArgList(track, follow, language, locations, oauth=oauth) i <- 0 if (!is.null(file.name)){ if (verbose==TRUE) message("Capturing tweets...") if (nchar(file.name)==0) { open.in.memory <- TRUE file.name <- tempfile() } conn <- file(description=file.name, open="a") write.tweets <- function(x){ if (nchar(x)>0) { i <<- i + 1 writeLines(x, conn, sep="") } } if (!is.null(tweets) && is.numeric(tweets) && tweets>0){ write.tweets <- function(x){ while (i<=tweets){ if (nchar(x)>0) { i <<- i + 1 writeLines(x, conn, sep="") } } } } } init <- Sys.time() url <- "https://stream.twitter.com/1.1/statuses/filter.json" if (!is.null(oauth)){ output <- tryCatch(oauth$OAuthRequest(URL=url, params=params, method="POST", customHeader=NULL, timeout = timeout, writefunction = write.tweets, cainfo=system.file("CurlSSL", "cacert.pem", package = "RCurl")), error=function(e) e) } if (!is.null(file.name)){ close(conn) } seconds <- round(as.numeric(difftime(Sys.time(), init, units="secs")),0) if (open.in.memory==TRUE){ raw.tweets <- readLines(file.name, warn=FALSE, encoding="UTF-8") if (verbose==TRUE){ message("Connection to Twitter stream was closed after ", seconds, " seconds with up to ", length(raw.tweets), " tweets downloaded.") } unlink(file.name) return(raw.tweets) } if (open.in.memory==FALSE) { if (verbose==TRUE) {message("Connection to Twitter stream was closed after ", seconds, " seconds with up to ", i, " tweets downloaded.")} } } format.param <- function(param.name, param){ param <- as.character(param) if (length(param)>1) param <- paste(param, collapse=",") param.field <- paste(param.name, "=", param, sep="") } buildArgList <- function(track=NULL, follow=NULL, language=NULL, locations=NULL, with=NULL,replies=NULL, oauth=NULL) { params <- list() if (!is.null(track)) params[["track"]] <- paste(track, collapse=",") if (!is.null(follow)) params[["follow"]] <- paste(as.character(follow), collapse=",") if (!is.null(locations)) params[["locations"]] <- paste(as.character(locations), collapse=",") if (!is.null(language)) params[["language"]] <- paste(as.character(language), collapse=",") if (!is.null(with)) params[["with"]] <- paste(as.character(with), collapse=",") if (!is.null(replies)) params[["replies"]] <- paste(as.character(replies), collapse=",") return(params) } createOAuthToken <- function(consumerKey, consumerSecret, accessToken, accessTokenSecret){ my_oauth <- ROAuth::OAuthFactory$new(consumerKey=consumerKey, consumerSecret=consumerSecret, oauthKey=accessToken, oauthSecret=accessTokenSecret, needsVerifier=FALSE, handshakeComplete=TRUE, verifier="1", requestURL="https://api.twitter.com/oauth/request_token", authURL="https://api.twitter.com/oauth/authorize", accessURL="https://api.twitter.com/oauth/access_token", signMethod="HMAC") return(my_oauth) }
navigate_hash <- function(hobj, numtree = NA, dataset_description = "Unknown"){ parentid <- NULL objectid <- 0 level <- 1 ln <- NA rn <- NA label_1X <- "%s [label = \"Node %s\\nX[%s] <= %s\\ngini index = %s\\nsamples = %s\\nvalue = %s\"];" label_1z <- "%s [label = \"Node %s\\nz[%s] <= %s\\ngini index = %s\\nsamples = %s\\nvalue = %s\"];" if(is.na(numtree)){ loop_start <- 1 loop_end <- length(hobj) } else { loop_start <- numtree loop_end <- numtree } if(numtree %notin% seq(1, length(hobj))){ msg <- "hhcartr(displayTree) Tree %s requested, only %s trees available." msgs <- sprintf(msg, numtree, length(hobj)) stop(msgs) } clear_dot_list() append_dot_list("digraph rmarkdown {") append_dot_list("nodesp = 0.75;") title_dot_stmt <- "graph [label = 'displayTree for Tree %s. Dataset: %s.\\nn_folds = %s, n_trees = %s, n_min = %s,\\nmin_node_impurity = %s, useIdentity = %s,\\nseed = %s.', labelloc='t', fontsize=28];" title_dot_stmt_formatted <- sprintf(title_dot_stmt, numtree, dataset_description, pkg.env$n_folds, pkg.env$n_trees, pkg.env$n_min, pkg.env$min_node_impurity, pkg.env$useIdentity, pkg.env$seed) append_dot_list(title_dot_stmt_formatted) append_dot_list("node [shape = box, color = black, fontsize = 12];") for(i in loop_start:loop_end){ zero_objectid_count() if(!hobj[[i]]$node_children_left_NA){ ln <- hobj[[i]]$node_children_left } if(!hobj[[i]]$node_children_right_NA){ rn <- hobj[[i]]$node_children_right } if(hobj[[i]]$node_using_householder){ label_1 <- label_1z } else { label_1 <- label_1X } label_1_o <- sprintf(label_1, hobj[[i]]$node_objectid, hobj[[i]]$node_objectid, hobj[[i]]$node_feature_index, round(hobj[[i]]$node_threshold, 4), round(hobj[[i]]$node_gini, 4), hobj[[i]]$node_tot_samples, hobj[[i]]$node_num_samples_per_class) append_dot_list(label_1_o) if(!hobj[[i]]$node_children_left_NA){ dispnode(ln, level, objectid) } if(!hobj[[i]]$node_children_right_NA){ dispnode(rn, level, objectid) } append_dot_list("}") file_name <- tempfile(fileext = ".gv") out <- file(file_name, 'w') lapply(get_dot_list(), write, out, append = TRUE) if(!is.na(numtree)){ tryCatch((grViz(diagram = file_name)), error = function(c) { c$message <- paste0(c$message, " (in ", file_name, ")") unlink(file_name) stop(c) }) unlink(file_name) } close(out) } } dispnode <- function(nn, level, pid){ ln <- NA rn <- NA label_1X <- "%s [label = \"Node %s\\nX[%s] <= %s\\ngini index = %s\\nsamples = %s\\nvalue = %s\"];" label_1z <- "%s [label = \"Node %s\\nz[%s] <= %s\\ngini index = %s\\nsamples = %s\\nvalue = %s\"];" label_2 <- "%s [label=\"Node %s\\ngini index = %s\\nsamples = %s\\nvalue = %s\"] ;" label_3 <- "%s -> %s ;" increment_objectid_count() nn$node_objectid <- get_objectid_count() nn$node_parentid <- pid if(nn$node_children_left_NA & nn$node_children_right_NA){ label_2_o <- sprintf(label_2, nn$node_objectid, nn$node_objectid, round(nn$node_gini, 4), nn$node_tot_samples, nn$node_num_samples_per_class) append_dot_list(label_2_o) } else { if(nn$node_using_householder){ label_1 <- label_1z } else { label_1 <- label_1X } label_1_o <- sprintf(label_1, nn$node_objectid, nn$node_objectid, nn$node_feature_index, round(nn$node_threshold, 4), round(nn$node_gini, 4), nn$node_tot_samples, nn$node_num_samples_per_class) append_dot_list(label_1_o) } label_3_o <- sprintf(label_3, nn$node_parentid, nn$node_objectid) append_dot_list(label_3_o) level <- level + 1 if(!nn$node_children_left_NA){ ln <- nn$node_children_left dispnode(ln, level, nn$node_objectid) } else { return() } if(!nn$node_children_right_NA){ rn <- nn$node_children_right dispnode(rn, level, nn$node_objectid) } else { return() } return() } displayTree <- function(ntree = 1, rpart_ = NA){ if(is.na(rpart_)){ allres <- pkg.env$folds_trees } else { allres <- rpart_ ntree <- 1 } if(length(allres) == 0){ stop("hhcartr(displayTree) no trees found. Run fit() or rpartTree() first.") } packages <- c("DiagrammeR") check_package(packages) dataset_description <- pkg.env$model_data_description navigate_hash(allres, ntree, dataset_description) return(grViz(unlist(get_dot_list()))) }
setPriors.HmscRandomLevel = function(rL, nu=NULL, a1=NULL, a2=NULL, b1=NULL, b2=NULL, alphapw=NULL, nfMax=NULL, nfMin=NULL, setDefault=FALSE, ...) { stopifnot(inherits(rL, "HmscRandomLevel")) xDim = max(rL$xDim, 1) if(!is.null(nu)){ if(length(nu) == 1){ rL$nu = rep(nu, xDim) } else{ if(length(nu) == xDim){ rL$nu = nu } else stop("length of nu argument must be either 1 or rL$xDim") } } else if(setDefault){ rL$nu = rep(3, xDim) } if(!is.null(a1)){ if(length(a1) == 1){ rL$a1 = rep(a1, xDim) } else{ if(length(a1) == xDim){ rL$a1 = a1 } else stop("length of a1 argument must be either 1 or rL$xDim") } } else if(setDefault){ rL$a1 = rep(50, xDim) } if(!is.null(b1)){ if(length(b1) == 1){ rL$b1 = rep(b1, xDim) } else{ if(length(b1) == xDim){ rL$b1 = b1 } else stop("length of b1 argument must be either 1 or rL$xDim") } } else if(setDefault){ rL$b1 = rep(1, xDim) } if(!is.null(a2)){ if(length(a2) == 1){ rL$a2 = rep(a2, xDim) } else{ if(length(a2) == xDim){ rL$a2 = a2 } else stop("length of a2 argument must be either 1 or rL$xDim") } } else if(setDefault){ rL$a2 = rep(50, xDim) } if(!is.null(b2)){ if(length(b2) == 1){ rL$b2 = rep(b2, xDim) } else{ if(length(b2) == xDim){ rL$b2 = b2 } else stop("length of b2 argument must be either 1 or rL$xDim") } } else if(setDefault){ rL$b2 = rep(1, xDim) } if(!is.null(alphapw)){ if(rL$sDim == 0) stop("prior for spatial scale was given, but not spatial coordinates were specified") if(ncol(alphapw)!=2) stop("alphapw must be a matrix with two columns") rL$alphapw = alphapw } else if(setDefault && rL$sDim>0){ alphaN = 100 if(is.null(rL$distMat)){ if (is(rL$s, "Spatial")) { enclosingRect <- as.data.frame(t(bbox(rL$s))) coordinates(enclosingRect) <- colnames(enclosingRect) proj4string(enclosingRect) <- proj4string(rL$s) enclosingRectDiag <- max(spDists(enclosingRect)) } else { enclosingRectDiag = sqrt(sum(apply(rL$s, 2, function(c) diff(range(c)))^2)) } } else { enclosingRectDiag = max(rL$distMat) } rL$alphapw = cbind(enclosingRectDiag*c(0:alphaN)/alphaN, c(0.5,rep(0.5/alphaN,alphaN))) } if(!is.null(nfMax)){ rL$nfMax = nfMax } else if(setDefault){ rL$nfMax = Inf } if(!is.null(nfMin)){ if(nfMin > nfMax) stop("nfMin must be not greater than nfMax") rL$nfMin = nfMin } else if(setDefault){ rL$nfMin = 2 } return(rL) }
formatPsi <- function(psi.values = NULL, to = "dataframe"){ to.dataframe.options <- c("dataframe", "Dataframe", "DATAFRAME", "data.frame", "Data.frame", "DATA.FRAME", "df") to.matrix.options <- c("matrix", "Matrix", "MATRIX", "m", "M") to.list.options <- c("list", "List", "LIST", "l", "L") if(inherits(psi.values, "list") == TRUE){ if(to %in% to.list.options){ warning("The input is a list, and your desired output is a list. I did nothing.") return(psi.values) } if(to %in% to.dataframe.options){ psi.dataframe <- .psiToDataframe(psi.values = psi.values) return(psi.dataframe) } if(to %in% to.matrix.options){ psi.dataframe <- .psiToDataframe(psi.values = psi.values) row.col.names <- unique(c(psi.dataframe$A, psi.dataframe$B)) psi.matrix <- matrix(NA, nrow=length(row.col.names), ncol=length(row.col.names)) colnames(psi.matrix) <- rownames(psi.matrix) <- row.col.names for(i in 1:nrow(psi.dataframe)){ A <- psi.dataframe[i, "A"] B <- psi.dataframe[i, "B"] psi.matrix[A, B] <- psi.matrix[B, A] <- psi.dataframe[i, "psi"] } psi.matrix[is.na(psi.matrix)] <- 0 return(psi.matrix) } } if(inherits(psi.values, "matrix") == TRUE){ if(to %in% to.matrix.options){ warning("The input is a maatrix, and your desired output is a matrix I did nothing.") return(psi.values) } if(to %in% to.dataframe.options){ psi.values.dist <- stats::as.dist(psi.values) dimensions <- attr(psi.values.dist, "Size") sequence.names <- if (is.null(attr(psi.values.dist, "Labels"))) sequence(dimensions) else attr(psi.values.dist, "Labels") psi.dataframe <- data.frame( A = rep(sequence.names[-length(sequence.names)], (length(sequence.names)-1):1), B = sequence.names[unlist(lapply(sequence(dimensions)[-1], function(x) x:dimensions))], psi = as.vector(psi.values.dist), stringsAsFactors = FALSE) return(psi.dataframe) } } if(inherits(psi.values, "data.frame") == TRUE){ if(to %in% to.dataframe.options){ warning("The input is a dataframe, and your desired output is a dataframe I did nothing.") return(psi.values) } row.col.names <- unique(c(psi.values$A, psi.values$B)) psi.matrix <- matrix(NA, nrow=length(row.col.names), ncol=length(row.col.names)) colnames(psi.matrix) <- rownames(psi.matrix) <- row.col.names for(i in 1:nrow(psi.values)){ A <- psi.values[i, "A"] B <- psi.values[i, "B"] psi.matrix[A, B] <- psi.matrix[B, A] <- psi.values[i, "psi"] } psi.matrix[is.na(psi.matrix)] <- 0 return(psi.matrix) } } .psiToDataframe <- function(psi.values = NULL){ if(inherits(psi.values, "list") == TRUE){ n.elements <- length(psi.values) } else { temp <- list() temp[[1]] <- psi.values psi.values <- temp names(psi.values) <- "A|B" n.elements <- 1 } nas <- rep(NA, n.elements) psi.dataframe <- data.frame(A = nas, B = nas, psi = nas, stringsAsFactors = FALSE) for(i in 1:n.elements){ psi.dataframe[i, "psi"] <- psi.values[[i]] psi.dataframe[i, c("A", "B")] <- unlist(strsplit(names(psi.values)[i], split='|', fixed=TRUE)) } return(psi.dataframe) }
stat = gene_stat (exp = example_data, r = 0.7) head(stat)
Officials.getByLevenshtein <- function (lastName) { Officials.getByLevenshtein.basic <- function (.lastName) { request <- "Officials.getByLevenshtein?" inputs <- paste("&lastName=",.lastName,sep="") output <- pvsRequest4(request,inputs) output$lastName.input <- .lastName output } output.list <- lapply(lastName, FUN= function (y) { Officials.getByLevenshtein.basic(.lastName=y) } ) output.list <- redlist(output.list) output <- dfList(output.list) output }
print.design <- function(x,show.order=NULL, group.print=TRUE, std.order=FALSE, ...){ if (!"design" %in% class(x)) stop("this function works for class design objects only") else{ if (is.null(design.info(x))) print.data.frame(x, ...) else{ di <- design.info(x) if (std.order) { print(cbind(run.order(x)[,c(1,2)],x)[ord(run.order(x)),]) cat("NOTE: columns run.no.in.std.order and run.no", " are annotation,", " not part of the data frame", fill=TRUE) if (length(grep("param",di$type))>0 & length(grep("wide",di$type))>0 ){ cat("Outer array:\n") print(di$outer, ...) } return(invisible()) } if (group.print) group.print <- di$type %in% c("full factorial.blocked", "FrF2.blocked", "FrF2.blockedcenter", "FrF2.splitplot", "FrF2.splitplot.folded", "Dopt.blocked", "Dopt.splitplot", "oa.blocked", "pb.blocked") if (is.null(show.order)) show.order <- group.print | di$replications > 1 | di$type=="crossed" | length(grep("param",di$type)) > 0 if (show.order){ if (!group.print) print(cbind(run.order(x)[,2:3],x), ...) else{ if (di$type %in% c("full factorial.blocked", "FrF2.blocked", "FrF2.blockedcenter", "Dopt.blocked", "oa.blocked", "pb.blocked")) printBy(cbind(run.order(x)[,2:3],x), di$block.name,...) if (di$type %in% c("FrF2.splitplot", "FrF2.splitplot.folded","Dopt.splitplot")) printBy(cbind(run.order(x)[,2:3],x), names(di$factor.names)[1:di$nfac.WP], ...) } } else { if (!group.print) print(cbind(x), ...) else { if (di$type %in% c("full factorial.blocked", "FrF2.blocked", "FrF2.blockedcenter", "Dopt.blocked")) printBy(cbind(x), di$block.name,...) if (di$type %in% c("FrF2.splitplot", "FrF2.splitplot.folded","Dopt.splitlot")) printBy(cbind(x), names(di$factor.names)[1:di$nfac.WP], ...) }} cat("class=design, type=", di$type,"\n") if (show.order) cat("NOTE: columns run.no and run.no.std.rp", " are annotation,", " not part of the data frame",fill=TRUE) if (length(grep("param",di$type))>0 & length(grep("wide",di$type))>0 ){ cat("Outer array:\n") print(di$outer, ...) } } } } printBy <- function(data, byvars, ...){ zaehl <- 0 zeil <- 0 while (zeil < nrow(data)){ zaehl <- zaehl + 1 current <- data[zeil + 1, byvars] curz <- zaehl aus <- data[-(1:nrow(data)),] while (zaehl == curz & zeil < nrow(data)){ zeil <- zeil + 1 if (all(data[zeil,byvars] == current)) aus <- rbind(aus, data[zeil,]) else { print(aus, ...) zaehl <- zaehl + 1 zeil <- zeil - 1 } if (zeil == nrow(data)) print(aus, ...) } } } summary.design <- function(object, brief = NULL, quote=FALSE, ...){ di <- design.info(object) if (is.null(di)) return(summary.data.frame(object=object, quote=quote, ...)) if (is.null(brief)) if (nrow(object) <= 40 & ncol(object)<=12) brief <- FALSE else brief <- TRUE if (is.language(di$creator)){ cat("Call:\n") print(di$creator, quote=quote, ...) cat("\n") } else {if (length(class(di$creator))>1) cat("design was generated with RcmdrPlugin.DoE\n\n") else { cat("Multi-step-call:\n") print(di$creator, quote=quote, ...) cat("\n")} } cat("Experimental design of type ", di$type,"\n") cat(di$nruns, " runs\n") blocks <- di$nblocks if (is.null(blocks)) blocks <- 1 if (blocks > 1){ if (length(grep("ccd",di$type))>0) cat("blocked design with ", blocks, " cube blocks", "and one star block\n", fill=TRUE) else cat("blocked design with ", blocks, " blocks") if (!all(di$blocksize==di$blocksize[1])){ cat("\nVarying block sizes: \n") print(di$blocksize)} else cat(" of size ", di$blocksize, "\n") if (!length(grep("Dopt",di$type))>0){ if (di$bbreps>1) cat("each type of block independently conducted ", di$bbreps, " times\n") if (di$wbreps > 1 & !di$repeat.only) cat("each run within each block independently conducted ", di$wbreps, " times\n") if (di$wbreps > 1 & di$repeat.only) cat("each run measured ", di$wbreps, " times (no proper replication)\n") } if (di$type=="full factorial.blocked"){ hilf <- factorize(di$nlevels) names(hilf) <- Letters[1:di$nfactors] hilf <- unlist(hilf) if (is.null(colnames(di$block.gen))) colnames(di$block.gen) <- names(hilf) hilf.primes <- apply(di$block.gen, 1, function(obj) unique(hilf[!obj==0])) for (p in unique(hilf.primes)){ chilf <- conf.set(di$block.gen[which(hilf.primes==p),,drop=FALSE], p) cat("\nConfounding of ", p, "-level pseudo-factors with blocks", "\n(each row gives one independent confounded effect):\n") print(chilf) cat("\n") } } } else if (di$replications>1) if (di$repeat.only) cat(di$replications, " measurements per run (not proper replications)\n") else cat("each run independently conducted ", di$replications, " times\n") cat("\n") pfn <- di$factor.names lfn <- max(sapply(pfn, "length")) pfn <- lapply(pfn, function(obj) if (length(obj)==lfn) obj else c(obj,rep("",lfn-length(obj)))) pfn <- as.data.frame(pfn) if (all(di$quantitative)){ if (!"ccd" %in% di$type) cat("Factor settings (scale ends):\n") else cat("Factor settings (cube):\n") } else cat("Factor settings:\n") print(pfn, quote=quote, ...) if ("ccd" %in% di$type){ cat("\nNumbers of cube and star points: \n") print(c(Cube=di$ncube, Star=di$nstar)) cat("Numbers of center points: \n") print(c(Cube=di$ncenter[1], Star=di$ncenter[2])) } if (length(grep("Dopt",di$type))>0 | length(grep("lhs",di$type))>0) if (!is.null(di$optimality.criteria)){ cat("\nOptimality criteria:\n ") print(unlist(di$optimality.criteria)) } if (!is.null(response.names(object))){ cat("\nResponses:\n") if (is.null(di$responselist)) print(response.names(object), quote=quote, ...) else print(di$responselist, quote=quote, ...) } if (length(grep("param",design.info(object)$type))>0 & length(grep("wide",design.info(object)$type))>0 ){ cat("\nOuter array:\n") print(design.info(object)$outer, quote=quote, ...) } if (substr(di$type,1,4)=="FrF2"){ cat("\nDesign generating information:\n") print(list(legend=di$aliased$legend), quote=quote, ...) neuver <- FALSE if (!is.null(di$FrF2.version) & length(di$FrF2.version)==1) if (compareVersion(di$FrF2.version, "1.1") >= 0) neuver <- TRUE if ((neuver || !(length(grep("blocked",di$type)) > 0 || length(grep("splitplot",di$type)) > 0)) && !(length(grep("param",di$type)) > 0 || length(grep("folded", di$type))>0) ) print(generators(object), quote=quote, ...) if (length(di$aliased) == 1) cat("\nno aliasing of main effects or 2fis", " among experimental factors\n", fill=TRUE) else{ if (all(sapply(di$aliased[-1], "length")==0)) cat("\nno aliasing of main effects or 2fis", " among experimental factors\n", fill=TRUE) else{ if (all(sapply(di$aliased, "length") >= 1) && length(di$aliased) > 1){ cat("\nAlias structure:\n") print(di$aliased[-1], quote=quote, ...)} else { cat("\nAlias structure:\n") if (length(di$aliased$main) > 0) print(di$aliased[2], quote=quote, ...) if (length(di$aliased$fi2) > 0) print(di$aliased[3], quote=quote, ...) if (length(di$aliased$fi3) > 0) print(di$aliased[4], quote=quote, ...) } } } if (di$type=="FrF2.blocked"){ if (length(di$aliased.with.blocks) > 0){ cat("Aliased with block main effects:\n") print(di$aliased.with.blocks, quote=quote, ...) } else cat("no main effects or 2fis aliased with blocks\n") } } if (substr(di$type,1,4)=="oa"){ cat("Generating Orthogonal Array:\n") print(di$generating.oa, quote=quote, ...) cat("Selected Columns:\n") print(di$selected.columns,...) if (di$nfactors <= 15){ cat("Numbers of generalized words of lengths 3 and 4:\n") print(c("3"=length3(object),"4"=length4(object)))} else if (di$nfactors <= 30) cat("Number of generalized words of length 3: ", length3(object),"\n", fill=TRUE) } nWPs <- di$nWPs if (is.null(nWPs) | length(nWPs)==0) nWPs <- 1 if (nWPs > 1){ cat("\nsplit-plot design: ", nWPs, " whole plots\n") cat(" first ", di$nfac.WP, " factors are whole plot factors\n") } if (!brief){ cat("\nThe design itself:\n") print(object, quote=quote, ...) } }
setGeneric("replace_errors", function( data , x , ref=NULL, ... , cl = NULL , Ncpus = getOption("Ncpus", 1) , value = c("NA", "suggestion")){ standardGeneric("replace_errors") }) setMethod('replace_errors', c("data.frame", "validator") , function(data, x, ref=NULL, ..., cl = NULL , Ncpus = getOption("Ncpus", 1) , value = c("NA", "suggestion")){ fh <- fh_localizer(x) replace_errors(data, fh, ref, ..., cl = cl, Ncpus = Ncpus) }) setMethod('replace_errors', c("data.frame", "ErrorLocalizer") , function(data, x , ref = NULL , ... , cl = NULL , Ncpus = getOption("Ncpus", 1) , value = c("NA", "suggestion")){ el <- locate_errors(data, x, ref, ..., cl = cl) replace_errors(data, el, ref, ..., cl = cl, Ncpus = Ncpus) }) setMethod('replace_errors', c("data.frame", "errorlocation") , function( data, x , ref = NULL, ... , cl = NULL , Ncpus = 1 , value = c("NA", "suggestion")){ value <- switch ( match.arg(value), "NA" = is.na(data) <- values(x, na_as_error = TRUE) ) attr(data,"errorlocation") <- x data })
TD_power <- function(case, mean = 0, sd = 1, sample_size = NULL, power = NULL, alternative = c("less", "greater", "two.sided"), alpha = 0.05, spec = 0.005) { if (!is.null(sample_size) & !is.null(power)) stop("Must supply only one of sample size or desired power") if (is.null(sample_size) & is.null(power)) stop("Must supply either sample size or desired power") if (!is.null(power)) if (power > 1 | power < 0) stop("Desired power must be between 0 and 1") if (!is.null(sample_size)) if (sample_size < 2) stop("Sample size must be greater than 1") if (alpha < 0 | alpha > 1) stop("Type I error rate must be between 0 and 1") alternative <- match.arg(alternative) n = sample_size if (is.null(power)) { if (alternative == "two.sided") { power = stats::pt(stats::qt(alpha/2, df = n-1, lower.tail = T), ncp = ((case - mean)/(sd*sqrt((n+1)/n))), df = n-1, lower.tail = T) - stats::pt(-stats::qt(alpha/2, df = n-1, lower.tail = T), ncp = ((case - mean)/(sd*sqrt((n+1)/n))), df = n-1, lower.tail = T) + 1 return(power) } if (alternative == "less") { power = stats::pt(stats::qt(alpha, df = n-1, lower.tail = T), ncp = ((case - mean)/(sd*sqrt((n+1)/n))), df = n-1, lower.tail = T ) return(power) } if (alternative == "greater") { power = stats::pt(stats::qt(alpha, df = n-1, lower.tail = F), ncp = ((case - mean)/(sd*sqrt((n+1)/n))), df = n-1, lower.tail = F ) return(power) } } if (is.null(sample_size)) { n = 2 search_pwr = 0 prev_search_pwr = 1 keep_going = TRUE while(keep_going == TRUE){ if (alternative == "two.sided") { search_pwr = stats::pt(stats::qt(alpha/2, df = n-1, lower.tail = T), ncp = ((case - mean)/(sd*sqrt((n+1)/n))), df = n-1, lower.tail = T) - stats::pt(-stats::qt(alpha/2, df = n-1, lower.tail = T), ncp = ((case - mean)/(sd*sqrt((n+1)/n))), df = n-1, lower.tail = T) + 1 } if (alternative == "less") { search_pwr = stats::pt(stats::qt(alpha, df = n-1, lower.tail = T), ncp = ((case - mean)/(sd*sqrt((n+1)/n))), df = n-1, lower.tail = T ) } if (alternative == "greater") { search_pwr = stats::pt(stats::qt(alpha, df = n-1, lower.tail = F), ncp = ((case - mean)/(sd*sqrt((n+1)/n))), df = n-1, lower.tail = F ) } if (abs(prev_search_pwr - search_pwr) < spec) { keep_going = FALSE message(paste0("Power (", format(round(search_pwr, 3), nsmall = 3), ") will not increase more than ", spec*100, "%", " per participant for n > ", n)) } prev_search_pwr = search_pwr n = n + 1 if (search_pwr > power) keep_going = FALSE } return(data.frame(n = n - 1, power = search_pwr)) } } BTD_power <- function(case, mean = 0, sd = 1, sample_size, alternative = c("less", "greater", "two.sided"), alpha = 0.05, nsim = 1000, iter = 1000) { if (sample_size < 2) stop("Sample size must be greater than 1") if (alpha < 0 | alpha > 1) stop("Type I error rate must be between 0 and 1") alternative <- match.arg(alternative) n = sample_size BTD_p_sim <- function() { con <- stats::rnorm(n, mean = mean, sd = sd) case <- stats::rnorm(1, mean = mean, sd = sd) + (case - mean) pval <- singcar::BTD(case, con, iter = iter, alternative = alternative)[["p.value"]] pval } pval <- vector(length = nsim) for(i in 1:nsim) { pval[i] <- BTD_p_sim() } power = sum(pval < alpha)/length(pval) return(power) } BTD_cov_power <- function(case, case_cov, control_task = c(0, 1), control_covar = c(0, 1), cor_mat = diag(2) + 0.3 - diag(c(0.3, 0.3)), sample_size, alternative = c("less", "greater", "two.sided"), alpha = 0.05, nsim = 1000, iter = 1000) { if (alpha < 0 | alpha > 1) stop("Type I error rate must be between 0 and 1") if (sum(eigen(cor_mat)$values > 0) < length(diag(cor_mat))) stop("cor_mat is not positive definite") if (sample_size < 2) stop("Sample size must be greater than 1") alternative <- match.arg(alternative) n = sample_size sum_stats <- rbind(control_task, control_covar) if (length(sum_stats[ , 2]) != nrow(cor_mat)) stop("Number of variables and number of correlations do not match") Sigma <- diag(sum_stats[ , 2]) %*% cor_mat %*% diag(sum_stats[ , 2]) mu <- sum_stats[ , 1] BTD_cov_p_sim <- function() { con <- MASS::mvrnorm(n+1, mu = mu, Sigma = Sigma) case_scores <- c(case, case_cov) case_score_emp <- vector(length = length(case_scores)) for (i in 1:length(case_scores)) { case_score_emp[i] <- con[1, i] + (case_scores[i] - mu[i]) } con <- con [-1, ] pval <- singcar::BTD_cov(case_task = case_score_emp[1], case_covar = case_score_emp[-1], control_task = con[ , 1], control_covar = con[ , -1], iter = iter, alternative = alternative)[["p.value"]] pval } pval <- vector(length = nsim) for(i in 1:nsim) { pval[i] <- BTD_cov_p_sim() } power = sum(pval < alpha)/length(pval) return(power) }
dct1d <- function(dat){ n <- length(dat); weight <- c(1,2*exp(-1i*(1:(n-1))*pi/(2*n))); dat <- c(dat[seq(1,n-1,2)], dat[seq(n,2,-2)]); out <- Re(weight*stats::fft(dat)); return(out) } fixedpoint <- function(tt,N,II,a2){ l <- 7 f <- 2*(pi^(2*l))*sum((II^l)*a2*exp(-II*(pi^2)*tt)) for (s in (l-1):2){ K0 <- prod(seq(1,2*s-1,2))/sqrt(2*pi) const <- (1+(1/2)^(s+1/2))/3 TT <- (2*const*K0/N/f)^(2/(3+2*s)) f <- 2*pi^(2*s)*sum(II^s*a2*exp(-II*pi^2*TT)) } out <- tt-(2*N*sqrt(pi)*f)^(-2/5) return(out) } botev <- function(x){ n <- 512 minimum <- min(x) maximum <- max(x) Range <- maximum - minimum MIN <- minimum-Range/10 MAX <- maximum+Range/10 R <- MAX-MIN dx <- R/n xmesh <- MIN+seq(0,R,dx) if (anyDuplicated(x)){ N <- length(as.numeric(names(table(x)))) } else { N <- length(x) } w <- graphics::hist(x,xmesh,plot=FALSE) initialdata <- (w$counts)/N initialdata <- initialdata/sum(initialdata) a <- dct1d(initialdata) II <- (1:(n-1))^2 a2 <- (a[2:n]/2)^2 tstar <- tryCatch(stats::uniroot(fixedpoint,c(0,.1), N=N,II=II,a2=a2,tol=10^(-14))$root, error=function(e).28*N^(-2/5)) bandwidth <- sqrt(tstar)*R return(bandwidth) } commonbandwidth <- function(x){ dnames <- names(x$x) n <- length(dnames) bw <- rep(0,n) for (i in 1:n){ bw[i] <- botev(x$x[[i]]) } return(stats::median(bw)) }
read_ipums_micro_yield <- function( ddi, vars = NULL, data_file = NULL, verbose = TRUE, var_attrs = c("val_labels", "var_label", "var_desc"), lower_vars = FALSE ) { vars <- enquo(vars) if (!is.null(var_attrs)) var_attrs <- match.arg(var_attrs, several.ok = TRUE) IpumsLongYield$new( ddi = ddi, vars = !!vars, data_file = data_file, verbose = verbose, var_attrs = var_attrs, lower_vars = lower_vars ) } read_ipums_micro_list_yield <- function( ddi, vars = NULL, data_file = NULL, verbose = TRUE, var_attrs = c("val_labels", "var_label", "var_desc"), lower_vars = FALSE ) { vars <- enquo(vars) if (!is.null(var_attrs)) var_attrs <- match.arg(var_attrs, several.ok = TRUE) IpumsListYield$new( ddi = ddi, vars = !!vars, data_file = data_file, verbose = verbose, var_attrs = var_attrs, lower_vars = lower_vars ) } IpumsLongYield <- R6::R6Class( "IpumsLongYield", inherit = hipread::HipLongYield, cloneable = FALSE, private = list(ddi = NULL, var_attrs = NULL), public = list( initialize = function( ddi, vars = NULL, data_file = NULL, verbose = TRUE, var_attrs = c("val_labels", "var_label", "var_desc"), lower_vars = FALSE ) { lower_vars_was_ignored <- check_if_lower_vars_ignored(ddi, lower_vars) if (lower_vars_was_ignored) { warning(lower_vars_ignored_warning()) } if (is.character(ddi)) ddi <- read_ipums_ddi(ddi, lower_vars = lower_vars) if (is.null(data_file)) data_file <- file.path(ddi$file_path, ddi$file_name) if (fostr_detect(data_file, "\\.csv$|\\.csv\\.gz$")) { stop( "read_ipums_micro_yield does not support reading from .csv ", "formatted data files, only from .dat (or .dat.gz) files" ) } data_file <- custom_check_file_exists(data_file, c(".dat.gz", ".csv", ".csv.gz")) if (verbose) custom_cat(short_conditions_text(ddi)) vars <- enquo(vars) if (!is.null(var_attrs)) var_attrs <- match.arg(var_attrs, several.ok = TRUE) ddi <- ddi_filter_vars(ddi, vars, "long", verbose) rt_info <- ddi_to_rtinfo(ddi) col_spec <- ddi_to_colspec(ddi, "long", verbose) super$initialize( file = data_file, var_info = col_spec, rt_info = rt_info, encoding = ddi$encoding ) private$ddi <- ddi private$var_attrs <- var_attrs }, yield = function(n = 10000) { out <- super$yield(n = n) if (is.null(out)) return(out) out <- set_ipums_var_attributes(out, private$ddi, private$var_attrs) out } ) ) IpumsListYield <- R6::R6Class( "IpumsListYield", inherit = hipread::HipListYield, cloneable = FALSE, private = list(ddi = NULL, var_attrs = NULL, rt_ddi = NULL), public = list( initialize = function( ddi, vars = NULL, data_file = NULL, verbose = TRUE, var_attrs = c("val_labels", "var_label", "var_desc"), lower_vars = FALSE ) { lower_vars_was_ignored <- check_if_lower_vars_ignored(ddi, lower_vars) if (lower_vars_was_ignored) { warning(lower_vars_ignored_warning()) } if (is.character(ddi)) ddi <- read_ipums_ddi(ddi, lower_vars = lower_vars) if (is.null(data_file)) data_file <- file.path(ddi$file_path, ddi$file_name) if (fostr_detect(data_file, "\\.csv$|\\.csv\\.gz$")) { stop( "read_ipums_micro_yield does not support reading from .csv ", "formatted data files, only from .dat (or .dat.gz) files" ) } data_file <- custom_check_file_exists(data_file, c(".dat.gz", ".csv", ".csv.gz")) if (verbose) custom_cat(short_conditions_text(ddi)) vars <- enquo(vars) if (!is.null(var_attrs)) var_attrs <- match.arg(var_attrs, several.ok = TRUE) rt_ddi <- get_rt_ddi(ddi) ddi <- ddi_filter_vars(ddi, vars, "list", verbose) rt_info <- ddi_to_rtinfo(ddi) col_spec <- ddi_to_colspec(ddi, "list", verbose) super$initialize( file = data_file, var_info = col_spec, rt_info = rt_info, encoding = ddi$encoding ) private$ddi <- ddi private$var_attrs <- var_attrs private$rt_ddi <- rt_ddi }, yield = function(n = 10000) { out <- super$yield(n = n) if (is.null(out)) return(out) names(out) <- rectype_label_names(names(out), private$rt_ddi) for (rt in names(out)) { out[[rt]] <- set_ipums_var_attributes(out[[rt]], private$ddi, private$var_attrs) } out } ) )
NULL plot.FigureOfMerit <- function(x, y, ..., from, to, col=RColorBrewer::brewer.pal(8, "Set2"), type="b", key, scales, xlab, ylab) { if (!missing(from) && missing(to)) fom <- "category" if (!missing(from)) { from.ix <- which(x@categories %in% from) if (length(from.ix) > 1) { stop("'from' must be a single land use category") } else if (length(from.ix) == 0) { stop("'from' is not a valid land use category") } } else { fom <- "overall" } if (!missing(from) && !missing(to)) { to.ix <- which(x@categories %in% to) if (length(to.ix) == 0) { stop("'to' is not a valid land use category") } if (length(to.ix) == 1 && from.ix == to.ix) stop("'from' cannot equal 'to'") fom <- "transition" } if (fom == "transition") { if (length(to.ix) > 1) { data.list <- list() var.list <- list() for (i in 1:length(to.ix)) { figureofmerit <- sapply(x@transition, function(x) x[from.ix, to.ix[i]]) if (!all(is.na(figureofmerit))) { var <- paste0("transition ", x@labels[from.ix], " -> ", x@labels[to.ix[i]]) var.list[[(length(var.list) + 1)]] <- var data.list[[(length(data.list) + 1)]] <- data.frame(x=1:length(x@factors), var=var, y=figureofmerit) } } data <- do.call(rbind, data.list) } else { var <- paste0("transition ", x@labels[from.ix], " -> ", x@labels[to.ix]) figureofmerit <- sapply(x@transition, function(x) x[from.ix, to.ix]) data <- data.frame(x=1:length(x@factors), var=var, y=figureofmerit) } } else if (fom == "category") { var <- paste0("transitions from ", x@labels[from.ix]) figureofmerit <- sapply(x@category, function(x) x[from.ix]) data <- data.frame(x=1:length(x@factors), var=var, y=figureofmerit) } else if (fom == "overall") { figureofmerit <- sapply(x@overall, function(x) x) var <- paste0("overall") data <- data.frame(x=1:length(x@factors), var=var, y=figureofmerit) } if (type == "transition" && length(to.ix) > 1) { default.key <- list(space="bottom", lines=list(type=type, pch=1, col=col[1:length(data.list)], size=5), text=list(sapply(var.list, function(x) x)), divide=1) } else { default.key <- list(space="bottom", lines=list(type=type, pch=1, col=col[1], size=5), text=list(var), divide=1) } if (missing(key)) { key <- default.key } else if (!is.null(key)) { matching.args <- names(default.key)[names(default.key) %in% names(key)] key <- c(key, default.key[!names(default.key) %in% names(key)]) for (arg in matching.args) { key[[arg]] <- c(key[[arg]], default.key[[arg]][!names(default.key[[arg]]) %in% names(key[[arg]])]) } } default.scales <- list(x=list(at=1:length(x@factors), labels=x@factors)) if (missing(scales)) { scales <- default.scales } else { matching.args <- names(default.scales)[names(default.scales) %in% names(scales)] scales <- c(scales, default.scales[!names(default.scales) %in% names(scales)]) for (arg in matching.args) { scales[[arg]] <- c(scales[[arg]], default.scales[[arg]][!names(default.scales[[arg]]) %in% names(scales[[arg]])]) } } default.xlab <- list(label="Resolution (multiple of native pixel size)") if (missing(xlab)) { xlab <- default.xlab } else { matching.args <- names(default.xlab)[names(default.xlab) %in% names(xlab)] xlab <- c(xlab, default.xlab[!names(default.xlab) %in% names(xlab)]) for (arg in matching.args) { xlab[[arg]] <- c(xlab[[arg]], default.xlab[[arg]][!names(default.xlab[[arg]]) %in% names(xlab[[arg]])]) } } default.ylab <- list(label="Figure of merit") if (missing(ylab)) { ylab <- default.ylab } else { matching.args <- names(default.ylab)[names(default.ylab) %in% names(ylab)] ylab <- c(ylab, default.ylab[!names(default.ylab) %in% names(ylab)]) for (arg in matching.args) { ylab[[arg]] <- c(ylab[[arg]], default.ylab[[arg]][!names(default.ylab[[arg]]) %in% names(ylab[[arg]])]) } } p <- lattice::xyplot(y~x, data=data, groups=var, key=key, line.col=col, panel=function(x,y,line.col,...) { lattice::panel.xyplot(x,y,type=type,col=line.col,...) }, xlab=xlab, ylab=ylab, scales=scales, ...) p } setMethod("plot", "FigureOfMerit", plot.FigureOfMerit)
fitCumChoose=function(nit,order){ ou=0 if(order==0) return(0) for(i in 1:order){ ou=ou+choose(nit,i) } return(ou) }
smooth_cifti <- function( x, cifti_target_fname=NULL, surf_FWHM=5, vol_FWHM=3, surfL_fname=NULL, surfR_fname=NULL, cerebellum_fname=NULL, subcortical_zeroes_as_NA=FALSE, cortical_zeroes_as_NA=FALSE, subcortical_merged=FALSE){ input_is_xifti <- is.xifti(x, messages=FALSE) surfL_return <- surfR_return <- FALSE if (input_is_xifti) { x_intent <- x$meta$cifti$intent if (!is.null(x_intent) && (x_intent %in% supported_intents()$value)) { x_extn <- supported_intents()$extension[supported_intents()$value == x_intent] } else { warning("The CIFTI intent was unknown, so smoothing as a dscalar.") x_extn <- "dscalar.nii" } cifti_original_fname <- file.path(tempdir(), paste0("to_smooth.", x_extn)) write_cifti(x, cifti_original_fname, verbose=FALSE) if (is.null(cifti_target_fname)) { cifti_target_fname <- gsub( "to_smooth.", "smoothed.", cifti_original_fname, fixed=TRUE ) } if (is.null(surfL_fname) && !is.null(x$surf$cortex_left)) { surfL_return <- TRUE surfL_fname <- file.path(tempdir(), "left.surf.gii") write_surf_gifti(x$surf$cortex_left, surfL_fname, hemisphere="left") } if (is.null(surfR_fname) && !is.null(x$surf$cortex_right)) { surfR_return <- TRUE surfR_fname <- file.path(tempdir(), "right.surf.gii") write_surf_gifti(x$surf$cortex_right, surfR_fname, hemisphere="right") } cifti_info <- x$meta brainstructures <- vector("character") if (!is.null(x$data$cortex_left)) { brainstructures <- c(brainstructures, "left") } if (!is.null(x$data$cortex_right)) { brainstructures <- c(brainstructures, "right") } if (!is.null(x$data$subcort)) { brainstructures <- c(brainstructures, "subcortical") } } else { cifti_original_fname <- x stopifnot(file.exists(cifti_original_fname)) cifti_info <- info_cifti(cifti_original_fname) brainstructures <- cifti_info$cifti$brainstructures if (is.null(cifti_target_fname)) { cifti_target_fname <- file.path( getwd(), paste0("smoothed.", get_cifti_extn(cifti_original_fname)) ) } } fix_dlabel <- FALSE if (!is.null(cifti_info$cifti$intent) && cifti_info$cifti$intent == 3007) { warning(paste( "Smoothing a label file will convert the labels to their numeric", "indices. Coercing `cifti_target_fname` to a \".dscalar\" file.\n" )) fix_dlabel <- TRUE cifti_target_fname <- gsub( "dlabel.nii", "dscalar.nii", cifti_target_fname, fixed=TRUE ) } cmd <- paste( "-cifti-smoothing", sys_path(cifti_original_fname), surf_FWHM / (2*sqrt(2*log(2))), vol_FWHM / (2*sqrt(2*log(2))), "COLUMN", sys_path(cifti_target_fname) ) if ("left" %in% brainstructures && is.null(surfL_fname)) { ciftiTools_warn(paste( "No left surface provided to `smooth_cifti`,", "so using the surface included in `ciftiTools`." )) if (!is.xifti(x, messages=FALSE)) { x <- read_cifti(x, brainstructures=brainstructures) } if (!is.null(x$meta$cifti$resamp_res)) { x_res <- x$meta$cifti$resamp_res } else if (!is.null(x$meta$cortex$medial_wall_mask$left)) { x_res <- length(x$meta$cortex$medial_wall_mask$left) } else { if (!is.null(x$data$cortex_left) && !is.null(x$data$cortex_right)) { if (nrow(x$data$cortex_left) != nrow(x$data$cortex_right)) { stop(paste( "The cortex resolution needs to be known to resample the cortex surface", "for use in smoothing. But, there was no resampling resolution", "or left medial wall mask in the `xifti`. Furthermore, the number of", "data vertices differed between the left and right cortices, meaning", "the cortex resolution cannot be inferred in any way." )) } } warning(paste( "No resampling resolution or left medial wall mask in the `xifti`.", "Using the number of left cortex vertices. This may cause an error if", "medial wall values were masked out." )) x_res <- nrow(x$data$cortex_left) } surfL_fname <- file.path(tempdir(), "left.surf.gii") surfL_fname <- resample_gifti( ciftiTools.files()$surf["left"], surfL_fname, hemisphere="left", file_type="surface", resamp_res=x_res ) } if ("right" %in% brainstructures && is.null(surfR_fname)) { ciftiTools_warn(paste( "No right surface provided to `smooth_cifti`,", "so using the surface included in `ciftiTools`." )) if (!is.xifti(x, messages=FALSE)) { x <- read_cifti(x, brainstructures=brainstructures) } if (!is.null(x$meta$cifti$resamp_res)) { x_res <- x$meta$cifti$resamp_res } else if (!is.null(x$meta$cortex$medial_wall_mask$right)) { x_res <- length(x$meta$cortex$medial_wall_mask$right) } else { if (!is.null(x$data$cortex_right) && !is.null(x$data$cortex_right)) { if (nrow(x$data$cortex_right) != nrow(x$data$cortex_right)) { stop(paste( "The cortex resolution needs to be known to resample the cortex surface", "for use in smoothing. But, there was no resampling resolution", "or right medial wall mask in the `xifti`. Furthermore, the number of", "data vertices differed between the right and right cortices, meaning", "the cortex resolution cannot be inferred in any way." )) } } warning(paste( "No resampling resolution or right medial wall mask in the `xifti`.", "Using the number of right cortex vertices. This may cause an error if", "medial wall values were masked out." )) x_res <- nrow(x$data$cortex_right) } surfR_fname <- file.path(tempdir(), "right.surf.gii") surfR_fname <- resample_gifti( ciftiTools.files()$surf["right"], surfR_fname, hemisphere="right", file_type="surface", resamp_res=x_res ) } if (!is.null(surfL_fname)) { cmd <- paste(cmd, "-left-surface", sys_path(surfL_fname)) } if (!is.null(surfR_fname)) { cmd <- paste(cmd, "-right-surface", sys_path(surfR_fname)) } if (!is.null(cerebellum_fname)) { cmd <- paste(cmd, "-cerebellum-surface", sys_path(cerebellum_fname)) } if (subcortical_zeroes_as_NA) { cmd <- paste(cmd, "-fix-zeros-volume") } if (cortical_zeroes_as_NA) { cmd <- paste(cmd, "-fix-zeros-surface") } if (subcortical_merged) { cmd <- paste(cmd, "-merged-volume") } run_wb_cmd(cmd) if (fix_dlabel) { old_target_fname <- cifti_target_fname cifti_target_fname <- gsub("dlabel", "dscalar", old_target_fname) names_fname <- tempfile() cat(names(cifti_info$cifti$labels), file = names_fname, sep = "\n") run_wb_cmd(paste( "-cifti-change-mapping", old_target_fname, "ROW", cifti_target_fname, "-scalar", "-name-file", names_fname )) } if (input_is_xifti) { read_xifti_args <- list( cifti_fname = cifti_target_fname, brainstructures = brainstructures ) if (surfL_return) { read_xifti_args$surfL_fname <- surfL_fname } if (surfR_return) { read_xifti_args$surfR_fname <- surfR_fname } return(do.call(read_xifti, read_xifti_args)) } else { return(invisible(cifti_target_fname)) } } smoothCIfTI <- function( x, cifti_target_fname=NULL, surf_FWHM=5, vol_FWHM=5, surfL_fname=NULL, surfR_fname=NULL, cerebellum_fname=NULL, subcortical_zeroes_as_NA=FALSE, cortical_zeroes_as_NA=FALSE, subcortical_merged=FALSE){ smooth_cifti( x=x, cifti_target_fname=cifti_target_fname, surf_FWHM=surf_FWHM, vol_FWHM=vol_FWHM, surfL_fname=surfL_fname, surfR_fname=surfR_fname, cerebellum_fname=cerebellum_fname, subcortical_zeroes_as_NA=subcortical_zeroes_as_NA, cortical_zeroes_as_NA=cortical_zeroes_as_NA, subcortical_merged=subcortical_merged ) } smoothcii <- function( x, cifti_target_fname=NULL, surf_FWHM=5, vol_FWHM=5, surfL_fname=NULL, surfR_fname=NULL, cerebellum_fname=NULL, subcortical_zeroes_as_NA=FALSE, cortical_zeroes_as_NA=FALSE, subcortical_merged=FALSE){ smooth_cifti( x=x, cifti_target_fname=cifti_target_fname, surf_FWHM=surf_FWHM, vol_FWHM=vol_FWHM, surfL_fname=surfL_fname, surfR_fname=surfR_fname, cerebellum_fname=cerebellum_fname, subcortical_zeroes_as_NA=subcortical_zeroes_as_NA, cortical_zeroes_as_NA=cortical_zeroes_as_NA, subcortical_merged=subcortical_merged ) } smooth_xifti <- function( x, cifti_target_fname=NULL, surf_FWHM=5, vol_FWHM=5, surfL_fname=NULL, surfR_fname=NULL, cerebellum_fname=NULL, subcortical_zeroes_as_NA=FALSE, cortical_zeroes_as_NA=FALSE, subcortical_merged=FALSE){ smooth_cifti( x=x, cifti_target_fname=cifti_target_fname, surf_FWHM=surf_FWHM, vol_FWHM=vol_FWHM, surfL_fname=surfL_fname, surfR_fname=surfR_fname, cerebellum_fname=cerebellum_fname, subcortical_zeroes_as_NA=subcortical_zeroes_as_NA, cortical_zeroes_as_NA=cortical_zeroes_as_NA, subcortical_merged=subcortical_merged ) }
superiority <- function(.data, env, gen, resp, verbose = TRUE) { factors <- .data %>% select({{env}}, {{gen}}) %>% mutate(across(everything(), as.factor)) vars <- .data %>% select({{resp}}, -names(factors)) %>% select_numeric_cols() factors %<>% set_names("ENV", "GEN") listres <- list() nvar <- ncol(vars) if (verbose == TRUE) { pb <- progress(max = nvar, style = 4) } for (var in 1:nvar) { data <- factors %>% mutate(Y = vars[[var]]) if(has_na(data)){ data <- remove_rows_na(data) has_text_in_num(data) } environments <- data %>% means_by(ENV, na.rm = TRUE) %>% add_cols(index = Y - mean(Y), class = ifelse(index < 0, "unfavorable", "favorable")) %>% as_tibble() data <- left_join(data, environments %>% select(ENV, class), by = "ENV") lin_fun <- function(mat) { P <- apply(mat, 1, function(x) { sum((x - apply(mat, 2, max, na.rm = TRUE))^2, na.rm = TRUE)/(2 * length(na.omit(x))) }) return(P) } mat_g <- make_mat(data, row = GEN, col = ENV, value = Y) ge_mf <- subset(data, class == "favorable") mat_f <- dplyr::select_if(make_mat(ge_mf, row = GEN, col = ENV, value = Y), function(x) !any(is.na(x))) ge_mu <- subset(data, class == "unfavorable") mat_u <- dplyr::select_if(make_mat(ge_mu, row = GEN, col = ENV, value = Y), function(x) !any(is.na(x))) temp <- list(environments = environments, index = tibble(GEN = rownames(mat_g), Y = apply(mat_g, 1, mean, na.rm = TRUE), Pi_a = lin_fun(mat_g), R_a = rank(lin_fun(mat_g)), Pi_f = lin_fun(mat_f), R_f = rank(lin_fun(mat_f)), Pi_u = lin_fun(mat_u), R_u = rank(lin_fun(mat_u)))) rownames(temp) <- NULL if (verbose == TRUE) { run_progress(pb, actual = var, text = paste("Evaluating trait", names(vars[var]))) } listres[[paste(names(vars[var]))]] <- temp } return(structure(listres, class = "superiority")) } print.superiority <- function(x, export = FALSE, file.name = NULL, digits = 3, ...) { if (!class(x) == "superiority") { stop("The object must be of class 'superiority'") } if (export == TRUE) { file.name <- ifelse(is.null(file.name) == TRUE, "superiority summary", file.name) sink(paste0(file.name, ".txt")) } opar <- options(pillar.sigfig = digits) on.exit(options(opar)) for (i in 1:length(x)) { var <- x[[i]] cat("Variable", names(x)[i], "\n") cat("---------------------------------------------------------------------------\n") cat("Superiority index considering all, favorable and unfavorable environments\n") cat("---------------------------------------------------------------------------\n") print(var$index) cat("---------------------------------------------------------------------------\n") cat("\n\n\n") } if (export == TRUE) { sink() } }
in.da <- function(springs,similarity) { cdist <- function(i,j,n) { ci <- min(i,j) cj <- max(i,j) return( min( abs(cj-ci), abs(n-cj+ci) ) ) } similarity <- similarity[rownames(springs),rownames(springs)] neighbor <- matrix(0,nrow=nrow(springs),ncol=nrow(springs)) for(i in seq(1,nrow(springs)-1)) { for(j in seq(i+1,nrow(springs))) { neighbor[i,j] <- neighbor[j,i] <- 1-2*cdist(i,j,nrow(springs))/nrow(springs) } } return(-sum(neighbor*similarity)) } rv.da <- function(springs,similarity) { proj <- do.radviz(similarity,springs)$proj$data[,c('rx','ry')] proj <- proj[rownames(springs),] d <- rep(0,nrow(springs)) for(i in seq(1,nrow(springs))) { d[i] <- sqrt(sum((proj[i,]-springs[i,])^2)) } return(sum(d)) }
crps.ensembleMOSgev0 <- function(fit, ensembleData, dates=NULL, ...) { gini.md <- function(x,na.rm=FALSE) { if(na.rm & any(is.na(x))) x <- x[!is.na(x)] n <-length(x) return(4*sum((1:n)*sort(x,na.last=TRUE))/(n^2)-2*mean(x)*(n+1)/n) } crps.GEVneq0 <- function(MEAN,SCALE,SHAPE, obs) { LOC <- MEAN - SCALE*(gamma(1-SHAPE)-1)/SHAPE SCdSH <- SCALE/SHAPE Gam1mSH <- gamma(1-SHAPE) prob0 <- pgev(0, loc=LOC, scale=SCALE, shape=SHAPE) probY <- pgev(obs, loc=LOC, scale=SCALE, shape=SHAPE) T1 <- (obs-LOC)*(2*probY-1) + LOC*prob0^2 T2 <- SCdSH * ( 1-prob0^2 - 2^SHAPE*Gam1mSH*pgamma(-2*log(prob0),1-SHAPE) ) T3 <- -2*SCdSH * ( 1-probY - Gam1mSH*pgamma(-log(probY),1-SHAPE) ) return( mean(T1+T2+T3) ) } eps <- 1e-5 matchITandFH(fit,ensembleData) M <- matchEnsembleMembers(fit,ensembleData) nForecasts <- ensembleSize(ensembleData) if (!all(M == 1:nForecasts)) ensembleData <- ensembleData[,M] M <- apply(ensembleForecasts(ensembleData), 1, function(z) all(is.na(z))) M <- M | is.na(ensembleVerifObs(ensembleData)) ensembleData <- ensembleData[!M,] dateTable <- dimnames(fit$B)[[2]] if (!is.null(dates)) { dates <- sort(unique(as.character(dates))) if (length(dates) > length(dateTable)) stop("parameters not available for some dates") K <- match( dates, dateTable, nomatch=0) if (any(!K) || !length(K)) stop("parameters not available for some dates") } else { dates <- dateTable K <- 1:length(dateTable) } ensDates <- ensembleValidDates(ensembleData) if (is.null(ensDates) || all(is.na(ensDates))) { if (length(dates) > 1) stop("date ambiguity") nObs <- nrow(ensembleData) Dates <- rep( dates, nObs) } else { if (any(M <- is.na(ensDates))) { ensembleData <- ensembleData[!M,] ensDates <- ensembleValidDates(ensembleData) } Dates <- as.character(ensDates) L <- as.logical(match( Dates, dates, nomatch=0)) if (all(!L) || !length(L)) stop("model fit dates incompatible with ensemble data") Dates <- Dates[L] ensembleData <- ensembleData[L,] nObs <- length(Dates) } obs <- ensembleVerifObs(ensembleData) nForecasts <- ensembleSize(ensembleData) CRPS <- rep(NA, nObs) ensembleData <- ensembleForecasts(ensembleData) crpsEns1 <- apply(abs(sweep(ensembleData, MARGIN=1,FUN ="-",STATS=obs)) ,1,mean,na.rm=TRUE) if (nrow(ensembleData) > 1) { crpsEns2 <- apply(apply(ensembleData, 2, function(z,Z) apply(abs(sweep(Z, MARGIN = 1, FUN = "-", STATS = z)),1,sum,na.rm=TRUE), Z = ensembleData),1,sum, na.rm = TRUE) } else { crpsEns2 <- sum(sapply(as.vector(ensembleData), function(z,Z) sum( Z-z, na.rm = TRUE), Z = as.vector(ensembleData)), na.rm = TRUE) } crpsEns <- crpsEns1 - crpsEns2/(2*(nForecasts*nForecasts)) l <- 0 for (d in dates) { l <- l + 1 k <- K[l] B <- fit$B[,k] if (all(Bmiss <- is.na(B))) next A <- fit$a[,k] C <- fit$c[,k] D <- fit$d[,k] Q <- fit$q[,k] S <- fit$s[,k] I <- which(as.logical(match(Dates, d, nomatch = 0))) for (i in I) { f <- ensembleData[i,] MEAN <- c(A,B)%*%c(1,f)+S*mean(f==0, na.rm = TRUE) SCALE <- C + D*gini.md(f,na.rm = TRUE) if( abs(Q) < eps ) { crps.eps.m <- crps.GEVneq0 (MEAN,SCALE,-eps, obs[i]) crps.eps.p <- crps.GEVneq0 (MEAN,SCALE,eps, obs[i]) w.m <- (eps-Q)/(2*eps) w.p <- (eps+Q)/(2*eps) CRPS[i] <- w.m*crps.eps.m + w.p*crps.eps.p } else { CRPS[i] <- crps.GEVneq0 (MEAN,SCALE,Q, obs[i]) } } } if (any(is.na(c(crpsEns,CRPS)))) warning("NAs in crps values") cbind(ensemble = crpsEns, EMOS = CRPS) }
BrierDecomp <- function(p, y, bins=10, bias.corrected=FALSE) { n <- length(p) if (length(bins) == 1) { n.bins <- floor(bins) p.breaks <- seq(0, 1, length.out=n.bins+1) } else { n.bins <- length(bins) - 1 bins <- sort(bins) stopifnot(min(bins)<= 0 & max(bins) >= 1) p.breaks <- bins } p.binning <- cut(p, breaks=p.breaks, include.lowest=TRUE, ordered_result=TRUE) p.binning <- as.numeric(p.binning) m.ind <- matrix(c(seq(n), p.binning), nrow=n) m.A <- matrix(0, nrow=n, ncol=n.bins) m.A[m.ind] <- 1 cs.A <- colSums(m.A) m.B <- matrix(0, nrow=n, ncol=n.bins) m.B[m.ind] <- y cs.B <- colSums(m.B) m.C <- matrix(0, nrow=n, ncol=n.bins) m.C[m.ind] <- p cs.C <- colSums(m.C) m.Y <- matrix(y, ncol=1) cs.Y <- colSums(m.Y) d0 <- which(cs.A < 1) d1 <- which(cs.A < 2) d0.set <- function(x) { if (length(d0) > 0) { x <- x[-d0] } x } d1.set <- function(x) { if (length(d1) > 0) { x <- x[-d1] } x } rel <- 1/n * sum( d0.set((cs.B - cs.C)^2 / cs.A) ) res <- 1/n * sum( d0.set(cs.A * (cs.B / cs.A - cs.Y / n)^2) ) unc <- cs.Y * (n - cs.Y) / n / n corr.s <- 1 / n * sum(d1.set(cs.B * (cs.A - cs.B) / (cs.A * (cs.A - 1)))) corr.t <- cs.Y * (n - cs.Y) / n / n / (n-1) alpha <- min(c(rel/corr.s, max(c(res / (corr.s - corr.t), (res - 1) / (corr.s - corr.t))), (1 - 4 * unc) / (4 * corr.t), 1) ) if (!is.finite(alpha)) { alpha <- 0 } rel2 <- rel - alpha * corr.s res2 <- res - alpha * corr.s + alpha * corr.t unc2 <- unc + alpha * corr.t d.rel.d.a <- -1 * (cs.B - cs.C) * (cs.B - cs.C) / (n * cs.A * cs.A) d.rel.d.b <- 2 * (cs.B - cs.C) / (n * cs.A) d.rel.d.c <- -2 * (cs.B - cs.C) / (n * cs.A) if (length(d0) > 0) { d.rel.d.a[d0] <- 0 d.rel.d.b[d0] <- 0 d.rel.d.c[d0] <- 0 } jacobian.rel <- matrix(c(d.rel.d.a, d.rel.d.b, d.rel.d.c), nrow=1) m.X <- cbind(m.A, m.B, m.C) cov.X.rel <- crossprod(scale(m.X, center=TRUE, scale=FALSE)) var.rel <- jacobian.rel %*% cov.X.rel %*% t(jacobian.rel) d.res.d.a <- -1 / n * (cs.B / cs.A - cs.Y / n) * (cs.B / cs.A + cs.Y / n) d.res.d.b <- 2 / n * (cs.B / cs.A - cs.Y / n) d.res.d.y <- 0 if (length(d0) > 0) { d.res.d.a[d0] <- 0 d.res.d.b[d0] <- 0 } jacobian.res <- matrix(c(d.res.d.a, d.res.d.b, d.res.d.y), nrow=1) m.X <- cbind(m.A, m.B, m.Y) cov.X.res <- crossprod(scale(m.X, center=TRUE, scale=FALSE)) var.res <- jacobian.res %*% cov.X.res %*% t(jacobian.res) var.unc <- (1 - 2 * cs.Y / n) * (1 - 2 * cs.Y / n) / n / n * crossprod(scale(m.Y, center=TRUE, scale=FALSE)) d.rel2.d.a <- -1 * ((cs.B - cs.C) * (cs.B - cs.C) + (cs.B * cs.B) / (cs.A - 1) - cs.A * cs.B * (cs.A - cs.B) / (cs.A - 1) / (cs.A - 1) ) / (n * cs.A * cs.A) d.rel2.d.b <- (2 * cs.B - 1) / (n * cs.A - n) - 2 * cs.C / (n * cs.A) d.rel2.d.c <- -2 * (cs.B - cs.C) / (n * cs.A) if (length(d1) > 0) { d.rel2.d.a[d1] <- 0 d.rel2.d.b[d1] <- 0 d.rel2.d.c[d1] <- 0 } jacobian.rel <- matrix(c(d.rel2.d.a, d.rel2.d.b, d.rel2.d.c), nrow=1) var.rel2 <- jacobian.rel %*% cov.X.rel %*% t(jacobian.rel) d.res2.d.a <- -1 / n * (cs.B / cs.A - cs.Y / n) * (cs.B / cs.A + cs.Y / n) + cs.B / (n * cs.A * cs.A * (cs.A - 1) * (cs.A - 1)) * ((cs.A - cs.B) * (cs.A - cs.B) - cs.B * (cs.B - 1)) d.res2.d.b <- 2 / n * (cs.B / cs.A - cs.Y / n) - (cs.A - 2 * cs.B) / (n * cs.A * (cs.A - 1)) d.res2.d.y <- (n - 2 * cs.Y) / n / n / (n - 1) if (length(d1) > 0) { d.res2.d.a[d1] <- 0 d.res2.d.b[d1] <- 0 } jacobian.res2 <- matrix(c(d.res2.d.a, d.res2.d.b, d.res2.d.y), nrow=1) var.res2 <- jacobian.res2 %*% cov.X.res %*% t(jacobian.res2) var.unc2 <- (n - 2 * cs.Y) * (n - 2 * cs.Y) / n / n / (n - 1) / (n - 1) * crossprod(scale(m.Y, center=TRUE, scale=FALSE)) sqrt0 <- function(x) { if (x <= 0) { return(0) } else { return(sqrt(x)) } } if (bias.corrected == FALSE) { ans <- rbind( component = c(REL=rel, RES=res, UNC=unc), component.sd = c(REL=sqrt0(drop(var.rel)), RES=sqrt0(drop(var.res)), UNC=sqrt0(drop(var.unc))) ) } else { ans <- rbind( component = c(REL=rel2, RES=res2, UNC=unc2), component.sd = c(REL=sqrt0(drop(var.rel2)), RES=sqrt0(drop(var.res2)), UNC=sqrt0(drop(var.unc2))) ) } return(ans) } BrierScoreDecomposition <- BrierDecomp
contr_one_hot <- function(n, contrasts = TRUE, sparse = FALSE) { if (sparse) { rlang::warn("`sparse = TRUE` not implemented for `contr_one_hot()`.") } if (!contrasts) { rlang::warn("`contrasts = FALSE` not implemented for `contr_one_hot()`.") } if (is.character(n)) { names <- n n <- length(names) } else if (is.numeric(n)) { n <- as.integer(n) if (length(n) != 1L) { rlang::abort("`n` must have length 1 when an integer is provided.") } names <- as.character(seq_len(n)) } else { rlang::abort("`n` must be a character vector or an integer of size 1.") } out <- diag(n) rownames(out) <- names colnames(out) <- names out }
test_that("get_timeline works", { x <- get_timeline(c("cnnbrk", "cnn"), n = 400) expect_s3_class(x, "data.frame") expect_true("id" %in% names(x)) expect_gt(nrow(x), 100) expect_gt(ncol(x), 20) }) test_that("get_my_timeline() works", { gmt <- get_my_timeline() expect_s3_class(gmt, "data.frame") expect_true(nrow(gmt) > 50) }) test_that("get_timelines() is deprecated", { expect_snapshot(x <- get_timelines("cnn", n = 10)) }) test_that("Doesn't trim at 280 characters, timeline_users <- get_timeline(user = "mvabercron", n = 20) text <- timeline_users$text[!is.na(timeline_users$text)] expect_true(any(nchar(text) > 280)|| all(!endsWith(text, "..."))) })
test_that("scalar y replaces all matching x", { x <- c(0, 1, 0) expect_equal(na_if(x, 0), c(NA, 1, NA)) expect_equal(na_if(x, 1), c(0, NA, 0)) }) test_that("na_if() gives meaningful errors", { expect_snapshot(error = TRUE, na_if(1:3, 1:2)) expect_snapshot(error = TRUE, na_if(1, 1:2)) })
kml_track<-function(sdata, sdata.CRS = 'WGS', output = 'open', type = 'point', ...){ sdata <- sdata[stats::complete.cases(sdata[,c("lon","lat")]),] sdata$DateTime <- with(sdata, as.POSIXct(DateTime, format = "%Y-%m-%d %H:%M:%S", tz = "GMT")) j <- levels(factor(sdata$id)) if(sdata.CRS == 'WGS'){ sdata.CRS <- '+proj=longlat +ellps=WGS84 +datum=WGS84' } if(type == 'point'){ sp::coordinates(sdata) <- ~ lon + lat sp::proj4string(sdata) <- sp::CRS(sdata.CRS) } else { lines <- sp::Line(cbind(sdata$lon, sdata$lat)) lineString <- sp::Lines(list(lines), ID=j) spLines <- sp::SpatialLines(list(lineString), proj4string=sp::CRS(sdata.CRS)) df.lines <- data.frame(ID=j) sdata <- sp::SpatialLinesDataFrame(spLines, data=df.lines, match.ID=F) } if(output == 'open'){ plotKML::plotKML(obj=sdata, ...) } else { plotKML::kml(obj=sdata, ...) } }
context("Packaging expression") test_that("can create a Dockerfile from expression", { output <- capture_output(the_dockerfile <- dockerfile(from = expression(library(sp)))) expect_s4_class(the_dockerfile,"Dockerfile") expect_true(any(stringr::str_detect(toString(the_dockerfile), "^RUN \\[\"install2.r\", \"sp\"\\]$"))) }) test_that("can create a Dockerfile from expression with multiple statements", { output <- capture_output(the_dockerfile <- dockerfile(from = expression({library(sp);library(fortunes)}))) expect_s4_class(the_dockerfile,"Dockerfile") expect_true(any(stringr::str_detect(toString(the_dockerfile), "^RUN \\[\"install2.r\", \"fortunes\", \"sp\"\\]$"))) }) test_that("can create a Dockerfile from expression vector", { output <- capture_output(the_dockerfile <- dockerfile(from = c(expression(library(sp)), expression(library(rprojroot))))) expect_s4_class(the_dockerfile,"Dockerfile") expect_true(any(stringr::str_detect(toString(the_dockerfile), "^RUN \\[\"install2.r\", \"rprojroot\", \"sp\"\\]$"))) })
dos2unix <- function(file) { txt <- readLines(file) con <- file(file, open="wb") writeLines(txt, con, sep="\n") close(con) }
sum.intdiff.lgamma <- function(G1,G2){ l <- length(G1) RES <- sapply(1:l,function(x) if (G2[x] - G1[x] > 0) {sum(log(G1[x]:(G2[x]-1)))} else 0) return(sum(RES)) }
i.eli_ines_seg <-function(x.cent = 0, y.cent = 0, xb=4, yh=4, seg=c(0,30), nseg=720, col="grey", lwd=1, lty=1, ...){ sektor <- seq(from=seg[1],to=seg[2],by=360/nseg) xx <- (x.cent + xb*sin( rad(sektor) )) yy <- (y.cent + yh*cos( rad(sektor) )) lines(xx,yy,col=col,lwd=lwd,lty=lty, ...) }
bspline_matrix <- function(x, m, q, Omega = NULL ){ if(is.null(Omega)){ Omega <- c(min(x), max(x)) } trunc_pol <- function(x, t, q) (x-t)^q * (x>t) h <- (Omega[2] - Omega[1]) / (m+1) knots <- seq(Omega[1]-q*h, Omega[2]+q*h, by = h) H <- outer(x, knots, trunc_pol, q) D <- diff(diag(dim(H)[2]), diff = q+1) / (gamma(q+1)*h^q) Phi <- (-1)^(q+1) * tcrossprod(H,D) Phi[Phi < 1e-10] <- 0 return(Phi) } MVP_spline <- function(tPhi_list, alpha){ v <- MVP_khatrirao_trans_rcpp(tPhi_list, alpha) base <- MVP_khatrirao_rcpp(tPhi_list, v) return(base) } MVP_penalty <- function(pen_list, alpha, pen_type = "curve"){ if(pen_type == "curve"){ pen <- rowSums( sapply( 1:length(pen_list), function(p) MVP_kronecker_rcpp(pen_list[[p]], alpha) ) ) return(pen) } if(pen_type == "diff"){ Pj <- length(pen_list) Jj <- sapply(1:Pj, function(p) dim(pen_list[[p]])[1]) n_left <- c(1, sapply(1:(Pj-1), function(p) prod(Jj[1:p]) )) n_right <- c(rev( sapply(1:(Pj-1), function(p) prod(rev(Jj)[1:p]) ) ), 1) if(Pj==1) n_left <- n_right <- 1 pen <- rowSums( sapply( 1:Pj, function(p) MVP_normalfactor_rcpp(pen_list[[p]], n_left[p], n_right[p], alpha) ) ) return(as.vector(pen)) } } L2norm_matrix <- function(m, q, d, Omega){ K <- m+q+1 h <- (Omega[2]-Omega[1]) / (m+1) n_gauss <- q+1 gauss_legendre <- statmod::gauss.quad(n_gauss) w_ref <- gauss_legendre$weights[order(gauss_legendre$nodes)] points_ref <- (h/2)*sort(gauss_legendre$nodes) + (Omega[1]+(h/2)) points <- as.vector( sapply( 1:(m+1), function(j) points_ref+(j-1)*h ) ) w <- rep(w_ref,(m+1)) Phi <- bspline_matrix(points, m, (q-d), Omega) G <- (h/2)*crossprod(Phi, Phi*w) if(d==0){ Psi <- G } else{ Delta <- diff(diag(K),diff=d) Psi <- (1 / (h^(2*d))) * crossprod(Delta,G%*%Delta) } return(Psi) } L2norm_matrix_list <- function(m, q, d, Omega){ P <- length(q) Reg_list <- lapply(1:P, function(p) L2norm_matrix(m[p],q[p],d[p],Omega[[p]]) ) return(Reg_list) } curvature_penalty <- function(m, q, Omega){ P <- length(m) d_mat <- 2*diag(P) if(P>1){ vec <- c(1,1,rep(0,P-2)) M <- matrix( unlist( unique(combinat::permn(vec)) ), nrow=P, byrow=F ) d_mat <- cbind(d_mat,M) } Psi_list <- lapply(1:dim(d_mat)[2], function(p) L2norm_matrix_list(m,q,d_mat[,p],Omega) ) nreg <- length(Psi_list) w_Psi <- sapply(1:nreg, function(j) 2/prod(factorial(d_mat[,j])) ) for(j in 1:nreg){ Psi_list[[j]][[1]] <- w_Psi[j]*Psi_list[[j]][[1]] } return(Psi_list) }
lsm_c_gyrate_mn <- function(landscape, directions = 8, cell_center = FALSE) { landscape <- landscape_as_list(landscape) result <- lapply(X = landscape, FUN = lsm_c_gyrate_mn_calc, directions = directions, cell_center = cell_center) layer <- rep(seq_along(result), vapply(result, nrow, FUN.VALUE = integer(1))) result <- do.call(rbind, result) tibble::add_column(result, layer, .before = TRUE) } lsm_c_gyrate_mn_calc <- function(landscape, directions, cell_center, points = NULL) { gyrate <- lsm_p_gyrate_calc(landscape, directions = directions, cell_center = cell_center, points = points) if (all(is.na(gyrate$value))) { return(tibble::tibble(level = "class", class = as.integer(NA), id = as.integer(NA), metric = "gyrate_cv", value = as.double(NA))) } gyrate_mn <- stats::aggregate(x = gyrate[, 5], by = gyrate[, 2], FUN = mean) return(tibble::tibble(level = "class", class = as.integer(gyrate_mn$class), id = as.integer(NA), metric = "gyrate_mn", value = as.double(gyrate_mn$value))) }
context("sts-functions") test_succeeds("sts_build_factored_variational_loss works", { skip_if_eager() observed_time_series <- rep(c(3.5, 4.1, 4.5, 3.9, 2.4, 2.1, 1.2), 5) + rep(c(1.1, 1.5, 2.4, 3.1, 4.0), each = 7) day_of_week <- observed_time_series %>% sts_seasonal(num_seasons = 7) local_linear_trend <- observed_time_series %>% sts_local_linear_trend() model <- observed_time_series %>% sts_sum(components = list(day_of_week, local_linear_trend)) optimizer <- tf$compat$v1$train$AdamOptimizer(0.1) build_variational_loss <- function() { res <- observed_time_series %>% sts_build_factored_variational_loss(model = model) variational_loss <- res[[1]] variational_loss } loss_and_dists <- observed_time_series %>% sts_build_factored_variational_loss(model = model) variational_loss <- loss_and_dists[[1]] train_op <- optimizer$minimize(variational_loss) with (tf$Session() %as% sess, { sess$run(tf$compat$v1$global_variables_initializer()) for (step in 1:5) { res <- sess$run(train_op) } avg_loss <- Map(function(x) sess$run(variational_loss), 1:2) %>% unlist() %>% mean() variational_distributions <- loss_and_dists[[2]] posterior_samples <- Map(function(d) d %>% tfd_sample(50), variational_distributions) %>% sess$run() }) expect_length(avg_loss, 1) expect_length(posterior_samples, 4) }) test_succeeds("sts_fit_with_hmc works", { observed_time_series <- rep(c(3.5, 4.1, 4.5, 3.9, 2.4, 2.1, 1.2), 5) + rep(c(1.1, 1.5, 2.4, 3.1, 4.0), each = 7) if (tensorflow::tf_version() >= "2.0") observed_time_series <- tensorflow::tf$convert_to_tensor(observed_time_series, dtype = tensorflow::tf$float64) day_of_week <- observed_time_series %>% sts_seasonal(num_seasons = 7) local_linear_trend <- observed_time_series %>% sts_local_linear_trend() model <- observed_time_series %>% sts_sum(components = list(day_of_week, local_linear_trend)) states_and_results <- observed_time_series %>% sts_fit_with_hmc( model, num_results = 10, num_warmup_steps = 5, num_variational_steps = 15 ) posterior_samples <- states_and_results[[1]] expect_length(posterior_samples, 4) }) test_succeeds("sts_one_step_predictive works", { observed_time_series <- rep(c(3.5, 4.1, 4.5, 3.9, 2.4, 2.1, 1.2), 5) + rep(c(1.1, 1.5, 2.4, 3.1, 4.0), each = 7) if (tensorflow::tf_version() >= "2.0") observed_time_series <- tensorflow::tf$convert_to_tensor(observed_time_series, dtype = tensorflow::tf$float64) day_of_week <- observed_time_series %>% sts_seasonal(num_seasons = 7) local_linear_trend <- observed_time_series %>% sts_local_linear_trend() model <- observed_time_series %>% sts_sum(components = list(day_of_week, local_linear_trend)) states_and_results <- observed_time_series %>% sts_fit_with_hmc( model, num_results = 10, num_warmup_steps = 5, num_variational_steps = 15 ) samples <- states_and_results[[1]] preds <- observed_time_series %>% sts_one_step_predictive(model, parameter_samples = samples, timesteps_are_event_shape = TRUE) pred_means <- preds %>% tfd_mean() pred_sds <- preds %>% tfd_stddev() skip("Batch dim behavior changed") expect_equal(preds$event_shape %>% length(), 2) }) test_succeeds("sts_forecast works", { observed_time_series <- rep(c(3.5, 4.1, 4.5, 3.9, 2.4, 2.1, 1.2), 5) + rep(c(1.1, 1.5, 2.4, 3.1, 4.0), each = 7) if (tensorflow::tf_version() >= "2.0") observed_time_series <- tensorflow::tf$convert_to_tensor(observed_time_series, dtype = tensorflow::tf$float64) day_of_week <- observed_time_series %>% sts_seasonal(num_seasons = 7) local_linear_trend <- observed_time_series %>% sts_local_linear_trend() model <- observed_time_series %>% sts_sum(components = list(day_of_week, local_linear_trend)) states_and_results <- observed_time_series %>% sts_fit_with_hmc( model, num_results = 10, num_warmup_steps = 5, num_variational_steps = 15 ) samples <- states_and_results[[1]] preds <- observed_time_series %>% sts_forecast(model, parameter_samples = samples, num_steps_forecast = 50) predictions <- preds %>% tfd_sample(10) expect_equal(predictions$get_shape()$as_list() %>% length(), 3) }) test_succeeds("sts_decompose_by_component works", { observed_time_series <- array(rnorm(2 * 1 * 12), dim = c(2, 1, 12)) day_of_week <- observed_time_series %>% sts_seasonal(num_seasons = 7, name = "seasonal") local_linear_trend <- observed_time_series %>% sts_local_linear_trend(name = "local_linear") model <- observed_time_series %>% sts_sum(components = list(day_of_week, local_linear_trend)) states_and_results <- observed_time_series %>% sts_fit_with_hmc( model, num_results = 10, num_warmup_steps = 5, num_variational_steps = 15 ) samples <- states_and_results[[1]] component_dists <- observed_time_series %>% sts_decompose_by_component(model = model, parameter_samples = samples) day_of_week_effect_mean <- component_dists[[1]] %>% tfd_mean() expect_equal(day_of_week_effect_mean$get_shape()$as_list() %>% length(), 3) }) test_succeeds("sts_build_factored_surrogate_posterior works", { skip_if_tfp_below("0.8") observed_time_series <- rep(c(3.5, 4.1, 4.5, 3.9, 2.4, 2.1, 1.2), 5) + rep(c(1.1, 1.5, 2.4, 3.1, 4.0), each = 7) day_of_week <- observed_time_series %>% sts_seasonal(num_seasons = 7) local_linear_trend <- observed_time_series %>% sts_local_linear_trend() model <- observed_time_series %>% sts_sum(components = list(day_of_week, local_linear_trend)) optimizer <- tf$compat$v1$train$AdamOptimizer(0.1) surrogate_posterior <- model %>% sts_build_factored_surrogate_posterior() loss_curve <- vi_fit_surrogate_posterior( target_log_prob_fn = model$joint_log_prob(observed_time_series), surrogate_posterior = surrogate_posterior, optimizer = optimizer, num_steps = 20 ) if (tf$executing_eagerly()) { posterior_samples <- surrogate_posterior %>% tfd_sample(50) } else { with (tf$control_dependencies(list(loss_curve)), { posterior_samples <- surrogate_posterior %>% tfd_sample(50) }) } expect_length(posterior_samples, 4) }) test_succeeds("sts_sample_uniform_initial_state works", { model <- sts_sparse_linear_regression(design_matrix = matrix(31 * 3, nrow = 31), weights_prior_scale = 0.1) p <- model$parameters[[1]] init <- sts_sample_uniform_initial_state(parameter = p, init_sample_shape = list(2, 2)) expect_equal(init$get_shape()$as_list() %>% length(), 2) }) test_succeeds("sts_decompose_forecast_by_component works", { observed_time_series <- array(rnorm(2 * 1 * 12), dim = c(2, 1, 12)) day_of_week <- observed_time_series %>% sts_seasonal(num_seasons = 7, name = "seasonal") local_linear_trend <- observed_time_series %>% sts_local_linear_trend(name = "local_linear") model <- observed_time_series %>% sts_sum(components = list(day_of_week, local_linear_trend)) states_and_results <- observed_time_series %>% sts_fit_with_hmc( model, num_results = 10, num_warmup_steps = 5, num_variational_steps = 15 ) samples <- states_and_results[[1]] forecast_dist <- observed_time_series %>% sts_forecast(model, parameter_samples = samples, num_steps_forecast = 50) component_forecasts <- sts_decompose_forecast_by_component(model, forecast_dist, samples) day_of_week_effect_mean <- component_forecasts[[1]] %>% tfd_mean() expect_equal(day_of_week_effect_mean$get_shape()$as_list() %>% length(), 3) })
chart.GroupWeights <- function(object, ..., grouping=c("groups", "category"), plot.type="line", main="Group Weights", las=3, xlab=NULL, cex.lab=0.8, element.color="darkgray", cex.axis=0.8){ if(!inherits(object, "optimize.portfolio")) stop("object must be of class 'optimize.portfolio'") if(plot.type %in% c("bar", "barplot")){ barplotGroupWeights(object=object, ...=..., grouping=grouping, main=main, las=las, xlab=xlab, cex.lab=cex.lab, element.color=element.color, cex.axis=cex.axis) } else if(plot.type == "line"){ constraints <- get_constraints(object$portfolio) tmp <- extractGroups(object) grouping <- grouping[1] if(grouping == "groups"){ weights <- tmp$group_weights if(is.null(weights)) stop("No weights detected for groups") if(any(is.infinite(constraints$cUP)) | any(is.infinite(constraints$cLO))){ ylim <- range(weights) } else { ylim <- range(c(constraints$cLO, constraints$cUP)) } } if(grouping == "category"){ weights <- tmp$category_weights if(is.null(weights)) stop("No weights detected for category") ylim <- range(weights) } columnnames = names(weights) numgroups = length(columnnames) if(is.null(xlab)) minmargin = 3 else minmargin = 5 if(main=="") topmargin=1 else topmargin=4 if(las > 1) { bottommargin = max(c(minmargin, (strwidth(columnnames,units="in"))/par("cin")[1])) * cex.lab if(bottommargin > 10 ) { bottommargin<-10 columnnames<-substr(columnnames,1,19) } } else { bottommargin = minmargin } par(mar = c(bottommargin, 4, topmargin, 2) +.1) plot(weights, axes=FALSE, xlab='', ylim=ylim, ylab="Weights", main=main, ...) if(grouping == "groups"){ if(!any(is.infinite(constraints$cLO))){ points(constraints$cLO, type="b", col="darkgray", lty="solid", lwd=2, pch=24) } if(!any(is.infinite(constraints$cUP))){ points(constraints$cUP, type="b", col="darkgray", lty="solid", lwd=2, pch=25) } } axis(2, cex.axis = cex.axis, col = element.color) axis(1, labels=columnnames, at=1:numgroups, las=las, cex.axis = cex.axis, col = element.color) box(col = element.color) } } barplotGroupWeights <- function(object, ..., grouping=c("groups", "category"), main="Group Weights", las=3, xlab=NULL, cex.lab=0.8, element.color="darkgray", cex.axis=0.8){ if(!inherits(object, "optimize.portfolio")) stop("object must be of class 'optimize.portfolio'") constraints <- get_constraints(object$portfolio) tmp <- extractGroups(object) if(grouping == "groups"){ weights <- tmp$group_weights if(is.null(weights)) stop("No weights detected for groups") } if(grouping == "category"){ weights <- tmp$category_weights if(is.null(weights)) stop("No weights detected for category") } columnnames = names(weights) numgroups = length(columnnames) barplot(weights, ylab = "", names.arg=columnnames, border=element.color, cex.axis=cex.axis, main=main, las=las, cex.names=cex.lab, xlab=xlab, ...) box(col=element.color) }
KRV <- function(y = NULL, X = NULL, adjust.type = NULL, kernels.otu, kernel.y, omnibus = "kernel_om", returnKRV = FALSE, returnR2 = FALSE){ om <- substring(tolower(omnibus), 1, 1) if (!is.null(adjust.type)) { adjust.type <- substring(tolower(adjust.type), 1, 1) if (adjust.type == "p") { if (!kernel.y %in% c("linear", "Gaussian")) { stop("Phenotype-only adjustment may only be used with numeric y, not pre-computed phenotype kernel. Try option 'both' instead or double check that you have entered either 'linear' or 'Gaussian' for kernel.y.") } } if (!adjust.type %in% c("p", "b")) { stop("I don't know that covariate adjustment choice. Please choose 'phenotype' or 'both', or leave this option NULL.") } } if (!is.list(kernels.otu)) { kernels.otu <- list(kernels.otu) } if (!all(unlist(lapply(kernels.otu, FUN = function(k) is.matrix(k))))) { stop("Please ensure kernels.otu is either a single n x n kernel matrix or a list of n x n kernel matrices.") } if (!is.null(X) & !all(X[,1] == 1)) { X1 <- cbind(1, X) X <- X1 } if (is.null(X) & !is.null(adjust.type)) { warning("X is NULL, so no covariate adjustment will be done.") adjust.type = NULL } if (is.matrix(kernel.y)){ n = nrow(kernels.otu[[1]]) if (!is.null(y)){ warning("When a phenotype kernel is provided, argument \"y\" will be ignored.\n") } if (ncol(kernels.otu[[1]]) != n | nrow(kernel.y) != n | ncol(kernel.y) != n){ stop("Kernel matrices need to be n x n, where n is the sample size.\n ") } } else if (!is.matrix(kernel.y)){ if (!(kernel.y %in% c("Gaussian", "linear"))){ stop("Please choose kernel.y = \"Gaussian\" or \"linear\", or enter a kernel matrix for \"kernel.y\".\n") } if(is.null(y)){ stop("Please enter a phenotype matrix for argument \"y\" or enter a kernel matrix for argument \"kernel.y\".\n") } n = NROW(y) if (!all(unlist(lapply(kernels.otu, FUN = function(x) nrow(x) == n & ncol(x) == n)))) { stop("Kernel matrix/matrices must be n x n, where n is the sample size. \n ") } if (any(is.na(y))){ ids = which(is.na(y)) stop(paste("Missing response for subject(s)", ids, "- please remove before proceeding. \n")) } if (!is.null(X)){ if (any(is.na(X))){ stop("NAs in covariates X, please impute or remove subjects with missing covariates values.\n") } if(NROW(X)!= NROW(y)) stop("Dimensions of X and y don't match.\n") } } pvals <- c() if (returnKRV) { KRVs <- c() } else { KRVs = NULL } if (returnR2) { R2 <- c() } else { R2 = NULL } for(i in 1:length(kernels.otu)){ res <- inner.KRV(y = y, X = X, adjust.type = adjust.type, kernel.otu=kernels.otu[[i]], kernel.y = kernel.y, returnKRV = TRUE, returnR2 = TRUE) pvals[i] <- res$pv if (returnKRV) { KRVs[i] <- res$KRV } if (returnR2) { R2[i] <- res$R2 } } kernel.names <- names(kernels.otu) names(pvals) <- kernel.names if (returnKRV) { names(KRVs) <- kernel.names } if (returnR2) { names(R2) <- kernel.names } if (length(kernels.otu) > 1) { if (om == "k") { K.om <- matrix(0, nrow = nrow(kernels.otu[[1]]), ncol = ncol(kernels.otu[[1]])) for(i in 1:length(kernels.otu)){ K.om = K.om + kernels.otu[[i]]/tr(kernels.otu[[i]]) } omnibus_p <- as.numeric(inner.KRV(y = y, X = X, adjust.type = adjust.type, kernel.otu = K.om, kernel.y = kernel.y)$pv) } else if (om == "c") { cauchy.t <- sum(tan((0.5 - pvals)*pi))/length(pvals) omnibus_p <- 1 - pcauchy(cauchy.t) } else { stop("I don't know that omnibus option. Please choose 'kernel_om' or 'Cauchy'.") } if (is.null(KRVs) & is.null(R2)) { return(list(p_values = pvals, omnibus_p = omnibus_p)) } else if (is.null(KRVs) & !is.null(R2)) { return(list(p_values = pvals, omnibus_p = omnibus_p, R2 = R2)) } else if (!is.null(KRVs) & is.null(R2)) { return(list(p_values = pvals, omnibus_p = omnibus_p, KRV = KRVs)) } else { return(list(p_values = pvals, omnibus_p = omnibus_p, KRV = KRVs, R2 = R2)) } } if (is.null(KRVs) & is.null(R2)) { return(list(p_values = pvals)) } else if (is.null(KRVs) & !is.null(R2)) { return(list(p_values = pvals, R2 = R2)) } else if (!is.null(KRVs) & is.null(R2)) { return(list(p_values = pvals, KRV = KRVs)) } else { return(list(p_values = pvals, KRV = KRVs, R2 = R2)) } }
list_compar <- function(lgrph, nd.var = "type", verbose = FALSE) { ldec.comp <- utils::combn(seq_len(length(lgrph)), 2) if (verbose) { print(paste0("there is ", ncol(ldec.comp), " pairwise comparisons to compute")) } grphAllcompar <- list() for (dec in seq_len(ncol(ldec.comp))) { idx.g <- ldec.comp[, dec] if (verbose) { tit <- paste0("compare decorations '", lgrph[[idx.g[1]]]$name, "' and '", lgrph[[idx.g[2]]]$name, "'") print(paste0(" ", dec, ") ", tit)) } grph <- eds_compar(lgrph[idx.g], nd.var) grph <- nds_compar(grph, nd.var) attributes(grph)$nd.var <- nd.var grphAllcompar[[dec]] <- grph } return(grphAllcompar) } nds_compar <- function(grphs, nd.var = "type") { g.nds <- lapply(grphs, function(x) iconr::named_elements(x, "nodes", nd.var)) common.nodes <- intersect(g.nds[[1]], g.nds[[2]]) for (i in 1:2) { igraph::V(grphs[[i]])$comm <- as.numeric(g.nds[[i]] %in% common.nodes) } return(grphs) } eds_compar <- function(grphs, nd.var = "type") { g.eds <- lapply(grphs, function(x) iconr::named_elements(x, "edges", nd.var)) common.edges <- intersect(g.eds[[1]], g.eds[[2]]) for (i in 1:2) { igraph::E(grphs[[i]])$comm <- as.numeric(g.eds[[i]] %in% common.edges) } return(grphs) }
library(ggplot2) library(reshape2) this_base <- "fig04-10_museum-exhibitions-jittering" my_data <- read.delim(paste0(this_base, ".tsv")) my_data_long <- melt(my_data, id = NULL, variable.name = "exhibition", value.name = "visit_length") levels(my_data_long$exhibition) <- gsub("\\.\\.\\.", ".&.", levels(my_data_long$exhibition)) levels(my_data_long$exhibition) <- gsub("\\.", " ", levels(my_data_long$exhibition)) set.seed(0) p <- ggplot(my_data_long, aes(x = visit_length, y = exhibition)) + geom_point(shape = 1, position = position_jitter(w = 0.1, h = 0.1)) + scale_x_continuous(breaks = seq(0, 80, 20), limits = c(-1, 100)) + scale_y_discrete(limits = rev(levels(my_data_long$exhibition))) + labs(x = NULL, y = "Times") + ggtitle("Fig 4.10 Museum Exhibitions: Jittering") + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), plot.title = element_text(size = rel(1.2), face = "bold", vjust = 1.5), axis.ticks.y = element_blank(), axis.title.y = element_blank()) p ggsave(paste0(this_base, ".png"), p, width = 6, height = 6)
load_palette <- function(palette) UseMethod('load_palette', palette) load_palette.character <- function(palette) { palette_list <- names(palettes) if (!palette %in% palette_list) stop(paste0("No palette named '", palette, "'. Please choose one of ", paste(palette_list, collapse=', '), '.'), call.=FALSE) return (palettes[[palette]]) } load_palette.ggthemr_palette <- function(palette) return (palette)
line_calc <- function(line_layer, higher_geo_lay, unique_id_code, crs) { crs = crs line_layer <- sf::st_transform(line_layer, crs) higher_geo_lay <- sf::st_transform(higher_geo_lay, crs) higher_geo_lay$TotalArea <- sf::st_area(higher_geo_lay$geometry) higher_geo_lay$TotalArea <- as.numeric(higher_geo_lay$TotalArea) sf::st_agr(line_layer) = "constant" sf::st_agr(higher_geo_lay) = "constant" int <- dplyr::as_tibble(sf::st_intersection(line_layer, higher_geo_lay)) int$foot_len <- sf::st_length(int$geometry) int$foot_len <- as.numeric(int$foot_len) int <- int %>% tidyr::drop_na(!!as.name(unique_id_code)) LengthByGeo <- int %>% dplyr::group_by(!!as.name(unique_id_code)) %>% dplyr::summarise(TotalLength = sum(foot_len), .groups = 'drop_last') combined_data <- dplyr::left_join(LengthByGeo, higher_geo_lay, by = unique_id_code) combined_data$Ratio <- combined_data$TotalLength / combined_data$TotalArea results <- combined_data[,c(unique_id_code, "TotalArea", "TotalLength", "Ratio")] return(results) }
get_mvn_params <- function(x, scale=1, correlations=TRUE, fix) { blocks <- c("parameter", "initial") params <- lapply(blocks, function(block) { block_lines <- grep("~", get_block(x$model, paste("proposal", block, sep="_")), value=TRUE) sub("[[:space:]]*~.*$", "", block_lines) }) names(params) <- blocks dimless_params <- lapply(params, function(param) { sub("[[:space:]]*\\[.*$", "", param) }) names(dimless_params) <- names(params) dims <- get_dims(x$model) vars <- list() for (block in names(params)) { if (!missing(fix)) { A <- matrix(fix, ncol=length(params[[block]]), nrow=length(params[[block]])) rownames(A) <- params[[block]] colnames(A) <- params[[block]] } else if (x$run_flag){ res <- bi_read(x, vars=unique(dimless_params[[block]]), init_to_param = TRUE) l <- list() for (param in names(res)) { if (prod(dim(res[[param]])) > 0) { y <- data.table(res[[param]]) dim_colnames <- setdiff(colnames(y), c("np", "value")) unique_dims <- unique(y[, dim_colnames, with=FALSE]) if (sum(dim(unique_dims)) > 0) { a <- lapply(seq_len(nrow(unique_dims)), function(row) { merge(unique_dims[row, ], y) }) for (dim_colname in dim_colnames) { if (is.factor(unique_dims[[dim_colname]])) { unique_dims[[dim_colname]] <- as.integer(unique_dims[[dim_colname]]) - 1 } } if (length(a) > 0) { names(a) <- unname(apply(unique_dims, 1, function(row) { paste0(param, "[", paste(row, collapse = ","), "]") })) } } else { a <- list(y) names(a) <- param } } a <- lapply(names(a), function(p) { for (col in colnames(unique_dims)) { a[[p]][[col]] <- NULL } data.table::setnames(a[[p]], "value", p) }) l <- c(l, a) } if (length(l) > 0) { wide <- l[[1]] if (length(l) > 1) { for (i in seq(2, length(l))) { wide <- merge(wide, l[[i]], by=intersect(colnames(wide), colnames(l[[i]]))) } } wide[["np"]] <- NULL if (ncol(wide) > 0) { if (ncol(wide) > 1 && correlations) { c <- 2.38**2 * stats::cov(wide) / ncol(wide) A <- tryCatch(t(as.matrix(chol(nearPD(c)$mat))), error=function(e) NULL) } else { A <- NULL } if (is.null(A)) { A <- diag(apply(wide, 2, sd)) rownames(A) <- colnames(wide) colnames(A) <- colnames(wide) } dA <- diag(A) for (i in seq_along(dA)) { if (dA[i]==0) { A[i, i] <- abs(mean(wide[, i, with=FALSE][[1]]))/10 } } } else { A <- matrix(ncol=0, nrow=0) } } else { A <- NULL } } else { A <- NULL } if (is.null(A)) { A <- diag(ncol=length(params[[block]]), nrow=length(params[[block]])) rownames(A) <- params[[block]] colnames(A) <- params[[block]] } if (prod(dim(A) > 0)) { if (!missing(scale)) { A <- A * sqrt(scale) } cov_input_name <- paste("__proposal", block, "cov", sep="_") dim_name <- paste("__dim", block, "cov", sep="_") long_cov <- reshape2::melt(A, varnames=paste(dim_name, 1:2, sep=".")) vars[[cov_input_name]] <- long_cov } } return(vars) }
NULL ggbarplot <- function(data, x, y, combine = FALSE, merge = FALSE, color = "black", fill = "white", palette = NULL, size = NULL, width = NULL, title = NULL, xlab = NULL, ylab = NULL, facet.by = NULL, panel.labs = NULL, short.panel.labs = TRUE, select = NULL, remove = NULL, order = NULL, add = "none", add.params = list(), error.plot = "errorbar", label = FALSE, lab.col = "black", lab.size = 4, lab.pos = c("out", "in"), lab.vjust = NULL, lab.hjust = NULL, lab.nb.digits = NULL, sort.val = c("none", "desc", "asc"), sort.by.groups = TRUE, top = Inf, position = position_stack(), ggtheme = theme_pubr(), ...) { .opts <- list( combine = combine, merge = merge, color = color, fill = fill, palette = palette, size = size, width = width, title = title, xlab = xlab, ylab = ylab, facet.by = facet.by, panel.labs = panel.labs, short.panel.labs = short.panel.labs, select = select , remove = remove, order = order, add = add, add.params = add.params, error.plot = error.plot, label = label, lab.col = lab.col, lab.size = lab.size, lab.pos = lab.pos, lab.vjust = lab.vjust, lab.hjust = lab.hjust, lab.nb.digits = lab.nb.digits, sort.val = sort.val, sort.by.groups = sort.by.groups, top = top, position = position, ggtheme = ggtheme, ...) if(!missing(data)) .opts$data <- data if(!missing(x)) .opts$x <- x if(!missing(y)) .opts$y <- y .user.opts <- as.list(match.call(expand.dots = TRUE)) .user.opts[[1]] <- NULL for(opt.name in names(.opts)){ if(is.null(.user.opts[[opt.name]])) .opts[[opt.name]] <- NULL } if(is.logical(merge)){ if(merge & missing(position)) .opts$position <- position_dodge(0.8) if(merge & missing(lab.col)) .opts$lab.col <- ".y." } else if(is.character(merge)){ .opts$position <- position_dodge(0.8) } .opts$fun <- ggbarplot_core .opts$fun_name <- "barplot" if(missing(ggtheme) & (!is.null(facet.by) | combine)) .opts$ggtheme <- theme_pubr(border = TRUE) p <- do.call(.plotter, .opts) if(.is_list(p) & length(p) == 1) p <- p[[1]] return(p) } ggbarplot_core <- function(data, x, y, color = "black", fill = "white", palette = NULL, size = NULL, width = 0.7, title = NULL, xlab = NULL, ylab = NULL, label = FALSE, lab.col = "black", lab.size = 4, lab.pos = c("out", "in"), lab.vjust = NULL, lab.hjust = NULL, lab.nb.digits = NULL, select = NULL, order = NULL, facet.by = NULL, sort.val = c("none", "desc", "asc"), sort.by.groups = TRUE, merge = FALSE, top = Inf, add = "none", add.params = list(), error.plot = "errorbar", position = position_stack(), ggtheme = theme_pubr(), ...) { sort.val <- match.arg(sort.val) if(!is.null(order)) data[, x] <- factor(data[, x], levels = order) else { xx <- .select_vec(data, x) if(inherits(xx, c("character", "numeric"))) data[, x] <- .select_vec(data, x) %>% as.factor() } error.plot = error.plot[1] lab.pos <- match.arg(lab.pos) label <- as.vector(label) if("none" %in% add) add <- "none" grouping.vars <- intersect(c(x, color, fill, facet.by), names(data)) . <- NULL if(is.null(add.params$fill)) add.params$fill <- "white" if(is.null(add.params$group)){ if(fill %in% names(data)) add.params$group <- fill else if(color %in% names(data)) add.params$group <- color } add.params <- .check_add.params(add, add.params, error.plot, data, color, fill, ...) if(any(.summary_functions() %in% add)) { data_sum <- desc_statby(data, measure.var = y, grps = grouping.vars) summary.funcs <- intersect(.summary_functions(), add) if(length(summary.funcs) > 1) stop("Only one summary function is allowed. ", "Choose one of ", .collapse(.summary_functions(), sep = ", ")) .center <- .get_errorbar_center_func(summary.funcs) add <- setdiff(add, .center) names(data_sum)[which(names(data_sum) == .center)] <- y if(inherits(xx, c("character", "numeric"))) data_sum[, x] <- .select_vec(data_sum, x) %>% as.factor() } else data_sum <- data if(top !=Inf & sort.val == "none") sort.val = "desc" if(top !=Inf) { data_sum <- data_sum[order(-data_sum[, y]), ] data_sum <- utils::head(data_sum, n = top) } grps <- unique(intersect(c(color, fill), names(data))) if(length(grps) > 0) grps <- .get_not_numeric_vars(data[, grps, drop = FALSE]) ngrps <- length(grps) if(!sort.by.groups) ngrps <- 0 if(ngrps > 0) dd <- data_sum[, c(grps, y)] else dd <- data_sum[, y, drop = FALSE] if(sort.val == "desc") dd[, y] <- -dd[, y] if(sort.val != "none") { if(ngrps == 0) data_sum <- data_sum[order(dd[, y]),] else if(ngrps == 1) data_sum <- data_sum[order(dd[, 1], dd[, y]),] else if(ngrps == 2) data_sum <- data_sum[order(dd[, 1], dd[, 2], dd[, y]),] data_sum[, x] <- factor(data_sum[, x], levels = data_sum[, x]) } if(inherits(position, "PositionDodge") & is.null(position$width)) position$width = 0.95 p <- ggplot(data, create_aes(list(x = x, y = y))) p <- p + geom_exec(geom_bar, data = data_sum, stat = "identity", color = color, fill = fill, position = position, size = size, width = width, ...) add.params <- add.params %>% .add_item(p = p, error.plot = error.plot) is.stacked.position <- inherits(position, "PositionStack") stack.groups <- unique(c(x, facet.by)) nb.bars.by.xposition <- data_sum %>% group_by(!!!syms(stack.groups)) %>% dplyr::count() %>% dplyr::pull(.data$n) %>% max() if(is.stacked.position) add.position <- "identity" else add.position <- position if(is.stacked.position & nb.bars.by.xposition >=2) { p <- add.params %>% .add_item(add = .remove_errorbar_func(add), position = add.position) %>% do.call(ggadd, .) if(any(.errorbar_functions() %in% add)){ p <- p + .geom_stacked_errorbar( data_sum, x, y, color = add.params$color, fill = add.params$fill, group = add.params$group, facet.by = facet.by, func = .get_summary_func(add), error.plot = error.plot ) } } else { p <- add.params %>% .add_item(add = add, position = add.position) %>% do.call(ggadd, .) } add.label <- FALSE if(is.logical(label)){ .lab <- y add.label <- label } else { data_sum$.ulabel. <- label .lab <- ".ulabel." add.label <- TRUE } if(add.label) { if(is.null(lab.vjust)) lab.vjust <- ifelse(lab.pos == "out", -0.4, 2 ) if(is.null(lab.hjust)) lab.hjust <- 0.5 if(!is.null(lab.nb.digits)){ if(is.numeric(.lab)) .lab <- round(.lab, digits = lab.nb.digits) else if(.lab[1] %in% colnames(data_sum)) data_sum[, .lab] <- dplyr::pull(data_sum, .lab) %>% round(digits = lab.nb.digits) } .cols <- unique(c(color, fill)) if(any(.cols %in% names(data))){ .in <- which(.cols %in% names(data)) lab.fill <- color.var <- .cols[.in] data_sum <- data_sum %>% dplyr::arrange(!!!syms(x), desc(!!!syms(color.var))) group <- intersect(.cols, names(data))[1] p <- p + geom_exec(geom_text, data = data_sum, label = .lab, vjust = lab.vjust, hjust = lab.hjust, size = lab.size, color = lab.col, fontface = "plain", position = position, group = group) } else{ p <- p + geom_exec(geom_text, data = data_sum, label = .lab, vjust = lab.vjust, hjust = lab.hjust, size = lab.size, color = lab.col, fontface = "plain", position = position) } } p <- ggpar(p, palette = palette, ggtheme = ggtheme, title = title, xlab = xlab, ylab = ylab,...) p } .geom_stacked_errorbar <- function(data_sum, x, y, color = NULL, fill = NULL, facet.by = NULL, group = NULL, func = "mean_se", error.plot = "errorbar"){ stack.groups <- unique(c(x, facet.by)) legend.var <- intersect(unique(c(color, fill, group)), colnames(data_sum)) error <- .get_errorbar_error_func(func) error.value <- data_sum %>% dplyr::pull(!!error) desc <- dplyr::desc errorbar.position <- data_sum %>% group_by(!!!syms(stack.groups)) %>% dplyr::arrange(!!sym(x), desc(!!sym(legend.var))) %>% dplyr::mutate( y = cumsum(!!sym(y)), ymin = .data$y - !!sym(error), ymax = .data$y + !!sym(error) ) %>% dplyr::ungroup() geom_error <- .get_geom_error_function(error.plot) args <- geom_exec( data = errorbar.position, color = color, group = group, x = x, ymin = "ymin", ymax = "ymax" ) mapping <- args$mapping option <- args$option if(error.plot == "errorbar") option$width <- 0.15 option[["mapping"]] <- create_aes(mapping) do.call(geom_error, option) } .get_geom_error_function <- function(error.plot = "errorbar"){ error.plot <- error.plot[1] geom_func <- ggplot2::geom_errorbar if(error.plot %in% c("pointrange", "lower_pointrange", "upper_pointrange")) geom_func <- ggplot2::geom_pointrange else if(error.plot %in% c("linerange", "lower_linerange", "upper_linerange")) geom_func <- ggplot2::geom_linerange else if(error.plot %in% c("errorbar", "lower_errorbar", "upper_errorbar")) geom_func <- ggplot2::geom_errorbar geom_func } .is_stacked <- function(p){ inherits(p$layers[[1]]$position, "PositionStack") } .remove_errorbar_func <- function(add){ setdiff(add, .errorbar_functions()) } .get_summary_func <- function(add){ intersect(.errorbar_functions(), add) } .get_errorbar_center_func <- function(func = "mean_se"){ . <- NULL func %>% strsplit("_", fixed = TRUE) %>% unlist() %>% .[1] } .get_errorbar_error_func <- function(func = "mean_se"){ res <- func %>% strsplit("_", fixed = TRUE) %>% unlist() if(length(res) >= 2){ res <- res[2] } else res <- NULL res }
check_store_every <- function(store_every) { testit::assert(length(store_every) == 1) if (is.na(store_every)) return() assertive::assert_is_a_number(store_every) assertive::assert_all_are_whole_numbers(store_every) if (store_every < -1 || store_every == 0) { stop( "'store_every' must be either NA, -1 or a non-zero positive value. \n", "'Actual value: ", store_every ) } }
peptide_type <- function(...) { lifecycle::deprecate_warn("0.2.0", "peptide_type()", "assign_peptide_type()", details = "This function has been renamed." ) assign_peptide_type(...) } assign_peptide_type <- function(data, aa_before = aa_before, last_aa = last_aa, aa_after = aa_after) { data %>% dplyr::mutate(N_term_tryp = dplyr::if_else({{ aa_before }} == "" | {{ aa_before }} == "K" | {{ aa_before }} == "R", TRUE, FALSE )) %>% dplyr::mutate(C_term_tryp = dplyr::if_else({{ last_aa }} == "K" | {{ last_aa }} == "R" | {{ aa_after }} == "", TRUE, FALSE )) %>% dplyr::mutate(pep_type = dplyr::case_when( .data$N_term_tryp + .data$C_term_tryp == 2 ~ "fully-tryptic", .data$N_term_tryp + .data$C_term_tryp == 1 ~ "semi-tryptic", .data$N_term_tryp + .data$C_term_tryp == 0 ~ "non-tryptic" )) %>% dplyr::select(-.data$N_term_tryp, -.data$C_term_tryp) }
.DollarNames.rga <- function(x, pattern) { grep(pattern, getRefClass(class(x))$methods(), value = TRUE) }
new_ptvapi_tibble <- function(response, parsed) { assertthat::assert_that(is.data.frame(parsed)) ptvapi_tibble <- tibble::new_tibble( parsed, nrow = nrow(parsed), class = "ptvapi", request = response$request, retrieved = response$retrieved, status_code = response$status_code, content = response$content ) tibble::validate_tibble(ptvapi_tibble) ptvapi_tibble } print.ptvapi <- function(x, ...) { if (!is.null(attr(x, "request"))) { cat("Request:", attr(x, "request"), "\n") } if (!is.null(attr(x, "retrieved"))) { cat("Retrieved:", attr(x, "retrieved"), "\n") } if (!is.null(attr(x, "status_code"))) { cat("Status code:", attr(x, "status_code"), "\n") } NextMethod() }
render <- function(statistic, ..., format, statDigits=4, sigDigits=4, pLargeCutoff=0.05, pSmallCutoff=1.0e-5) { UseMethod('render') } get_render_args <- function(args, strict, stat, fnname) { res <- list( statDigits=4, sigDigits=4, pLargeCutoff=0.05, pSmallCutoff=1.0e-5 ) for(ni in names(res)) { if(ni %in% names(stat)) { res[[ni]] <- stat[[ni]] } if(ni %in% names(args)) { res[[ni]] <- args[[ni]] args[[ni]] <- NULL } } if(!("format" %in% names(res))) { if("format" %in% names(args)) { res$format <- args$format args$format <- NULL } else if("format" %in% names(stat)) { res$format <- stat$format } else { res$format <- getRenderingFormat() } } if(!isTRUE(res$format %in% formats)) { res$format <- "ascii" } if(strict) { if(length(args)>0) { stop(paste("unexpected arguments", fnname)) } } res } render.sigr_significance <- function(statistic, ..., format, statDigits=4, sigDigits=4, pLargeCutoff=0.05, pSmallCutoff=1.0e-5) { wrapr::stop_if_dot_args(substitute(list(...)), "sigr::render.sigr_significance") sig <- statistic$significance symbol <- statistic$symbol if (missing(format) || is.null(format)) { format <- getRenderingFormat() } if(!isTRUE(format %in% formats)) { format <- "ascii" } fsyms <- syms[format,] pString <- paste0(fsyms['startI'],symbol,fsyms['endI']) if(is.na(sig)||is.infinite(sig)||is.nan(sig)) { pString <- paste0(pString,fsyms['eq'],'n.a.') } else if(sig>=pLargeCutoff) { pString <- paste0(pString,fsyms['eq'],'n.s.') } else { sigStr <- paste0('%.',sigDigits,'g') if(sig<pSmallCutoff) { pString <- paste0(pString,fsyms['lt'],sprintf(sigStr,pSmallCutoff)) } else { pString <- paste0(pString,fsyms['eq'],sprintf(sigStr,sig)) } } pString } as.character.sigr_statistic <- function(x, ...) { render_args <- get_render_args(list(...), TRUE, x, "sigr::as.character.sigr_statistic") render(x, format = render_args$format, statDigits = render_args$statDigits, sigDigits = render_args$sigDigits, pLargeCutoff = render_args$pLargeCutoff, pSmallCutoff = render_args$pSmallCutoff) } format.sigr_statistic <- function(x, ...) { render_args <- get_render_args(list(...), TRUE, x, "sigr::format.sigr_statistic") render(x, format = render_args$format, statDigits = render_args$statDigits, sigDigits = render_args$sigDigits, pLargeCutoff = render_args$pLargeCutoff, pSmallCutoff = render_args$pSmallCutoff) } print.sigr_statistic <- function(x, ...) { render_args <- get_render_args(list(...), FALSE, x, "sigr::print.sigr_statistic") print(render(x, format = render_args$format, statDigits = render_args$statDigits, sigDigits = render_args$sigDigits, pLargeCutoff = render_args$pLargeCutoff, pSmallCutoff = render_args$pSmallCutoff), ...) } wrapSignificance <- function(significance, symbol='p') { r <- list(significance=significance, symbol=symbol) class(r) <- c('sigr_significance', 'sigr_statistic') r }
ptuvn <- function(x, mean, sd, lower, upper){ result <- (stats::pnorm(x,mean,sd)- stats::pnorm(lower,mean,sd))/(stats::pnorm(upper,mean,sd) - stats::pnorm(lower,mean,sd)) result[x <= lower] <- 0 ; result[x >= upper] <- 1 result }
kronecker_list <- function(L){ isvecORmat <- function(x){is.matrix(x) || is.vector(x)} stopifnot(all(unlist(lapply(L,isvecORmat)))) retmat <- L[[1]] for(i in 2:length(L)){ retmat <- kronecker(retmat,L[[i]]) } retmat } ttm<-function(tnsr,mat,m=NULL){ stopifnot(is.matrix(mat)) if(is.null(m)) stop("m must be specified") mat_dims <- dim(mat) modes_in <- tnsr@modes stopifnot(modes_in[m]==mat_dims[2]) modes_out <- modes_in modes_out[m] <- mat_dims[1] tnsr_m = unfold(tnsr,row_idx = m, col_idx = (1:tnsr@num_modes)[-m])@data retarr_m <- mat%*%tnsr_m fold(retarr_m, row_idx = m, col_idx = (1:tnsr@num_modes)[-m], modes = modes_out) } ttl<-function(tnsr,list_mat,ms=NULL){ if(is.null(ms)||!is.vector(ms)) stop ("m modes must be specified as a vector") if(length(ms)!=length(list_mat)) stop("m modes length does not match list_mat length") num_mats <- length(list_mat) if(length(unique(ms))!=num_mats) warning("consider pre-multiplying matrices for the same m for speed") mat_nrows <- vector("list", num_mats) mat_ncols <- vector("list", num_mats) for(i in 1:num_mats){ mat <- list_mat[[i]] m <- ms[i] mat_dims <- dim(mat) modes_in <- tnsr@modes stopifnot(modes_in[m]==mat_dims[2]) modes_out <- modes_in modes_out[m] <- mat_dims[1] tnsr_m = unfold(tnsr,row_idx = m, col_idx = (1:tnsr@num_modes)[-m])@data retarr_m <- mat%*%tnsr_m tnsr = fold(retarr_m, row_idx = m, col_idx = (1:tnsr@num_modes)[-m], modes = modes_out) } tnsr }
.proctime00 <- proc.time() library(utils) options(digits = 5) options(show.signif.stars = FALSE) SweaveTeX <- function(file, ...) { if(!file.exists(file)) stop("File", file, "does not exist in", getwd()) texF <- sub("\\.[RSrs]nw$", ".tex", file) Sweave(file, ...) if(!file.exists(texF)) stop("File", texF, "does not exist in", getwd()) readLines(texF) } p0 <- paste0 latexEnv <- function(lines, name) { stopifnot(is.character(lines), is.character(name), length(lines) >= 2, length(name) == 1) beg <- p0("\\begin{",name,"}") end <- p0("\\end{",name,"}") i <- grep(beg, lines, fixed=TRUE) j <- grep(end, lines, fixed=TRUE) if((n <- length(i)) != length(j)) stop(sprintf("different number of %s / %s", beg,end)) if(any(j-1 < i+1)) stop(sprintf("positionally mismatched %s / %s", beg,end)) lapply(mapply(seq, i+1,j-1, SIMPLIFY=FALSE), function(ind) lines[ind]) } t1 <- SweaveTeX("swv-keepSrc-1.Rnw") if(FALSE) writeLines(t1) inp <- latexEnv(t1, "Sinput") out <- latexEnv(t1, "Soutput") stopifnot(length(inp) == 5, grepl(" length(out) == 1, any(grepl("\\includegraphics", t1))) t2 <- SweaveTeX("keepsource.Rnw") comml <- grep(" stopifnot(length(comml) == 2, grepl("initial comment line", comml[1]), grepl("last comment", comml[2])) Sweave("customgraphics.Rnw") Sweave(f <- "Sexpr-verb-ex.Rnw") require(tools) texi2pdf(sub("Rnw$","tex", f)) tf <- textConnection("RdTeX", "w") Rd2latex("Sexpr-hide-empty.Rd", tf, stages="build") tex <- textConnectionValue(tf); close(tf); rm(tf) (H2end <- tex[grep("^Hello", tex):length(tex)]) stopifnot((n <- length(H2end)) <= 4, H2end[-c(1L,n)] == "") cat('Time elapsed: ', proc.time() - .proctime00,'\n')
groupMedians <- function(variables, group, na.rm=FALSE) { verify_Xy = my_verify(variables, group, na.rm=na.rm) X = verify_Xy$X y = verify_Xy$y ng = nlevels(y) Meds = matrix(0, ncol(X), ng) for (j in 1:ncol(X)) { Meds[j,] = tapply(X[,j], y, FUN=median, na.rm=na.rm) } if (is.null(colnames(X))) { rownames(Meds) = paste("X", 1:ncol(X), sep="") } else { rownames(Meds) = colnames(X) } colnames(Meds) = levels(y) Meds }
hatvalues.CountsEPPM <- function (model, ...) { x <- model$covariates.matrix.mean if (NCOL(x) < 1L) return(structure(rep.int(0, NROW(x)), .Names = rownames(x))) if (is.null(model$offset$mean)) { offset.mean <- rep(0, NROW(x)) } wts <- weights(model$model) if (is.null(wts)) { wts <- rep(1, NROW(x)) } beta <- model$coefficients$mean.est[1:ncol(x)] eta <- as.vector(x %*% beta + offset.mean) vone <- rep(1,length(eta)) mean <- attr(model$link, which="mean")$linkinv(eta) if (model$model.type=="mean only") { scale.factor <- matrix(rep.int(1, NROW(x)), ncol=1) } else { z <- model$covariates.matrix.scalef if (is.null(model$offset$scalef)) { offset.scalef <- rep(0, NROW(z)) } gamma <- model$coefficients$scalef.est[1:ncol(z)] scale.factor_eta <- as.vector(z %*% gamma + offset.scalef) scale.factor <- exp(scale.factor_eta) } vvariance <- mean*scale.factor dmu <- attr(model$link, which="mean")$mu.eta(eta) if (model$data.type==TRUE) { wk.mean <- mean wk.wts <- wts wk.vvariance <- vvariance wk.dmu <- dmu wk.x <- x } else { wks <- length(x[1,]) nend <- 0 for (ilist in 1:length(model$list.data)) { for ( i in 1:length(model$list.data[[ilist]])) { nt <- model$list.data[[ilist]][i] if (nt>0) { if (nend==0) { wk.x <- as.vector(c(rep(x[ilist,],nt))) wk.mean <- c(rep(mean[ilist],nt)) wk.wts <- c(rep(wts[ilist],nt)) wk.vvariance <- c(rep(vvariance[ilist],nt)) wk.dmu <- c(rep(dmu[ilist],nt)) } else { wk.x <- append(wk.x, as.vector(c(rep(x[ilist,],nt))), after=(nend*wks)) wk.mean <- append(wk.mean, c(rep(mean[ilist],nt)), after=nend) wk.wts <- append(wk.wts, c(rep(wts[ilist],nt)), after=nend) wk.vvariance <- append(wk.vvariance, c(rep(vvariance[ilist],nt)), after=nend) wk.dmu <- append(wk.dmu, c(rep(dmu[ilist],nt)), after=nend) } nend <- nend + nt } } } wk.x <- t(matrix(wk.x, nrow=wks)) } wkm <- sqrt(as.vector(wk.wts * wk.dmu * wk.dmu / wk.vvariance)) * wk.x xwx1 <- chol2inv(qr.R(qr(wkm))) as.vector(diag(wkm %*% xwx1 %*% t(wkm))) }
tally( ~ Longevity, margin = TRUE, data = MammalLongevity)
detfct.fit <- function(ddfobj, optim.options, bounds, misc.options){ showit <- misc.options$showit silent <- misc.options$silent epsilon <- sqrt(.Machine$double.eps) misc.options$optim.history <- rep(NA, length(getpar(ddfobj))+2) iter <- 0 metaiter <- 0 if(is.null(ddfobj$adjustment) | ddfobj$type=="unif" | misc.options$mono | misc.options$nofit){ if(misc.options$mono & ddfobj$type!="unif"){ save.mono <- misc.options$mono save.mono.strict <- misc.options$mono.strict misc.options$mono <- FALSE misc.options$mono.strict <- FALSE lt <- detfct.fit.opt(ddfobj, optim.options, bounds, misc.options, fitting="key") misc.options$mono <- save.mono misc.options$mono.strict <- save.mono.strict ddfobj <- assign.par(ddfobj, lt$par) if(check.bounds(lt, bounds$lower, bounds$upper, ddfobj, showit, bounds$setlower, bounds$setupper)){ bounds <- setbounds(rep(NA, length(lt$par)), rep(NA, length(lt$par)), lt$par, ddfobj) } } lt <- detfct.fit.opt(ddfobj, optim.options, bounds, misc.options) if(misc.options$mono){ hess <- numDeriv::hessian(flnl, lt$par, ddfobj=ddfobj, misc.options=misc.options) attr(lt, "details") <- list(nhatend=hess) } }else{ initialvalues <- getpar(ddfobj) if(showit>=2) cat("DEBUG: starting to cycle the optimisation...\n") while(iter < misc.options$maxiter){ metaiter <- 0 for(fitting in c("adjust", "key", "all")){ if(fitting == "adjust" | fitting == "key"){ refit.save <- misc.options$refit misc.options$refit <- FALSE } if(showit >= 2) { cat("DEBUG:", fitting, "iteration ", iter, ".", metaiter, "\n") cat("DEBUG: initial values =", paste(round(initialvalues, 7), collapse=", "), "\n") } lt <- try(detfct.fit.opt(ddfobj, optim.options, bounds, misc.options, fitting=fitting), silent = silent) metaiter <- metaiter + 1 if(all(class(lt)=="try-error")){ if(showit>=2){ cat("DEBUG: iteration", iter, ", fitting", fitting, "failed.\n") } if(fitting=="all"){ stop("Fitting failed! Try again with better initial values.\n") } }else{ bounds <- lt$bounds if(showit >= 2){ cat("DEBUG: iteration", paste(iter, metaiter, sep="."), ":\n Converge =", lt$converge, "\n lnl =", lt$value, "\n parameters =", paste(round(lt$par, 7), collapse=", "), "\n") } if(any(is.na(lt$par))){ lt$par[is.na(lt$par)] <- initialvalues[is.na(lt$par)] } optim.history <- lt$optim.history misc.options$optim.history <- optim.history oh <- optim.history[!is.na(optim.history[,1]) & optim.history[, 1]==0, ] if(fitting=="all" & !is.null(nrow(oh))){ initialvalues <- oh[which.max(oh[2]), -(1:2)] ddfobj <- assign.par(ddfobj, initialvalues) }else{ ddfobj <- assign.par(ddfobj, lt$par) initialvalues <- getpar(ddfobj) } } misc.options$refit <- refit.save if(fitting == "all" & lt$conv==0) break } if(lt$conv==0) break iter <- iter + 1 } if(iter > misc.options$maxiter){ warning("Maximum iterations exceeded!", iter, ">", misc.options$maxiter, "\n") } } if(showit >= 1){ cat("\nDEBUG: Convergence!", "\n Iteration ", paste(iter, metaiter, sep="."), "\n Converge =", lt$converge, "\n lnl =", lt$value, "\n parameters =", paste(round(lt$par, 7), collapse=", "), "\n") } lt$optim.history <- lt$optim.history[-1, ] return(lt) }
meanTranspose <- function(x,tol=1e-6) { n = nrow(x) p = ncol(x) if(sum(is.na(x))==0) { nu = colMeans(x) xnew = scale(x,center=TRUE,scale=FALSE) mu = rowMeans(xnew) xnew = t(scale(t(xnew),center=TRUE,scale=FALSE)) } else { ind = 1 xnew = x mut = nut = 0 while(abs(ind)>tol) { mu = rowMeans(xnew,na.rm=TRUE) xnew = xnew - mu nu = colMeans(xnew,na.rm=TRUE) xnew = t(t(xnew) - nu) ind = sum(mu) + sum(nu) mut = mut + mu nut = nut + nu } xnew[is.na(x)] = 0 mu = mut nu = nut } M = t(t((matrix(0,n,p) + mu)) + nu) return(list(x=x,xcen=xnew,mu=mu,nu=nu,M=M)) }
gglasso <- function(x, y, group = NULL, loss = c("ls", "logit", "sqsvm", "hsvm","wls"), nlambda = 100, lambda.factor = ifelse(nobs < nvars, 0.05, 0.001), lambda = NULL, pf = sqrt(bs), weight = NULL, dfmax = as.integer(max(group)) + 1, pmax = min(dfmax * 1.2, as.integer(max(group))), eps = 1e-08, maxit = 3e+08, delta,intercept=TRUE) { this.call <- match.call() loss <- match.arg(loss) if (!is.matrix(x)) stop("x has to be a matrix") if (any(is.na(x))) stop("Missing values in x not allowed!") y <- drop(y) np <- dim(x) nobs <- as.integer(np[1]) nvars <- as.integer(np[2]) vnames <- colnames(x) if (is.null(vnames)) vnames <- paste("V", seq(nvars), sep = "") if (length(y) != nobs) stop("x and y have different number of rows") if (!is.numeric(y)) stop("The response y must be numeric. Factors must be converted to numeric") c1 <- loss %in% c("logit", "sqsvm", "hsvm") c2 <- any(y %in% c(-1, 1) == FALSE) if (c1 && c2) stop("Classification method requires the response y to be in {-1,1}") if (loss=="wls" & !is.matrix(weight)) stop("User must specify weight matrix for (loss='wls')") if (is.null(group)) { group <- 1:nvars } else if (length(group) != nvars) stop("group length does not match the number of predictors in x") bn <- as.integer(max(group)) bs <- as.integer(as.numeric(table(group))) if (!identical(as.integer(sort(unique(group))), as.integer(1:bn))) stop("Groups must be consecutively numbered 1,2,3,...") ix <- rep(NA, bn) iy <- rep(NA, bn) j <- 1 for (g in 1:bn) { ix[g] <- j iy[g] <- j + bs[g] - 1 j <- j + bs[g] } ix <- as.integer(ix) iy <- as.integer(iy) group <- as.integer(group) if (missing(delta)) delta <- 1 if (delta < 0) stop("delta must be non-negtive") delta <- as.double(delta) if (length(pf) != bn) stop("The size of group-lasso penalty factor must be same as the number of groups") maxit <- as.integer(maxit) pf <- as.double(pf) eps <- as.double(eps) dfmax <- as.integer(dfmax) pmax <- as.integer(pmax) nlam <- as.integer(nlambda) if (is.null(lambda)) { if (lambda.factor >= 1) stop("lambda.factor should be less than 1") flmin <- as.double(lambda.factor) ulam <- double(1) } else { flmin <- as.double(1) if (any(lambda < 0)) stop("lambdas should be non-negative") ulam <- as.double(rev(sort(lambda))) nlam <- as.integer(length(lambda)) } intr <- as.integer(intercept) fit <- switch(loss, ls = ls(bn, bs, ix, iy, nobs, nvars, x, y, pf, dfmax, pmax, nlam, flmin, ulam, eps, maxit, vnames, group, intr), logit = logit(bn, bs, ix, iy, nobs, nvars, x, y, pf, dfmax, pmax, nlam, flmin, ulam, eps, maxit, vnames, group, intr), sqsvm = sqsvm(bn, bs, ix, iy, nobs, nvars, x, y, pf, dfmax, pmax, nlam, flmin, ulam, eps, maxit, vnames, group, intr), hsvm = hsvm(delta, bn, bs, ix, iy, nobs, nvars, x, y, pf, dfmax, pmax, nlam, flmin, ulam, eps, maxit, vnames, group, intr), wls = wls(bn, bs, ix, iy, nobs, nvars, x, y, pf, weight, dfmax, pmax, nlam, flmin, ulam, eps, maxit, vnames, group, intr) ) if (is.null(lambda)) fit$lambda <- lamfix(fit$lambda) fit$call <- this.call class(fit) <- c("gglasso", class(fit)) fit }
pgfpoissonpascal <- function(s,params) { m<-s[abs(s)>1] if (length(m)>0) warning("At least one element of the vector s are out of interval [-1,1]") if (length(params)<3) stop("At least one value in params is missing") if (length(params)>3) stop("The length of params is 3") theta<-params[1] p<-params[2] k<-params[3] if (theta<=0) stop ("Parameter theta must be positive") if (p<=0) stop ("Parameter lambda must be positive") if (k<=0) stop ("Parameter k must be positive") exp(theta*((1+p-p*s)^(-k)-1)) }
setOldClass(c("tbl_df", "tbl", "data.frame")) setClass( "sample_sets", slots = c( sample_sets = "tbl_df", samples = "tbl_df", demographics = "tbl_df", cohorts = "tbl_df" ) ) sample_sets <- function( sample_sets = s4pss_sample_sets_tbl(), samples = s4pss_samples_tbl(), demographics = s4pss_demographics_tbl(), cohorts = s4pss_pgs_cohorts_tbl()) { s4_sample_sets <- methods::new( "sample_sets", sample_sets = sample_sets, samples = samples, demographics = demographics, cohorts = cohorts ) return(s4_sample_sets) } s4pss_sample_sets_tbl <- function(pss_id = character()) { tbl <- tibble::tibble(pss_id = pss_id) return(tbl) } s4pss_samples_tbl <- function(pss_id = character(), sample_id = integer(), stage = character(), sample_size = integer(), sample_cases = integer(), sample_controls = integer(), sample_percent_male = double(), phenotype_description = character(), ancestry_category = character(), ancestry = character(), country = character(), ancestry_additional_description = character(), study_id = character(), pubmed_id = character(), cohorts_additional_description = character()) { tbl <- tibble::tibble( pss_id = pss_id, sample_id = sample_id, stage = stage, sample_size = sample_size, sample_cases = sample_cases, sample_controls = sample_controls, sample_percent_male = sample_percent_male, phenotype_description = phenotype_description, ancestry_category = ancestry_category, ancestry = ancestry, country = country, ancestry_additional_description = ancestry_additional_description, study_id = study_id, pubmed_id = pubmed_id, cohorts_additional_description = cohorts_additional_description ) return(tbl) } s4pss_demographics_tbl <- function(pss_id = character(), sample_id = integer(), variable = character(), estimate_type = character(), estimate = double(), unit = character(), variability_type = character(), variability = double(), interval_type = character(), interval_lower = double(), interval_upper = double()) { tbl <- tibble::tibble( pss_id = pss_id, sample_id = sample_id, variable = variable, estimate_type = estimate_type, estimate = estimate, unit = unit, variability_type = variability_type, variability = variability, interval_type = interval_type, interval_lower = interval_lower, interval_upper = interval_upper ) return(tbl) } s4pss_pgs_cohorts_tbl <- function(pss_id = character(), sample_id = integer(), cohort_symbol = character(), cohort_name = character()) { tbl <- tibble::tibble( pss_id = pss_id, sample_id = sample_id, cohort_symbol = cohort_symbol, cohort_name = cohort_name ) return(tbl) } coerce_to_s4_sample_sets <- function(lst_tbl = NULL) { if (is.null(lst_tbl)) { s4_sample_sets <- sample_sets() return(s4_sample_sets) } s4_sample_sets <- sample_sets( sample_sets = lst_tbl$sample_sets, samples = lst_tbl$samples, demographics = lst_tbl$demographics, cohorts = lst_tbl$cohorts ) s4_sample_sets@sample_sets <- drop_metadata_cols(s4_sample_sets@sample_sets) s4_sample_sets@samples <- drop_metadata_cols(s4_sample_sets@samples) s4_sample_sets@demographics <- drop_metadata_cols(s4_sample_sets@demographics) s4_sample_sets@cohorts <- drop_metadata_cols(s4_sample_sets@cohorts) return(s4_sample_sets) }
selectSampleSystematic <- function(frame, outstrata, sortvariable = NULL, writeFiles = FALSE, verbatim = TRUE) { strata.sample.systematic <- function(frame, strata, nh, sortvariable, repl) { selected <- NULL WEIGHTS <- NULL j <- 0 for (i in (c(unique(as.numeric(frame$STRATO))))) { j <- j+1 framestrat <- frame[frame[,strata] == i,] if (!is.null(sortvariable)) { framestrat <- framestrat[order(framestrat[,c(sortvariable)]),] } step <- nrow(framestrat) / nh[j] start <- sample(step,1) s <- round(seq(start,nrow(framestrat),step),0) if (length(s) < nh[j]) { s <- c(1,s) } sel <- framestrat$ID[s] wgt <- rep(nrow(framestrat)/length(sel),length(sel)) selected <- c(selected,sel) WEIGHTS <- c(WEIGHTS,wgt) } attr(selected, "WEIGHTS") <- WEIGHTS selected } colnames(frame) <- toupper(colnames(frame)) if(is.factor(frame$ID)) frame$ID <- as.character(frame$ID) colnames(outstrata) <- toupper(colnames(outstrata)) if (!is.null(sortvariable)) { sortvariable <- toupper(sortvariable) if (!(sortvariable %in% colnames(frame))) { cat("\n Sort variable not in frame") stop } } outstrata$SOLUZ <- round(outstrata$SOLUZ) frame$DOMAINVALUE <- factor(frame$DOMAINVALUE) numdom <- length(levels(frame$DOMAINVALUE)) samptot <- NULL chktot <- NULL if (numdom > 1) { for (d in (levels(frame$DOMAINVALUE))) { domframe <- frame[frame$DOMAINVALUE == d, ] domstrata <- outstrata[outstrata$DOM1 == d, ] strataord <- domstrata[order(as.numeric(domstrata$STRATO)), ] lista <- domframe lista$STRATO <- lista$LABEL listaord <- lista[order(as.numeric(lista$STRATO)), ] s <- strata.sample.systematic(listaord, c("STRATO"), strataord$SOLUZ, sortvariable, repl = FALSE) samp <- data.frame(listaord[listaord$ID %in% s, ], WEIGHTS = attr(s, "WEIGHTS"), stringsAsFactors = TRUE) samptot <- rbind(samptot, samp) chk <- data.frame(DOMAINVALUE = d, STRATO = strataord$STRATO, Nh_frame = as.vector(table(listaord$STRATO)), Nh_strata = strataord$N, planned_units = strataord$SOLUZ, selected_units = as.vector(table(samp$STRATO)), sum_of_wgts = tapply(samp$WEIGHTS, samp$STRATO, sum), stringsAsFactors = TRUE) chktot <- rbind(chktot, chk) } } if (numdom == 1) { domframe <- frame domstrata <- outstrata strataord <- domstrata[order(as.numeric(domstrata$STRATO)), ] lista <- domframe lista$STRATO <- lista$LABEL listaord <- lista[order(lista$STRATO), ] s <- strata.sample.systematic(listaord, c("STRATO"), strataord$SOLUZ, sortvariable, repl = FALSE) samp <- data.frame(listaord[listaord$ID %in% s, ], WEIGHTS = attr(s, "WEIGHTS"), stringsAsFactors = TRUE) samptot <- rbind(samptot, samp) chk <- data.frame(DOMAINVALUE = strataord$DOM1, STRATO = strataord$STRATO, Nh_frame = as.vector(table(listaord$STRATO)), Nh_strata = strataord$N, planned_units = strataord$SOLUZ, selected_units = as.vector(table(samp$STRATO)), sum_of_wgts = tapply(samp$WEIGHTS, samp$STRATO, sum), stringsAsFactors = TRUE) chktot <- rbind(chktot, chk) } colnames(samptot) <- toupper(colnames(samptot)) colnames(chktot) <- toupper(colnames(chktot)) cens <- sum((chktot$NH_STRATA == chktot$PLANNED_UNITS) == TRUE) cens.units <- sum(chktot$PLANNED_UNITS[chktot$NH_STRATA == chktot$PLANNED_UNITS]) if (verbatim == TRUE) { cat("\n*** Sample has been drawn successfully ***") cat("\n", nrow(samptot), " units have been selected from ", nrow(outstrata), " strata\n") if (cens > 0) { cat("\n==> There have been ", cens, " take-all strata ") cat("\nfrom which have been selected ", cens.units, "units\n") } } if (writeFiles == TRUE) write.table(samptot, "sample.csv", sep = ",", row.names = FALSE, col.names = TRUE, quote = FALSE) if (writeFiles == TRUE) write.table(chktot, "sampling_check.csv", sep = ",", row.names = FALSE, col.names = TRUE, quote = FALSE) outstrata$FPC <- outstrata$SOLUZ/outstrata$N fpc <- outstrata[, c("DOM1","STRATO","FPC")] samptot <- merge(samptot, fpc, by.x = c("DOMAINVALUE","STRATO"),by.y=c("DOM1","STRATO"),all.x=TRUE) return(samptot) }
context("Drop constant cols") test_that("Error handling", { x <- "wontwork" expect_error(drop_constant_cols(x), regexp = "must be a data.(table|frame)") expect_warning(drop_constant_cols(data.frame(x = 1:5), copy = FALSE), regexp = "copy") }) test_that("No constant cols", { DT <- data.table(x = 1:5, y = 11:15) drop_constant_cols(DT) expect_equal(names(DT), c("x", "y")) }) test_that("Standard use", { DT <- data.table(x = c(1, 1), y = c(1, 2)) drop_constant_cols(DT) expect_equal(names(DT), c("y")) }) test_that("Standard use, copying", { DT <- data.table(x = c(1, 1), y = c(1, 2)) expect_equal(names(drop_constant_cols(DT, copy = TRUE)), c("y")) expect_equal(names(DT), c("x", "y")) }) test_that("No constant cols, data frame", { DFi <- data.frame(x = 1:5, y = 11:15) DFe <- data.frame(x = 1:5, y = 11:15) expect_identical(drop_constant_cols(DFi, copy = TRUE), DFe) }) test_that("Standard use, data frame, one col returned", { DFi <- data.frame(x = rep_len(1, 5), y = 11:15) expect_equal(names(drop_constant_cols(DFi, copy = TRUE)), "y") expect_true(is.data.frame(drop_constant_cols(DFi, copy = TRUE))) }) test_that("Indistinct names", { DT <- data.table(a = c(2, 3), j = c(1, 1), x = c(1, 1), y = c(1, 2)) setnames(DT, "x", "y") drop_constant_cols(DT) expect_equal(ncol(DT), 2L) expect_equal(names(DT), c("a", "y")) expect_equal(DT[["y"]], c(1, 2)) }) test_that("All columns dropped", { DFi <- data.frame(x = rep_len(1, 5), y = rep_len("1", 5)) expect_equal(nrow(drop_constant_cols(DFi)), nrow(DFi)) expect_equal(ncol(drop_constant_cols(DFi)), 0) DT <- as.data.table(DFi) drop_constant_cols(DT) expect_equal(nrow(DT), 0) expect_equal(ncol(DT), 0) })
void_snps_stats <- function(x) { a <- names(x)[ !(names(x) %in% snpstatnames) ] x[,a] } void_ped_stats <- function(x) { a <- names(x)[ !(names(x) %in% pedstatnames) ] x[,a] } setMethod("[", signature(x="bed.matrix",i="numeric",j="missing", drop="missing"), function( x, i, j) { if(any(i <= 0)) i <- (1:nrow(x))[i] x@bed <- .Call('gg_extract_inds_indices', x@bed, i) x@ped <- x@ped[i,] x@snps <- void_snps_stats(x@snps) if(getOption("gaston.auto.set.stats", TRUE)) x <- set.stats.snps(x, verbose = FALSE) x } ); setMethod("[", signature(x="bed.matrix",i="logical",j="missing", drop="missing"), function( x, i, j) { if(any(is.na(i))) stop("NAs not allowed") x@bed <- .Call('gg_extract_inds_bool', x@bed, i) x@ped <- x@ped[i,] x@snps <- void_snps_stats(x@snps) if(getOption("gaston.auto.set.stats", TRUE)) x <- set.stats.snps(x, verbose = FALSE) x } ); setMethod("[", signature(x="bed.matrix",i="missing",j="numeric", drop="missing"), function( x, i, j) { if(any(j <= 0)) j <- (1:ncol(x))[j] x@bed <- .Call('gg_extract_snps_indices', x@bed, j) x@snps <- x@snps[j,] x@p <- x@p[j] x@mu <- x@mu[j] x@sigma <- x@sigma[j] x@ped <- void_ped_stats(x@ped) if(getOption("gaston.auto.set.stats", TRUE)) x <- set.stats.ped(x, verbose = FALSE) x } ); setMethod("[", signature(x="bed.matrix",i="missing",j="logical", drop="missing"), function( x, i, j) { if(any(is.na(j))) stop("NAs not allowed") x@bed <- .Call('gg_extract_snps_bool', x@bed, j) x@snps <- x@snps[j,] x@p <- x@p[j] x@mu <- x@mu[j] x@sigma <- x@sigma[j] x@ped <- void_ped_stats(x@ped) if(getOption("gaston.auto.set.stats", TRUE)) x <- set.stats.ped(x, verbose = FALSE) x } ); setMethod("[", signature(x="bed.matrix",i="logical",j="logical", drop="missing"), function( x, i, j) { if(any(is.na(j))) stop("NAs not allowed") x@bed <- .Call('gg_extract_snps_bool', x@bed, j) x@snps <- x@snps[j,] x@p <- x@p[j] x@mu <- x@mu[j] x@sigma <- x@sigma[j] if(any(is.na(i))) stop("NAs not allowed") x@bed <- .Call('gg_extract_inds_bool', x@bed, i) x@ped <- x@ped[i,] x@ped <- void_ped_stats(x@ped) x@snps <- void_snps_stats(x@snps) if(getOption("gaston.auto.set.stats", TRUE)) x <- set.stats(x, verbose = FALSE) x } ); setMethod("[", signature(x="bed.matrix",i="logical",j="numeric", drop="missing"), function( x, i, j) { if(any(j <= 0)) j <- (1:ncol(x))[j] x@bed <- .Call('gg_extract_snps_indices', x@bed, j) x@snps <- x@snps[j,] x@p <- x@p[j] x@mu <- x@mu[j] x@sigma <- x@sigma[j] if(any(is.na(i))) stop("NAs not allowed") x@bed <- .Call('gg_extract_inds_bool', x@bed, i) x@ped <- x@ped[i,] x@ped <- void_ped_stats(x@ped) x@snps <- void_snps_stats(x@snps) if(getOption("gaston.auto.set.stats", TRUE)) x <- set.stats(x, verbose = FALSE) x } ); setMethod("[", signature(x="bed.matrix",i="numeric",j="logical", drop="missing"), function( x, i, j) { if(any(is.na(j))) stop("NAs not allowed") x@bed <- .Call('gg_extract_snps_bool', x@bed, j) x@snps <- x@snps[j,] x@p <- x@p[j] x@mu <- x@mu[j] x@sigma <- x@sigma[j] if(any(i <= 0)) i <- (1:nrow(x))[i] x@bed <- .Call('gg_extract_inds_indices', x@bed, i) x@ped <- x@ped[i,] x@ped <- void_ped_stats(x@ped) x@snps <- void_snps_stats(x@snps) if(getOption("gaston.auto.set.stats", TRUE)) x <- set.stats(x, verbose = FALSE) x } ); setMethod("[", signature(x="bed.matrix",i="numeric",j="numeric", drop="missing"), function( x, i, j) { if(any(j <= 0)) j <- (1:ncol(x))[j] x@bed <- .Call('gg_extract_snps_indices', x@bed, j) x@snps <- x@snps[j,] x@p <- x@p[j] x@mu <- x@mu[j] x@sigma <- x@sigma[j] if(any(i <= 0)) i <- (1:nrow(x))[i] x@bed <- .Call('gg_extract_inds_indices', x@bed, i) x@ped <- x@ped[i,] x@ped <- void_ped_stats(x@ped) x@snps <- void_snps_stats(x@snps) if(getOption("gaston.auto.set.stats", TRUE)) x <- set.stats(x, verbose = FALSE) x } );
spread_all <- function(.x, recursive = TRUE, sep = ".") { if (!is.tbl_json(.x)) .x <- as.tbl_json(.x) reserved_cols <- c("..id", "..name1", "..name2", "..type", "..value", "..suffix") assertthat::assert_that(!(any(reserved_cols %in% names(.x)))) if (nrow(.x) == 0) return(.x) unq_types <- .x %>% json_types("..type") %>% magrittr::extract2("..type") %>% unique if (!("object" %in% unq_types)) { warning("no JSON records are objects, returning .x") return(.x) } exist_cols <- names(.x) json <- json_get(.x) .x <- .x %>% dplyr::mutate(..id = seq_len(n())) y <- .x %>% gather_object("..name1") %>% json_types("..type") if (recursive) { while(any(y$..type == "object")) y <- dplyr::bind_rows( y %>% dplyr::filter(..type != "object"), recursive_gather(y, sep) ) } else { y <- y %>% dplyr::filter(..type != 'object') } key_freq <- y %>% dplyr::group_by(..id, ..name1) %>% dplyr::tally() while (any(key_freq$n > 1) || any(key_freq$..name1 %in% exist_cols)) { warning("results in duplicate column names, appending . y_dedupe <- y %>% dplyr::group_by(..id, ..name1) %>% dplyr::mutate(..suffix = 1L:n()) %>% dplyr::mutate(..suffix = ..suffix + ifelse(..name1 %in% exist_cols, 1L, 0L)) %>% dplyr::mutate(..suffix = ifelse(..suffix == 1L, "", paste0(".", ..suffix))) %>% dplyr::ungroup() %>% dplyr::mutate(..name1 = paste0(..name1, ..suffix)) %>% dplyr::select(-..suffix) y <- tbl_json(y_dedupe, json_get(y)) key_freq <- y %>% dplyr::group_by(..id, ..name1) %>% dplyr::tally() } name_order <- y %>% dplyr::filter(..type %in% c("string", "number", "logical", "null")) %>% magrittr::extract2("..name1") %>% unique y_string <- spread_type(y, "string", append_values_string) y_number <- spread_type(y, "number", append_values_number) y_logical <- spread_type(y, "logical", append_values_logical) z <- dplyr::as_tibble(.x) %>% dplyr::left_join(y_string, by = "..id") %>% dplyr::left_join(y_number, by = "..id") %>% dplyr::left_join(y_logical, by = "..id") all_null <- y %>% dplyr::group_by(..name1) %>% dplyr::summarize(all.null = all(..type == "null")) %>% dplyr::filter(all.null) if (nrow(all_null) > 0) { null_names <- all_null %>% magrittr::extract2("..name1") z[, null_names] <- NA } final_columns <- names(.x) %>% dplyr::setdiff(c("..id", "..JSON")) %>% c(name_order) z[, final_columns, drop = FALSE] %>% tbl_json(json) } recursive_gather <- function(.x, sep) { .x %>% dplyr::filter(..type == "object") %>% gather_object("..name2") %>% dplyr::mutate(..name1 = paste(..name1, ..name2, sep = sep)) %>% dplyr::select(-..type, -..name2) %>% json_types("..type") } spread_type <- function(.x, this.type, append.fun) { any_type <- any(.x$..type == this.type) if (!any_type) return(dplyr::tibble(..id = integer(0))) .x %>% dplyr::filter(..type == this.type) %>% append.fun("..value") %>% dplyr::as_tibble() %>% dplyr::select(..id, ..name1, ..value) %>% tidyr::spread(..name1, ..value) }
tokenize <- function(file, tokenizer = tokenizer_csv(), skip = 0, n_max = -1L) { ds <- datasource(file, skip = skip, skip_empty_rows = FALSE) tokenize_(ds, tokenizer, n_max) } NULL tokenizer_delim <- function(delim, quote = '"', na = "NA", quoted_na = TRUE, comment = "", trim_ws = TRUE, escape_double = TRUE, escape_backslash = FALSE, skip_empty_rows = TRUE) { structure( list( delim = delim, quote = quote, na = na, quoted_na = quoted_na, comment = comment, trim_ws = trim_ws, escape_double = escape_double, escape_backslash = escape_backslash, skip_empty_rows = skip_empty_rows ), class = "tokenizer_delim" ) } tokenizer_csv <- function(na = "NA", quoted_na = TRUE, quote = "\"", comment = "", trim_ws = TRUE, skip_empty_rows = TRUE) { tokenizer_delim( delim = ",", na = na, quoted_na = quoted_na, quote = quote, comment = comment, trim_ws = trim_ws, escape_double = TRUE, escape_backslash = FALSE, skip_empty_rows = skip_empty_rows ) } tokenizer_tsv <- function(na = "NA", quoted_na = TRUE, quote = "\"", comment = "", trim_ws = TRUE, skip_empty_rows = TRUE) { tokenizer_delim( delim = "\t", na = na, quoted_na = quoted_na, quote = quote, comment = comment, trim_ws = trim_ws, escape_double = TRUE, escape_backslash = FALSE, skip_empty_rows = skip_empty_rows ) } tokenizer_line <- function(na = character(), skip_empty_rows = TRUE) { structure(list(na = na, skip_empty_rows = skip_empty_rows), class = "tokenizer_line" ) } tokenizer_log <- function(trim_ws) { structure(list(trim_ws = trim_ws), class = "tokenizer_log") } tokenizer_fwf <- function(begin, end, na = "NA", comment = "", trim_ws = TRUE, skip_empty_rows = TRUE) { structure(list( begin = as.integer(begin), end = as.integer(end), na = na, comment = comment, trim_ws = trim_ws, skip_empty_rows = skip_empty_rows ), class = "tokenizer_fwf" ) } tokenizer_ws <- function(na = "NA", comment = "", skip_empty_rows = TRUE) { structure(list(na = na, comment = comment, skip_empty_rows = skip_empty_rows), class = "tokenizer_ws" ) }
library(dplyr) library(readr) library(magrittr) write_finemap_sumstats <- function(z, LD_file, n, k, prefix) { cfg = list(z=paste0(prefix,".z"), ld=LD_file, snp=paste0(prefix,".snp"), config=paste0(prefix,".config"), k=paste0(prefix,".k"), log=paste0(prefix,".log"), meta=paste0(prefix,".master")) write.table(z,cfg$z,quote=F,col.names=F) if (!is.null(k)) { write.table(t(k),cfg$k,quote=F,col.names=F,row.names=F) write("z;ld;snp;config;k;log;n-ind",file=cfg$meta) write(paste(cfg$z, cfg$ld, cfg$snp, cfg$config, cfg$k, cfg$log, n, sep=";"), file=cfg$meta,append=TRUE) } else { write("z;ld;snp;config;log;n-ind",file=cfg$meta) write(paste(cfg$z, cfg$ld, cfg$snp, cfg$config, cfg$log, n, sep=";"), file=cfg$meta,append=TRUE) } return(cfg) } run_finemap <- function(z, LD_file, n, k, args = "", prefix="data") { cfg = write_finemap_sumstats(z, LD_file, n, k, prefix) cmd = paste("finemap --sss --log", "--in-files", cfg$meta, args) dscrutils::run_cmd(cmd) snp = read.table(cfg$snp,header=TRUE,sep=" ") snp$snp = as.character(snp$snp) snp = rank_snp(snp) config = read.table(cfg$config,header=TRUE,sep=" ") ncausal = finemap_extract_ncausal(cfg$log) return(list(snp=snp, set=config, ncausal=ncausal)) } rank_snp <- function(snp) { snp <- arrange(snp, -snp_prob) %>% mutate( rank = seq(1, n()), snp_prob_cumsum = cumsum(snp_prob) / sum(snp_prob)) %>% select(rank, snp, snp_prob, snp_prob_cumsum, snp_log10bf) return(snp) } finemap_extract_ncausal <- function(logfile) { lines <- grep("->", readLines(logfile), value = TRUE) lines <- gsub("\\(|\\)|>", "", lines) splits <- strsplit(lines, "\\s+") tab <- data.frame( ncausal_num = sapply(splits, function(x) as.integer(x[2])), ncausal_prob = sapply(splits, function(x) as.double(x[4]))) tab <- mutate(tab, type = ifelse(duplicated(ncausal_num), "post", "prior")) return(tab) } finemap_mvar <- function(zscore, LD_file, n, k, args, prefix, parallel = FALSE) { if (is.null(dim(zscore))) { zscore = matrix(ncol=1,zscore) } single_core = function(r) run_finemap(zscore[,r], LD_file, n, k, args, paste0(prefix, '_condition_', r)) if (parallel) return(parallel::mclapply(1:ncol(zscore), function(r) single_core(r), mc.cores = min(8, ncol(zscore)))) else return(lapply(1:ncol(zscore), function(r) single_core(r))) } eval(parse(text=commandArgs(T))) dat = readRDS(input) sumstats = dat$sumstats N = nrow(dat$data$X) ld = tempfile(fileext = ".ld") write.table(cor(dat$data$X),ld,quote=F,col.names=F,row.names=F) posterior = finemap_mvar(sumstats[1,,] / sumstats[2,,], ld, N, k=NULL, args, prefix=tempfile(fileext = ".finemap")) saveRDS(posterior, paste0(output, '.rds'))
if (require(microbenchmark)) { stopifnot(identical( icd:::icd9_add_leading_zeroes_alt_rcpp(c("1", "E2", "V1", "E"), short_code = TRUE), icd:::icd9_add_leading_zeroes_rcpp(c("1", "E2", "V1", "E"), short_code = TRUE) )) bad_codes <- sample(c("E2", "V01", "1234", "12", "1", "E99", "E987", "V"), size = 1e4, replace = TRUE ) microbenchmark::microbenchmark( icd:::icd9_add_leading_zeroes_alt_rcpp(bad_codes, short_code = TRUE), icd:::icd9_add_leading_zeroes_rcpp(bad_codes, short_code = TRUE) ) }
if (compareVersion(paste(R.version$major, R.version$minor, sep=".") ,"2.9.0") < 0) { load(system.file(file.path("unitTestData", "regression.Rdata"), package="RevoIOQ")) } else if (compareVersion(paste(R.version$major, R.version$minor, sep="."), "2.10.1") < 0) { load(system.file(file.path("unitTestData", "regression_2.9.0.Rdata"), package="RevoIOQ")) } else if (compareVersion(paste(R.version$major, R.version$minor, sep="."), "2.14.1") < 0) { load(system.file(file.path("unitTestData", "regression_2.10.1.Rdata"), package="RevoIOQ")) } else if (compareVersion(paste(R.version$major, R.version$minor, sep="."), "2.15.2") < 0) { load(system.file(file.path("unitTestData", "regression_2.14.1.Rdata"), package="RevoIOQ")) } else if (compareVersion(paste(R.version$major, R.version$minor, sep="."), "3.0.1") < 0) { load(system.file(file.path("unitTestData", "regression_2.15.2.Rdata"), package="RevoIOQ")) } else if (compareVersion(paste(R.version$major, R.version$minor, sep="."), "3.0.3") < 0) { load(system.file(file.path("unitTestData", "regression_3.0.1.Rdata"), package="RevoIOQ")) } else if (compareVersion(paste(R.version$major, R.version$minor, sep="."), "3.1.0") < 0) { load(system.file(file.path("unitTestData", "regression_3.0.3.Rdata"), package="RevoIOQ")) } else { load(system.file(file.path("unitTestData", "regression_3.1.0.Rdata"), package="RevoIOQ")) } test.lm<- function(){ ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14) trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69) group <- gl(2,10,20, labels=c("Ctl","Trt")) weight <- c(ctl, trt) kalama.age <- 18:29 kalama.height <- c(76.1, 77.0,78.1, 78.2,78.8,79.7,79.9, 81.1,81.2,81.8,82.8,83.5) gesell.age <- c(15, 26,10, 9, 15,20, 18, 11, 8,20, 7, 9,10,11, 11, 10, 12, 42, 17, 11, 10) gesell.score <- c(95, 71,83,91,102,87, 93,100,104,94,113,96,83,84, 102,100, 105, 57, 121, 86, 100) library(MASS) gasB.test <- lm(Gas ~ Temp, data=whiteside, subset= Insul=="Before") gasA.test <- update(gasB.test, subset= Insul=="After") gasBA.test <- lm(Gas ~ Insul/Temp - 1, data = whiteside) gasQ.test <- lm(Gas ~ Insul/(Temp + I(Temp^2)) - 1, data =whiteside) oldOpts <- options(contrasts = c("contr.helmert", "contr.poly")) gasPR.test <- lm(Gas ~ Insul + Temp, data=whiteside) anova.gas.test <- anova(gasPR.test, gasBA.test) options(contrasts = c("contr.treatment", "contr.poly")) gasBA1.test <- lm (Gas ~ Insul*Temp, data=whiteside) options(oldOpts) checkEquals(lm(weight ~ group), lm.D9, tolerance=10e-06) checkEquals(lm(weight ~ group - 1), lm.D90, tolerance=10e-06) checkEquals(lm(kalama.height ~ kalama.age), kalama.lm, tolerance=10e-06) checkEquals(lm(gesell.score ~ gesell.age), gesell.lm1, tolerance=10e-06) checkEquals(lm(gesell.score[-18] ~ gesell.age[-18]), gesell.lm2, tolerance=10e-06) checkEquals(gasB.test, gasB) checkEquals(gasA.test, gasA) checkEquals(gasBA.test, gasBA) checkEquals(gasPR.test, gasPR) checkEquals(anova.gas.test, anova.gas) checkEquals(gasBA1.test, gasBA1) } test.glm <- function(){ oldOpts <- options(contrasts = c("contr.treatment", "contr.poly")) ldose <- rep(0:5, 2) numdead <- c(1,4,9, 13,18, 20, 0, 2, 6, 10,12, 16) sex <- factor(rep(c("M","F"),c(6,6))) SF <- cbind(numdead, numalive = 20 - numdead) budworm.lg.test <- glm(SF ~ sex*ldose, family=binomial) budworm.lgA.test <- update(budworm.lg.test, . ~ sex * I(ldose - 3)) budworm.anova.test <- anova(update(budworm.lg.test, . ~ . + sex + I(ldose^2)), test="Chisq") budworm.lg0.test <- glm(SF ~ sex + ldose - 1, family=binomial) library(MASS) attach(birthwt) race <- factor(race, labels = c("white","black","other")) ptd <- factor(ptl > 0) ftv <- factor(ftv) levels(ftv)[-(1:2)]<-"2+" bwt <- data.frame(low=factor(low), age, lwt, race, smoke=(smoke>0), ptd, ht=(ht>0), ui=(ui>0), ftv) detach(); rm(race, ptd, ftv) birthwt.glm.test <- glm(low ~ ., family=binomial, data=bwt) birthwt.step.test <- stepAIC(birthwt.glm.test, trace=FALSE) birthwt.step2.test <- stepAIC(birthwt.glm.test, ~ .^2 + I(scale(age)^2) + I(scale(lwt)^2), trace=FALSE) birthwt.pred.test <- table(bwt$low, predict(birthwt.step2.test) > 0) options(oldOpts) if (compareVersion(paste(R.version$major, R.version$minor, sep="."), "3.2.0") >= 0) { budworm.lg.test$data <- NULL budworm.lg$data <- NULL budworm.lgA.test$data <- NULL budworm.lgA$data <- NULL budworm.anova.test$data <- NULL budworm.anova$data <- NULL budworm.lg0.test$data <- NULL budworm.lg0$data <- NULL birthwt.glm.test$data <- NULL birthwt.glm$data <- NULL birthwt.step.test$data <- NULL birthwt.step$data <- NULL } checkEquals(budworm.lg.test, budworm.lg, tolerance=10e-06) checkEquals(budworm.lgA.test, budworm.lgA, tolerance=10e-06) checkEquals(budworm.anova.test, budworm.anova, tolerance=10e-06) checkEquals(budworm.lg0.test, budworm.lg0, tolerance=10e-06) checkEquals(birthwt.glm.test, birthwt.glm, tolerance=10e-06) checkEquals(birthwt.step.test, birthwt.step, tolerance=10e-06) checkEquals(birthwt.pred.test, birthwt.pred, tolerance=10e-06) } test.nls <- function(){ library(MASS) wtloss.st <- c(b0=90, b1=95, th=120) wtloss.fm.test <- nls(Weight ~ b0 + b1*2^(-Days/th),data=wtloss, start=wtloss.st, trace=TRUE) expn <- function(b0,b1, th, x){ temp <- 2^(-x/th) model.func <- b0 + b1 * temp Z <- cbind(1, temp, (b1 * x * temp * log(2))/th^2) dimnames(Z) <- list(NULL, c("b0", "b1", "th")) attr(model.func, "gradient") <- Z model.func } wtloss.gr.test <- nls(Weight ~ expn(b0, b1, th, Days), data=wtloss, start = wtloss.st, trace=TRUE) checkEquals(wtloss.fm.test, wtloss.fm, tolerance=10e-06) checkEquals(wtloss.gr.test, wtloss.gr, tolerance=10e-06) negenv <- new.env() attach(negenv) assign("negexp", selfStart(model = ~ b0 + b1*exp(-x/th), initial = negexp.SSival, parameters = c("b0", "b1", "th"), template = function(x, b0, b1, th){}), pos=2) wtloss.formula <- as.formula(Weight ~ negexp(Days, B0, B1, theta), env="negenv") wtloss.ss.test <- nls(wtloss.formula, data = wtloss, trace = TRUE) detach("negenv") A <- model.matrix(~ Strip - 1, data = muscle) rats.nls1.test <- nls(log(Length) ~ cbind(A, rho^Conc), data=muscle, start = c(rho=0.1), algorithm = "plinear") B <- coef(rats.nls1.test) st <- list(alpha = B[2:22], beta=B[23], rho = B[1]) rats.nls2.test <- nls(log(Length) ~ alpha[Strip] + beta*rho^Conc, data=muscle, start=st) checkEquals(wtloss.ss.test, wtloss.ss, tolerance=10e-06) checkEquals(summary(wtloss.fm.test), summary(wtloss.fm),tolerance =10e-06) checkEquals(vcov(wtloss.gr.test), vcov(wtloss.gr), tolerance=10e-06) checkEquals(rats.nls1.test, rats.nls1, tolerance=10e-06) checkEquals(rats.nls2.test, rats.nls2, tolerance=10e-06) }
test_that("error if cannot start", { app <- new_app() app$listen <- function(...) Sys.sleep(1) expect_error( new_app_process(app, process_timeout = 100), "presser app subprocess did not start" ) app <- new_app() app$listen <- function(...) stop("oops") expect_error( new_app_process(app), class = "callr_status_error", "failed to start presser app process.*oops" ) app <- new_app() app$listen <- function(...) "foobar" expect_error( new_app_process(app), "Unexpected message from presser app subprocess" ) }) test_that("get_state", { app <- new_app() on.exit(proc$stop(), add = TRUE) proc <- new_app_process(app) expect_equal(proc$get_state(), "live") proc$.process$kill() expect_equal(proc$get_state(), "dead") expect_output(proc$stop(), "presser process dead") expect_equal(proc$get_state(), "not running") }) test_that("env vars", { app <- new_app() on.exit(proc$stop(), add = TRUE) withr::local_envvar(list(FOO = "foo")) proc <- new_app_process(app) proc$local_env(list(FOO = "bar")) expect_equal(Sys.getenv("FOO", ""), "bar") proc$stop() expect_equal(Sys.getenv("FOO", ""), "foo") })
summaryTransition <- setClass( "summaryTransition", representation( result = "data.frame", trans_object = "list" ) ) summary.transition <- function( object, ... ) { reference_positives <- sum(object$references) predicted_positives <- sum(object$predictions) rejects <- object$matchings$rejected true_positives <- sum(!rejects) abs_lags <- object$matchings$abs_lag[!rejects] %>% mean_sd(digits = 1, nsmall = 1) %>% sapply( function(x) if(is.nan(x)) NA_real_ else x, simplify = FALSE ) %>% c(stringsAsFactors = FALSE, row.names = list(NULL)) %>% do.call(data.frame, .) signed_lags <- object$matchings$signed_lag[!rejects] %>% mean_sd(digits = 1, nsmall = 1) %>% sapply( function(x) if(is.nan(x)) NA_real_ else x, simplify = FALSE ) %>% c(stringsAsFactors = FALSE, row.names = list(NULL)) %>% do.call(data.frame, .) rmse <- object$matchings$abs_lag[!rejects]^2 %>% mean(.) %>% sqrt(.) %>% round(1) %>% sapply(function(x) if(is.nan(x)) NA_real_ else x) rmse_prop <- 1 - rmse/object$window_size recall <- true_positives / reference_positives precision <- true_positives / predicted_positives class(object) <- "list" data.frame( window_size = object$window_size, reference_positives = reference_positives, predicted_positives = predicted_positives, true_positives = true_positives, n_rejected_pairs = sum(rejects), mean_abs_lag_indices = abs_lags$mean, sd_abs_lag_indices = abs_lags$sd, mean_sd_abs_lag_indices = gsub( "NaN", "NA", abs_lags$sum_string ), mean_signed_lag_indices = signed_lags$mean, sd_signed_lag_indices = signed_lags$sd, mean_sd_signed_lag_indices = gsub( "NaN", "NA", signed_lags$sum_string ), recall = recall, precision = precision, rmse_lag_indices = rmse, rmse_prop = rmse_prop, row.names = NULL, stringsAsFactors = FALSE ) %>% cbind( ., aggregated_performance = rowMeans( .[ ,c("recall", "precision", "rmse_prop")] ) ) %>% new("summaryTransition", result = ., trans_object = object) } add_summaryTransition <- function(e1, e2) { not_used <- "Not used in combined objects" e1 <- e1@trans_object e2 <- e2@trans_object references <- c( e1$references, e2$references ) predictions <- c( e1$predictions, e2$predictions ) matchings <- rbind( e1$matchings, e2$matchings ) window_size <- e1$window_size %>% c(e2$window_size) %>% unique() %T>% {if (length(.) > 1) stop( "Cannot add if spurious pairing thresholds", " differ for the objects", call. = FALSE )} %>% as.numeric() list( window_size = window_size, references = references, predictions = predictions, reference_transition_indices = not_used, prediction_transition_indices = not_used, pruned_reference_transition_indices = not_used, pruned_prediction_transition_indices = not_used, false_negative_indices = not_used, false_positive_indices = not_used, reference_preferences = not_used, prediction_preferences = not_used, matchings = matchings ) %>% summary.transition(.) } setMethod("+", signature(e1 = "summaryTransition", e2 = "summaryTransition"), function(e1, e2) add_summaryTransition(e1, e2)) subtract_summaryTransition <- function(e1, e2) { diff_vars <- c( "window_size","recall", "precision", "mean_abs_lag_indices", "mean_signed_lag_indices", "rmse_lag_indices", "rmse_prop", "aggregated_performance" ) result <- sapply( diff_vars, function(x) e1@result[ ,x] - e2@result[ ,x], simplify = FALSE ) %>% do.call(data.frame, .) %>% {stats::setNames(., paste("diff", names(.), sep = "_"))} %>% data.frame( window_size = e1@result$window_size, ., stringsAsFactors = FALSE, row.names = NULL ) if(result$diff_window_size != 0) { warning( "Spurious pairing thresholds differ for the objects", call. = FALSE ) result$window_size <- paste( e1@result$window_size, e2@result$window_size, sep = "--" ) } list(differences = result, e1 = e1@result, e2 = e2@result) } setMethod("-", signature(e1 = "summaryTransition", e2 = "summaryTransition"), function(e1, e2) subtract_summaryTransition(e1, e2)) setAs("summaryTransition", "data.frame", function(from) from@result) setAs("summaryTransition", "list", function(from) as.list(from@result))
fitNBP <- function(y,group=NULL,lib.size=colSums(y),tol=1e-5,maxit=40,verbose=FALSE) { y <- as.matrix(y) if(is.null(group)) group <- rep(1,ncol(y)) group <- as.factor(group) if(length(group) != ncol(y)) stop("length(group) must agree with ncol(y)") ngenes <- nrow(y) nlib <- ncol(y) ngroups <- length(levels(group)) res.df <- ncol(y)-ngroups ind <- matrix(FALSE,nlib,ngroups) for (i in 1:ngroups) ind[,i] <- group==levels(group)[i] offset <- matrix(1,ngenes,1) %*% log(lib.size) mu <- pmax(y,0.5) phi <- 0 w <- mu z <- w*(log(mu)-offset) beta <- matrix(0,ngenes,ngroups) eta <- offset for (i in 1:ngroups) { beta[,i] <- rowSums(z[,ind[,i],drop=FALSE])/rowSums(w[,ind[,i],drop=FALSE]) eta[,ind[,i]] <- eta[,ind[,i]]+beta[,i] } if(verbose) cat("mean coef",colMeans(beta),"\n") mu <- exp(eta) iter <- 0 repeat{ iter <- iter+1 if(iter > maxit) { warning("maxit exceeded") break } e2 <- (y-mu)^2 dV <- mu*mu inneriter <- 0 repeat { inneriter <- inneriter+1 if(inneriter > 10) stop("problem with inner iteration") V <- mu*(1+phi*mu) X2 <- sum(e2/V)/res.df-ngenes if(X2 >= 0) { low <- phi break } else { if(phi==0) break if(inneriter > 4) phi <- 0.9*phi else phi <- (low+phi)/2 if(verbose) cat("mean disp",phi,"\n") } } if(X2<0) break dX2 <- sum(e2/V/V*dV)/res.df step.phi <- X2/pmax(dX2,1e-6) phi <- phi+step.phi conv.crit <- step.phi/(phi+1) if(verbose) cat("Conv criterion",conv.crit,"\n") if(conv.crit < tol) break w <- mu/(1+phi*mu) z <- (y-mu)/V*mu eta <- offset for (i in 1:ngroups) { beta[,i] <- beta[,i]+rowSums(z[,ind[,i],drop=FALSE])/rowSums(w[,ind[,i],drop=FALSE]) eta[,ind[,i]] <- eta[,ind[,i]]+beta[,i] } if(verbose) cat("mean coef",colMeans(beta),"\n") if(verbose) cat("disp",phi,"\n") mu <- exp(eta) } colnames(beta) <- levels(group) dimnames(mu) <- dimnames(y) list(coefficients=beta,fitted.values=mu,dispersion=phi) }
modl <- function(tserie, method='arima' ,algorithm=NULL ,formula=NULL ,initialWindow=NULL,horizon=NULL,fixedWindow=NULL){ if(methods::is(tserie,"prep")) tserie <- tserie$tserie else if(!stats::is.ts(tserie)) stop('Not a ts or prep object') model <- NULL errors <- NULL tserieDF <- NULL k <- 60 if(method=='arima'){ model <- modl.arima(tserie) errors <- c(forecast::accuracy(model)[2],forecast::accuracy(model)[3],forecast::accuracy(model)[4]) } else if(method=='dataMining'){ if(is.null(algorithm)) stop('Data mining regression algorithm required. Consult names here:\nhttp://topepo.github.io/caret/train-models-by-tag.html') if(is.null(fixedWindow)) fixedWindow <- TRUE if(is.null(initialWindow)) initialWindow <- as.integer(k/2) if(is.null(horizon)) horizon <- as.integer(k/4) timeControl <- modl.trControl(initialWindow,horizon,fixedWindow,givenSummary=TRUE) tserieDF <- modl.tsToDataFrame(tserie,formula) model <- modl.dataMining(Class ~ .,tserieDF,algorithm,timeControl,metric='RMSE',maximize=FALSE) winningIndex <- which.min(model$results["RMSE"][,1]) errors <- c(model$results["RMSE"][winningIndex,1] ,model$results["MAE"][winningIndex,1] ,model$results["MAPE"][winningIndex,1]) } else stop('Invalid modelling method') names(errors) <- c("RMSE","MAE","MAPE") obj <- list() class(obj) <- "modl" obj$tserie <- tserie obj$tserieDF <- tserieDF obj$method <- method obj$algorithm <- algorithm obj$horizon <- horizon obj$model <- model obj$errors <- errors return (obj) } modl.arima <- function(tserie){ return (forecast::auto.arima(tserie,seasonal=FALSE)) } modl.tsToDataFrame <- function(tserie,formula=NULL){ if(!stats::is.ts(tserie)) stop('Not a ts object') k <- 60 if(is.null(formula)) formula <- c(1:16) else if(length(formula)<6) stop('Parameter formula needs to have at least 6 elements') numE <- max(formula)-min(formula)+1 n <- length(formula)-1 if(length(tserie)<numE) stop('Sample exceeds ts length') mat <- data.frame() continuar <- TRUE i <- 0 while(continuar){ aux <- 1 vaux <- NULL while(aux <= n+1){ vaux <- c(vaux,tserie[i+formula[aux]]) aux <- aux+1 } mat <- rbind(mat,vaux) i <- i+1 if(i > length(tserie)-numE) continuar <- FALSE } if(i < k) stop('Not enough observations to make good prediction: you need minimum a 60 length series.\n') for(i in 1:(n+1)){ if (i==n+1) colnames(mat)[i] <- 'Class' else colnames(mat)[i] <- paste0('c_',i) } return (mat) } modl.trControl <- function(initialWindow,horizon,fixedWindow,givenSummary=FALSE){ k <- 60 if(givenSummary) return (caret::trainControl(method="timeslice",initialWindow=initialWindow,horizon=horizon,fixedWindow=fixedWindow,summaryFunction = modl.sumFunction)) else return (caret::trainControl(method="timeslice",initialWindow=initialWindow,horizon=horizon,fixedWindow=fixedWindow)) } modl.dataMining <- function(form,tserieDF,algorithm,timeControl,metric="RMSE",maximize=FALSE){ return (caret::train(form,data=tserieDF,method=algorithm,trControl=timeControl,metric=metric,maximize=maximize)) } modl.sumFunction <- function(data,lev = NULL,model = NULL){ rmse <- caret::RMSE(data$obs,data$pred) mae <- Metrics::mae(data$obs,data$pred) mape <- TSPred::MAPE(data$obs,data$pred) output <- c(rmse,mae,mape) names(output) <- c("RMSE","MAE","MAPE") return (output) } summary.modl <- function(object,...){ cat("Fitted model object\n") if(object$method=='arima') cat("~Modelling method: ARIMA\n") else if(object$method=='dataMining') cat ("~Modelling method: Data mining\n~Algorithm: ",object$algorithm,"\n") cat("~Original time serie: \n") utils::str(object$tserie) cat("~Original time serie as data frame") utils::str(object$tserieDF) cat("~Model (best tuning parameters): \n") if(object$method=='dataMining') print(object$model$bestTune) else if(object$method=='arima') print(forecast::arimaorder(object$model)) cat("~Error measures: \n") print(object$errors) } print.modl <- function(x,...){ cat("Fitted model object\n") cat("Class: modl\n\n") cat("Attributes: \n\n") cat("$method: ",x$method,"\n\n") if(!is.null(x$algorithm)) cat("$algorithm: ",x$algorithm,"\n\n") cat("$tserie: \n") print(x$tserie) cat("\n") cat("$tserieDF: \n") utils::str(x$tserieDF) cat("\n") cat("$model: \n") print(x$model) cat("\n") cat("$errors: \n") print(x$errors) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) knitr::opts_chunk$set(fig.width=10, fig.height=8,fig.align = 'center') library(httptest) httptest::start_vignette("MMR_Distribution") library(SC2API) library(ggplot2) data <- get_league_data(season_id = 43, queue_id = 201, team_type = 0, league_id = 6, host_region = "eu") ladder_id <- data$tier$division[[1]]$ladder_id ladder_id ladder_data <- get_ladder_data(ladder_id = ladder_id, host_region = "eu") mmr <- ladder_data$team$rating head(mmr) ladder_data_current <- get_gm_leaderboard(2, host_region = "us") mmrCurrent <- ladder_data_current$mmr head(mmrCurrent) ladder_data_current2 <- get_gm_leaderboard(2, host_region = "kr") mmrCurrent2 <- ladder_data_current$mmr identical(mmrCurrent,mmrCurrent2) ggplot() + geom_histogram(aes(x=mmr)) + theme_light() races <- sapply(ladder_data$team$member, function(x) x$played_race_count[[1]]$race$en_US) df <- data.frame(mmr,races) df <- df[df$races!='Random',] head(df) ggplot(df,aes(x = mmr, group = races, fill = races)) + geom_histogram() + scale_fill_manual(values = c('Orange','Blue','Red')) + facet_wrap(~races) + theme_light() ggplot(df,aes(x = mmr)) + geom_density(aes(y = ..density.., group = races, colour = races), kernel=c("gaussian"), adjust = 1.5, position = "identity", lwd = 1) + scale_color_manual(values = c('Orange','Blue','Red')) + theme_light() httptest::end_vignette()
`recode.hap` <- function(hap,all.marq){ nb.marq = length(hap[1,]) nb.ind = length(hap[,1]) hap.recode= matrix(NA,ncol=nb.marq,nrow=nb.ind) for(i in 1:nb.marq){ for(k in 1:length(all.marq[[i]])){ hap.recode[hap[,i]==all.marq[[i]][k],i]=k } } hap.recode }
mwar.ani = function( x, k = 15, conf = 2, mat = matrix(1:2, 2), widths = rep(1, ncol(mat)), heights = rep(1, nrow(mat)), lty.rect = 2, ... ) { nmax = ani.options('nmax') if (missing(x)) x = sin(seq(0, 2 * pi, length = 50)) + rnorm(50, sd = 0.2) n = length(x) if (k > n) stop('The window width k must be smaller than the length of x!') idx = matrix(1:k, nrow = k, ncol = n - k + 1) + matrix(rep(0:(n - k), each = k), nrow = k, ncol = n - k + 1) phi = se = numeric(ncol(idx)) j = 1 for (i in 1:ncol(idx)) { if (j > nmax) break fit = arima(x[idx[, i]], order = c(1, 0, 0)) phi[i] = coef(fit)['ar1'] se[i] = sqrt(vcov(fit)[1, 1]) j = j + 1 } layout(mat, widths, heights) U = phi + conf * se L = phi - conf * se j = 1 minx = maxx = NULL for (i in 1:ncol(idx)) { if (j > nmax) break dev.hold() plot(x, xlab = '', ylab = 'Original data') minx = c(minx, min(x[idx[, i]])) maxx = c(maxx, max(x[idx[, i]])) rect(1:i, minx, k:(i + k - 1), maxx, lty = lty.rect, border = 1:i) plot(x, xlim = c(1, n), ylim = range(c(U, L), na.rm = TRUE), type = 'n', ylab = 'AR(1) coefficient', xlab = '') arrows(1:i + k/2 - 0.5, L[1:i], 1:i + k/2 - 0.5, U[1:i], angle = 90, code = 3, length = par('din')[1]/n * 0.4, col = 1:i) points(1:i + k/2 - 0.5, phi[1:i], ...) ani.pause() j = j + 1 } invisible(list(phi = phi, lower = L, upper = U)) }
lsdm_est_logist_quant <- function( probcurves, theta, quantiles, wgt_theta, est.icc=TRUE, b=NULL, a=NULL) { I <- nrow(probcurves) b0 <- NULL if (est.icc){ pars.probcurves <- matrix( 0, nrow=I, ncol=5 ) colnames(pars.probcurves) <- c("b.2PL", "a.2PL", "sigma.2PL", "b.1PL", "sigma.1PL") rownames(pars.probcurves) <- rownames(probcurves) for (kk in 1:I){ if (!is.null(b)){ b0 <- b[kk] a0 <- a[kk] } pars.probcurves[kk,1:3] <- lsdm_est_logist_2pl( y=probcurves[kk,], theta=theta, wgt_theta=wgt_theta, b0=b0, a0=a0 ) pars.probcurves[kk,4:5] <- lsdm_est_logist_rasch( y=probcurves[kk,], theta=theta, wgt_theta=wgt_theta ) } } probcurves.quant <- sapply( quantiles, FUN=function(ql){ sapply( 1:I, FUN=function(kk){ lsdm_extract_probquantile(vec=probcurves[kk,], theta=theta, quant=ql) } ) } ) probcurves.quant <- as.data.frame(probcurves.quant) colnames(probcurves.quant) <- paste( "Q", 100*quantiles, sep="") rownames(probcurves.quant) <- rownames(probcurves) if (est.icc){ pars.probcurves <- cbind( probcurves.quant, pars.probcurves ) } else { pars.probcurves <- probcurves.quant } for (vv in 1:(length(quantiles))){ pars.probcurves[,vv] <- as.numeric( pars.probcurves[,vv] ) } return(pars.probcurves) }
design.efficiency.old <- function(design) { if ("CrossoverSearchResult" %in% class(design)) design <- design@design if ("CrossoverDesign" %in% class(design)) { design <- design@design } design <- t(design) nper <- dim(design)[2] nseq <- dim(design)[1] ntrt <- length(levels(as.factor(design))) n<-rep(1,nseq) group<-rep(1:nseq,nper*n) subject<-rep(1:sum(n), rep(nper,sum(n))) per<-rep(1:nper, sum(n)) trt<-NULL for(i in 1:nseq){ trt<-c(trt,rep(design[i,],n[i])) } trt.mat<-matrix(trt,sum(n),nper,byrow=T) car.mat<-matrix(0,sum(n),nper,byrow=T) car.mat[,1]<-1 car.mat[,2:nper]<-trt.mat[,1:(nper-1)] car<-NULL for(i in 1:sum(n)){ car<-c(car,car.mat[i,]) } nsubj<-sum(n) ndata<-nsubj*nper mean01<-matrix(1,ndata,1) subj01<-matrix(0,ndata,nsubj) per01<-matrix(0,ndata,nper) trt01<-matrix(0,ndata,ntrt) car01<-matrix(0,ndata,ntrt) for(i in 1:nsubj){ subj01[,i][subject==i]<-1 } for(i in 1:nper){ per01[,i][per==i]<-1 } for(i in 1:ntrt){ trt01[,i][trt==i]<-1 } car01[,1:ntrt][per==1]<-0 for(j in 2:nper){ car01[,1:ntrt][per==j]<-trt01[,1:ntrt][per==(j-1)] } xmat.no.subjects<-matrix(cbind(mean01,per01,trt01,car01),ndata,(1+nper+2*ntrt),byrow=F) xmat<-matrix(cbind(mean01,subj01,per01,trt01,car01),ndata,(1+nsubj+nper+2*ntrt),byrow=F) xtx<-t(xmat)%*%xmat xtx.inv<-ginv(xtx) n.cols.all<-1+nsubj+nper+2*ntrt n.cols.car.upp<-n.cols.all n.cols.car.low<-n.cols.car.upp-(ntrt-1) n.cols.trt.upp<-n.cols.car.low-1 n.cols.trt.low<-n.cols.trt.upp-(ntrt-1) xtx.inv.car.adj<-xtx.inv[n.cols.car.low:n.cols.car.upp,n.cols.car.low:n.cols.car.upp] xtx.inv.trt.adj<-xtx.inv[n.cols.trt.low:n.cols.trt.upp,n.cols.trt.low:n.cols.trt.upp] xmat<-matrix(cbind(mean01,subj01,per01,trt01),ndata,(1+nsubj+nper+ntrt),byrow=F) xtx<-t(xmat)%*%xmat xtx.inv<-ginv(xtx) n.cols.all<-1+nsubj+nper+ntrt n.cols.trt.upp<-n.cols.all n.cols.trt.low<-n.cols.trt.upp-(ntrt-1) xtx.inv.trt<-xtx.inv[n.cols.trt.low:n.cols.trt.upp,n.cols.trt.low:n.cols.trt.upp] var.trt.pair.adj<-matrix(0,ntrt,ntrt) for(i in 1:ntrt){ for(j in 1:ntrt){ if (i!=j) { var.trt.pair.adj[i,j]<-xtx.inv.trt.adj[i,i]+xtx.inv.trt.adj[j,j] - 2*xtx.inv.trt.adj[i,j] }}} var.trt.pair<-matrix(0,ntrt,ntrt) for(i in 1:ntrt){ for(j in 1:ntrt){ if (i!=j) { var.trt.pair[i,j]<-xtx.inv.trt[i,i]+xtx.inv.trt[j,j] - 2*xtx.inv.trt[i,j] }}} rep<-matrix(0,ntrt) for(i in 1:ntrt){ rep[i]<-sum(trt.mat==i) } var.trt.pair.ideal<-matrix(0,ntrt,ntrt) for(i in 1:ntrt){ for(j in 1:ntrt){ if (i!=j) { var.trt.pair.ideal[i,j]<-1/rep[i] + 1/rep[j] }}} eff.trt.pair<-matrix(0,ntrt,ntrt) for(i in 1:ntrt){ for(j in 1:ntrt){ if (i!=j) { eff.trt.pair[i,j]<-var.trt.pair.ideal[i,j]/var.trt.pair[i,j] }}} eff.trt.pair.adj<-matrix(0,ntrt,ntrt) for(i in 1:ntrt){ for(j in 1:ntrt){ if (i!=j) { eff.trt.pair.adj[i,j]<-var.trt.pair.ideal[i,j]/var.trt.pair.adj[i,j] }}} av.eff.trt.pair<-sum(eff.trt.pair)/(ntrt*(ntrt-1)) av.eff.trt.pair.adj<-sum(eff.trt.pair.adj)/(ntrt*(ntrt-1)) return(list(xmat.no.subjects=xmat.no.subjects, var.trt.pair=var.trt.pair,eff.trt.pair=eff.trt.pair,av.eff.trt.pair=av.eff.trt.pair, var.trt.pair.adj=var.trt.pair.adj,eff.trt.pair.adj=eff.trt.pair.adj,av.eff.trt.pair.adj=av.eff.trt.pair.adj)) } test.eff <- function() { f <- stop path <- system.file("data", package="Crossover") for (file in dir(path=path)) { if (file %in% c("clatworthy1.rda", "clatworthyC.rda", "pbib2combine.rda", "exampleSearchResults2t.rda")) next designs <- load(paste(path, file, sep="/")) for (designS in designs) { design <- get(designS) r1 <- design.efficiency(design) r2 <- design.efficiency.old(design) if(!isTRUE(all.equal(r1$var.trt.pair.adj, r2$var.trt.pair.adj))) { f(paste("Unequal variances for",designS," (",max(abs(r1$var.trt.pair.adj - r2$var.trt.pair.adj)),")!\n")) } if(!isTRUE(all.equal(r1$eff.trt.pair.adj, r2$eff.trt.pair.adj))) { f(paste("Unequal efficiencies for",designS," (",max(abs(r1$eff.trt.pair.adj - r2$eff.trt.pair.adj))," - ",getCounts(design),")!\n")) } if(!isTRUE(all.equal(r1$xmat, r2$xmat.no.subjects, check.names=FALSE))) { } } } } test.eff()
NCEP.interp.surface <- function(variable, lat, lon, dt, reanalysis2=FALSE, interpolate.space=TRUE, interpolate.time=TRUE, keep.unpacking.info=FALSE, return.units=TRUE, interp='linear', p=1, status.bar=TRUE){ iterations <- max(c(length(variable),length(lat), length(lon), length(dt), length(reanalysis2), length(interpolate.space), length(interpolate.time), length(interp), length(p))) if(status.bar){ pb <- tkProgressBar(title="Total progress", min = 0, max=iterations, width=300) } else { pb <- NULL } variable <- rep(variable, length.out=iterations) lat <- rep(lat, length.out=iterations) lon <- rep(lon, length.out=iterations) dt <- rep(dt, length.out=iterations) reanalysis2 <- rep(reanalysis2, length.out=iterations) interpolate.space <- rep(interpolate.space, length.out=iterations) interpolate.time <- rep(interpolate.time, length.out=iterations) interp <- rep(interp, length.out=iterations) p <- rep(p, length.out=iterations) interp <- ifelse(!interpolate.space, 'IDW', interp) possible.lats <- c(90.0, 87.5, 85.0, 82.5, 80.0, 77.5, 75.0, 72.5, 70.0, 67.5, 65.0, 62.5, 60.0, 57.5, 55.0, 52.5, 50.0, 47.5, 45.0, 42.5, 40.0, 37.5, 35.0, 32.5, 30.0, 27.5, 25.0, 22.5, 20.0, 17.5, 15.0, 12.5, 10.0, 7.5, 5.0, 2.5, 0.0, -2.5, -5.0, -7.5, -10.0, -12.5, -15.0, -17.5, -20.0, -22.5, -25.0, -27.5, -30.0, -32.5, -35.0, -37.5, -40.0, -42.5, -45.0, -47.5, -50.0, -52.5, -55.0, -57.5, -60.0, -62.5, -65.0, -67.5, -70.0, -72.5, -75.0, -77.5, -80.0, -82.5, -85.0, -87.5, -90.0) possible.lons <- c(0.0, 2.5, 5.0, 7.5, 10.0, 12.5, 15.0, 17.5, 20.0, 22.5, 25.0, 27.5, 30.0, 32.5, 35.0, 37.5, 40.0, 42.5, 45.0, 47.5, 50.0, 52.5, 55.0, 57.5, 60.0, 62.5, 65.0, 67.5, 70.0, 72.5, 75.0, 77.5, 80.0, 82.5, 85.0, 87.5, 90.0, 92.5, 95.0, 97.5, 100.0, 102.5, 105.0, 107.5, 110.0, 112.5, 115.0, 117.5, 120.0, 122.5, 125.0, 127.5, 130.0, 132.5, 135.0, 137.5, 140.0, 142.5, 145.0, 147.5, 150.0, 152.5, 155.0, 157.5, 160.0, 162.5, 165.0, 167.5, 170.0, 172.5, 175.0, 177.5, 180.0, 182.5, 185.0, 187.5, 190.0, 192.5, 195.0, 197.5, 200.0, 202.5, 205.0, 207.5, 210.0, 212.5, 215.0, 217.5, 220.0, 222.5, 225.0, 227.5, 230.0, 232.5, 235.0, 237.5, 240.0, 242.5, 245.0, 247.5, 250.0, 252.5, 255.0, 257.5, 260.0, 262.5, 265.0, 267.5, 270.0, 272.5, 275.0, 277.5, 280.0, 282.5, 285.0, 287.5, 290.0, 292.5, 295.0, 297.5, 300.0, 302.5, 305.0, 307.5, 310.0, 312.5, 315.0, 317.5, 320.0, 322.5, 325.0, 327.5, 330.0, 332.5, 335.0, 337.5, 340.0, 342.5, 345.0, 347.5, 350.0, 352.5, 355.0, 357.5) not.in.reanalysis2 <- c('air.sig995','lftx.sfc','lftx4.sfc','omega.sig995','pottmp.sig995','rhum.sig995','slp','uwnd.sig995','vwnd.sig995') not.in.reanalysis1 <- c('mslp') gridsize <- as.integer(250) tgridsize <- as.integer(60*60*6) scale.offset.missingvals.temp <- tempfile() out.temp <- tempfile() wx.out <- c() units <- c() spread <- c() unpacking.info.acquired <- FALSE MK.interp <- function(pt1, pt2, pos){ return(pt1 + pos * (pt2 - pt1)) } for(i in 1:iterations){ if(any(c('air.sig995','lftx.sfc','lftx4.sfc','omega.sig995','pottmp.sig995','pr_wtr.eatm','pres.sfc','rhum.sig995','slp','mslp','uwnd.sig995','vwnd.sig995') == variable[i]) == FALSE) { stop(paste("'",variable[i],"'", " not a valid variable name in reference to the surface",sep='')) } if(reanalysis2[i] == TRUE && any(not.in.reanalysis2 == variable[i])) { reanalysis2[i] <- FALSE warning(paste(variable[i], " is not available at the surface in the Reanalysis II dataset. Using Reanalysis I instead.",sep='')) } if(reanalysis2[i] == FALSE && any(not.in.reanalysis1 == variable[i])) { reanalysis2[i] <- TRUE warning(paste(variable[i], " is not available at the surface in the Reanalysis I dataset. Using Reanalysis II instead.",sep='')) } name <- strsplit(variable[i], "\\.")[[1]][1] level <- ifelse(length(strsplit(variable[i], "\\.")[[1]]) > 1, strsplit(variable[i], "\\.")[[1]][2], "") lon[i] <- ifelse(lon[i] < 0, 360+lon[i], lon[i]) if(lon[i] >= 357.5){ temp.out <- robust.NCEP.interp.surface(variable=variable[i], lat=lat[i], lon=lon[i], dt=dt[i], reanalysis2=reanalysis2[i], interpolate.space=interpolate.space[i], interpolate.time=interpolate.time[i], keep.unpacking.info=keep.unpacking.info, return.units=return.units, interp=interp[i], p=p[i]) wx.out[i] <- temp.out$wx.out spread[i] <- temp.out$spread if(return.units == TRUE){ units[i] <- as.character(temp.out$units) } if(!is.null(pb)){ cval <- pb$getVal() Sys.sleep(0.000001) setTkProgressBar(pb, cval+1, label=paste(round((cval+1)/iterations*100, 0), "% done")) if(pb$getVal() == iterations) {close(pb)} } next } if(interp[i] == 'IDW' | interp[i] == 'idw'){ NCEP.deg.dist <- function (long1, lat1, long2, lat2) { rad <- pi/180 a1 <- lat1 * rad a2 <- long1 * rad b1 <- lat2 * rad b2 <- long2 * rad dlon <- b2 - a2 dlat <- b1 - a1 a <- (sin(dlat/2))^2 + cos(a1) * cos(b1) * (sin(dlon/2))^2 c <- 2 * atan2(sqrt(a), sqrt(1 - a)) R <- 40041.47/(2 * pi) d <- R * c return(d) } ilat0 <- floor(lat[i] * 100 / gridsize) * gridsize ilat1 <- ilat0 + gridsize ilon0 <- floor(lon[i] * 100 / gridsize) * gridsize ilon1 <- ilon0 + gridsize lat0.lon0.d <- NCEP.deg.dist(long1=ilon0/100, lat1=ilat0/100, long2=lon[i], lat2=lat[i])^p[i] lat0.lon1.d <- NCEP.deg.dist(long1=ilon1/100, lat1=ilat0/100, long2=lon[i], lat2=lat[i])^p[i] lat1.lon0.d <- NCEP.deg.dist(long1=ilon0/100, lat1=ilat1/100, long2=lon[i], lat2=lat[i])^p[i] lat1.lon1.d <- NCEP.deg.dist(long1=ilon1/100, lat1=ilat1/100, long2=lon[i], lat2=lat[i])^p[i] if(any(c(lat0.lon0.d, lat0.lon1.d, lat1.lon0.d, lat1.lon1.d) == 0)){ min.d <- which(c(lat0.lon0.d, lat0.lon1.d, lat1.lon0.d, lat1.lon1.d) == 0) interpolate.space[i] <- FALSE } else { lat0.lon0.inv.d <- 1/lat0.lon0.d lat0.lon1.inv.d <- 1/lat0.lon1.d lat1.lon0.inv.d <- 1/lat1.lon0.d lat1.lon1.inv.d <- 1/lat1.lon1.d total.inv.d <- sum(lat0.lon0.inv.d, lat0.lon1.inv.d, lat1.lon0.inv.d, lat1.lon1.inv.d) all.latlons <- c(lat0.lon0.inv.d, lat0.lon1.inv.d, lat1.lon0.inv.d, lat1.lon1.inv.d) min.d <- which(all.latlons == max(all.latlons)) } lat0.lon0.f <- if(interpolate.space[i] == TRUE) { lat0.lon0.inv.d/total.inv.d } else if(min.d == 1) {1} else {0} lat0.lon1.f <- if(interpolate.space[i] == TRUE) { lat0.lon1.inv.d/total.inv.d } else if(min.d == 2) {1} else {0} lat1.lon0.f <- if(interpolate.space[i] == TRUE) { lat1.lon0.inv.d/total.inv.d } else if(min.d == 3) {1} else {0} lat1.lon1.f <- if(interpolate.space[i] == TRUE) { lat1.lon1.inv.d/total.inv.d } else if(min.d == 4) {1} else {0} dt.f <- strptime(dt[i], "%Y-%m-%d %H:%M:%S",'UTC') year <- as.numeric(format(dt.f, "%Y")) idatetime <- floor(as.numeric(as.POSIXct(dt[i], tz='UTC')) / tgridsize) ts0 <- idatetime * tgridsize ts1 <- ts0 + tgridsize f0ts <- (as.numeric(as.POSIXct(dt[i], tz='UTC')) - ts0) / tgridsize f0ts <- ifelse(interpolate.time[i] == FALSE, round(f0ts, digits=0), f0ts) } else if(interp[i] == 'linear'){ ilat0 <- floor(lat[i] * 100 / gridsize) * gridsize ilat1 <- ilat0 + gridsize f0lat <- (lat[i] * 100.0 - ilat0) / gridsize f0lat <- ifelse(interpolate.space[i] == FALSE, round(f0lat, digits=0), f0lat) ilon0 <- floor(lon[i] * 100 / gridsize) * gridsize ilon1 <- ilon0 + gridsize f0lon <- (lon[i] * 100.0 - ilon0) / gridsize; f0lon <- ifelse(interpolate.space[i] == FALSE, round(f0lon, digits=0), f0lon) dt.f <- strptime(dt[i], "%Y-%m-%d %H:%M:%S",'UTC') year <- as.numeric(format(dt.f, "%Y")) idatetime <- floor(as.numeric(as.POSIXct(dt[i], tz='UTC')) / tgridsize) ts0 <- idatetime * tgridsize ts1 <- ts0 + tgridsize f0ts <- (as.numeric(as.POSIXct(dt[i], tz='UTC')) - ts0) / tgridsize f0ts <- ifelse(interpolate.time[i] == FALSE, round(f0ts, digits=0), f0ts) } else stop("'interp' must be either 'IDW' or 'linear'") if(format(dt.f, "%m-%d %H:%M:%S") > "12-31 17:59:59") { temp.out <- robust.NCEP.interp.surface(variable=variable[i], lat=lat[i], lon=lon[i], dt=dt[i], reanalysis2=reanalysis2[i], interpolate.space=interpolate.space[i], interpolate.time=interpolate.time[i], keep.unpacking.info=keep.unpacking.info, return.units=return.units, interp=interp[i], p=p[i]) wx.out[i] <- temp.out$wx.out spread[i] <- temp.out$spread if(return.units == TRUE){ units[i] <- as.character(temp.out$units) } next } lat.range <- c(which(possible.lats == (ilat1/100))-1, which(possible.lats == (ilat0/100))-1) lon.range <- c(which(possible.lons == (ilon0/100))-1, which(possible.lons == (ilon1/100))-1) beg.jdate <- as.numeric(difftime(as.POSIXct(ts0, origin='1970-01-01', tz="UTC"), as.POSIXct(paste(year,"/1/1 0:0:0", sep=''), "%Y/%m/%d %H:%M:%S", tz="UTC"), units='hours'))/6 end.jdate <- as.numeric(difftime(as.POSIXct(ts1, origin='1970-01-01', tz="UTC"), as.POSIXct(paste(year,"/1/1 0:0:0", sep=''), "%Y/%m/%d %H:%M:%S", tz="UTC"), units='hours'))/6 columns <- length(seq((ilon0/100),(ilon1/100), by=2.5)) + 1 actual.columns <- columns-1 rows <- length(seq((ilat0/100),(ilat1/100), by=2.5)) if(i == 1 | keep.unpacking.info == FALSE | unpacking.info.acquired == FALSE){ trying.out <- 1 fail <- 0 while(trying.out != 0){ trying.out <- try(download.file(paste("http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis",ifelse(reanalysis2[i] == TRUE, "2",""),"/surface/",variable[i],".",year,".nc.das", sep=''), mode="wb", method="libcurl", scale.offset.missingvals.temp), silent=TRUE) fail <- fail + 1 if(fail >= 5) {stop(paste("\nThere is a problem connecting to the NCEP database with the information provided. \nTry entering http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis",ifelse(reanalysis2[i] == TRUE, "2",""),"/surface/",variable[i],".",year,".nc.das into a web browser to obtain an error message.", sep = ""))} } add.offset <- if(any(grepl('add_offset', readLines(scale.offset.missingvals.temp)))){as.numeric(strsplit(strsplit(grep('add_offset', x=readLines(scale.offset.missingvals.temp), value=TRUE, fixed=TRUE), ';')[[1]][1], 'add_offset ')[[1]][2]) } else { 0 } scale.factor <- if(any(grepl('scale_factor', readLines(scale.offset.missingvals.temp)))){as.numeric(strsplit(strsplit(grep('scale_factor', x=readLines(scale.offset.missingvals.temp), value=TRUE, fixed=TRUE), ';')[[1]][1], 'scale_factor ')[[1]][2]) } else { 1 } missing.values <- as.numeric(strsplit(strsplit(grep('missing_value', x=readLines(scale.offset.missingvals.temp), value=TRUE, fixed=TRUE), ';')[[1]][1], 'missing_value ')[[1]][2]) if(return.units == TRUE){ var.loc.units <- min(grep(name, x = readLines(scale.offset.missingvals.temp), value = FALSE, fixed = TRUE)) all.loc.units <- grep("String units", x = readLines(scale.offset.missingvals.temp), value = FALSE, fixed = TRUE) all.units <- grep("String units", x = readLines(scale.offset.missingvals.temp), value = TRUE, fixed = TRUE) units[i] <- strsplit(all.units[which(all.loc.units > var.loc.units)[1]], "\"")[[1]][2] } unpacking.info.acquired <- TRUE } trying.out <- 1 fail <- 0 while(trying.out != 0){ trying.out <- try(download.file(paste("http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis",ifelse(reanalysis2[i] == TRUE, "2",""),"/surface/",variable[i],".",year,".nc.ascii?",name,"[",beg.jdate,":",end.jdate,"][",lat.range[1],":",lat.range[2],"][",lon.range[1],":",lon.range[2],"]", sep=''), mode="wb", method="libcurl", out.temp), silent=TRUE) fail <- fail + 1 if(fail >= 5) {stop(paste("\nThere is a problem connecting to the NCEP database with the information provided. \nTry entering http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis",ifelse(reanalysis2[i] == TRUE, "2",""),"/surface/",variable[i],".",year,".nc.ascii?",name,"[",beg.jdate,":",end.jdate,"][",lat.range[1],":",lat.range[2],"][",lon.range[1],":",lon.range[2],"] into a web browser to obtain an error message.", sep = ""))} } outdata <- read.table(file=out.temp, sep=',', skip=12, header=FALSE, na.strings=missing.values, nrows=((end.jdate-beg.jdate)+1)*rows) rec0.1 <- ifelse(outdata$V2[2] == missing.values, NA, outdata$V2[2] * scale.factor + add.offset) rec1.1 <- ifelse(outdata$V2[4] == missing.values, NA, outdata$V2[4] * scale.factor + add.offset) rec2.1 <- ifelse(outdata$V3[2] == missing.values, NA, outdata$V3[2] * scale.factor + add.offset) rec3.1 <- ifelse(outdata$V3[4] == missing.values, NA, outdata$V3[4] * scale.factor + add.offset) rec4.1 <- ifelse(outdata$V2[1] == missing.values, NA, outdata$V2[1] * scale.factor + add.offset) rec5.1 <- ifelse(outdata$V2[3] == missing.values, NA, outdata$V2[3] * scale.factor + add.offset) rec6.1 <- ifelse(outdata$V3[1] == missing.values, NA, outdata$V3[1] * scale.factor + add.offset) rec7.1 <- ifelse(outdata$V3[3] == missing.values, NA, outdata$V3[3] * scale.factor + add.offset) if(interp[i] == 'IDW' | interp[i] == 'idw'){ t1 <- sum((lat0.lon0.f*rec0.1) + (lat0.lon1.f*rec2.1) + (lat1.lon0.f*rec4.1) + (lat1.lon1.f*rec6.1)) t2 <- sum((lat0.lon0.f*rec1.1) + (lat0.lon1.f*rec3.1) + (lat1.lon0.f*rec5.1) + (lat1.lon1.f*rec7.1)) wx.out[i] <- MK.interp(t1, t2, f0ts) } else { rec0 <- MK.interp(rec0.1, rec4.1, f0lat) rec1 <- MK.interp(rec1.1, rec5.1, f0lat) rec2 <- MK.interp(rec2.1, rec6.1, f0lat) rec3 <- MK.interp(rec3.1, rec7.1, f0lat) rec0 <- MK.interp(rec0, rec2, f0lon) rec1 <- MK.interp(rec1, rec3, f0lon) wx.out[i] <- MK.interp(rec0, rec1, f0ts) } if(interpolate.space[i] == TRUE){ if(interpolate.time[i] == TRUE){ spread[i] <- sd(c(rec0.1,rec1.1,rec2.1,rec3.1,rec4.1,rec5.1,rec6.1,rec7.1)) } else if(f0ts == 1){ spread[i] <- sd(c(rec1.1,rec3.1,rec5.1,rec7.1)) } else spread[i] <- sd(c(rec0.1,rec2.1,rec4.1,rec6.1)) } else if(interpolate.space[i] == FALSE){ if(interpolate.time[i] == TRUE){ spread[i] <- sd(c(t1, t2)) } else if(interpolate.time[i] == FALSE){ spread[i] <- NA } } rec0.1 <- c() rec1.1 <- c() rec2.1 <- c() rec3.1 <- c() rec4.1 <- c() rec5.1 <- c() rec6.1 <- c() rec7.1 <- c() outdata <- c() if(!is.null(pb)){ cval <- pb$getVal() Sys.sleep(0.000001) setTkProgressBar(pb, cval+1, label=paste(round((cval+1)/iterations*100, 0), "% done")) } } unlink(c(scale.offset.missingvals.temp, out.temp)) if(!is.null(pb)) { if(pb$getVal() == iterations) {close(pb)} } if(return.units == TRUE){ units <- units[is.na(units)==FALSE] for(x in 1:length(unique(units))){ print(noquote(paste("Units of variable '", unique(variable)[x], "' are ", unique(units)[x], sep=''))) } } attr(wx.out, "standard deviation") <- spread return(wx.out) }