code
stringlengths
1
13.8M
model { theta[1] ~ dnorm(theta.mu[1], theta.tau[1]) theta[2] ~ dnorm(theta.mu[2], theta.tau[2]) theta[3] ~ dlnorm(theta.mu[3], theta.tau[3]) theta[4] ~ dlnorm(theta.mu[4], theta.tau[4]) eta[1] ~ dnorm(eta.mu[1], eta.tau[1]) eta[2] ~ dnorm(eta.mu[2], eta.tau[2]) eta[3] ~ dlnorm(eta.mu[3], eta.tau[3]) eta[4] ~ dlnorm(eta.mu[4], eta.tau[4]) for (i in 1:k.II) { muE.II[i] <- theta[1] + theta[2] * d.II[i]^theta[4] / (theta[3]^theta[4] + d.II[i]^theta[4]) tauE.II[i] <- n.II[i] / sigmaE^2 YE.II[i] ~ dnorm(muE.II[i], tauE.II[i]) muS.II[i] <- eta[1] + eta[2] * d.II[i]^eta[4] / (eta[3]^eta[4] + d.II[i]^eta[4]) tauS.II[i] <- n.II[i] / sigmaS^2 YS.II[i] ~ dnorm(muS.II[i], tauS.II[i]) } muE.III <- theta[1] + theta[2] * d.III^theta[4] / (theta[3]^theta[4] + d.III^theta[4]) tauE.III <- n.III / sigmaE^2 for (i in 1:k.III) { YE.III[i] ~ dnorm(muE.III, tauE.III) } muS.III <- eta[1] + eta[2] * d.III^eta[4] / (eta[3]^eta[4] + d.III^eta[4]) tauS.III <- n.III / sigmaS^2 for (i in 1:k.III) { YS.III[i] ~ dnorm(muS.III, tauS.III) } }
context("Checking F-test significance helper functions") test_that("Can judge when an F-statistic is significant", { model.summary <- summary(lm(weight ~ feed, data = chickwts)) expect_equal(IsFSignificant(model.summary), TRUE) } ) test_that("Can judge when an F-statistic is NOT significant", { set.seed(1001) value <- rnorm(n = 100) group <- rep(1:4, times = 25) fake.data <- data.frame(value, group) model.summary <- summary(lm(value ~ group, data = fake.data)) expect_equal(IsFSignificant(model.summary), FALSE) } ) test_that("An F-statistic can be > 1 but still NOT significant", { set.seed(1001) red <- rnorm(n = 30) set.seed(1001) green <- rnorm(n = 30, mean = 0.3) set.seed(1001) blue <- rnorm(n = 30, mean = -0.3) value <- c(red, green, blue) group <- rep(c("red", "green", "blue"), each = 30) fake.data <- data.frame(group, value) model.summary <- summary(lm(value ~ group, data = fake.data)) expect_equal(IsFSignificant(model.summary), FALSE) } )
keep_empty <- function(fun) { function(x) { ret <- rep_along(x, "") update <- which(is.na(x) | x != "") ret[update] <- fun(x[update]) ret } } style_subtle <- keep_empty(function(x) { force(x) if (isTRUE(get_pillar_option_subtle())) { crayon_grey_0.6(x) } else { x } }) style_subtle_num <- function(x, negative) { if (isTRUE(get_pillar_option_subtle_num())) { style_subtle(x) } else { ifelse(negative, style_neg(x), x) } } style_hint <- keep_empty(function(x) { force(x) if (isTRUE(get_pillar_option_subtle())) { crayon_grey_0.8(x) } else { x } }) style_spark_na <- function(x) { crayon_yellow(x) } style_bold <- keep_empty(function(x) { if (isTRUE(get_pillar_option_bold())) { crayon_bold(x) } else { x } }) style_na <- function(x) { crayon_red(x) } style_neg <- keep_empty(function(x) { if (isTRUE(get_pillar_option_neg())) { crayon_red(x) } else { x } }) pillar_na <- function(use_brackets_if_no_color = FALSE) { if (use_brackets_if_no_color && !has_color()) { "<NA>" } else { style_na("NA") } } style_list <- function(x) { style_subtle(x) } num_colors <- local({ num_colors <- NULL function(forget = FALSE) { if (is.null(num_colors) || forget) { num_colors <<- cli::num_ansi_colors() } num_colors } }) has_color <- function() { num_colors() > 1 } make_style_fast <- function(...) { rlang::local_options(cli.num_colors = 16L) style_16 <- crayon::make_style(..., colors = 16) start_16 <- stats::start(style_16) finish_16 <- crayon::finish(style_16) style_256 <- crayon::make_style(..., colors = 256) start_256 <- stats::start(style_256) finish_256 <- crayon::finish(style_256) function(...) { if (has_color()) { colors <- num_colors() if (colors >= 256) { paste0(start_256, ..., finish_256) } else { paste0(start_16, ..., finish_16) } } else { paste0(...) } } } crayon_underline <- function(...) {} crayon_italic <- function(...) {} crayon_red <- function(...) {} crayon_yellow <- function(...) {} crayon_bold <- function(...) {} crayon_grey_0.6 <- function(...) {} crayon_grey_0.8 <- function(...) {} assign_crayon_styles <- function() { crayon_underline <<- make_style_fast("underline") crayon_italic <<- make_style_fast("italic") crayon_red <<- make_style_fast("red") crayon_yellow <<- make_style_fast("yellow") crayon_bold <<- make_style_fast("bold") crayon_grey_0.6 <<- make_style_fast(grDevices::grey(0.6), grey = TRUE) crayon_grey_0.8 <<- make_style_fast(grDevices::grey(0.8), grey = TRUE) }
get_issues_by_type <- function(city, issue_type, status = "open,acknowledged,closed,archived", limit = 100) { total <- 0 page <- 1 pagelimit <- min(100,limit) url <- paste("https://seeclickfix.com/api/v2/issues?place_url=",city,"&search=",issue_type,"&status=",status, "&per_page=",pagelimit,"&page=",page,sep = "") url <- gsub(" ","%20",x=url) rawdata <- RCurl::getURL(url) scf <- jsonlite::fromJSON(txt=rawdata,simplifyDataFrame = T,flatten=F) issue_id = scf$issues$id issue_status = scf$issues$status summary = scf$issues$summary description = scf$issues$description rating = scf$issues$rating lat = scf$issues$lat lng = scf$issues$lng issue_address = scf$issues$address created_at = scf$issues$created_at acknowledged_at = scf$issues$acknowledged_at closed_at = scf$issues$closed_at reopened_at = scf$issues$reopened_at updated_at = scf$issues$updated_at shortened_url = scf$issues$shortened_url video_url = scf$issues$media$video_url image_full = scf$issues$media$image_full image_square_100x100 = scf$issues$media$image_square_100x100 representative_image_url = scf$issues$media$representative_image_url issue_types = scf$issues$point$type url = scf$issues$url html_url = scf$issues$html_url comment_url = scf$issues$comment_url flag_url = scf$issues$flag_url close_url = if(length(scf$issues$transitions$close_url)>0){scf$issues$transitions$close_url} else{NA} open_url = if(length(scf$issues$transitions$open_url)>0){scf$issues$transitions$open_url} else{NA} reporter_id = scf$issues$reporter$id reporter_name = scf$issues$reporter$name reporter_wittytitle = scf$issues$reporter$witty_title reporter_role = scf$issues$reporter$role reporter_civicpoints = scf$issues$reporter$civic_points reporter_avatar_full = scf$issues$reporter$avatar$full reporter_avatar_square = scf$issues$reporter$avatar$square_100x100 allout <- data.frame( issue_id, issue_status, summary, description, rating, lat, lng, issue_address, created_at, acknowledged_at, closed_at, reopened_at, updated_at, shortened_url, video_url, image_full, image_square_100x100, representative_image_url, issue_types, url, html_url, comment_url, flag_url, close_url, open_url, reporter_id, reporter_name, reporter_wittytitle, reporter_role, reporter_civicpoints, reporter_avatar_full, reporter_avatar_square ) total <- nrow(allout) limit <- min(limit,scf$metadata$pagination$entries) while(limit>total){ page <- page+1 if((limit-total)<100){pagelimit <- (limit-total)} url <- paste("https://seeclickfix.com/api/v2/issues?place_url=",city,"&search=",issue_type,"&status=",status, "&per_page=",pagelimit,"&page=",page,sep = "") url <- gsub(" ","%20",x=url) rawdata <- RCurl::getURL(url) scf <- jsonlite::fromJSON(txt=rawdata,simplifyDataFrame = T,flatten=F) issue_id = scf$issues$id issue_status = scf$issues$status summary = scf$issues$summary description = scf$issues$description rating = scf$issues$rating lat = scf$issues$lat lng = scf$issues$lng issue_address = scf$issues$address created_at = scf$issues$created_at acknowledged_at = scf$issues$acknowledged_at closed_at = scf$issues$closed_at reopened_at = scf$issues$reopened_at updated_at = scf$issues$updated_at shortened_url = scf$issues$shortened_url video_url = scf$issues$media$video_url image_full = scf$issues$media$image_full image_square_100x100 = scf$issues$media$image_square_100x100 representative_image_url = scf$issues$media$representative_image_url issue_types = scf$issues$point$type url = scf$issues$url html_url = scf$issues$html_url comment_url = scf$issues$comment_url flag_url = scf$issues$flag_url close_url = if(length(scf$issues$transitions$close_url)>0){scf$issues$transitions$close_url} else{NA} open_url = if(length(scf$issues$transitions$open_url)>0){scf$issues$transitions$open_url} else{NA} reporter_id = scf$issues$reporter$id reporter_name = scf$issues$reporter$name reporter_wittytitle = scf$issues$reporter$witty_title reporter_role = scf$issues$reporter$role reporter_civicpoints = scf$issues$reporter$civic_points reporter_avatar_full = scf$issues$reporter$avatar$full reporter_avatar_square = scf$issues$reporter$avatar$square_100x100 holder <- data.frame( issue_id, issue_status, summary, description, rating, lat, lng, issue_address, created_at, acknowledged_at, closed_at, reopened_at, updated_at, shortened_url, video_url, image_full, image_square_100x100, representative_image_url, issue_types, url, html_url, comment_url, flag_url, close_url, open_url, reporter_id, reporter_name, reporter_wittytitle, reporter_role, reporter_civicpoints, reporter_avatar_full, reporter_avatar_square ) allout <- rbind(allout,holder) total <- nrow(allout) } return(allout) }
library(testthat) library(correlation) is_dev_version <- length(strsplit(packageDescription("correlation")$Version, "\\.")[[1]]) > 3 if (is_dev_version) { Sys.setenv("RunAllcorrelationTests" = "yes") } else { Sys.setenv("RunAllcorrelationTests" = "no") } test_check("correlation")
source("utils.R") context("Pool's createObject and destroyObject methods") describe("createObject", { it("throws if `factory` throws or returns NULL", { expect_error(poolCreate(MockPooledObj), "attempt to apply non-function") expect_error(poolCreate(function(x) NULL), "Object creation was not successful.") }) }) describe("destroyObject", { pool <- poolCreate(MockPooledObj$new, minSize = 1, maxSize = 3, idleTimeout = 0) it("throws if onDestroy fails", { checkCounts(pool, free = 1, taken = 0) failOnDestroy <<- TRUE a <- poolCheckout(pool) b <- poolCheckout(pool) checkCounts(pool, free = 0, taken = 2) op <- options(warn = 2) on.exit(options(op), add = TRUE) expect_error({ poolReturn(b) later::run_now() }, regexp = paste0( "Object of class MockPooledObj could not be ", "destroyed properly, but was successfully removed ", "from pool." ), class = "error" ) checkCounts(pool, free = 0, taken = 1) failOnDestroy <<- FALSE poolReturn(a) checkCounts(pool, free = 1, taken = 0) }) poolClose(pool) gc() })
context("Shallow copies of variables") with_mock_crunch({ ds <- cachedLoadDataset("test ds") test_that("copy creates a correct VariableDefinition", { expect_is(copy(ds$gender), "VariableDefinition") expected <- VariableDefinition( name = "Gender (copy)", alias = "gender_copy", description = "Gender", notes = "", discarded = FALSE, format = list(summary = list(digits = 2)), view = list( include_missing = FALSE, show_counts = FALSE, show_codes = FALSE, column_width = NULL ), derivation = list( `function` = "copy_variable", args = list( list(variable = "https://app.crunch.io/api/datasets/1/variables/gender/") ) ) ) expect_json_equivalent(copy(ds$gender), expected) }) test_that("deep copy creates a non-derived variable", { expect_false(copy(ds$gender, deep = TRUE)$derived) }) }) with_test_authentication({ with(test.dataset(newDatasetFromFixture("apidocs")), { q1_url <- self(ds$q1) varcat_url <- self(variables(ds)) test_that("Can copy and manipulate a categorical variable", { expect_false("copy1" %in% names(ds)) expect_true("q1" %in% names(ds)) expect_silent(ds$copy1 <- copy(ds$q1, name = "copy1")) expect_identical(as.vector(ds$copy1), as.vector(ds$q1)) expect_false(name(ds$copy1) == name(ds$q1)) expect_false(alias(ds$copy1) == alias(ds$q1)) expect_false(self(ds$copy1) == self(ds$q1)) ds <- refresh(ds) expect_true("copy1" %in% names(ds)) expect_true("q1" %in% names(ds)) names(categories(ds$copy1))[2] <- "Canine" expect_identical( names(categories(ds$copy1))[1:3], c("Cat", "Canine", "Bird") ) expect_identical( names(categories(ds$q1))[1:3], c("Cat", "Dog", "Bird") ) categories(ds$q1)[1:2] <- categories(ds$q1)[2:1] expect_identical( names(categories(ds$copy1))[1:3], c("Cat", "Canine", "Bird") ) expect_identical( names(categories(ds$q1))[1:3], c("Dog", "Cat", "Bird") ) }) test_that("Can copy an array variable and manipulate it independently", { ds$allpets2 <- copy(ds$allpets) expect_true("allpets" %in% names(ds)) expect_true("allpets2" %in% names(ds)) expect_identical(name(ds$allpets2), "All pets owned (copy)") name(ds$allpets2) <- "Copy of allpets" expect_identical(name(ds$allpets2), "Copy of allpets") expect_identical(name(ds$allpets), "All pets owned") subvariables(ds$allpets2)[1:2] <- subvariables(ds$allpets2)[2:1] expect_identical( names(subvariables(ds$allpets2)), c("Dog", "Cat", "Bird") ) expect_identical( names(subvariables(ds$allpets)), c("Cat", "Dog", "Bird") ) names(subvariables(ds$allpets))[2] <- "Canine" expect_identical( names(subvariables(ds$allpets2)), c("Dog", "Cat", "Bird") ) expect_identical( names(subvariables(ds$allpets)), c("Cat", "Canine", "Bird") ) }) test_that("Can copy subvariables (as non-subvars)", { }) }) })
pacotestRvineSeq <- function(data, RVM, pacotestOptions, level=0.05, illustration=2, stopIfRejected = TRUE) { pacotestOptions = pacotestset(pacotestOptions) data <- as.matrix(data) d <- dim(RVM$Matrix)[1] o <- diag(RVM$Matrix) if (!is(RVM, "RVineMatrix")) stop("'RVM' has to be an RVineMatrix object.") if (any(data > 1) || any(data < 0)) stop("Data has be in the interval [0,1].") if (dim(data)[2] != d) stop("Dimensions of 'data' and 'RVM' do not match.") if (dim(data)[1] < 2) stop("Number of observations has to be at least 2.") oldRVM <- RVM if (any(o != length(o):1)) { RVM <- getFromNamespace('normalizeRVineMatrix','VineCopula')(RVM) data <- data[, o[length(o):1]] } testResultSummary = data.frame(matrix(ncol = 4, nrow = d-2)) names(testResultSummary) = c("Tree", "NumbOfRejections", "IndividualTestLevel", "Interpretation") rejectH0 = FALSE out = matrix(list(),nrow = d, ncol =d) pValues = matrix(NA, nrow=d, ncol=d) for (k in (d-1):2) { numbTests = (d-2)*(d-1)/2 thisTreeLevel = level/numbTests numbRejections = 0 for (i in (k - 1):1) { subRVM = extractSubTree(RVM, tree = (d-k+1), copulaNumber = (k-i), data) svcmDataFrame = rVineDataFrameRep(subRVM$RVM) if (exists('estUncertWithRanks', pacotestOptions)) { withDerivs = pacotestOptions$estUncertWithRanks } else { withDerivs = FALSE } cPitData = getCpitsFromVine(subRVM$data, svcmDataFrame, withDerivs) copulaInd = nrow(svcmDataFrame) cPit1 = getCpit1(cPitData, svcmDataFrame, copulaInd) cPit2 = getCpit2(cPitData, svcmDataFrame, copulaInd) if (!is.data.frame(subRVM$data)) { subRVM$data = as.data.frame(subRVM$data) } Udata = cbind(cPit1,cPit2) cPit1Name = paste(dimnames(subRVM$data)[[2]][svcmDataFrame$var1[copulaInd]], paste(dimnames(subRVM$data)[[2]][svcmDataFrame$condset[[copulaInd]]], collapse=","), sep="|") cPit2Name = paste(dimnames(subRVM$data)[[2]][svcmDataFrame$var2[copulaInd]], paste(dimnames(subRVM$data)[[2]][svcmDataFrame$condset[[copulaInd]]], collapse=","), sep="|") dimnames(Udata)[[2]] = c(cPit1Name, cPit2Name) W = subRVM$data[,svcmDataFrame$condset[[copulaInd]], drop=FALSE] out[k,i][[1]] = pacotest(Udata,W,pacotestOptions, data = subRVM$data, svcmDataFrame = svcmDataFrame, cPitData = cPitData) pValues[k,i] = out[k,i][[1]]$pValue if (illustration == 1) { message(oldRVM$Matrix[i, i],",",oldRVM$Matrix[k, i], "|", paste(oldRVM$Matrix[(k + 1):d, i],collapse = ","), " pValue:", out[k,i][[1]]$pValue) } if (out[k,i][[1]]$pValue < thisTreeLevel) { numbRejections = numbRejections +1 } } testResultSummary[(d-k), 1:3] = c((d-k+1), numbRejections, thisTreeLevel) if (numbRejections > 0) { testResultSummary[(d-k), 4] = paste(numbRejections, "rejections at a individual test level of ", thisTreeLevel, "--> Sequential test procedure can be stopped due to a rejection") } else if (numbRejections == 0) { if (k == 2) { testResultSummary[(d-k), 4] = paste("Simplifying assumption can not be rejected at a ", level*100, " % level") } else { testResultSummary[(d-k), 4] = "No rejection --> Continue the sequential test in the next tree" } } rejectH0 = any(rejectH0, numbRejections>0) if (illustration == 2) { message((d-k+1),". Tree: ", testResultSummary$Interpretation[(d-k)]) } if (rejectH0 & stopIfRejected) { message("Stopped the sequential test due to a rejection") return(list(pacotestResultLists=out, pValues = pValues, testResultSummary = testResultSummary)) } } return(list(pacotestResultLists = out, pValues = pValues, testResultSummary = testResultSummary)) } pacotestRvineSingleCopula <- function(data, RVM, pacotestOptions, tree, copulaNumber) { pacotestOptions = pacotestset(pacotestOptions) data <- as.matrix(data) d <- dim(RVM$Matrix)[1] o <- diag(RVM$Matrix) if (!is(RVM, "RVineMatrix")) stop("'RVM' has to be an RVineMatrix object.") if (any(data > 1) || any(data < 0)) stop("Data has be in the interval [0,1].") if (dim(data)[2] != d) stop("Dimensions of 'data' and 'RVM' do not match.") if (dim(data)[1] < 2) stop("Number of observations has to be at least 2.") if (!(tree > 1 && tree <= (d-1))) stop("'tree' has do be larger than 2 and at most dim (of the vine) - 1") if (!(copulaNumber > 0 && copulaNumber <= (d-tree))) stop("Invalid copula number") if (any(o != length(o):1)) { RVM <- getFromNamespace('normalizeRVineMatrix','VineCopula')(RVM) data <- data[, o[length(o):1]] } subRVM = extractSubTree(RVM, tree = tree, copulaNumber = copulaNumber, data) svcmDataFrame = rVineDataFrameRep(subRVM$RVM) if (exists('estUncertWithRanks', pacotestOptions)) { withDerivs = pacotestOptions$estUncertWithRanks } else { withDerivs = FALSE } cPitData = getCpitsFromVine(subRVM$data, svcmDataFrame, withDerivs) copulaInd = nrow(svcmDataFrame) cPit1 = getCpit1(cPitData, svcmDataFrame, copulaInd) cPit2 = getCpit2(cPitData, svcmDataFrame, copulaInd) if (!is.data.frame(subRVM$data)) { subRVM$data = as.data.frame(subRVM$data) } Udata = cbind(cPit1,cPit2) cPit1Name = paste(dimnames(subRVM$data)[[2]][svcmDataFrame$var1[copulaInd]], paste(dimnames(subRVM$data)[[2]][svcmDataFrame$condset[[copulaInd]]], collapse=","), sep="|") cPit2Name = paste(dimnames(subRVM$data)[[2]][svcmDataFrame$var2[copulaInd]], paste(dimnames(subRVM$data)[[2]][svcmDataFrame$condset[[copulaInd]]], collapse=","), sep="|") dimnames(Udata)[[2]] = c(cPit1Name, cPit2Name) W = subRVM$data[,svcmDataFrame$condset[[copulaInd]], drop=FALSE] pacotestResultList = pacotest(Udata,W,pacotestOptions, data = subRVM$data, svcmDataFrame = svcmDataFrame, cPitData = cPitData) return(pacotestResultList) }
get_Splinebasis <- function(objterm, data=parent.frame(), specials="NPHNLL", all.vars.func=all_specials_vars, unique=TRUE, order=c("formula", "specials")){ order <- match.arg(order) indxvar <- attr(objterm, "specials")[specials] nvars <- length(unlist(indxvar)) if(nvars==0){ return(NULL) } else{ if(order=="specials"){ oindxvar <- 1:nvars } else { oindxvar <- order(unlist(indxvar)) } var_list <- NULL Spline_list <- NULL for(is in specials){ fun <- mget(is, mode = "function", envir = parent.frame(), inherits=TRUE, ifnotfound=list(NULL))[[1]] for( i in indxvar[[is]]){ thecall <- match.call(fun, attr(objterm,"variables")[[i+1]]) thevar <- thecall[["x"]] Knots <- eval(as.expression(thecall[["Knots"]])) if( !is.null(thecall[["Boundary.knots"]]) ){ therange <- eval(as.expression(thecall[["Boundary.knots"]])) } else { therange <- eval(call("range", thevar), envir=data) } thecall[["Spline"]] <- ifelse(is.null(thecall[["Spline"]]), eval(formals(fun)$Spline)[1], thecall[["Spline"]]) if( is.null(thecall[["Spline"]])){ thespline <- BSplineBasis(knots=c(therange[1], eval(as.expression(thecall[["Knots"]])), therange[2]), degree=ifelse(is.null(thecall[["Degree"]]), formals(fun)[["Degree"]], thecall[["Degree"]]), keep.duplicates=FALSE) } else if( thecall[["Spline"]]== "tp-spline" ){ thespline <- TPSplineBasis(knots=eval(as.expression(thecall[["Knots"]])), degree=ifelse(is.null(thecall[["Degree"]]), formals(fun)[["Degree"]], thecall[["Degree"]]), min=therange[1], max=therange[2], type="standard") } else if( thecall[["Spline"]]== "tpi-spline" ){ thespline <- TPSplineBasis(knots=eval(as.expression(thecall[["Knots"]])), degree=ifelse(is.null(thecall[["Degree"]]), formals(fun)[["Degree"]], thecall[["Degree"]]), min=therange[1], max=therange[2], type="increasing") } else if( thecall[["Spline"]]== "b-spline" ){ if (is.null(thecall[["Degree"]])) {thecall[["Degree"]]<-3} thespline <- BSplineBasis(knots=c(therange[1], eval(as.expression(thecall[["Knots"]])), therange[2]), degree=ifelse(is.null(thecall[["Degree"]]), formals(fun)[["Degree"]], thecall[["Degree"]]), keep.duplicates=FALSE) } else if( thecall[["Spline"]]== "m-spline" ){ if (is.null(thecall[["Degree"]])) {thecall[["Degree"]]<-3} thespline <- MSplineBasis(knots=c(therange[1], eval(as.expression(thecall[["Knots"]])), therange[2]), degree=ifelse(is.null(thecall[["Degree"]]), formals(fun)[["Degree"]], thecall[["Degree"]]), keep.duplicates=FALSE) } else { stop("wrong type of spline specification", attr(objterm,"variables")[[i+1]]) } var_list <- c( var_list, thevar) Spline_list <- c( Spline_list, thespline) } } names(Spline_list) <- var_list return(Spline_list[oindxvar]) } } get_TimeSplinebasis <- function(objterm, data=parent.frame(), specials="NPHNLL", all.vars.func=all_specials_vars, unique=TRUE, order=c("formula", "specials")){ order <- match.arg(order) indxvar <- attr(objterm, "specials")[specials] nvars <- length(unlist(indxvar)) if(nvars==0){ return(NULL) } else{ if(order=="specials"){ oindxvar <- 1:nvars } else { oindxvar <- order(unlist(indxvar)) } var_list <- list() Spline_list <- list() for(is in specials){ fun <- mget(is, mode = "function", envir = parent.frame(), inherits=TRUE, ifnotfound=list(NULL))[[1]] for( i in indxvar[[is]]){ thecall <- match.call(fun, attr(objterm,"variables")[[i+1]]) thevar <- thecall[["timevar"]] if( !is.null(thecall[[paste("Spline", is, sep=".")]])){ thespline <- eval(as.expression(thecall[[paste("Spline", is, sep=".")]])) } else { Knots <- eval(as.expression(thecall[["Knots.t"]])) if( !is.null(thecall[["Boundary.knots.t"]]) ){ therange <- eval(as.expression(thecall[["Boundary.knots.t"]])) } else { therange <- eval(call("range", thevar), envir=data) } thecall[["Spline"]] <- ifelse(is.null(thecall[["Spline"]]), eval(formals(fun)$Spline)[1], thecall[["Spline"]]) if( is.null(thecall[["Spline"]])){ thespline <- BSplineBasis(knots=c(therange[1], eval(as.expression(thecall[["Knots.t"]])), therange[2]), degree=ifelse(is.null(thecall[["Degree.t"]]), formals(fun)[["Degree.t"]], thecall[["Degree.t"]]), keep.duplicates=FALSE) } else if( thecall[["Spline"]]== "tp-spline" ){ thespline <- TPSplineBasis(knots=eval(as.expression(thecall[["Knots.t"]])), degree=ifelse(is.null(thecall[["Degree.t"]]), formals(fun)[["Degree.t"]], thecall[["Degree.t"]]), min=therange[1], max=therange[2], type="standard") } else if( thecall[["Spline"]]== "tpi-spline" ){ thespline <- TPSplineBasis(knots=eval(as.expression(thecall[["Knots.t"]])), degree=ifelse(is.null(thecall[["Degree.t"]]), formals(fun)[["Degree.t"]], thecall[["Degree.t"]]), min=therange[1], max=therange[2], type="standard") } else if( thecall[["Spline"]]== "b-spline" ){ if (is.null(thecall[["Degree.t"]])) {thecall[["Degree.t"]]<-3} thespline <- BSplineBasis(knots=c(therange[1], eval(as.expression(thecall[["Knots.t"]])), therange[2]), degree=ifelse(is.null(thecall[["Degree.t"]]), formals(fun)[["Degree.t"]], thecall[["Degree.t"]]), keep.duplicates=FALSE) } else if( thecall[["Spline"]]== "m-spline" ){ if (is.null(thecall[["Degree.t"]])) {thecall[["Degree.t"]]<-3} thespline <- BSplineBasis(knots=c(therange[1], eval(as.expression(thecall[["Knots.t"]])), therange[2]), degree=ifelse(is.null(thecall[["Degree.t"]]), formals(fun)[["Degree.t"]], thecall[["Degree.t"]]), keep.duplicates=FALSE) } else { stop("wrong type of spline specification", attr(objterm,"variables")[[i+1]]) } } var_list <- c( var_list, thevar) Spline_list <- c( Spline_list, thespline) } } names(Spline_list) <- var_list return(Spline_list[oindxvar]) } }
FilterInformationGain = R6Class("FilterInformationGain", inherit = Filter, public = list( initialize = function() { param_set = ps( type = p_fct(c("infogain", "gainratio", "symuncert"), default = "infogain"), equal = p_lgl(default = FALSE), discIntegers = p_lgl(default = TRUE), threads = p_int(lower = 0L, default = 0L, tags = "threads") ) super$initialize( id = "information_gain", task_type = c("classif", "regr"), param_set = param_set, feature_types = c("integer", "numeric", "factor", "ordered"), packages = "FSelectorRcpp", man = "mlr3filters::mlr_filters_information_gain" ) } ), private = list( .calculate = function(task, nfeat) { pv = self$param_set$values pv$type = pv$type %??% "infogain" pv$equal = pv$equal %??% task$task_type == "regr" x = setDF(task$data(cols = task$feature_names)) y = task$truth() scores = invoke(FSelectorRcpp::information_gain, x = x, y = y, .args = pv) set_names(scores$importance, scores$attributes) } ) ) mlr_filters$add("information_gain", FilterInformationGain)
`ll.jRCI.ase.b0.A2` = function(par, yi, ind.lst, X, sex, ni, ni0, xs, iphi, theta) { logL = ll.tRCI.A(par0=c(par[1:2], c(0, 0), par[-(1:2)]), yi=yi, ind.lst=ind.lst, X=X, twosex=TRUE, iphi=iphi) logL = logL + ll.aRC(par0=c(0, par[3]), ni[sex == 1], ni0[sex == 1], xs[sex == 1], theta) logL = logL + ll.aRC(par0=c(0, par[4]), ni[sex == -1], ni0[sex == -1], xs[sex == -1], theta) return(logL) }
`globalCostMatrix` <- function(lm, step.matrix=symmetric1, window.function=noWindow, native=TRUE, seed=NULL, ...) { if (!is.stepPattern(step.matrix)) stop("step.matrix is no stepMatrix object"); n <- nrow(lm); m <- ncol(lm); nsteps<-dim(step.matrix)[1]; if(!is.null(seed)) { cm <- seed; } else { cm <- matrix(NA,nrow=n,ncol=m); cm[1,1] <- lm[1,1]; } sm <- matrix(NA,nrow=n,ncol=m); if(native){ wm <- matrix(FALSE,nrow=n,ncol=m); wm[window.function(row(wm),col(wm), query.size=n, reference.size=m, ...)]<-TRUE; storage.mode(wm) <- "logical"; storage.mode(lm) <- "double"; storage.mode(cm) <- "double"; storage.mode(step.matrix) <- "double"; out <- .Call(C_computeCM_Call, wm,lm,cm,step.matrix); } else { warning("Native dtw implementation not available: using (slow) interpreted fallback"); dir <- step.matrix; npats <- attr(dir,"npat"); for (j in 1:m) { for (i in 1:n) { if(!window.function(i,j, query.size=n, reference.size=m, ...)) { next; } if(!is.na(cm[i,j])) { next; } clist<-numeric(npats)+NA; for (s in 1:nsteps) { p<-dir[s,1]; ii<-i-dir[s,2]; jj<-j-dir[s,3]; if(ii>=1 && jj>=1) { cc<-dir[s,4]; if(cc == -1) { clist[p]<-cm[ii,jj]; } else { clist[p]<-clist[p]+cc*lm[ii,jj]; } } } minc<-which.min(clist); if(length(minc)>0) { cm[i,j]<-clist[minc]; sm[i,j]<-minc; } } } out <- list(costMatrix=cm,directionMatrix=sm); } out$stepPattern <- step.matrix; return(out); }
reduced_skillspace_beta_2_probs <- function( Z, beta ) { res <- cdm_sumnorm( exp( Z %*% beta )[,1] ) return(res) }
get_site_ID <- function(lake_name){ siteID <- get_metadata(lake_name, 'siteID') return(siteID) } temp_types = function(){ return(c('Lake.Temp.Summer.Satellite','Lake.Temp.Summer.InSitu')) }
vaws <- function(y, kstar = 16, sigma2 = 1, mask = NULL, scorr = 0, spmin = 0.25, ladjust = 1, wghts = NULL, u = NULL, maxni = FALSE) { args <- match.call() dy <- dim(y) nvec <- dy[1] dy <- dy[-1] d <- length(dy) if (length(dy) > 3) stop("Vector AWS for more than 3 dimensional grids is not implemented") lambda <- 2 * sigma2 * ladjust * switch(d, qchisq(pchisq(14.6, 1), nvec), qchisq(pchisq(9.72, 1), nvec), qchisq(pchisq(8.82, 1), nvec)) if (is.null(wghts)) wghts <- c(1, 1, 1) wghts <- switch(length(dy), c(0, 0), c(wghts[1] / wghts[2], 0), wghts[1] / wghts[2:3]) n1 <- switch(d, dy, dy[1], dy[1]) n2 <- switch(d, 1, dy[2], dy[2]) n3 <- switch(d, 1, 1, dy[3]) n <- n1 * n2 * n3 if (is.null(mask)) { mask <- array(TRUE, dy) } dmask <- dim(mask) if(is.null(dmask)) dmask <- length(mask) nvoxel <- sum(mask) position <- array(0,dmask) position[mask] <- 1:nvoxel dim(y) <- c(nvec,n) y <- y[,mask] if(!is.null(u)){ dim(u) <- c(nvec,n) u <- u[,mask] } h0 <- 0 if (any(scorr > 0)) { h0 <- numeric(length(scorr)) for (i in 1:length(h0)) h0[i] <- geth.gauss(scorr[i]) if (length(h0) < d) h0 <- rep(h0[1], d) cat("Corresponding bandwiths for specified correlation:", h0, "\n") } hseq <- 1 zobj <- list(bi = rep(1, nvoxel), theta = y) bi <- zobj$bi cat("Progress:") total <- cumsum(1.25 ^ (1:kstar)) / sum(1.25 ^ (1:kstar)) mc.cores <- setCores(, reprt = FALSE) k <- 1 hmax <- 1.25 ^ (kstar / d) lambda0 <- lambda mae <- NULL while (k <= kstar) { hakt0 <- gethani(1, 1.25 * hmax, 2, 1.25 ^ (k - 1), wghts, 1e-4) hakt <- gethani(1, 1.25 * hmax, 2, 1.25 ^ k, wghts, 1e-4) cat("step", k, "hakt", hakt, "time", format(Sys.time()), "\n") hseq <- c(hseq, hakt) dlw <- (2 * trunc(hakt / c(1, wghts)) + 1)[1:d] if (scorr[1] >= 0.1) lambda0 <- lambda0 * Spatialvar.gauss(hakt0 / 0.42445 / 4, h0, d) / Spatialvar.gauss(hakt0 / 0.42445 / 4, 1e-5, d) zobj <- .Fortran(C_vaws, as.double(y), as.integer(position), as.integer(nvec), as.integer(n1), as.integer(n2), as.integer(n3), hakt = as.double(hakt), as.double(lambda0), as.double(zobj$theta), bi = as.double(zobj$bi), vred = double(nvoxel), theta = double(nvec * nvoxel), as.integer(mc.cores), as.double(spmin), double(prod(dlw)), as.double(wghts), double(nvec * mc.cores) )[c("bi", "theta", "hakt","vred")] if (maxni) bi <- zobj$bi <- pmax(bi, zobj$bi) if (!is.null(u)) { cat( "bandwidth: ", signif(hakt, 3), " MSE: ", signif(mean((zobj$theta - u) ^ 2), 3), " MAE: ", signif(mean(abs(zobj$theta - u)), 3), " mean(bi)=", signif(mean(zobj$bi), 3), "\n" ) mae <- c(mae, signif(mean(abs(zobj$theta - u)), 3)) } x <- 1.25 ^ k scorrfactor <- x / (3 ^ d * prod(scorr) * prod(h0) + x) lambda0 <- lambda * scorrfactor if (max(total) > 0) { cat(signif(total[k], 2) * 100, "% . ", sep = "") } k <- k + 1 gc() } cat("\n") y0 <- theta <- array(0,c(nvec,n)) y0[,mask] <- y theta[,mask] <- zobj$theta dim(y0) <- dim(theta) <- c(nvec,dy) bi <- vred <- array(dy) bi[mask] <- zobj$bi vred[mask] <- zobj$vred rm(zobj) awsobj( y0, theta, sigma2 * vred, hakt, sigma2, lkern = 1L, lambda, ladjust, aws = TRUE, memory = FALSE, args, hseq = hseq, homogen = FALSE, earlystop = FALSE, family = "Gaussian", wghts = wghts, mae = mae, psnr = NULL, ni = bi ) } vawscov <- function(y, kstar = 16, invcov = NULL, mask = NULL, scorr = 0, spmin = 0.25, ladjust = 1, wghts = NULL, u = NULL, maxni = FALSE) { args <- match.call() dy <- dim(y) nvec <- dy[1] dy <- dy[-1] d <- length(dy) if (length(dy) > 3) stop("Vector AWS for more than 3 dimensional grids is not implemented") lambda <- 2 * ladjust * switch(d, qchisq(pchisq(14.6, 1), nvec), qchisq(pchisq(9.72, 1), nvec), qchisq(pchisq(8.82, 1), nvec)) if (is.null(wghts)) wghts <- c(1, 1, 1) wghts <- switch(length(dy), c(0, 0), c(wghts[1] / wghts[2], 0), wghts[1] / wghts[2:3]) n1 <- switch(d, dy, dy[1], dy[1]) n2 <- switch(d, 1, dy[2], dy[2]) n3 <- switch(d, 1, 1, dy[3]) n <- n1 * n2 * n3 if (is.null(mask)) { mask <- array(TRUE, dy) } dmask <- dim(mask) if(is.null(dmask)) dmask <- length(mask) nvoxel <- sum(mask) position <- array(0,dmask) position[mask] <- 1:nvoxel dim(y) <- c(nvec,n) y <- y[,mask] nvd <- nvec * (nvec + 1) / 2 dim(invcov) <- c(nvd,n) invcov <- invcov[,mask] if(!is.null(u)){ dim(u) <- c(nvec,n) u <- u[,mask] } h0 <- 0 if (any(scorr > 0)) { h0 <- numeric(length(scorr)) for (i in 1:length(h0)) h0[i] <- geth.gauss(scorr[i]) if (length(h0) < d) h0 <- rep(h0[1], d) cat("Corresponding bandwiths for specified correlation:", h0, "\n") } hseq <- 1 zobj <- list(bi = rep(1, nvoxel), theta = y) bi <- zobj$bi cat("Progress:") total <- cumsum(1.25 ^ (1:kstar)) / sum(1.25 ^ (1:kstar)) mc.cores <- setCores(, reprt = FALSE) k <- 1 hmax <- 1.25 ^ (kstar / d) lambda0 <- lambda mae <- NULL while (k <= kstar) { hakt0 <- gethani(1, 1.25 * hmax, 2, 1.25 ^ (k - 1), wghts, 1e-4) hakt <- gethani(1, 1.25 * hmax, 2, 1.25 ^ k, wghts, 1e-4) cat("step", k, "hakt", hakt, "time", format(Sys.time()), "\n") hseq <- c(hseq, hakt) dlw <- (2 * trunc(hakt / c(1, wghts)) + 1)[1:d] if (scorr[1] >= 0.1) lambda0 <- lambda0 * Spatialvar.gauss(hakt0 / 0.42445 / 4, h0, d) / Spatialvar.gauss(hakt0 / 0.42445 / 4, 1e-5, d) zobj <- .Fortran(C_vaws2cov, as.double(y), as.integer(position), as.integer(nvec), as.integer(nvec * (nvec + 1) / 2), as.integer(n1), as.integer(n2), as.integer(n3), hakt = as.double(hakt), as.double(lambda0), as.double(zobj$theta), bi = as.double(zobj$bi), vred = double(nvoxel), theta = double(nvec * nvoxel), as.double(invcov), as.integer(mc.cores), as.double(spmin), double(prod(dlw)), as.double(wghts), double(nvec * mc.cores), double(nvec * mc.cores), double(nvec * (nvec + 1) / 2 * mc.cores) )[c("bi", "theta", "hakt", "vred")] if (maxni) bi <- zobj$bi <- pmax(bi, zobj$bi) if (!is.null(u)) { cat( "bandwidth: ", signif(hakt, 3), " MSE: ", signif(mean((zobj$theta - u[mask]) ^ 2), 3), " MAE: ", signif(mean(abs(zobj$theta - u[mask])), 3), " mean(bi)=", signif(mean(zobj$bi), 3), "\n" ) mae <- c(mae, signif(mean(abs(zobj$theta - u)), 3)) } x <- 1.25 ^ k scorrfactor <- x / (3 ^ d * prod(scorr) * prod(h0) + x) lambda0 <- lambda * scorrfactor if (max(total) > 0) { cat(signif(total[k], 2) * 100, "% . ", sep = "") } k <- k + 1 gc() } cat("\n") theta <- array(0,c(nvec,n)) theta[,mask] <- zobj$theta dim(theta) <- c(nvec,dy) bi <- vred <- array(dy) bi[mask] <- zobj$bi vred[mask] <- zobj$vred rm(zobj) y0 <- array(0,c(nvec,n)) y0[,mask] <- y dim(y0) <- c(nvec,dy) rm(y) invcov0 <- array(0,c(nvd,n)) invcov0[,mask] <- invcov dim(invcov0) <- c(nvd,dy) rm(invcov) awsobj( y0, theta, sweep(invcov0, 2:(d + 1), vred, "*"), hakt, invcov0, lkern = 1L, lambda, ladjust, aws = TRUE, memory = FALSE, args, hseq = hseq, homogen = FALSE, earlystop = FALSE, family = "Gaussian", wghts = wghts, mae = mae, psnr = NULL, ni = bi ) }
mltrain <- function(object, ...) { UseMethod("mltrain") } mlpredict <- function(model, newdata, ...) { UseMethod("mlpredict") } mltrain.default <- function(object, ...) { funcname <- paste("mltrain.base", object$base.method, sep = "") stop(paste("The function '", funcname, "(object, ...)' is not implemented", sep = "")) } mlpredict.default <- function(model, newdata, ...) { funcname <- paste("mlpredict.", class(model), sep = "") stop(paste("The function '", funcname, "(dataset, newdata, ...)' is not implemented", sep = "")) } mltrain.baseSVM <- function(object, ...) { if (requireNamespace("e1071", quietly = TRUE)) { formula <- stats::as.formula(paste("`", object$labelname, "` ~ .", sep="")) model <- e1071::svm(formula, object$data, probability = TRUE, ...) } else { stop(paste("There are no installed package 'e1071' to use SVM classifier", "as base method")) } model } mlpredict.svm <- function(model, newdata, ...) { if (!requireNamespace("e1071", quietly = TRUE)) { stop(paste("There are no installed package 'e1071' to use SVM classifier", "as base method")) } result <- stats::predict(model, newdata, probability = TRUE, ...) prediction <- as.character(result) all.prob <- attr(result, "probabilities") data.frame( prediction = prediction, probability = all.prob[cbind(rownames(newdata), prediction)], row.names = rownames(newdata) ) } mltrain.baseC5.0 <- function(object, ...) { if (requireNamespace("C50", quietly = TRUE)) { formula <- stats::as.formula(paste("`", object$labelname, "` ~ .", sep="")) model <- C50::C5.0(formula, object$data, ...) } else { stop(paste("There are no installed package 'C50' to use C5.0 classifier", "as base method")) } model } mlpredict.C5.0 <- function(model, newdata, ...) { if (!requireNamespace("C50", quietly = TRUE)) { stop(paste("There are no installed package 'C50' to use C5.0 classifier", "as base method")) } result <- C50::predict.C5.0(model, newdata, type = "prob", ...) prediction <- colnames(result)[apply(result, 1, which.max)] data.frame( prediction = prediction, probability = result[cbind(rownames(newdata), prediction)], row.names = rownames(newdata) ) } mltrain.baseCART <- function(object, ...) { if (requireNamespace("rpart", quietly = TRUE)) { formula <- stats::as.formula(paste("`", object$labelname, "` ~ .", sep="")) model <- rpart::rpart(formula, object$data, ...) } else { stop(paste("There are no installed package 'rpart' to use Cart classifier", "as base method")) } model } mlpredict.rpart <- function(model, newdata, ...) { if (!requireNamespace("rpart", quietly = TRUE)) { stop(paste("There are no installed package 'rpart' to use Cart classifier", "as base method")) } result <- stats::predict(model, newdata, type = "prob", ...) rownames(result) <- rownames(newdata) prediction <- colnames(result)[apply(result, 1, which.max)] data.frame( prediction = prediction, probability = result[cbind(rownames(newdata), prediction)], row.names = rownames(newdata) ) } mltrain.baseRF <- function(object, ...) { if (requireNamespace("randomForest", quietly = TRUE)) { traindata <- object$data[, -object$labelindex] labeldata <- object$data[, object$labelindex] model <- randomForest::randomForest(traindata, labeldata, ...) } else { stop(paste("There are no installed package 'randomForest' to use", "randomForest classifier as base method")) } model } mlpredict.randomForest <- function(model, newdata, ...) { if (!requireNamespace("randomForest", quietly = TRUE)) { stop(paste("There are no installed package 'randomForest' to use", "randomForest classifier as base method")) } result <- stats::predict(model, newdata, type = "prob", ...) prediction <- colnames(result)[apply(result, 1, which.max)] data.frame( prediction = prediction, probability = result[cbind(rownames(newdata), prediction)], row.names = rownames(newdata) ) } mltrain.baseNB <- function(object, ...) { if (requireNamespace("e1071", quietly = TRUE)) { formula <- stats::as.formula(paste("`", object$labelname, "` ~ .", sep="")) duplicate <- any(table(object$data[,object$labelname]) == 1) model <- e1071::naiveBayes(formula, rbind(object$data, utiml_ifelse(duplicate, object$data, NULL)), type = "raw", ...) } else { stop(paste("There are no installed package 'e1071' to use naiveBayes", "classifier as base method")) } model } mlpredict.naiveBayes <- function(model, newdata, ...) { if (!requireNamespace("e1071", quietly = TRUE)) { stop(paste("There are no installed package 'e1071' to use naiveBayes", "classifier as base method")) } result <- stats::predict(model, newdata, type = "raw", ...) rownames(result) <- rownames(newdata) classes <- colnames(result)[apply(result, 1, which.max)] data.frame( prediction = classes, probability = result[cbind(rownames(newdata), classes)], row.names = rownames(newdata) ) } mltrain.baseKNN <- function(object, ...) { if (!requireNamespace("kknn", quietly = TRUE)) { stop(paste("There are no installed package 'kknn' to use kNN classifier as", "base method")) } object$extrakNN <- list(...) object } mlpredict.baseKNN <- function(model, newdata, ...) { if (!requireNamespace("kknn", quietly = TRUE)) { stop(paste("There are no installed package 'kknn' to use kNN classifier as", "base method")) } formula <- stats::as.formula(paste("`", model$labelname, "` ~ .", sep = "")) args <- list(...) if (is.null(model$extrakNN[["k"]]) || !is.null(args[["k"]])) { result <- kknn::kknn(formula, rep_nom_attr(model$data, FALSE), rep_nom_attr(newdata), ...) } else { result <- kknn::kknn(formula, rep_nom_attr(model$data, FALSE), rep_nom_attr(newdata), k = model$extrakNN[["k"]], ...) } prediction <- as.character(result$fitted.values) all.prob <- as.matrix(result$prob) rownames(all.prob) <- rownames(newdata) data.frame( prediction = prediction, probability = all.prob[cbind(rownames(newdata), prediction)], row.names = rownames(newdata) ) } mltrain.baseXGB <- function(object, ...) { if (!requireNamespace("xgboost", quietly = TRUE)) { stop(paste("There are no installed package 'xgboost' to use xgboost", "classifier as base method")) } def.args <- list( data = as.matrix(rep_nom_attr(object$data[, -object$labelindex])), label = as.numeric(object$data[, object$labelindex]) - 1, nthread = 1, nrounds = 3, verbose = FALSE, objective = ifelse(nlevels(object$data[, object$labelindex]) == 2, "binary:logistic", "multi:softprob") ) if (nlevels(object$data[, object$labelindex]) > 2) { def.args$num_class <- nlevels(object$data[, object$labelindex]) } args <- list(...) for (narg in names(args)) { def.args[[narg]] <- args[[narg]] } model <- do.call(xgboost::xgboost, def.args) attr(model, "classes") <- levels(object$data[, object$labelindex]) model } mlpredict.xgb.Booster <- function(model, newdata, ...) { if (!requireNamespace("xgboost", quietly = TRUE)) { stop(paste("There are no installed package 'xgboost' to use xgboost", "classifier as base method")) } classes <- attr(model, "classes") pred <- stats::predict(model, as.matrix(rep_nom_attr(newdata)), ...) if (length(classes) == 2) { bipartitions <- as.numeric(pred >= 0.5) probabilities <- ifelse(bipartitions == 1, pred, 1 - pred) } else { pred <- matrix(pred, nrow=nrow(newdata), byrow = TRUE) which.pred <- apply(pred, 1, which.max) bipartitions <- classes[which.pred] probabilities <- pred[cbind(seq(nrow(newdata)), which.pred)] } data.frame( prediction = bipartitions, probability = probabilities, row.names = rownames(newdata) ) } mltrain.baseMAJORITY <- function(object, ...) { values <- table(object$data[, object$labelindex]) model <- list( classes = names(values), predict = names(which.max(values)) ) class(model) <- 'majorityModel' model } mlpredict.majorityModel <- function(model, newdata, ...) { data.frame( prediction = rep(model$predict, nrow(newdata)), probability = rep(1, nrow(newdata)), row.names = rownames(newdata) ) } mltrain.baseRANDOM <- function(object, ...) { model <- list( classes = as.character(unique(object$data[, object$labelindex])) ) class(model) <- 'randomModel' model } mlpredict.randomModel <- function(model, newdata, ...) { data.frame( prediction = sample(model$classes, nrow(newdata), replace = TRUE), probability = sapply(stats::runif(nrow(newdata)), function (score) { max(score, 1 - score) }), row.names = rownames(newdata) ) } mlpredict.emptyModel <- function (model, newdata, ...) { data.frame( prediction = rep(0, nrow(newdata)), probability = rep(1, nrow(newdata)), row.names = rownames(newdata) ) } print.majorityModel <- function (x, ...) { cat("Majority Base Model\n\n") cat("Label: ", attr(x, "label"), "\n") cat("Class: ", paste(x$classes, collapse = ' | ')) cat("Predict: ", x$predict) } print.randomModel <- function (x, ...) { cat("Random Base Model\n\n") cat("Label: ", attr(x, "label"), "\n") cat("Class: ", paste(x$classes, collapse = ' | ')) }
StSignificanceTestingCadVsRad <- function(dataset, FOM, FPFValue = 0.2, method = "1T-RRRC", alpha = 0.05, plots = FALSE) { options(stringsAsFactors = FALSE) if (length(dataset$ratings$NL[,1,1,1]) != 1) stop("dataset has to be single-treatment multiple-readers with CAD as the first reader") if ((dataset$descriptions$type == "ROC") && (FOM %in% c("PCL", "ALROC"))) stop("Cannot use LROC FOM with ROC data") if (method == "1T-RRFC") { ret <- SingleModalityRRFC(dataset, FOM, FPFValue, alpha) } else if (method == "1T-RRRC") { ret <- SingleModalityRRRC(dataset, FOM, FPFValue, alpha) } else if (method == "2T-RRRC") { ret <- DualModalityRRRC (dataset, FOM, FPFValue, alpha) } else stop("incorrect method specified") if (plots) { genericPlot <- CadVsRadPlots (dataset, FOM) retNames <- names(ret) retNames <- c(retNames, "Plots") len <- length(ret) ret1 <- vector("list", len+1) for (i in 1:len){ ret1[[i]] <- ret[[i]] } ret1[[len+1]] <- genericPlot names(ret1) <- retNames } else ret1 <- ret return(ret1) } SingleModalityRRFC <- function(dataset, FOM, FPFValue, alpha) { thetajc <- as.matrix(UtilFigureOfMerit(dataset, FOM, FPFValue)) Psijc <- thetajc[-1] - thetajc[1] ret <- t.test(Psijc, conf.level = 1-alpha) Tstat <- as.numeric(ret$statistic) df <- as.numeric(ret$parameter) pval <- ret$p.value CIAvgRadFom <- as.numeric(ret$conf.int)+thetajc[1] avgDiffFom <- mean(Psijc) CIAvgDiffFom <- as.numeric(ret$conf.int) return (list ( fomCAD = thetajc[1], fomRAD = thetajc[-1], avgRadFom = mean(thetajc[-1]), CIAvgRadFom = CIAvgRadFom, avgDiffFom = avgDiffFom, CIAvgDiffFom = CIAvgDiffFom, varR = var(thetajc[-1]), Tstat = Tstat, df = df, pval = pval )) } SingleModalityRRRC <- function (dataset, FOM, FPFValue, alpha) { ret <- DiffFomVarCov2(dataset, FOM, FPFValue) varError <- ret$var; Cov2 <- ret$cov2 J <- length(dataset$ratings$NL[1,,1,1]) - 1 thetajc <- as.matrix(UtilFigureOfMerit(dataset, FOM, FPFValue)) Psijc <- thetajc[1,2:(J+1)] - thetajc[1,1] MSR <- 0 avgDiffFom <- mean(Psijc) for (j in 1:J){ MSR <- MSR + (Psijc[j] - avgDiffFom)^2 } MSR <- MSR / (J - 1) MSdenOR_single <- MSR + max(J * Cov2, 0) DdfhSingle <- MSdenOR_single^2 / (MSR^2 / (J - 1)) TstatStar <- avgDiffFom / sqrt(MSdenOR_single/J) pval <- 1 - pt(abs(TstatStar),DdfhSingle) + pt(-abs(TstatStar),DdfhSingle) CIAvgDiffFom <- array(dim=2) CIAvgDiffFom[1] <- qt(alpha/2,df = DdfhSingle) CIAvgDiffFom[2] <- qt(1-alpha/2,df = DdfhSingle) CIAvgDiffFom <- CIAvgDiffFom * sqrt(MSdenOR_single/J) CIAvgDiffFom <- CIAvgDiffFom + avgDiffFom CIAvgRad <- mean(thetajc[2:(J+1)]) + CIAvgDiffFom - mean(Psijc) return (list ( fomCAD = thetajc[1], fomRAD = thetajc[-1], avgRadFom = mean(thetajc[-1]), CIAvgRad = CIAvgRad, avgDiffFom = avgDiffFom, CIAvgDiffFom = CIAvgDiffFom, varR = var(as.numeric(thetajc[-1])), varError = varError, cov2 = Cov2, Tstat = TstatStar, df = DdfhSingle, pval = pval )) } DualModalityRRRC <- function(dataset, FOM, FPFValue, alpha) { K <- length(dataset$ratings$NL[1,1,,1]) type <- dataset$descriptions$type if ((type == "LROC") && (FOM %in% c("PCL", "ALROC"))) { ret1 <- dataset2ratings(dataset, FOM) TP <- ret1$zjk2 zjk2Il <- ret1$zjk2Il K2 <- length(TP[1,]) K1 <- K - K2 FP <- ret1$zjk1[,1:K1] J <- length(FP[,1]) - 1 combinedNL <- array(-Inf, dim=c(2,J,K,1)) for (j in 1:J){ combinedNL[1,j,1:K1,1] <- FP[1,] } combinedNL[2,,1:K1,1] <- FP[2:(J+1),] combinedLL <- array(-Inf, dim=c(2,J,K2,1)) for (j in 1:J){ combinedLL[1,j,,1] <- TP[1,] } combinedLL[2,,,1] <- TP[2:(J+1),] combinedLLIl <- array(-Inf, dim=c(2,J,K2,1)) for (j in 1:J){ combinedLLIl[1,j,,1] <- zjk2Il[1,] } combinedLLIl[2,,,1] <- zjk2Il[2:(J+1),] } else if ((type == "LROC") && (FOM == "Wilcoxon")) { datasetRoc <- DfLroc2Roc(dataset) type <- datasetRoc$descriptions$type NL <- datasetRoc$ratings$NL LL <- datasetRoc$ratings$LL K <- length(NL[1,1,,1]) K2 <- length(LL[1,1,,1]) K1 <- K - K2 FP <- NL[1,,1:K1,1] TP <- LL[1,,,1] J <- length(FP[,1]) - 1 combinedNL <- array(-Inf, dim=c(2,J,K,1)) for (j in 1:J){ combinedNL[1,j,1:K1,1] <- FP[1,] } combinedNL[2,,1:K1,1] <- FP[2:(J+1),] combinedLL <- array(-Inf, dim=c(2,J,K2,1)) for (j in 1:J){ combinedLL[1,j,,1] <- TP[1,] } combinedLL[2,,,1] <- TP[2:(J+1),] } else if ((type == "ROC") && (FOM == "Wilcoxon")) { NL <- dataset$ratings$NL LL <- dataset$ratings$LL K <- length(NL[1,1,,1]) K2 <- length(LL[1,1,,1]) K1 <- K - K2 FP <- NL[1,,1:K1,1] TP <- LL[1,,,1] J <- length(FP[,1]) - 1 combinedNL <- array(-Inf, dim=c(2,J,K,1)) for (j in 1:J){ combinedNL[1,j,1:K1,1] <- FP[1,] } combinedNL[2,,1:K1,1] <- FP[2:(J+1),] combinedLL <- array(-Inf, dim=c(2,J,K2,1)) for (j in 1:J){ combinedLL[1,j,,1] <- TP[1,] } combinedLL[2,,,1] <- TP[2:(J+1),] } else stop("Incorrect FOM with LROC data") IDs <- rep(1, K2) dim(IDs) <- c(K2,1) weights <- rep(0, K2) dim(weights) <- c(K2,1) if (type == "LROC") { NL <- combinedNL LL = combinedLL LL_IL = combinedLLIl fileName <- paste0("DualModalityRRRC(", dataset$descriptions$fileName, ")") name <- NA design <- "FCTRL" truthTableStr <- array(dim = c(2,J,K,2)) truthTableStr[,,1:K1,1] <- 1 truthTableStr[,,(K1+1):K,2] <- 1 type <- "LROC" perCase <- rep(1,K2) IDs <- dataset$lesions$IDs weights <- dataset$lesions$weights modalityID = as.character(c(1,2)) readerID = as.character(1:J) datasetCombined <- convert2dataset(NL, LL, LL_IL, perCase, IDs, weights, fileName, type, name, truthTableStr, design, modalityID, readerID) } else { NL <- combinedNL LL = combinedLL LL_IL = NA fileName <- paste0("DualModalityRRRC(", dataset$descriptions$fileName, ")") name <- NA design <- "FCTRL" truthTableStr <- array(dim = c(2,J,K,2)) truthTableStr[,,1:K1,1] <- 1 truthTableStr[,,(K1+1):K,2] <- 1 type <- "ROC" perCase <- rep(1,K2) IDs <- dataset$lesions$IDs weights <- dataset$lesions$weights modalityID = as.character(c(1,2)) readerID = as.character(1:J) datasetCombined <- convert2dataset(NL, LL, LL_IL, perCase, IDs, weights, fileName, type, name, truthTableStr, design, modalityID, readerID) } stats1 <- StSignificanceTesting(datasetCombined, FOM = FOM, method = "OR", alpha = alpha, analysisOption = "RRRC", FPFValue = FPFValue) thetajc <- stats1$FOMs$foms thetajc <- as.matrix(thetajc) fomCAD <- thetajc[1,1] fomRAD <- thetajc[2,] avgRadFom <- mean(fomRAD) varDiffFom <- var(fomRAD) avgDiffFom <- avgRadFom - fomCAD FStat <- stats1$RRRC$FTests$FStat[1] ddf <- stats1$RRRC$FTests$DF[2] ndf <- stats1$RRRC$FTests$DF[1] pval <- stats1$RRRC$FTests$p[1] varR <- stats1$ANOVA$VarCom["VarR", "Estimates"] varTR <- stats1$ANOVA$VarCom["VarTR", "Estimates"] varError <- stats1$ANOVA$VarCom["Var", "Estimates"] cov1 <- stats1$ANOVA$VarCom["Cov1", "Estimates"] cov2 <- stats1$ANOVA$VarCom["Cov2", "Estimates"] cov3 <- stats1$ANOVA$VarCom["Cov3", "Estimates"] ciDiffFom <- stats1$RRRC$ciDiffTrt t <- ciDiffFom rowNames <- rownames(t) x1 <- strsplit(rowNames, split = "-")[[1]] rowNames <- paste0(x1[2], "-", x1[1]) rownames(t) <- rowNames t$Estimate <- -ciDiffFom$Estimate t$t <- -ciDiffFom$t t$CILower <- -ciDiffFom$CIUpper t$CIUpper <- -ciDiffFom$CILower ciDiffFom <- t ciAvgRdrEachTrt <- stats1$RRRC$ciAvgRdrEachTrt return (list ( fomCAD = fomCAD, fomRAD = fomRAD, avgRadFom = avgRadFom, avgDiffFom = avgDiffFom, varDiffFom = varDiffFom, ciDiffFom = ciDiffFom, ciAvgRdrEachTrt = ciAvgRdrEachTrt, varR = varR, varTR = varTR, cov1 = cov1, cov2 = cov2, cov3 = cov3, varError = varError, FStat = FStat, ndf = ndf, df = ddf, pval = pval )) } CadVsRadPlots <- function(dataset, FOM) { ret1 <- dataset2ratings(dataset, FOM) zjk1 <- ret1$zjk1 zjk2 <- ret1$zjk2 type <- dataset$descriptions$type if (type == "ROC") { genericPlot <- PlotEmpiricalOperatingCharacteristics(dataset, rdrs = 1:length(zjk1[,1]), opChType = "ROC")$Plot } else if ((type == "LROC") && ((FOM == "PCL") || (FOM == "ALROC"))) { if (type == "LROC") genericPlot <- LrocPlots (zjk1, zjk2, seq(1,length(zjk1[,1])-1))$lrocPlot } else if ((type == "LROC") && (FOM == "Wilcoxon")) { if (type == "LROC") { datasetRoc <- DfLroc2Roc(dataset) genericPlot <- PlotEmpiricalOperatingCharacteristics(datasetRoc, rdrs = 1:length(zjk1[,1]), opChType = "ROC")$Plot } } else if ((type == "FROC") && (FOM %in% c("HrAuc", "AFROC", "wAFROC"))) { if (FOM == "HrAuc") genericPlot <- PlotEmpiricalOperatingCharacteristics(dataset, rdrs = 1:length(zjk1[,1]), opChType = "ROC")$Plot if (FOM == "AFROC") genericPlot <- PlotEmpiricalOperatingCharacteristics(dataset, rdrs = 1:length(zjk1[,1]), opChType = "AFROC")$Plot if (FOM == "wAFROC") genericPlot <- PlotEmpiricalOperatingCharacteristics(dataset, rdrs = 1:length(zjk1[,1]), opChType = "wAFROC")$Plot }else stop("data type has to be ROC, FROC or LROC") return(genericPlot) } DiffFomVarCov2 <- function (dataset, FOM, FPFValue) { J <- length(dataset$descriptions$readerID) K <- length(dataset$ratings$NL[1,1,,1]) dsCad <- DfExtractDataset(dataset, trts = 1, rdrs = 1) dsRad <- DfExtractDataset(dataset, trts = 1, rdrs = c(2:J)) jkFomValuesCad <- UtilPseudoValues(dsCad, FOM, FPFValue)$jkFomValues jkFomValuesRad <- UtilPseudoValues(dsRad, FOM, FPFValue)$jkFomValues jkDiffFomValues <- array(dim = c(J-1,K)) for (j in 1:(J-1)) jkDiffFomValues[j,] <- jkFomValuesRad[1,j,] - jkFomValuesCad[1,1,] J <- J - 1 Covariance <- array(dim = c(J, J)) for (j in 1:J){ for (jp in 1:J){ Covariance[j, jp] <- cov(jkDiffFomValues[j, ], jkDiffFomValues[jp, ]) } } varError <- 0;count <- 0 for (j in 1:J){ varError <- varError + Covariance[j, j] count <- count + 1 } varError <- varError / count varError <- varError *(K-1)^2/K Cov2 <- 0;count <- 0 for (j in 1:J){ for (jp in 1:J){ if (jp != j){ Cov2 <- Cov2 + Covariance[j, jp] count <- count + 1 } } } Cov2 <- Cov2 / count Cov2 <- Cov2 *(K-1)^2/K return (list ( var = varError, cov2 = Cov2 )) } LrocOperatingPointsFromRatings <- function( zk1, zk2Cl ) { if (FALSE) { zk1 <- c(rep(0, 4), 1.424443, rep(-50,5)) zk2Cl <- c(0.5542791, 1.2046176, -50, 3.4596787, 2.732657) K2 <- length(zk2Cl) K1 <- length(zk1) - K2 zk1 <- zk1[zk1 != -50] zk2Cl <- zk2Cl[zk2Cl != -50] } else { K2 <- length(zk2Cl) K1 <- length(zk1) - K2 zk1 <- zk1[is.finite(zk1)] zk2Cl <- zk2Cl[is.finite(zk2Cl)] } FPF <- 1 PCL <- NULL zk1Temp <- zk1;zk2ClTemp <- zk2Cl while(1) { cutoff <- min( c( zk1Temp, zk2ClTemp ) ) zk1Temp <- zk1[ zk1 > cutoff ] zk2ClTemp <- zk2Cl[ zk2Cl > cutoff ] FPF1 <- length( zk1Temp ) / K1 PCL1 <- length( zk2ClTemp ) / K2 FPF <- c( FPF, FPF1 ) if (length(PCL) == 0) PCL <- c(PCL1, PCL1) else PCL <- c( PCL, PCL1 ) if( FPF1 == 0 && PCL1 == 0 ) { break } } FPF <- rev(FPF) PCL <- rev(PCL) return( list( FPF = FPF, PCL = PCL ) ) } LrocPlots <- function (zjk1, zjk2, doJ) { J <- length(zjk1[,1]) j <- 1;zjk1Temp <- zjk1[j,];zk2Temp <- zjk2[j,] lroc <- LrocOperatingPointsFromRatings( zjk1Temp, zk2Temp ) FPF <- lroc$FPF;PCL <- lroc$PCL lrocPlotData <- data.frame(FPF = FPF, PCL = PCL, reader = "R-CAD") for (j in 2:J) { if ((j - 1) %in% doJ) { zjk1Temp <- zjk1[j,] zk2Temp <- zjk2[j,] lroc <- LrocOperatingPointsFromRatings( zjk1Temp, zk2Temp ) FPF <- lroc$FPF PCL <- lroc$PCL reader = paste0("R-", as.character(j - 1)) lrocPlotData <- rbind(lrocPlotData, data.frame(FPF = FPF, PCL = PCL, reader = reader)) } } lrocPlot <- ggplot(data = lrocPlotData, aes(x = FPF, y = PCL, color = reader)) + geom_line() g <- ggplot_build(lrocPlot) colors <- as.character(unique(g$data[[1]]$colour)) colors[1] <- " sizes <- c(2, rep(1, length(doJ))) lrocPlot <- ggplot(data = lrocPlotData, aes(x = FPF, y = PCL, color = reader)) + geom_line(aes(size = reader)) + scale_color_manual(values = colors) + scale_size_manual(values = sizes) + theme(legend.title = element_blank(), legend.position = legendPosition <- c(1, 0), legend.justification = c(1, 0)) return(list( lrocPlot = lrocPlot, afrocPlot = NULL) ) }
context("test set_dimension_name") test_that("set_dimension_name works", { d <- st_mrs_age_test$dimension$when d <- set_dimension_name(d, "test") expect_equal(get_dimension_name(d), "test") })
print.summary_greek <- function (x, digits = max(3L, getOption("digits") - 3L), symbolic.cor = x$symbolic.cor, signif.stars = getOption("show.signif.stars"), concise = FALSE, ...) { cat("\nCall:", if(!concise) "\n" else " ", paste(deparse(x$call), sep = "\n", collapse = "\n"), if (!concise) "\n\n", sep = "") cat("Statistical Model of form: y = X", greek$beta, " + ", greek$epsilon, sep = "", collapse = "\n\n") resid <- x$residuals df <- x$df rdf <- df[2L] if (!concise) { cat(if (!is.null(x$weights) && diff(range(x$weights))) "Weighted ", "Residuals:\n", sep = "") } if (rdf > 5L) { nam <- c("Min", greekLetters::greeks("Q_1"), "Median", greekLetters::greeks("Q_3"), "Max") rq <- if (length(dim(resid)) == 2L) structure(apply(t(resid), 1L, stats::quantile), dimnames = list(nam, dimnames(resid)[[2L]])) else { zz <- zapsmall(stats::quantile(resid), digits + 1L) structure(zz, names = nam) } if (!concise) print(rq, digits = digits, ...) } else if (rdf > 0L) { print(resid, digits = digits, ...) } else { cat("ALL", df[1L], "residuals are 0: no residual degrees of freedom!") cat("\n") } if (length(x$aliased) == 0L) { cat("\nNo Coefficients\n") } else { if (nsingular <- df[3L] - df[1L]) cat("\nCoefficients: (", nsingular, " not defined because of singularities)\n", sep = "") else { cat("\n"); if (!concise) cat("Coefficients:\n") } coefs <- x$coefficients if (!is.null(aliased <- x$aliased) && any(aliased)) { cn <- names(aliased) coefs <- matrix(NA, length(aliased), 4, dimnames = list(cn, colnames(coefs))) coefs[!aliased, ] <- x$coefficients } stats::printCoefmat(coefs, digits = digits, signif.stars = signif.stars, signif.legend = (!concise), na.print = "NA", eps.Pvalue = if (!concise) .Machine$double.eps else 1e-4, ...) } cat("\nResidual standard error:", format(signif(x$sigma, digits)), "on", rdf, "degrees of freedom") cat("\n") if (nzchar(mess <- stats::naprint(x$na.action))) cat(" (", mess, ")\n", sep = "") if (!is.null(x$fstatistic)) { cat("Multiple ", greekLetters::greeks("R^2"),":", formatC(x$r.squared, digits = digits)) cat(",\tAdjusted ", greekLetters::greeks("R^2"),":", formatC(x$adj.r.squared, digits = digits), "\nF-statistic:", formatC(x$fstatistic[1L], digits = digits), "on", x$fstatistic[2L], "and", x$fstatistic[3L], "DF, p-value:", format.pval(stats::pf(x$fstatistic[1L], x$fstatistic[2L], x$fstatistic[3L], lower.tail = FALSE), digits = digits, if (!concise) .Machine$double.eps else 1e-4)) cat("\n") } correl <- x$correlation if (!is.null(correl)) { p <- NCOL(correl) if (p > 1L) { cat("\nCorrelation of Coefficients:\n") if (is.logical(symbolic.cor) && symbolic.cor) { print(stats::symnum(correl, abbr.colnames = NULL)) } else { correl <- format(round(correl, 2), nsmall = 2, digits = digits) correl[!lower.tri(correl)] <- "" print(correl[-1, -p, drop = FALSE], quote = FALSE) } } } cat("\n") invisible(x) }
context("mice.impute.jomoImpute") data <- boys[c(1:10, 101:110, 501:510, 601:620, 701:710), ] type <- c(2, 0, 0, 0, -2, 0, 1, 1, 0) names(type) <- names(data) z1 <- mice.impute.jomoImpute(data = data, type = type, format = "native") test_that("jomoImpute returns native class", { expect_is(z1, "mitml") }) blocks <- make.blocks(list(c("bmi", "chl", "hyp"), "age")) method <- c("jomoImpute", "pmm") pred <- make.predictorMatrix(nhanes, blocks) pred["B1", "hyp"] <- -2
LFE<-function(xx,yy,T=5){ N<-nrow(xx) p<-ncol(xx) if ( (T<1)|(T>N)){ stop("use wrong T") } M<-matrix(0,nrow = p,ncol = p) ins_update<-sample(c(1:N),T) weight<-sapply(c(1:T),function(i){ k<-ins_update[i] tmp_yyy<-abs(yy-yy[k]) tmp_yy<-rep(0,length(tmp_yyy)) tmp_yy[which(tmp_yyy==0)]<-1 dis<-colSums((t(xx)-xx[k,])^2) dis_h<-tmp_yy*dis dis_m<-(1-tmp_yy)*dis nh<-which(dis_h==min(dis_h[dis_h>0]))[1] nm<-which(dis_m==min(dis_m[dis_m>0]))[1] MM<-abs(t(xx)-as.numeric(xx[nm,]))%*% (t(abs(t(xx)-as.numeric(xx[nm,]))))- abs(t(xx)-as.numeric(xx[nh,]))%*% (t(abs(t(xx)-as.numeric(xx[nh,])))) M<<-M+MM }) eggvalue<-eigen(-M) eggvect<-eggvalue$vectors eggvalue<-eggvalue$values eggvalue<-pmax(eggvalue,0) if (sum(eggvalue)>0){ eggvalue<-eggvalue/sum(eggvalue) } new_w<-eggvect%*%(eggvalue*t(eggvect)) new_w[which(new_w<0)]=0 w<-new_w/sqrt(sum(new_w^2)) class(w)<-"LFE" return(w) }
lineLum <- function(intInt, z, f.rest=115.27, omega.m = 0.27, omega.lambda = 0.73, H.0 = 71) { 1.04e-3*intInt*f.rest/(1+z)* D.L(z, omega.m=omega.m, omega.lambda=omega.lambda, H.0=H.0)^2 }
"xSub_census_multiple_spatial"
print.spm <- function(x,...) { object <- x cat("\n This is an spm() fit object; a list with components named:\n\n") cat(" ",names(object),"\n\n") cat(" The names() function can be used to obtain names \n") cat(" of components and sub-components.\n\n") cat(" The summary() function can be used to summarise\n") cat(" the fit aspects of the object.\n\n") }
library(dynbenchmark) library(tidyverse) library(qsub) run_remote("find . -maxdepth 2 -type d -ls", args = c("-2", derived_file(experiment_id = '01-datasets_preproc/raw/real', remote = T)), remote = T)$stdout list_raw_datasets_remote <- function() { run_remote( "find", args = c( derived_file(experiment_id = '01-datasets_preproc/raw/real', remote = T), "-maxdepth", "2", "-type", "f" ), remote = T )$stdout %>% gsub(".*(real/.*)\\.rds", "\\1", .) } list_datasets_remote <- function() { run_remote( "find", args = c( derived_file(experiment_id = '01-datasets/real', remote = T), "-maxdepth", "3", "-type", "f", "-regex", "'.*dataset\\.rds'" ), remote = T )$stdout %>% gsub(".*(real/.*)/dataset\\.rds", "\\1", .) } dataset_ids_to_process <- setdiff(list_raw_datasets_remote(), list_datasets_remote()) process_raw_dataset_wrapper <- function(id) { raw_dataset <- readr::read_rds(dynbenchmark::dataset_raw_file(id)) raw_dataset$id <- id do.call(dynbenchmark::process_raw_dataset, raw_dataset) TRUE } qsub_config <- qsub::override_qsub_config( name = "filter_norm", memory = "30G", wait = FALSE, stop_on_error = TRUE ) handle <- qsub_lapply(dataset_ids_to_process, process_raw_dataset_wrapper, qsub_environment = character(), qsub_config = qsub_config) local_folder_sync <- derived_file("", "01-datasets/real/") remote_folder_sync <- derived_file("", "01-datasets/real/", remote = TRUE) qsub::rsync_remote("prism", remote_folder_sync, "", local_folder_sync)
model_addsupereff <- function(datadea, dmu_eval = NULL, dmu_ref = NULL, orientation = NULL, weight_slack_i = NULL, weight_slack_o = NULL, rts = c("crs", "vrs", "nirs", "ndrs", "grs"), L = 1, U = 1, compute_target = TRUE, returnlp = FALSE, ...) { if (!is.deadata(datadea)) { stop("Data should be of class deadata. Run read_data function first!") } rts <- tolower(rts) rts <- match.arg(rts) if (!is.null(datadea$ud_inputs) || !is.null(datadea$ud_outputs)) { warning("This model does not take into account the undesirable feature for inputs/outputs.") } if (rts == "grs") { if (L > 1) { stop("L must be <= 1.") } if (U < 1) { stop("U must be >= 1.") } } dmunames <- datadea$dmunames nd <- length(dmunames) if (is.null(dmu_eval)) { dmu_eval <- 1:nd } else if (!all(dmu_eval %in% (1:nd))) { stop("Invalid set of DMUs to be evaluated (dmu_eval).") } names(dmu_eval) <- dmunames[dmu_eval] nde <- length(dmu_eval) if (is.null(dmu_ref)) { dmu_ref <- 1:nd } else if (!all(dmu_ref %in% (1:nd))) { stop("Invalid set of reference DMUs (dmu_ref).") } names(dmu_ref) <- dmunames[dmu_ref] ndr <- length(dmu_ref) input <- datadea$input output <- datadea$output inputnames <- rownames(input) outputnames <- rownames(output) ni <- nrow(input) no <- nrow(output) nzimin <- apply(input, MARGIN = 1, function(x) min(x[x > 0])) / 100 nzomin <- apply(output, MARGIN = 1, function(x) min(x[x > 0])) / 100 for (ii in dmu_eval) { input[which(input[, ii] == 0), ii] <- nzimin[which(input[, ii] == 0)] output[which(output[, ii] == 0), ii] <- nzomin[which(output[, ii] == 0)] } inputref <- matrix(input[, dmu_ref], nrow = ni) outputref <- matrix(output[, dmu_ref], nrow = no) nc_inputs <- datadea$nc_inputs nc_outputs <- datadea$nc_outputs nnci <- length(nc_inputs) nnco <- length(nc_outputs) if (is.null(weight_slack_i)) { weight_slack_i <- matrix(1 / input[, dmu_eval], nrow = ni) / (ni + no - nnci - nnco) } else { if (is.matrix(weight_slack_i)) { if ((nrow(weight_slack_i) != ni) || (ncol(weight_slack_i) != nde)) { stop("Invalid matrix of weights of the input slacks (number of inputs x number of evaluated DMUs).") } } else if ((length(weight_slack_i) == 1) || (length(weight_slack_i) == ni)) { weight_slack_i <- matrix(weight_slack_i, nrow = ni, ncol = nde) } else { stop("Invalid vector of weights of the input slacks.") } } weight_slack_i[nc_inputs, ] <- 0 if ((!is.null(orientation)) && (orientation == "oo")) { weight_slack_i <- matrix(0, nrow = ni, ncol = nde) } rownames(weight_slack_i) <- inputnames colnames(weight_slack_i) <- dmunames[dmu_eval] if (is.null(weight_slack_o)) { weight_slack_o <- matrix(1 / output[, dmu_eval], nrow = no) / (ni + no - nnci - nnco) } else { if (is.matrix(weight_slack_o)) { if ((nrow(weight_slack_o) != no) || (ncol(weight_slack_o) != nde)) { stop("Invalid matrix of weights of the output slacks (number of outputs x number of evaluated DMUs).") } } else if ((length(weight_slack_o) == 1) || (length(weight_slack_o) == no)) { weight_slack_o <- matrix(weight_slack_o, nrow = no, ncol = nde) } else { stop("Invalid vector of weights of the output slacks.") } } weight_slack_o[nc_outputs, ] <- 0 if ((!is.null(orientation)) && (orientation == "io")) { weight_slack_o <- matrix(0, nrow = no, ncol = nde) } rownames(weight_slack_o) <- outputnames colnames(weight_slack_o) <- dmunames[dmu_eval] target_input <- NULL target_output <- NULL project_input <- NULL project_output <- NULL slack_input <- NULL slack_output <- NULL DMU <- vector(mode = "list", length = nde) names(DMU) <- dmunames[dmu_eval] if (rts == "crs") { f.con.rs <- NULL f.dir.rs <- NULL f.rhs.rs <- NULL } else { f.con.rs <- cbind(matrix(1, nrow = 1, ncol = ndr), matrix(0, nrow = 1, ncol = ni + no)) if (rts == "vrs") { f.dir.rs <- "=" f.rhs.rs <- 1 } else if (rts == "nirs") { f.dir.rs <- "<=" f.rhs.rs <- 1 } else if (rts == "ndrs") { f.dir.rs <- ">=" f.rhs.rs <- 1 } else { f.con.rs <- rbind(f.con.rs, f.con.rs) f.dir.rs <- c(">=", "<=") f.rhs.rs <- c(L, U) } } f.con.1 <- cbind(inputref, -diag(ni), matrix(0, nrow = ni, ncol = no)) f.con.2 <- cbind(outputref, matrix(0, nrow = no, ncol = ni), diag(no)) for (i in 1:nde) { ii <- dmu_eval[i] w0i <- which(weight_slack_i[, i] == 0) nw0i <- length(w0i) w0o <- which(weight_slack_o[, i] == 0) nw0o <- length(w0o) f.obj <- c(rep(0, ndr), weight_slack_i[, i], weight_slack_o[, i]) f.con.se <- rep(0, ndr) f.con.se[dmu_ref == ii] <- 1 f.con.se <- c(f.con.se, rep(0, ni + no)) f.con.w0 <- matrix(0, nrow = (nw0i + nw0o), ncol = (ndr + ni + no)) f.con.w0[, ndr + c(w0i, ni + w0o)] <- diag(nw0i + nw0o) f.con <- rbind(f.con.1, f.con.2, f.con.se, f.con.w0, f.con.rs) f.dir <- c(rep("<=", ni), rep(">=", no), rep("=", 1 + nw0i + nw0o), f.dir.rs) f.dir[nc_inputs] <- "=" f.dir[ni + nc_outputs] <- "=" f.rhs <- c(input[, ii], output[, ii], rep(0, 1 + nw0i + nw0o), f.rhs.rs) if (returnlp) { lambda <- rep(0, ndr) names(lambda) <- dmunames[dmu_ref] t_input <- rep(0, ni) names(t_input) <- inputnames t_output <- rep(0, no) names(t_output) <- outputnames var <- list(lambda = lambda, t_input = t_input, t_output = t_output) DMU[[i]] <- list(direction = "min", objective.in = f.obj, const.mat = f.con, const.dir = f.dir, const.rhs = f.rhs, var = var) } else { res <- lp("min", f.obj, f.con, f.dir, f.rhs) if (res$status == 0) { objval <- res$objval lambda <- res$solution[1 : ndr] names(lambda) <- dmunames[dmu_ref] t_input <- res$solution[(ndr + 1) : (ndr + ni)] names(t_input) <- inputnames t_output <- res$solution[(ndr + ni + 1) : (ndr + ni + no)] names(t_output) <- outputnames delta_num <- 1 + sum(t_input / input[, ii]) / (ni - nnci) delta_den <- 1 - sum(t_output / output[, ii]) / (no - nnco) delta <- delta_num / delta_den if (compute_target) { target_input <- as.vector(inputref %*% lambda) names(target_input) <- inputnames target_output <- as.vector(outputref %*% lambda) names(target_output) <- outputnames project_input <- input[, ii] + t_input names(project_input) <- inputnames project_output <- output[, ii] - t_output names(project_output) <- outputnames slack_input <- project_input - target_input names(slack_input) <- inputnames slack_output <- target_output - project_output names(slack_output) <- outputnames } } else { delta <- NA objval <- NA lambda <- NA t_input <- NA t_output <- NA if (compute_target) { target_input <- NA target_output <- NA project_input <- NA project_output <- NA slack_input <- NA slack_output <- NA } } DMU[[i]] <- list(delta = delta, objval = objval, lambda = lambda, t_input = t_input, t_output = t_output, slack_input = slack_input, slack_output = slack_output, project_input = project_input, project_output = project_output, target_input = target_input, target_output = target_output) } } deaOutput <- list(modelname = "addsupereff", rts = rts, L = L, U = U, DMU = DMU, data = datadea, dmu_eval = dmu_eval, dmu_ref = dmu_ref, weight_slack_i = weight_slack_i, weight_slack_o = weight_slack_o, orientation = "NA") return(structure(deaOutput, class = "dea")) }
eigenw <- function(listw, quiet=NULL) { if(!inherits(listw, "listw")) stop("not a listw object") if (is.null(quiet)) quiet <- !get("verbose", envir = .spatialregOptions) stopifnot(is.logical(quiet)) w <- listw2mat(listw) sym <- all(w == t(w)) e <- eigen(w, symmetric=sym, only.values=TRUE)$values if (!quiet) { cat("Largest eigenvalue:", if(is.complex(e)) {max(Re(e[which(Im(e) == 0)]))} else max(e), "Sum of eigenvalues:", sum(e), "\n") } e } griffith_sone <- function(P, Q, type="rook") { stopifnot(P >= 1) stopifnot(Q >= 1) p <- seq(1:P) q <- seq(1:Q) if (type=="rook") { res0 <- outer((2*cos((pi*p)/(P+1))), (2*cos((pi*q)/(Q+1))), FUN="+") } else { e2a <- outer((cos((pi*p)/(P+1))), (cos((pi*q)/(Q+1))), FUN="+") e2b <- outer((2*cos((pi*p)/(P+1))), (cos((pi*q)/(Q+1))), FUN="*") res <- 2*(e2a+e2b) } res <- sort(c(res0), decreasing=TRUE) res } subgraph_eigenw <- function(nb, glist=NULL, style="W", zero.policy=NULL, quiet=NULL) { if(!inherits(nb, "nb")) stop("Not a neighbours list") if (is.null(quiet)) quiet <- !get("verbose", envir = .spatialregOptions) stopifnot(is.logical(quiet)) if (is.null(zero.policy)) zero.policy <- get("zeroPolicy", envir = .spatialregOptions) stopifnot(is.logical(zero.policy)) if (!(style %in% c("W", "B", "C", "S", "U", "minmax"))) stop(paste("Style", style, "invalid")) can.sim <- FALSE if (style %in% c("W", "S")) can.sim <- can.be.simmed(nb2listw(nb, glist=glist, style=style)) nc <- n.comp.nb(nb) t0 <- table(nc$comp.id) elist <- vector(mode="list", length=length(t0)) singleton <- names(t0)[which(t0 == 1)] if (length(singleton) > 0) elist[as.integer(singleton)] <- 0.0 doubles <- names(t0)[which(t0 == 2)] if (length(doubles) > 0) { for (i in doubles) elist[[as.integer(i)]] <- c(1.0, -1.0) } rest <- which(sapply(elist, is.null)) for (i in rest) { nbi <- subset(nb, nc$comp.id == i) gli <- NULL if (!is.null(glist)) gli <- subset(glist, nc$comp.id == i) if (can.sim) { elist[[i]] <- eigenw(similar.listw(nb2listw(nbi, glist=gli, style=style))) } else { elist[[i]] <- eigenw(nb2listw(nbi, glist=gli, style=style)) } } eout <- sort(unlist(elist)) if (length(eout) != length(nb)) stop("length mismatch, eout:", length(eout)) eout }
setMethod( f= "plotPoolGraph", signature(x="SymbolicModel_by_PoolNames"), definition=function (x){ internalConnections<-lapply( x@internal_fluxes, function(flr){ tuple( as.character(flr@sourceName) ,as.character(flr@destinationName) ) } ) inBoundConnections<-lapply( x@in_fluxes, function(fl){ as.character(fl@destinationName) } ) outBoundConnections<- lapply( x@out_fluxes, function(fl){ as.character(fl@sourceName) } ) plotPoolGraphFromTupleLists(internalConnections,inBoundConnections,outBoundConnections) } ) state_variable_names <- function (object){ unique( c( unlist( lapply( object@internal_fluxes ,function(flr){ c( as.character(flr@sourceName) ,as.character(flr@destinationName) ) } ) ) ,unlist( lapply( object@in_fluxes, function(fl){as.character(fl@destinationName) } ) ) ,unlist( lapply( object@out_fluxes, function(fl){ as.character(fl@sourceName) } ) ) ) ) }
data(ttrc) rownames(ttrc) <- ttrc$Date ttrc$Date <- NULL input <- list( all=ttrc[1:250,], top=ttrc[1:250,], mid=ttrc[1:250,] ) input$top[1:10,] <- NA input$mid[9:20,] <- NA load(system.file("unitTests/output.runFun.rda", package="TTR")) test.runSum <- function() { checkEqualsNumeric( runSum(input$all$Close), output$allSum ) checkEquals( attributes(runSum(input$all$Close)), attributes(output$allSum) ) checkEqualsNumeric( runSum(input$top$Close), output$topSum ) checkEquals( attributes(runSum(input$top$Close)), attributes(output$topSum) ) checkException( runSum(input$mid$Close) ) checkException( runSum(input$all[,1:2]) ) checkEqualsNumeric( tail(runSum(input$all$Close,250),1), sum(input$all$Close) ) checkException( runSum(input$all$Close, n = -1) ) checkException( runSum(input$all$Close, n = NROW(input$all) + 1) ) } test.wilderSum <- function() { checkEqualsNumeric( wilderSum(input$all$Close), output$allwSum ) checkEquals( attributes(wilderSum(input$all$Close)), attributes(output$allwSum) ) checkEqualsNumeric( wilderSum(input$top$Close), output$topwSum ) checkEquals( attributes(wilderSum(input$top$Close)), attributes(output$topwSum) ) checkException( wilderSum(input$mid$Close) ) checkException( wilderSum(input$all[,1:2]) ) checkException( wilderSum(input$all$Close, n = -1) ) checkException( wilderSum(input$all$Close, n = NROW(input$all) + 1) ) } test.runMin <- function() { checkEqualsNumeric( runMin(input$all$Close), output$allMin ) checkEquals( attributes(runMin(input$all$Close)), attributes(output$allMin) ) checkEqualsNumeric( runMin(input$top$Close), output$topMin ) checkEquals( attributes(runMin(input$top$Close)), attributes(output$topMin) ) checkException( runMin(input$mid$Close) ) checkException( runMin(input$all[,1:2]) ) checkException( runMin(input$all$Close, n = -1) ) checkException( runMin(input$all$Close, n = NROW(input$all) + 1) ) checkEqualsNumeric( tail(runMin(input$all$Close,250),1), min(input$all$Close) ) } test.runMin.cumulative <- function() { ttr <- runMin(input$all$Close, 1, TRUE) base <- cummin(input$all$Close) checkEqualsNumeric(base, ttr) } test.runMax <- function() { checkEqualsNumeric( runMax(input$all$Close), output$allMax ) checkEquals( attributes(runMax(input$all$Close)), attributes(output$allMax) ) checkEqualsNumeric( runMax(input$top$Close), output$topMax ) checkEquals( attributes(runMax(input$top$Close)), attributes(output$topMax) ) checkException( runMax(input$mid$Close) ) checkException( runMax(input$all[,1:2]) ) checkException( runMax(input$all$Close, n = -1) ) checkException( runMax(input$all$Close, n = NROW(input$all) + 1) ) checkEqualsNumeric( tail(runMax(input$all$Close,250),1), max(input$all$Close) ) } test.runMax.cumulative <- function() { ttr <- runMax(input$all$Close, 1, TRUE) base <- cummax(input$all$Close) checkEqualsNumeric(base, ttr) } test.runMean <- function() { checkEqualsNumeric( runMean(input$all$Close), output$allMean ) checkEquals( attributes(runMean(input$all$Close)), attributes(output$allMean) ) checkEqualsNumeric( runMean(input$top$Close), output$topMean ) checkEquals( attributes(runMean(input$top$Close)), attributes(output$topMean) ) checkException( runMean(input$mid$Close) ) checkException( runMean(input$all[,1:2]) ) checkException( runMean(input$all$Close, n = -1) ) checkException( runMean(input$all$Close, n = NROW(input$all) + 1) ) checkEqualsNumeric( tail(runMean(input$all$Close,250),1), mean(input$all$Close) ) } test.runMean.cumulative <- function() { ttr <- runMean(input$all$Close, 5, TRUE) base <- cumsum(input$all$Close) / seq_along(input$all$Close) is.na(base) <- 1:4 checkEqualsNumeric(base, ttr) } test.runMean.cumulative.n.equals.1 <- function() { n.1.cum <- runMean(1, n = 1, cumulative = TRUE) n.1.noncum <- runMean(1, n = 1, cumulative = FALSE) checkEqualsNumeric(n.1.cum, n.1.noncum) } test.runMedian <- function() { checkEqualsNumeric( runMedian(input$all$Close), output$allMedian ) checkEquals( attributes(runMedian(input$all$Close)), attributes(output$allMedian) ) checkEqualsNumeric( runMedian(input$top$Close), output$topMedian ) checkEquals( attributes(runMedian(input$top$Close)), attributes(output$topMedian) ) checkException( runMedian(input$mid$Close) ) checkException( runMedian(input$all[,1:2]) ) checkException( runMedian(input$all$Close, n = -1) ) checkException( runMedian(input$all$Close, n = NROW(input$all) + 1) ) checkEqualsNumeric( tail(runMedian(input$all$Close,250),1), median(input$all$Close) ) } test.runMedian.cumulative <- function() { cummedian <- compiler::cmpfun( function(x) { med <- x * NA_real_ for (i in seq_along(x)) { med[i] <- median(x[1:i]) } med } ) base <- cummedian(input$all$Close) is.na(base) <- 1:4 ttr <- runMedian(input$all$Close, 5, "mean", TRUE) checkEqualsNumeric(base, ttr) is.na(base) <- 1:5 ttr <- runMedian(input$all$Close, 6, "mean", TRUE) checkEqualsNumeric(base, ttr) } test.runMedian.cumulative.leading.NA <- function() { na <- rep(NA, 10) x <- input$all$Close xmed <- runMedian(x, 1, "mean", TRUE) y <- c(na, input$all$Close) ymed <- runMedian(y, 1, "mean", TRUE) checkEqualsNumeric(ymed, c(na, xmed)) } test.runMedian.cumulative.n.equals.1 <- function() { n.1.cum <- runMedian(1, n = 1, cumulative = TRUE) n.1.noncum <- runMedian(1, n = 1, cumulative = FALSE) checkEqualsNumeric(n.1.cum, n.1.noncum) } test.runCov <- function() { checkEqualsNumeric( runCov(input$all$High, input$all$Low), output$allCov ) checkEquals( attributes(runCov(input$all$High, input$all$Low)), attributes(output$allCov) ) checkEqualsNumeric( runCov(input$top$High, input$top$Low), output$topCov ) checkEquals( attributes(runCov(input$top$High, input$top$Low)), attributes(output$topCov) ) checkException( runCov(input$mid$High, input$mid$Low) ) checkException( runCov(input$all$High) ) checkException( runCov(input$all[,1:2], input$all$Low) ) checkException( runCov(input$all$Close, n = -1) ) checkException( runCov(input$all$Close, n = NROW(input$all) + 1) ) checkEqualsNumeric( tail(runCov(input$all$High, input$all$Low, 250),1), cov(input$all$High, input$all$Low) ) checkEqualsNumeric( runCov(xts::as.xts(input$all)$High, input$all$Low), output$allCov ) checkEqualsNumeric( runCov(xts::as.xts(input$all)$High, xts::as.xts(input$all)$Low), output$allCov ) } test.runCov.xts.nonleading.na <- function() { top <- input$top$Close mid <- input$mid$Close checkException(runCov(top, mid)) } test.runCov.cumulative <- function() { cumcov <- compiler::cmpfun( function(x) { cov <- x * NA_real_ for (i in seq_along(x)) { y <- x[1:i] cov[i] <- cov(y, y) } cov } ) x <- input$all$Close base <- cumcov(x) is.na(base) <- 1:4 ttr <- runCov(x, x, 5, "all.obs", TRUE, TRUE) checkEqualsNumeric(base, ttr) is.na(base) <- 1:5 ttr <- runCov(x, x, 6, "all.obs", TRUE, TRUE) checkEqualsNumeric(base, ttr) } test.runCor <- function() { checkEqualsNumeric( runCor(input$all$High, input$all$Low), output$allCor ) checkEquals( attributes(runCor(input$all$High, input$all$Low)), attributes(output$allCor) ) checkEqualsNumeric( runCor(input$top$High, input$top$Low), output$topCor ) checkEquals( attributes(runCor(input$top$High, input$top$Low)), attributes(output$topCor) ) checkException( runCor(input$mid$High, input$mid$Low) ) checkException( runCor(input$all$High) ) checkException( runCor(input$all[,1:2], input$all$Low) ) checkException( runCor(input$all$Close, n = -1) ) checkException( runCor(input$all$Close, n = NROW(input$all) + 1) ) checkEqualsNumeric( tail(runCor(input$all$High, input$all$Low, 250),1), cor(input$all$High, input$all$Low) ) } test.runVar <- function() { checkEqualsNumeric( runVar(input$all$Close), output$allVar ) checkEquals( attributes(runVar(input$all$Close)), attributes(output$allVar) ) checkEqualsNumeric( runVar(input$top$Close), output$topVar ) checkEquals( attributes(runVar(input$top$Close)), attributes(output$topVar) ) checkException( runVar(input$mid$Close) ) checkException( runVar(input$all[,1:2], input$all$Low) ) checkException( runVar(input$all$Close, n = -1) ) checkException( runVar(input$all$Close, n = NROW(input$all) + 1) ) checkEqualsNumeric( tail(runVar(input$all$Close,n=250),1), var(input$all$Close) ) } test.runSD <- function() { checkEqualsNumeric( runSD(input$all$Close), output$allSD ) checkEquals( attributes(runSD(input$all$Close)), attributes(output$allSD) ) checkEqualsNumeric( runSD(input$top$Close), output$topSD ) checkEquals( attributes(runSD(input$top$Close)), attributes(output$topSD) ) checkException( runSD(input$mid$Close) ) checkException( runSD(input$all[,1:2]) ) checkException( runSD(input$all$Close, n = -1) ) checkException( runSD(input$all$Close, n = NROW(input$all) + 1) ) checkEqualsNumeric( tail(runSD(input$all$Close,250),1), sd(input$all$Close) ) } test.runMAD <- function() { checkEqualsNumeric( runMAD(input$all$Close), output$allMAD ) checkEquals( attributes(runMAD(input$all$Close)), attributes(output$allMAD) ) checkEqualsNumeric( runMAD(input$top$Close), output$topMAD ) checkEquals( attributes(runMAD(input$top$Close)), attributes(output$topMAD) ) checkException( runMAD(input$mid$Close) ) checkException( runMAD(input$all[,1:2]) ) checkException( runMAD(input$all$Close, n = -1) ) checkException( runMAD(input$all$Close, n = NROW(input$all) + 1) ) checkEqualsNumeric( tail(runMAD(input$all$Close,250),1), mad(input$all$Close) ) } test.runMAD.cumulative <- function() { cummad <- compiler::cmpfun( function(x) { mad <- x * NA_real_ for (i in seq_along(x)) { y <- x[1:i] mad[i] <- mad(y) } mad } ) x <- input$all$Close base <- cummad(x) is.na(base) <- 1:4 ttr <- runMAD(x, 5, cumulative = TRUE) checkEqualsNumeric(base, ttr) is.na(base) <- 1:5 ttr <- runMAD(x, 6, cumulative = TRUE) checkEqualsNumeric(base, ttr) } test.runMAD.cumulative.leading.NA <- function() { na <- rep(NA, 10) x <- input$all$Close xmed <- runMAD(x, 1, cumulative = TRUE) y <- c(na, input$all$Close) ymed <- runMAD(y, 1, cumulative = TRUE) checkEqualsNumeric(ymed, c(na, xmed)) } test.runPercentRank_exact.multiplier_bounds <- function() { x <- input$all$Close checkException( runPercentRank(x, 10, exact.multiplier = -0.1) ) checkException( runPercentRank(x, 10, exact.multiplier = 1.1) ) } xdata <- c(7.9, 5.2, 17.5, -12.7, 22, 4.3, -15.7, -9.3, 0.6, 0, -22.8, 7.6, -5.5, 1.7, 5.6, 15.1, 6.6, 11.2, -7.8, -4.3) xrank10_1 <- c(NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.4, 0.1, 0.8, 0.5, 0.7, 0.9, 1, 0.8, 0.9, 0.2, 0.4) xrank10_0 <- c(NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.3, 0, 0.7, 0.4, 0.6, 0.8, 0.9, 0.7, 0.8, 0.1, 0.3) test.runPercentRank_exact.multiplier_eq0 <- function() { xrank <- round(xrank10_0, 2) checkIdentical(xrank, runPercentRank(xdata, 10, FALSE, 0)) } test.runPercentRank_exact.multiplier_eq0.5 <- function() { xrank <- round(xrank10_0 + 0.05, 2) checkIdentical(xrank, runPercentRank(xdata, 10, FALSE, 0.5)) } test.runPercentRank_exact.multiplier_eq1 <- function() { xrank <- round(xrank10_0 + 0.1, 2) checkIdentical(xrank, runPercentRank(xdata, 10, FALSE, 1)) } test.runPercentRank_cumulTRUE_exact.multiplier_eq0 <- function() { xrank <- c(0, 0, 2, 0, 4, 1, 0, 2, 3, 3, 0, 8, 4, 7, 10, 13, 11, 14, 4, 6) / 1:20 xrank[1:9] <- NA xrank[10] <- 0 checkIdentical(xrank, runPercentRank(xdata, 10, TRUE, 0)) } test.runPercentRank_cumulTRUE_exact.multiplier_eq0.5 <- function() { xrank <- (c(0, 0, 2, 0, 4, 1, 0, 2, 3, 3, 0, 8, 4, 7, 10, 13, 11, 14, 4, 6) + 0.5) / 1:20 xrank[1:9] <- NA xrank[10] <- 0.5 checkIdentical(xrank, runPercentRank(xdata, 10, TRUE, 0.5)) } test.runPercentRank_cumulTRUE_exact.multiplier_eq1 <- function() { xrank <- (c(0, 0, 2, 0, 4, 1, 0, 2, 3, 3, 0, 8, 4, 7, 10, 13, 11, 14, 4, 6) + 1) / 1:20 xrank[1:9] <- NA xrank[10] <- 1 checkIdentical(xrank, runPercentRank(xdata, 10, TRUE, 1)) }
context("arg.check.ggautoimage tests") test_that("arg.check.ggautoimage sanity check", { expect_error(arg.check.ggautoimage(factor(1:2), 1:2, 1:2, factor(1:2), "none", NULL, NULL, list()), "x, y, and z must be vectors") expect_error(arg.check.ggautoimage(1:2, factor(1:2), 1:2, factor(1:2), "none", NULL, NULL, list()), "x, y, and z must be vectors") expect_error(arg.check.ggautoimage(1:2, 1:2, factor(1:2), factor(1:2), "none", NULL, NULL, list()), "x, y, and z must be vectors") expect_error(arg.check.ggautoimage(1:3, 1:2, 1:2, factor(1:2), "none", NULL, NULL, list()), "x, y, and z must have the same length") expect_error(arg.check.ggautoimage(1:2, 1:3, 1:2, factor(1:2), "none", NULL, NULL, list()), "x, y, and z must have the same length") expect_error(arg.check.ggautoimage(1:2, 1:2, 1:3, factor(1:2), "none", NULL, NULL, list()), "x, y, and z must have the same length") expect_error(arg.check.ggautoimage(c("jim", "jim"), 1:2, 1:2, factor(1:2), "none", NULL, NULL, list()), "x, y, and z must be numeric") expect_error(arg.check.ggautoimage(1:2, c("jim", "jim"), 1:2, factor(1:2), "none", NULL, NULL, list()), "x, y, and z must be numeric") expect_error(arg.check.ggautoimage(1:2, 1:2, c("jim", "jim"), factor(1:2), "none", NULL, NULL, list()), "x, y, and z must be numeric") expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, 1:3, "none", NULL, NULL, list()), "f must have the same length as x, y, and z") expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, 1:2, "none", NULL, NULL, list()), "f must be a factor") expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), c("none", "none"), NULL, NULL, list()), "proj must be a single character string") expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), 1, NULL, NULL, list()), "proj must be a single character string") expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), "none", 1, NULL, list()), "lines must be a list") expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), "none", list(), NULL, list()), "lines must have components x and y") expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), "none", list(x = 1:2), NULL, list()), "lines must have components x and y") expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), "none", list(y = 1:2), NULL, list()), "lines must have components x and y") expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), "none", list(x = 1:3, y = 1:2), NULL, list())) expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), "none", list(x = factor(1:2), y = 1:2), NULL, list())) expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), "none", NULL, 1, list()), "points must be a list") expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), "none", NULL, list(), list()), "points must have components x and y") expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), "none", NULL, list(x = 1:2, y = 1:3), list())) expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), "none", NULL, list(x = factor(1:2), y = 1:2), list())) expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), "none", NULL, list(x = 1:2, y = 1:3), list())) expect_error(arg.check.ggautoimage(1:2, 1:2, 1:2, factor(1:2), "none", NULL, NULL, 1), "interp.args must be a list") })
IMG_EXTENSIONS <- c('jpg', 'jpeg', 'png') has_file_allowed_extension <- function(filename, extensions) { tolower(fs::path_ext(filename)) %in% tolower(extensions ) } is_image_file <- function(filename) { has_file_allowed_extension(filename, IMG_EXTENSIONS) } folder_make_dataset <- function(directory, class_to_idx, extensions = NULL, is_valid_file = NULL) { directory <- normalizePath(directory) both_none <- is.null(extensions) && is.null(is_valid_file) both_something <- !is.null(extensions) && ! is.null(is_valid_file) if (both_none || both_something) value_error("Both extensions and is_valid_file cannot be None or not None at the same time") if (!is.null(extensions)) { is_valid_file <- function(filename) { has_file_allowed_extension(filename, extensions) } } paths <- c() indexes <- c() for (target_class in sort(names(class_to_idx))) { class_index <- class_to_idx[target_class] target_dir <- fs::path_join(c(directory, target_class)) if (!fs::is_dir(target_dir)) next fnames <- fs::dir_ls(target_dir, recurse = TRUE) fnames <- fnames[is_valid_file(fnames)] paths <- c(paths, fnames) indexes <- c(indexes, rep(class_index, length(fnames))) } list( paths, indexes ) } folder_dataset <- torch::dataset( name = "folder", initialize = function(root, loader, extensions = NULL, transform = NULL, target_transform = NULL, is_valid_file = NULL) { self$root <- root self$transform <- transform self$target_transform <- target_transform class_to_idx <- self$.find_classes(root) samples <- folder_make_dataset(self$root, class_to_idx, extensions, is_valid_file) if (length(samples[[1]]) == 0) { msg <- glue::glue("Found 0 files in subfolders of {self$root}") if (!is.null(extensions)) { msg <- paste0(msg, glue::glue("\nSupported extensions are {paste(extensions, collapse=',')}")) } runtime_error(msg) } self$loader <- loader self$extensions <- extensions self$classes <- names(class_to_idx) self$class_to_idx <- class_to_idx self$samples <- samples self$targets <- samples[[2]] }, .find_classes = function(dir) { dirs <- fs::dir_ls(dir, recurse = FALSE, type = "directory") dirs <- sapply(fs::path_split(dirs), function(x) tail(x, 1)) class_too_idx <- seq_along(dirs) names(class_too_idx) <- sort(dirs) class_too_idx }, .getitem = function(index) { path <- self$samples[[1]][index] target <- self$samples[[2]][index] sample <- self$loader(path) if (!is.null(self$transform)) sample <- self$transform(sample) if (!is.null(self$target_transform)) target <- self$target_transform(target) list(x = sample, y = target) }, .length = function() { length(self$samples[[1]]) } ) magick_loader <- function(path) { magick::image_read(path) } base_loader <- function(path) { ext <- tolower(fs::path_ext(path)) if (ext %in% c("jpg", "jpeg")) img <- jpeg::readJPEG(path) else if (ext %in% c("png")) img <- png::readPNG(path) else runtime_error(sprintf("unknown extension '%s' in path '%s'", ext, path)) if (length(dim(img)) == 2) img <- abind::abind(img, img, img, along = 3) else if (length(dim(img)) == 3 && dim(img)[1] == 1) img <- abind::abind(img, img, img, along = 1) img } image_folder_dataset <- dataset( "image_folder", inherit = folder_dataset, initialize = function(root, transform=NULL, target_transform=NULL, loader=NULL, is_valid_file=NULL) { if (is.null(loader)) loader <- base_loader if (!is.null(is_valid_file)) extensions <- NULL else extensions <- IMG_EXTENSIONS super$initialize(root, loader, extensions, transform=transform, target_transform=target_transform, is_valid_file=is_valid_file) self$imgs <- self$samples } )
context("test-rx_space") test_that("space special character works", { expect_equal(rx_space() %>% as.character(), " ") expect_true(grepl(rx_space(), " ")) expect_true(grepl(rx_space(), "cat dog")) expect_true(grepl(rx_space(inverse = TRUE), "\t")) expect_true(grepl(rx_space(inverse = TRUE), "\n")) expect_true(grepl(rx_space(inverse = TRUE), "\r")) expect_false(grepl(rx_space(), "")) expect_false(grepl(rx_space(), "\t")) expect_false(grepl(rx_space(), "\n")) expect_false(grepl(rx_space(), "\r")) expect_false(grepl(rx_space(inverse = TRUE), " ")) expect_equal( regmatches("cat dog", gregexpr(rx_space(inverse = TRUE), "cat dog"))[[1]], c("c", "a", "t", "d", "o", "g") ) expect_error(rx_space(inverse = "nope")) })
NULL NULL subsetItemPool <- function(x, i = NULL) { if (!inherits(x, "item_pool")) { stop("'x' must be an 'item_pool' object") } if (!validObject(x)) { stop("'x' is not a valid 'item_pool' object") } if (is.null(i)) { return(x) } if (!all(i %in% 1:x@ni)) { stop("'i' contains item indices not defined in 'x'") } i <- unique(i) raw <- x@raw[i, ] raw_se <- x@raw_se[i, ] new_p <- loadItemPool(raw, raw_se) return(new_p) } combineItemPoolData <- function(raw1, raw2, unique) { tmp <- setdiff(names(raw1), names(raw2)) raw2[tmp] <- NA tmp <- setdiff(names(raw2), names(raw1)) raw1[tmp] <- NA raw <- rbind(raw1, raw2) if (unique) { idx <- which(!duplicated(raw$ID)) raw <- raw[idx, ] } return(raw) } combineItemPool <- function(x1, x2, unique = TRUE, verbose = TRUE) { if (!inherits(x1, "item_pool") || !inherits(x2, "item_pool")) { stop("operands must be 'item_pool' objects") } if (!validObject(x1)) { stop("'x1' is not a valid 'item_pool' object") } if (!validObject(x2)) { stop("'x2' is not a valid 'item_pool' object") } raw <- combineItemPoolData(x1@raw , x2@raw , unique = unique) raw_se <- combineItemPoolData(x1@raw_se, x2@raw_se, unique = unique) o <- loadItemPool(raw, raw_se, unique = unique) id <- c(x1@raw$ID, x2@raw$ID) if (verbose) { if (sum(duplicated(id)) > 0) { warning(sprintf("duplicate item IDs found: %s", paste0(id[duplicated(id)], collapse = ", "))) } } return(o) } setMethod( f = "[", signature = c("item_pool", "numeric"), definition = function(x, i, j, ...) { return(subsetItemPool(x, i)) } ) setMethod( f = "c", signature = "item_pool", definition = function(x, ...) { arg <- list(...) pool <- x for (p in arg) { pool <- combineItemPool(pool, p) } return(pool) } ) `+.item_pool` <- function(x1, x2) { if (!inherits(x1, "item_pool") || !inherits(x2, "item_pool")) { stop("operands must be 'item_pool' objects") } new_p <- combineItemPool(x1, x2) return(new_p) } `-.item_pool` <- function(x1, x2) { if (!inherits(x1, "item_pool") || !inherits(x2, "item_pool")) { stop("operands must be 'item_pool' objects") } if (any(x2@id %in% x1@id)) { idx <- which(!(x1@id %in% x2@id)) if (length(idx) > 0) { o <- subsetItemPool(x1, idx) return(o) } else { warning("subset not performed: the resulting 'item_pool' object is empty") return(x1) } } return(x1) } `==.item_pool` <- function(x1, x2) { if (!inherits(x1, "item_pool") || !inherits(x2, "item_pool")) { stop("operands must be 'item_pool' objects") } return(identical(x1, x2)) }
calc_kl <- function(feature, target, len_target, pos_target) { crosstable <- fast_crosstable(target, len_target, pos_target, feature) counts_feature <- c(crosstable[2] + crosstable[4], crosstable[1] + crosstable[3]) KL.plugin(crosstable[c(2, 4)]/counts_feature[1], crosstable[c(1, 3)]/counts_feature[2]) }
paletteer_d <- function(palette, n, direction = 1, type = c("discrete", "continuous")) { if (abs(direction) != 1) { abort("direction must be 1 or -1") } type <- match.arg(type) palette <- try(palette, silent = TRUE) if (inherits(palette, "try-error")) { palette <- attr(palette, "condition")$message palette <- sub("^.*?\"", "", palette) palette <- sub("\".*$", "", palette) } check_palette(palette, d_names) palette <- unlist(strsplit(palette, "::")) pal <- paletteer::palettes_d[[palette]] if (missing(n)) { n <- length(pal) } if (type == "discrete" && n > length(pal)) { abort(paste("Number of requested colors greater than this palette can offer which is ", length(pal), ".", sep = "" )) } out <- switch(type, continuous = (grDevices::colorRampPalette(pal))(n), discrete = pal[1:n] ) if (direction == -1) { prismatic::color(rev(out)) } else { prismatic::color(out) } }
IUT.design <- function(method = c("s1", "s2", "s2.f"), s1.rej, t1.rej, s1.acc, t1.acc, n1, s2.rej, t2.rej, n2, s1.rej.delta=0, t1.rej.delta=0, s1.acc.delta=0, t1.acc.delta=0, s2.rej.delta=0, t2.rej.delta=0, n1.delta=0, n2.delta=0, p0.s, p0.t, p1.s, p1.t, signif.level = 0.05, power.level = 0.85, show.time = TRUE, output = c("minimax","optimal","maxpower","admissible", "all"), plot.out=FALSE){ method <- match.arg(method) output <- match.arg(output) if (show.time==TRUE) {ptm <- proc.time()} switch(method, s1 = { s <- seq(s1.rej - s1.rej.delta, s1.rej + s1.rej.delta) t <- seq(t1.rej - t1.rej.delta, t1.rej + t1.rej.delta) n <- seq(n1 - n1.delta, n1 + n1.delta) combn <- expand.grid(p0.s = p0.s, p0.t = p0.t, p1.s = p1.s, p1.t = p1.t, s = s, t = t, n = n) err <- pmax(mapply(IUT.power, method = "s1", s1.rej = combn$s, t1.rej = combn$t, n1 = combn$n, p.s = combn$p0.s, p.t = 0, USE.NAMES = F), mapply(IUT.power, method = "s1", s1.rej = combn$s, t1.rej = combn$t, n1 = combn$n, p.s = 1 - combn$p0.t, p.t = combn$p0.t, USE.NAMES = F)) pow <- mapply(IUT.power, method = "s1", s1.rej = combn$s, t1.rej = combn$t, n1 = combn$n, p.s = combn$p1.s, p.t = combn$p1.t, USE.NAMES = F) names(combn) <- c("p0.s", "p0.t", "p1.s", "p1.t", "s.rej", "t.rej", "N") }, s2 = { s1 <- seq(s1.rej - s1.rej.delta, s1.rej + s1.rej.delta) s2 <- seq(s1.acc - s1.acc.delta, s1.acc + s1.acc.delta) t1 <- seq(t1.rej - t1.rej.delta, t1.rej + t1.rej.delta) t2 <- seq(t1.acc - t1.acc.delta, t1.acc + t1.acc.delta) a1 <- seq(s2.rej - s2.rej.delta, s2.rej + s2.rej.delta) a2 <- seq(t2.rej - t2.rej.delta, t2.rej + t2.rej.delta) n1 <- seq(n1 - n1.delta, n1 + n1.delta) n2 <- seq(n2 - n2.delta, n2 + n2.delta) combn <- expand.grid(p0.s = p0.s, p0.t = p0.t, p1.s = p1.s, p1.t = p1.t, s1 = s1, t1 = t1, s2 = s2, t2 = t2, a1 = a1, a2 = a2, n1 = n1, n2 = n2) err <- pmax(mapply(IUT.power, method = "s2", s1.rej = combn$s1, t1.rej = combn$t1, n1 = combn$n1, s1.acc = combn$s2, t1.acc = combn$t2, n2 = combn$n2, s2.rej = combn$a1, t2.rej = combn$a2, p.s = combn$p0.s, p.t = 0, USE.NAMES = F), mapply(IUT.power, method = "s2", s1.rej = combn$s1, t1.rej = combn$t1, n1 = combn$n1, s1.acc = combn$s2, t1.acc = combn$t2, n2 = combn$n2, s2.rej = combn$a1, t2.rej = combn$a2, p.s = 1 - combn$p0.t, p.t = combn$p0.t, USE.NAMES = F)) pow <- mapply(IUT.power, method = "s2", s1.rej = combn$s1, t1.rej = combn$t1, n1 = combn$n1, s1.acc = combn$s2, t1.acc = combn$t2, n2 = combn$n2, s2.rej = combn$a1, t2.rej = combn$a2, p.s = combn$p1.s, p.t = combn$p1.t, USE.NAMES = F) PET <- mapply(IUT.power, method = "s2", s1.rej = combn$s1, t1.rej = combn$t1, n1 = combn$n1, s1.acc = combn$s2, t1.acc = combn$t2, n2 = combn$n2, s2.rej = combn$a1, t2.rej = combn$a2, p.s = combn$p0.s, p.t = combn$p0.t, output.all= TRUE, USE.NAMES = F)[2,] EN <- mapply(IUT.power, method = "s2", s1.rej = combn$s1, t1.rej = combn$t1, n1 = combn$n1, s1.acc = combn$s2, t1.acc = combn$t2, n2 = combn$n2, s2.rej = combn$a1, t2.rej = combn$a2, p.s = combn$p0.s, p.t = combn$p0.t, output.all= TRUE, USE.NAMES = F)[3,] names(combn) <- c("p0.s", "p0.t", "p1.s", "p1.t", "s1.rej", "t1.rej", "s1.acc", "t1.acc", "s2.rej", "t2.rej", "N1", "N2") }, s2.f = { s2 <- seq(s1.acc - s1.acc.delta, s1.acc + s1.acc.delta) t2 <- seq(t1.acc - t1.acc.delta, t1.acc + t1.acc.delta) a1 <- seq(s2.rej - s2.rej.delta, s2.rej + s2.rej.delta) a2 <- seq(t2.rej - t2.rej.delta, t2.rej + t2.rej.delta) n1 <- seq(n1 - n1.delta, n1 + n1.delta) n2 <- seq(n2 - n2.delta, n2 + n2.delta) combn <- expand.grid(p0.s = p0.s, p0.t = p0.t, p1.s = p1.s, p1.t = p1.t, s2 = s2, t2 = t2, a1 = a1, a2 = a2, n1 = n1, n2 = n2) err <- pmax(mapply(IUT.power, method = "s2.f", n1 = combn$n1, s1.acc = combn$s2, t1.acc = combn$t2, n2 = combn$n2, s2.rej = combn$a1, t2.rej = combn$a2, p.s = combn$p0.s, p.t = 0, USE.NAMES = F), mapply(IUT.power, method = "s2.f", n1 = combn$n1, s1.acc = combn$s2, t1.acc = combn$t2, n2 = combn$n2, s2.rej = combn$a1, t2.rej = combn$a2, p.s = 1 - combn$p0.t, p.t = combn$p0.t, USE.NAMES = F)) pow <- mapply(IUT.power, method = "s2.f", n1 = combn$n1, s1.acc = combn$s2, t1.acc = combn$t2, n2 = combn$n2, s2.rej = combn$a1, t2.rej = combn$a2, p.s = combn$p1.s, p.t = combn$p1.t, USE.NAMES = F) PET <- mapply(IUT.power, method = "s2.f", n1 = combn$n1, s1.acc = combn$s2, t1.acc = combn$t2, n2 = combn$n2, s2.rej = combn$a1, t2.rej = combn$a2, p.s = combn$p0.s, p.t = combn$p0.t, output.all=TRUE, USE.NAMES = F)[2,] EN <- mapply(IUT.power, method = "s2.f", n1 = combn$n1, s1.acc = combn$s2, t1.acc = combn$t2, n2 = combn$n2, s2.rej = combn$a1, t2.rej = combn$a2, p.s = combn$p0.s, p.t = combn$p0.t, output.all=TRUE, USE.NAMES = F)[3,] Error=Power=N1=N2=N=NULL names(combn) <- c("p0.s", "p0.t", "p1.s", "p1.t", "s1.acc", "t1.acc", "s2.rej", "t2.rej", "N1", "N2") }) if (method !="s1"){ result <- data.frame(combn, Error = err, Power = pow, PET, EN) tmp <- subset(result, Error <= signif.level & Power >= power.level) y <- tmp[,c("PET","EN")]; con.ind <- chull(y)[chull((y))==cummin(chull((y)))] x <- switch (output, all = {tmp}, minimax = {subset(tmp , N1+N2 == min(N1+N2, na.rm = T))}, optimal = {subset(tmp , EN == min(EN, na.rm = T))}, maxpower = {subset(tmp , Power == max(Power, na.rm = T))}, admissible = { subset(tmp[con.ind,],(N1+N2 >= min(N1+N2, na.rm = T)) & (EN == min(EN, na.rm = T))) }) if(nrow(na.omit(x))==0) { errmesg <- paste(" No feasible solution found. \n\tIncrease maximum sample size. Current nmax value = ",n1+n2+n1.delta+n2.delta,".",sep="") stop(message=errmesg) } else{ if (plot.out==TRUE){ xout <- tmp n <- nrow(xout) maxN <- xout[,"N1"]+xout[,"N2"] nmima <- ((1:n)[maxN==min(maxN)])[1] nopt <- ((1:n)[xout[,"EN"]==min(xout[,"EN"])])[1] nopt1 <- min(nopt+5,n) nadm <- setdiff(con.ind, c(1, nopt)) npow <- ((1:n)[result[,"Power"]==max(result[,"Power"])])[1] plot(maxN[1:nopt1],xout[1:nopt1,"EN"],type="l",xlab="Maximum Sample Size N = N1 + N2" ,ylab=expression(paste("E( N | ",p[0], " )")), main = "Two-stage Multinomial Designs") points(maxN[nmima],xout[1,"EN"],pch="M") points(maxN[nopt],xout[nopt,"EN"],pch="O") points(maxN[nadm],xout[nadm,"EN"],pch="A") points(maxN[npow],xout[npow,"EN"],pch="P") } return(na.omit(x)) } } else { result <- data.frame(combn, Error = err, Power = pow) tmp <- subset(result, Error <= signif.level, Power >= power.level) x <- switch (output, all = {tmp}, minimax = {subset(tmp , N == min(N, na.rm = T))}, maxpower = {subset(tmp , Power == max(Power, na.rm = T))}) if(nrow(na.omit(x))==0) { errmesg <- paste("No feasible solution found. \n\tIncrease maximum sample size. Current nmax value = ",n,".",sep="") stop(message=errmesg) } else return(na.omit(x)) } if (show.time==TRUE) {print(proc.time() - ptm)} }
test_that("relay athletes two lines, one athlete missing works", { skip_on_cran() file <- "http://leonetiming.com/2019/Indoor/GregPageRelays/Results.htm" raw_data <- try(read_results(file), silent = TRUE) if (any(grep("error", class(raw_data)))) { skip("Link to external data is broken") } else { df <- tf_parse(raw_data, relay_athletes = TRUE) relay_athletes_test <- df[226, ] %>% dplyr::select(Relay_Athlete_1, Relay_Athlete_2, Relay_Athlete_3, Relay_Athlete_4) %>% as.list() %>% unname() relay_athletes_standard <- c("Allyson Gaedje", "Hailey Erkkila", NA, "Reagan Bachman") expect_equivalent(relay_athletes_test, relay_athletes_standard) } })
tiny <- 1e-8 dat_test <- expand.grid( age = seq(25, 85 - tiny, length.out = 50), bmi = seq(20, 40, length.out = 50), KEEP.OUT.ATTRS = F ) rQDR2018A <- function(...){round(QDR2018A(...), 1)} gQDR2018A <- function(...){rQDR2018A(sex = "Female", ...)} expect_true( current = is.double(gQDR2018A(age = 60, ht = 1.83, wt = 90)), info = "QDR2018A-Female output class" ) expect_identical( current = length(gQDR2018A(age = 60, ht = 1.83, wt = 90)), target = 1L, info = "QDR2018A-Female output length" ) dat_test[["risk_min"]] <- with(dat_test, QDR2018A(sex = "Female", age = age, bmi = bmi, tds = -8)) dat_test[["risk_max"]] <- with(dat_test, QDR2018A(sex = "Female", age = age, bmi = bmi, ethn = "Bangladeshi", smoke = "Heavy", tds = 14, apsy = T, ster = T, cvd = T, gdm = T, learn = T, psy = T, pcos = T, stat = T, htn = T, fhdm = T)) expect_true( current = min(dat_test[["risk_min"]]) >= 0, info = "QDR2018A-Female [min(risk) >= 0]" ) expect_true( current = min(dat_test[["risk_min"]]) <= 0.1, info = "QDR2018A-Female [min(risk) <= 0.1]" ) expect_true( current = max(dat_test[["risk_max"]]) <= 100, info = "QDR2018A-Female [max(risk) <= 100]" ) expect_true( current = max(dat_test[["risk_max"]]) >= 99.9, info = "QDR2018A-Female [max(risk) >= 99.9]" ) dat_test[, c("risk_min", "risk_max")] <- NULL expect_error( current = rQDR2018A(age = 60), pattern = "sex & age must be specified", info = "QDR2018A-Female [missing(sex)]" ) expect_error( current = gQDR2018A(), pattern = "sex & age must be specified", info = "QDR2018A-Female [missing(age)]" ) tQDR2018A <- function(...){gQDR2018A(age = 60, ...)} expect_error( current = tQDR2018A(ht = 1.83), pattern = "Either bmi or ht & wt must be specified", info = "QDR2018A-Female [missing(bmi) & missing(wt)]" ) expect_error( current = tQDR2018A(wt = 90), pattern = "Either bmi or ht & wt must be specified", info = "QDR2018A-Female [missing(bmi) & missing(ht)]" ) expect_error( current = tQDR2018A(bmi = 30, ht = 1.83, wt = 90), pattern = "Either bmi or ht & wt must be specified", info = "QDR2018A-Female [!missing(bmi) & !missing(ht) & !missing(wt)]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(age = 60, ht = 1.83, wt = 90, ...)} expect_error( current = tQDR2018A(fpg = 4.5), pattern = "unused argument", info = "QDR2018A-Female [!missing(fpg)]" ) expect_error( current = tQDR2018A(hba1c = 31.5), pattern = "unused argument", info = "QDR2018A-Female [!missingl(hba1c)]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(bmi = 30, ...)} expect_error( current = tQDR2018A(age = 24), pattern = "all\\(age >= 25 & age < 85\\) is not TRUE", info = "QDR2018A-Female [age < 25]" ) expect_error( current = tQDR2018A(age = 85), pattern = "all\\(age >= 25 & age < 85\\) is not TRUE", info = "QDR2018A-Female [age >= 85]]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(age = 60, ...)} expect_error( current = tQDR2018A(bmi = (40/2.1^2) - 1), pattern = "all\\(bmi >= 40/2\\.1\\^2 & bmi <= 180/1\\.4\\^2\\) is not TRUE", info = "QDR2018A-Female [bmi < 40/2.1^2]" ) expect_error( current = tQDR2018A(bmi = (180/1.4^2) + 1), pattern = "all\\(bmi >= 40/2\\.1\\^2 & bmi <= 180/1\\.4\\^2\\) is not TRUE", info = "QDR2018A-Female [bmi > 180/1.4^2]" ) expect_warning( current = tQDR2018A(bmi = 19), pattern = "bmi < 20\\. Setting bmi == 20", info = "QDR2018A-Female [bmi < 20]" ) expect_warning( current = tQDR2018A(bmi = 41), pattern = "bmi > 40\\. Setting bmi == 40", info = "QDR2018A-Female [bmi > 40]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(age = 60, wt = 90, ...)} expect_error( current = tQDR2018A(ht = 1.3), pattern = "all\\(ht >= 1\\.4 & ht <= 2\\.1\\) is not TRUE", info = "QDR2018A-Female [ht < 1.4]" ) expect_error( current = tQDR2018A(ht = 2.2), pattern = "all\\(ht >= 1\\.4 & ht <= 2\\.1\\) is not TRUE", info = "QDR2018A-Female [ht > 2.1]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(age = 60, ht = 1.83, ...)} expect_error( current = tQDR2018A(wt = 39), pattern = "all\\(wt >= 40 & wt <= 180\\) is not TRUE", info = "QDR2018A-Female [wt < 40]" ) expect_error( current = tQDR2018A(wt = 181), pattern = "all\\(wt >= 40 & wt <= 180\\) is not TRUE", info = "QDR2018A-Female [wt > 180]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(age = 60, ht = 1.83, wt = 90, ...)} expect_error( current = tQDR2018A(tds = -8.1), pattern = "all\\(tds >= -8 & tds <= 14\\) is not TRUE", info = "QDR2018A-Female [tds < -8]" ) expect_error( current = tQDR2018A(tds = 14.1), pattern = "all\\(tds >= -8 & tds <= 14\\) is not TRUE", info = "QDR2018A-Female [tds > 14]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(age = 60, ht = 1.83, wt = 90, ...)} expect_error( current = tQDR2018A(apsy = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Female [!{apsy %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(ster = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Female [!{ster %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(cvd = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Female [!{cvd %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(gdm = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Female [!{gdm %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(learn = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Female [!{learn %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(psy = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Female [!{psy %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(pcos = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Female [!{pcos %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(stat = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Female [!{stat %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(htn = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Female [!{htn %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(fhdm = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Female [!{fhdm %in% c(0, 1, F, T)}]" ) rm(tQDR2018A) rm(gQDR2018A) gQDR2018A <- function(...){rQDR2018A(sex = "Male", ...)} expect_true( current = is.double(gQDR2018A(age = 60, ht = 1.83, wt = 90)), info = "QDR2018A-Female output class" ) expect_identical( current = length(gQDR2018A(age = 60, ht = 1.83, wt = 90)), target = 1L, info = "QDR2018A-Female output length" ) dat_test[["risk_min"]] <- with(dat_test, QDR2018A(sex = "Male", age = age, bmi = bmi, ethn = "WhiteNA", smoke = "Non", tds = -8)) dat_test[["risk_max"]] <- with(dat_test, QDR2018A(sex = "Male", age = age, bmi = bmi, ethn = "Bangladeshi", smoke = "Heavy", tds = 14, apsy = T, ster = T, cvd = T, learn = T, psy = T, stat = T, htn = T, fhdm = T)) expect_true( current = min(dat_test[["risk_min"]]) >= 0, info = "QDR2018A-Male [min(risk) >= 0]" ) expect_true( current = min(dat_test[["risk_min"]]) <= 0.1, info = "QDR2018A-Male [min(risk) <= 0.1]" ) expect_true( current = max(dat_test[["risk_max"]]) <= 100, info = "QDR2018A-Male [max(risk) <= 100]" ) expect_true( current = max(dat_test[["risk_max"]]) >= 99.9, info = "QDR2018A-Male [max(risk) >= 99.9]" ) dat_test[, c("risk_min", "risk_max")] <- NULL expect_error( current = rQDR2018A(age = 60), pattern = "sex & age must be specified", info = "QDR2018A-Male [missing(sex)]" ) expect_error( current = gQDR2018A(), pattern = "sex & age must be specified", info = "QDR2018A-Male [missing(age)]" ) tQDR2018A <- function(...){gQDR2018A(age = 60, ...)} expect_error( current = tQDR2018A(ht = 1.83), pattern = "Either bmi or ht & wt must be specified", info = "QDR2018A-Male [missing(bmi) & missing(wt)]" ) expect_error( current = tQDR2018A(wt = 90), pattern = "Either bmi or ht & wt must be specified", info = "QDR2018A-Male [missing(bmi) & missing(ht)]" ) expect_error( current = tQDR2018A(bmi = 30, ht = 1.83, wt = 90), pattern = "Either bmi or ht & wt must be specified", info = "QDR2018A-Male [!missing(bmi) & !missing(ht) & !missing(wt)]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(age = 60, ht = 1.83, wt = 90, ...)} expect_error( current = tQDR2018A(fpg = 4.5), pattern = "unused argument", info = "QDR2018A-Male [!missing(fpg)]" ) expect_error( current = tQDR2018A(hba1c = 31.5), pattern = "unused argument", info = "QDR2018A-Male [!missing(hba1c)]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(age = 60, ht = 1.83, wt = 90, ...)} expect_error( current = tQDR2018A(gdm = T), pattern = "pcos and gdm must be set to FALSE for male sex", info = "QDR2018A-Male [gdm = T]" ) expect_error( current = tQDR2018A(pcos = T), pattern = "pcos and gdm must be set to FALSE for male sex", info = "QDR2018A-Male [pcos = T]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(bmi = 30, ...)} expect_error( current = tQDR2018A(age = 24), pattern = "all\\(age >= 25 & age < 85\\) is not TRUE", info = "QDR2018A-Male [age < 25]" ) expect_error( current = tQDR2018A(age = 85), pattern = "all\\(age >= 25 & age < 85\\) is not TRUE", info = "QDR2018A-Male [age >= 85]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(age = 60, ...)} expect_error( current = tQDR2018A(bmi = (40/2.1^2) - 1), pattern = "all\\(bmi >= 40/2\\.1\\^2 & bmi <= 180/1\\.4\\^2\\) is not TRUE", info = "QDR2018A-Male [bmi < 40/2.1^2]" ) expect_error( current = tQDR2018A(bmi = (180/1.4^2) + 1), pattern = "all\\(bmi >= 40/2\\.1\\^2 & bmi <= 180/1\\.4\\^2\\) is not TRUE", info = "QDR2018A-Male [bmi > 180/1.4^2]" ) expect_warning( current = tQDR2018A(bmi = 19), pattern = "bmi < 20\\. Setting bmi == 20", info = "QDR2018A-Male [bmi < 20]" ) expect_warning( current = tQDR2018A(bmi = 41), pattern = "bmi > 40\\. Setting bmi == 40", info = "QDR2018A-Male [bmi > 40]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(age = 60, wt = 90, ...)} expect_error( current = tQDR2018A(ht = 1.3), pattern = "all\\(ht >= 1\\.4 & ht <= 2\\.1\\) is not TRUE", info = "QDR2018A-Male [ht < 1.4]" ) expect_error( current = tQDR2018A(ht = 2.2), pattern = "all\\(ht >= 1\\.4 & ht <= 2\\.1\\) is not TRUE", info = "QDR2018A-Male [ht > 2.1]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(age = 60, ht = 1.83, ...)} expect_error( current = tQDR2018A(wt = 39), pattern = "all\\(wt >= 40 & wt <= 180\\) is not TRUE", info = "QDR2018A-Male [wt < 40]" ) expect_error( current = tQDR2018A(wt = 181), pattern = "all\\(wt >= 40 & wt <= 180\\) is not TRUE", info = "QDR2018A-Male [wt > 180]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(age = 60, ht = 1.83, wt = 90, ...)} expect_error( current = tQDR2018A(tds = -8.1), pattern = "all\\(tds >= -8 & tds <= 14\\) is not TRUE", info = "QDR2018A-Male [tds < -8]" ) expect_error( current = tQDR2018A(tds = 14.1), pattern = "all\\(tds >= -8 & tds <= 14\\) is not TRUE", info = "QDR2018A-Male [tds > 14]" ) rm(tQDR2018A) tQDR2018A <- function(...){gQDR2018A(age = 60, ht = 1.83, wt = 90, ...)} expect_error( current = tQDR2018A(apsy = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Male [!{apsy %in% c(0, 1, F, T)}]") expect_error( current = tQDR2018A(ster = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Male [!{ster %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(cvd = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Male [!{cvd %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(learn = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Male [!{learn %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(psy = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Male [!{psy %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(stat = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Male [!{stat %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(htn = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Male [!{htn %in% c(0, 1, F, T)}]" ) expect_error( current = tQDR2018A(fhdm = -1), pattern = "all\\(\\w+ %in% c\\(FALSE, TRUE\\)\\) is not TRUE", info = "QDR2018A-Male [!{fhdm %in% c(0, 1, F, T)}]" ) rm(tQDR2018A) rm(gQDR2018A) rm(tiny, dat_test, rQDR2018A)
hypercube2 <- function(nsnp, x, y, theta){ stopifnot(nargs() == 4, nsnp > 0, length(x) == length(y)) out <- .Fortran("hypercube", n=as.integer(nsnp), x=as.integer(x), y=as.integer(y), theta=as.double(theta), k = double(1)) return(out[["k"]]) } hypercube <- function(X, theta){ stopifnot(nargs() == 2) nid <- nrow(X) nsnp <- ncol(X) DK <- matrix(0, ncol=nid, nrow=nid) for (i in 1:(nid-1)){ DK[i,i] <- hypercube2(nsnp, X[i,], X[i,], theta) for (j in (i+1):nid){ xy <- hypercube2(nsnp, X[i,], X[j,], theta) DK[i,j] <- DK[j,i] <- xy } } DK[nid, nid] <- hypercube2(nsnp, X[nid,], X[nid,], theta) return(DK) }
plot.ice = function(x, plot_margin = 0.05, frac_to_plot = 1, plot_points_indices = NULL, plot_orig_pts_preds = TRUE, pts_preds_size = 1.5, colorvec, color_by = NULL, x_quantile = FALSE, plot_pdp = TRUE, centered = FALSE, prop_range_y = TRUE, rug_quantile = seq(from = 0, to = 1, by = 0.1), centered_percentile = 0, point_labels = NULL, point_labels_size = NULL, prop_type = "sd", ...){ DEFAULT_COLORVEC = c("firebrick3", "dodgerblue3", "gold1", "darkorchid4", "orange4", "forestgreen", "grey", "black") if (class(x) != "ice"){ stop("object is not of class \"ice\"") } if (frac_to_plot <= 0 || frac_to_plot > 1 ){ stop("frac_to_plot must be in (0,1]") } if(!(prop_type %in% c("sd","range"))){ stop("prop_type must be either 'sd' or 'range'") } grid = x$gridpts n_grid = length(grid) ecdf_fcn = NULL if (x_quantile){ ecdf_fcn = ecdf(grid) grid = ecdf_fcn(grid) } ice_curves = x$ice_curves N = nrow(ice_curves) if (!is.null(point_labels)){ if (length(point_labels) != N){ stop("point_labels must be same length as number of ICE curves: ", N) } } legend_text = NULL if (missing(colorvec) && missing(color_by)){ colorvec = sort(rgb(rep(0.4, N), rep(0.4, N), rep(0.4, N), runif(N, 0.4, 0.8))) } if (!missing(colorvec) && !missing(color_by)){ if (!missing(colorvec) && length(colorvec) < N){ stop("color vector has length ", length(colorvec), " but there are ", N, " lines to plot") } } if (!missing(color_by) && missing(colorvec)){ arg_type = class(color_by) if(!(arg_type %in% c("character", "numeric", "factor"))){ stop("color_by must be a column name in X or a column index") } if(class(color_by) == "character"){ if(!(color_by %in% names(x$Xice))){ stop("The predictor name given by color_by was not found in the X matrix") } x_color_by = x$Xice[, color_by] } else if (length(color_by) > N){ stop("The color_by_data vector you passed in has ", length(color_by), " entries but the ICEbox object only has ", N, " curves.") } else if (length(color_by) == N){ x_color_by = color_by } else{ if( color_by < 1 || color_by > ncol(x$Xice) || (color_by%%1 !=0)){ stop("color_by must be a column name in X or a column index") } x_color_by = x$Xice[, color_by] } x_unique = sort(unique(x_color_by)) num_x_color_by = length(x_unique) if (num_x_color_by <= 10){ if (missing(colorvec)){ which_category = match(x_color_by, x_unique) colorvec = DEFAULT_COLORVEC[which_category] } legend_text = as.data.frame(cbind(x_unique, DEFAULT_COLORVEC[1 : num_x_color_by])) x_column_name = ifelse(length(color_by) == N, "data vector level", ifelse(is.character(color_by), color_by, paste("x_", color_by, sep = ""))) names(legend_text) = c(x_column_name,"color") cat("ICE Plot Color Legend\n") print(legend_text, row.names = FALSE) } else { if (is.factor(x_color_by)){ warning("color_by is a factor with greater than 10 levels: coercing to numeric.") x_color_by = as.numeric(x_color_by) } alpha_blend_colors = matrix(0, nrow = N, ncol = 3) alpha_blend_colors[, 1] = seq(from = 1, to = 0, length.out = N) alpha_blend_colors[, 2] = seq(from = 0, to = 1, length.out = N) alpha_blend_colors[, 3] = 0 rgbs = array(NA, N) for (i in 1 : N){ rgbs[i] = rgb(alpha_blend_colors[i, 1], alpha_blend_colors[i, 2], alpha_blend_colors[i, 3]) } colorvec = rgbs[sort(x_color_by, index.return = T)$ix] cat("ICE Plot Color Legend: red = low values of the color_by variable and green = high values\n") } } if (is.null(plot_points_indices)){ plot_points_indices = sample(1 : N, round(frac_to_plot * N)) } else { if (frac_to_plot < 1){ stop("frac_to_plot has to be 1 when plot_points_indices is passed to the plot function.") } } ice_curves = ice_curves[plot_points_indices, ] if (nrow(ice_curves) == 0){ stop("no rows selected: frac_to_plot too small.") } if (centered){ centering_vector = ice_curves[, max(ncol(ice_curves) * centered_percentile, 1)] ice_curves = ice_curves - centering_vector } colorvec = colorvec[plot_points_indices] min_ice_curves = min(ice_curves) max_ice_curves = max(ice_curves) range_ice_curves = max_ice_curves - min_ice_curves min_ice_curves = min_ice_curves - plot_margin * range_ice_curves max_ice_curves = max_ice_curves + plot_margin * range_ice_curves arg_list = list(...) arg_list = modifyList(arg_list, list(x = grid, y = ice_curves[1, ])) if( is.null(arg_list$xlab)){ xlab = x$xlab arg_list = modifyList(arg_list, list(xlab = xlab)) if (x_quantile){ xlab = paste("quantile(", xlab, ")", sep = "") arg_list = modifyList(arg_list, list(xlab = xlab)) } if (!missing(color_by)){ xlab = paste(xlab, "colored by", ifelse(length(color_by) == N, "a provided data vector", color_by)) arg_list = modifyList(arg_list, list(xlab = xlab)) } } if( is.null(arg_list$ylab)){ if (x$logodds){ ylab = "partial log-odds" arg_list = modifyList(arg_list, list(ylab = ylab)) } else if(x$probit){ ylab = "partial probit" arg_list = modifyList(arg_list, list(ylab = ylab)) }else { ylab = paste("partial yhat", ifelse(centered, "(centered)", "")) arg_list = modifyList(arg_list, list(ylab = ylab)) } } if( is.null(arg_list$xaxt) ){ xaxt = ifelse(x$nominal_axis, "n", "s") arg_list = modifyList(arg_list, list(xaxt = xaxt)) } if (is.null(arg_list$ylim)){ ylim = c(min_ice_curves, max_ice_curves) arg_list = modifyList(arg_list, list(ylim = ylim)) } if (is.null(arg_list$type)){ type = "n" arg_list = modifyList(arg_list, list(type = type)) } do.call("plot", arg_list) if (x$nominal_axis){ axis(1, at = sort(x$xj), labels = sort(x$xj), cex.axis = arg_list$cex.axis) } if (centered && prop_range_y && !x$logodds && !x$probit){ at = seq(min(ice_curves), max(ice_curves), length.out = 5) at = at - min(abs(at)) if(prop_type == "range"){ labels = round(at / x$range_y, 2) }else{ labels = round(at / x$sd_y, 2) } axis(4, at = at, labels = labels, cex.axis = arg_list$cex.axis) } for (i in 1 : nrow(ice_curves)){ points(grid, ice_curves[i, ], col = colorvec[i], type = "l") } if (plot_orig_pts_preds){ yhat_actual = x$actual_prediction[plot_points_indices] if (centered){ yhat_actual = yhat_actual - centering_vector } if (x_quantile){ xj = ecdf_fcn(x$xj)[plot_points_indices] } else { xj = x$xj[plot_points_indices] } for (i in 1 : length(xj)){ points(xj[i], yhat_actual[i], col = rgb(0.1, 0.1, 0.1), pch = 16, cex = pts_preds_size) points(xj[i], yhat_actual[i], col = colorvec[i], pch = 16, cex = round(pts_preds_size * 0.7)) } } if (!is.null(point_labels)){ text(xj, yhat_actual, pos = 4, labels = point_labels[plot_points_indices], cex = ifelse(is.null(point_labels_size), pts_preds_size, point_labels_size)) } if (!is.null(rug_quantile) && !x_quantile){ axis(side = 1, line = -0.1, at = quantile(x$xj, rug_quantile), lwd = 0, tick = T, tcl = 0.4, lwd.ticks = 2, col.ticks = "blue4", labels = FALSE, cex.axis = arg_list$cex.axis) } if (plot_pdp){ pdp = apply(ice_curves, 2, mean) if (centered){ pdp = pdp - pdp[ceiling(length(pdp) * centered_percentile + 0.00001)] } num_lines = length(plot_points_indices) points(grid, pdp, col = "yellow", type = "l", lwd = min(5.5 + (num_lines / 100) * 0.75, 8)) points(grid, pdp, col = "BLACK", type = "l", lwd = 4) } invisible(list(ice_curves = ice_curves, range_ice_curves = range_ice_curves, plot_points_indices = plot_points_indices, legend_text = legend_text, pdp = pdp)) }
tar_test("progress of successful pattern", { pipeline <- pipeline_init( list( target_init( name = "data", expr = quote(seq_len(3L)) ), target_init( name = "map", expr = quote(data), pattern = quote(map(data)) ) ) ) local <- local_init(pipeline) local$run() progress <- local$scheduler$progress$database$read_data() progress <- as_data_frame(progress) progress <- progress[progress$name == "map", ] expect_equal(progress$progress, c("started", "built")) }) tar_test("progress of a pattern with a canceled branch", { pipeline <- pipeline_init( list( target_init( name = "data", expr = quote(seq_len(3L)) ), target_init( name = "map", expr = quote(targets::tar_cancel(data > 2L)), pattern = quote(map(data)) ) ) ) local <- local_init(pipeline) local$run() progress <- local$scheduler$progress$database$read_data() progress <- as_data_frame(progress) progress <- progress[progress$name == "map", ] expect_equal(progress$progress, c("started", "canceled")) }) tar_test("progress of a pattern with a errored branch", { pipeline <- pipeline_init( list( target_init( name = "data", expr = quote(seq_len(3L)) ), target_init( name = "map", expr = quote(stopifnot(data < 3L)), pattern = quote(map(data)) ) ) ) local <- local_init(pipeline) expect_error(local$run(), class = "tar_condition_run") progress <- local$scheduler$progress$database$read_data() progress <- as_data_frame(progress) progress <- progress[progress$name == "map", ] expect_equal(progress$progress, c("started", "errored")) }) tar_test("same, but continue on error", { pipeline <- pipeline_init( list( target_init( name = "data", expr = quote(seq_len(3L)) ), target_init( name = "map", expr = quote(stopifnot(data > 1L)), pattern = quote(map(data)), error = "continue" ) ) ) local <- local_init(pipeline) local$run() progress <- local$scheduler$progress$database$read_data() progress <- as_data_frame(progress) progress <- progress[progress$name == "map", ] expect_equal(progress$progress, c("started", "errored")) }) tar_test("patternview_validate()", { expect_silent(patternview_validate(patternview_init())) })
mvtprqmc <- function(n, L, l, u, nu, mu){ d <- length(l); eta <- mu[d]; Z <- matrix(0, nrow = d, ncol = n); if(n*(d-1) > 2e7){ warning("High memory requirements for storage of QMC sequence\nConsider reducing n") } x <- as.matrix(randtoolbox::sobol(n, dim = d - 1, init = TRUE, scrambling = 1, seed = ceiling(1e6 * runif(1)))) const <- log(2*pi) / 2 - lgamma(nu / 2) - (nu / 2 - 1) * log(2) + lnNpr(-eta, Inf) + 0.5 * eta^2; R <- eta + trandn(rep(-eta, n), rep(Inf, n)); p <- (nu - 1) * log(R) - eta * R; R <- R / sqrt(nu); for(k in 1:(d-1)){ col <- c(L[k,1:k] %*% Z[1:k,]) tl <- R * l[k] - mu[k] - col; tu <- R * u[k] - mu[k] - col; Z[k,] <- mu[k] + norminvp(x[1:n,k], tl, tu); p <- p + lnNpr(tl,tu) + .5*mu[k]^2-mu[k]*Z[k,]; } col <- c(L[d,] %*% Z); tl <- R * l[d] - col tu <- R * u[d] - col; p <- p + lnNpr(tl, tu); return(exp(const)*mean(exp(p))) }
plot.sfnetwork = function(x, draw_lines = TRUE, ...) { dots = list(...) nsf = node_geom(x) use_edges = TRUE if (! has_spatially_explicit_edges(x)) { if (draw_lines) { x = explicitize_edges(x) } else { use_edges = FALSE } } dots$x = if (use_edges) c(nsf, edge_geom(x)) else nsf pch_missing = is.null(dots$pch) dots$pch = if (pch_missing) 20 else dots$pch do.call(plot, dots) } autoplot.sfnetwork = function(object, ...) { g = ggplot2::ggplot() + ggplot2::geom_sf(data = nodes_as_sf(object)) if (has_spatially_explicit_edges(object)) { g + ggplot2::geom_sf(data = edges_as_sf(object)) } else { message("Spatially implicit edges are drawn as lines", call. = FALSE) object = explicitize_edges(object) g + ggplot2::geom_sf(data = edges_as_sf(object)) } }
`singOrd` <- function(d,yy,r,itermax=100,eps=1e-6,verbose=0){ z<-cbind(1:length(d)) z<-z-sum(d*z)/sum(d) z<-z/wNorm(d,z) a<-crossprod(z,d*yy) iter<-1; sold<-Inf repeat{ z<-twoDirections(z,d); z<-cbind(z/wNorm(d,z)) a<-crossprod(z,d*yy) snew<-sum(d*(yy-z%*%a)^2) if (verbose > 2) print(c(round(sold,6),round(snew,6))) if ((iter == itermax) || ((sold - snew) < eps) || (snew < eps)) break() iter<-iter+1; sold<-snew } list(yhat=z%*%a,z=z,a=a) }
sirt_moving_average <- function(x, B, fill=TRUE) { x1 <- cumsum(x) N <- length(x) y <- rep(NA,N) i <- seq(B+1, N-B) xdiff <- x1[ -seq(1,B) ] - x1[ -seq(N-B+1,N) ] xdiff <- xdiff[ - seq(1,B) ] y[i] <- ( x1[i] + xdiff - c(0,x1[ -seq(N-2*B,N) ]) ) / (2*B+1) if(fill){ j <- seq(0,B-1) ybeg <- sapply(j, function(z) sum( x[ seq(1,(2*z+1)) ]) / (2*z+1) ) yend <- sapply(rev(j), function(z) sum( x[ seq(N-2*z,N) ] ) / (2*z+1) ) y[j+1] <- ybeg y[ rev(N-j) ] <- yend } return(y) } .movingAverage <- sirt_moving_average
context("unbreak_functions") test_that("0-row output when regex does not match", { df <- data.frame( groupvar = c("Grp a", "Grp", "b", "Grp c", "Grp d"), vals = c(2, 1, NA, 1, 1), stringsAsFactors = FALSE ) dfub <- unbreak_vals(df, regex = "nothing", ogcol = groupvar, newcol = r_ub ) expect_true( nrow(dfub) == 0 ) }) test_that("warning when slice_groups has a value", { df <- data.frame( groupvar = c("Grp a", "Grp", "b", "Grp c", "Grp d"), vals = c(2, 1, NA, 1, 1), stringsAsFactors = FALSE ) expect_warning( unbreak_vals(df, regex = "nothing", ogcol = groupvar, newcol = r_ub, slice_groups = FALSE ) ) }) test_that("errors for missing argument specifications", { df <- data.frame( groupvar = c("Grp a", "Grp", "b", "Grp c", "Grp d"), vals = c(2, 1, NA, 1, 1), stringsAsFactors = FALSE ) expect_error( unbreak_vals(df, regex = "nothing", ogcol = groupvar, slice_groups = FALSE ) ) expect_error( unbreak_vals(df, regex = "nothing", newcol = unbrokencol, slice_groups = FALSE ) ) expect_error( unbreak_vals(df, ogcol = groupvar, newcol = unbroken, slice_groups = FALSE ) ) }) test_that("unbreak_rows stops if regex does not match anything", { bball <- data.frame( stringsAsFactors = FALSE, v1 = c( "Player", NA, "Sleve McDichael", "Dean Wesrey", "Karl Dandleton" ), v2 = c("Most points", "in a game", "55", "43", "41"), v3 = c("Season", "(year ending)", "2001", "2000", "2010") ) expect_error(unbreak_rows(bball, "many", v2)) expect_error(unbreak_rows(bball, "many", v7)) }) test_that("grepl matches produce message", { bball <- data.frame( stringsAsFactors = FALSE, v1 = c( "Player", NA, "Sleve McDichael", "Dean Wesrey", "Karl Dandleton" ), v2 = c("Most points", "in a game", "55", "43", "41"), v3 = c("Season", "(year ending)", "2001", "2000", "2010") ) expect_message(unbreak_rows(bball, "Most", v2)) bb3 <- data.frame( stringsAsFactors = FALSE, v1 = c( "Player", NA, "Sleve McDichael", "Dean Wesrey", "Karl Dandleton", "Player", NA, "Mike Sernandez", "Glenallen Mixon", "Rey McSriff" ), v2 = c( "Most points", "in a game", "55", "43", "41", "Most varsity", "games played", "111", "109", "104" ), v3 = c( "Season", "(year ending)", "2001", "2000", "2010", "Season", "(year ending)", "2005", "2004", "2002" ) ) expect_message(unbreak_rows(bb3, "Most", v2)) })
hasSubsetInM <- function(y, x){ stopifnot(is.matrix(x), is.matrix(y), typeof(x) == "integer", typeof(y) == "integer", ncol(x) <= ncol(y)) C_hasSubsetInM(y, x) } findAllSubsets <- function(x, k, cols = seq_len(ncol(x))){ stopifnot(is.matrix(x), is.integer(x), is.integer(k), length(k) == 1L, k<=length(cols), is.integer(cols), cols >= 1L, max(cols) <= ncol(x), anyDuplicated(cols) == 0L) out <- combn( cols, k, FUN = function(a) C_uniqueCombs(x, a), simplify = FALSE) do.call(rbind, out) } conj_conCov <- function(cols, x, y, f){ stopifnot(mode(x)=="numeric", x>=0, x<=1, is.integer(cols), is.matrix(cols), ncol(cols)<=ncol(x), cols>=1L, cols<= ncol(x), mode(y)=="numeric", y>=0, y<=1, is.integer(f), length(f)==nrow(x), f>=1L) out <- apply(cols, 1, C_conj_conCov, x, y, f) if (!is.matrix(out)) out <- matrix(out, nrow = 2L) rownames(out) <- c("con", "cov") out } disj_conCov <- function(cols, x, y, f){ stopifnot(mode(x)=="numeric", x>=0, x<=1, is.integer(cols), cols>=1L, cols<= ncol(x), mode(y)=="numeric", y>=0, y<=1, is.integer(f), length(f)==nrow(x), f>=1L) out <- apply(cols, 1, C_disj_conCov, x, y, f) if (!is.matrix(out)) out <- matrix(out, nrow = 2L) rownames(out) <- c("con", "cov") out }
controller <- manipulateWidget( { dygraph(data[range[1]:range[2] - 2000, c("year", series)], main = title) }, data = mwSharedValue(), title = mwSharedValue(), range = mwSlider(min = 2010, max = 2001 + (nrow(data)-1), c(2001, 2001 + (nrow(data)-1))), series = mwSelect(choices = colnames(data)[-1], value = {colnames(data)[3]}, .display = TRUE), .compare = c("series"), .runApp = FALSE ) library(dygraphs) ui <- fillPage( fillRow( flex = c(NA, 1), div( textInput("title", label = "Title", value = "glop"), sliderInput("obs", "Number of observations:", min = 10, max = 1000, value = 500) ), mwModuleUI("mw", height = "100%") ) ) server <- function(input, output, session) { data <- reactive({ if(runif(1) > 0.5){ data.frame( year = 2000+1:input$obs, series1 = rnorm(input$obs), series2 = rnorm(input$obs), series3 = rnorm(input$obs) ) } else { data.frame( year = 2000+1:input$obs, series1 = rnorm(input$obs), series2 = rnorm(input$obs) ) } }) ctrl <- mwModule("mw", controller, data = data, title = reactive(input$title)) observeEvent(input$obs, { ctrl$setValueAll("range", c(2001, 2001 + (nrow(data())-1))) }, ignoreInit = TRUE) } shinyApp(ui, server)
knitr::opts_chunk$set(fig.width = 4, fig.align = 'center', echo = FALSE, warning = FALSE, message = FALSE, tidy = FALSE)
gen.gc = function(gen, pro = 0, ancestors = 0, vctProb = c(0.5, 0.5, 0.5, 0.5), typeCG = "IND") { retour = gen.detectionErreur(gen = gen, pro = pro, ancestors = ancestors, print.it = FALSE, named = TRUE, typeCG = typeCG, check = c(3, 5, 11, 34, 18, 10)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen pro = retour$pro ancestors = retour$ancestors typeCG = retour$typeCG named = retour$named if(typeCG == "IND") { if(is(pro, "GLgroup")) { CG = GLPrivCGPLUS(gen = gen, pro = as.numeric(unlist(pro)), ancestors = ancestors, vctProb = vctProb, print.it = FALSE, named = named) return(GLPrivCGgroup(CG, grppro = pro)) } else return(GLPrivCGPLUS(gen = gen, pro = pro, ancestors = ancestors, vctProb, print.it = FALSE, named = named)) } else { if(is(pro, "GLgroup")) { CG = GLPrivCGPLUS(gen = gen, pro = as.numeric(unlist(pro)), ancestors = ancestors, vctProb = vctProb, print.it = FALSE, named = named) CG = GLPrivCGgroup(CG, grppro = pro) if(typeCG == "MEAN") return(GLPrivCGmoyen(CG = CG, named = named)) if(typeCG == "CUMUL") stop("CUMUL is not available per group") if(typeCG == "TOTAL") return(GLPrivCGtotal(CG = CG, named = named)) if(typeCG == "PRODUCT") return(GLPrivCGproduit(CG = CG, named = named)) } else { CG = GLPrivCGPLUS(gen = gen, pro = as.numeric(unlist(pro)), ancestors = ancestors, vctProb = vctProb, print.it = FALSE, named = named) if(typeCG == "MEAN") return(GLPrivCGmoyen(CG = CG, named = named)) if(typeCG == "CUMUL") return(GLPrivCGcumul(CG = CG, named = named)) if(typeCG == "TOTAL") return(GLPrivCGtotal(CG = CG, named = named)) if(typeCG == "PRODUCT") return(GLPrivCGproduit(CG = CG, named = named)) } } } gen.completeness = function(gen, pro = 0, genNo = -1, type = "MEAN", ...) { if( type != "IND" ) if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour <- gen.detectionErreur(gen = gen, pro = pro, genNo = genNo, typecomp = type, named = TRUE, check = c(1, 5, 16, 171, 10)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen <- retour$gen pro <- retour$pro genNo <- retour$genNo type <- retour$typecomp named <- retour$named if(type == "IND"){ tableau = sapply(pro, function(x, gen, genNo, named) { GLPriv.completeness3V(gen$ind, gen$father, gen$mother, pro = x, genNo = genNo, named = named) } , gen = gen, genNo = genNo, named = named) if(is.null(dim(tableau))) tableau <- t(as.matrix(tableau)) if(type == "IND") dimnames(tableau)[[2]] <- as.character(paste("Ind", as.character(pro))) dimnames(tableau)[[1]] <- as.character(genNo) return(data.frame(tableau)) } else if(type == "MEAN") { return(GLPriv.completeness3V(gen$ind, gen$father, gen$mother, pro = pro, genNo = genNo, named = named)) } } gen.completenessVar = function(gen, pro = 0, genNo = -1, ...) { if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour = gen.detectionErreur(gen = gen, pro = pro, genNo = genNo, named = TRUE, check = c(1, 5, 16, 10)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen pro = retour$pro genNo = retour$genNo named = retour$named corrFactor = 1 tab = sapply(pro, function(x, gen, genNo, named) GLPriv.completeness3V(gen$ind, gen$father, gen$mother, pro = x, genNo = genNo, named = named), gen = gen, genNo = genNo, named = named) if(is.null(dim(tab))) tab <- t(as.matrix(tab)) tab = data.frame(apply(tab, 1, var) * corrFactor) dimnames(tab)[[1]] <- as.character(genNo) dimnames(tab)[[2]] <- "completeness.var" return(tab) } gen.branching = function(gen, pro = 0, ancestors = gen.founder(gen), bflag = 0) { if(sum(as.numeric(pro)) == 0) pro = gen.pro(gen) if(bflag == 0) { pro.segment = gen.pro(gen) ancestors = gen.founder(gen.branching(gen, pro.segment, ancestors, bflag = 1)) } retour = gen.detectionErreur(gen = gen, pro = pro, ancestors = ancestors, check = c(3, 36, 37)) if(retour$erreur) stop(retour$messageErreur) gen = retour$gen pro = retour$pro ancestors = retour$ancestors tmpgen <- integer(length([email protected])) tmpNelem <- integer(1) .Call("SPLUSebranche", [email protected], pro, length(pro), ancestors, length(ancestors), tmpgen, tmpNelem, specialsok = T) length(tmpgen) <- tmpNelem tmpNelem <- length(tmpgen) ebranche = new("GLgen", .Data = tmpgen, Date = date()) ebranche.asc = gen.genout(ebranche) sexeAbsent=FALSE if(length(setdiff(unique(ebranche.asc[,"sex"]), c(1,2,"H","F")))>0) { diff = setdiff(unique(ebranche.asc[,"sex"]), c(1,2,"H","F")) ebranche.asc=data.frame(ind=ebranche.asc$ind,father=ebranche.asc$father,mother=ebranche.asc$mother) sexeAbsent=TRUE warning(paste("The \"sex\" column contains invalid values:",diff, "\nThe column won't be considered for further calculations.")) } pro.ebranche = gen.pro(ebranche) pro.enTrop = setdiff(pro.ebranche, pro) if(sum(as.numeric(pro.enTrop)) != 0) { ebranche.asc = ebranche.asc[(!(ebranche.asc$ind %in% pro.enTrop)), ] ebranche = gen.genealogy(ebranche.asc) pro.ebranche = gen.pro(ebranche) } fond.ebranche = gen.founder(ebranche) pro.quiSontFond = pro.ebranche[pro.ebranche %in% fond.ebranche] ebranche.asc = ebranche.asc[(!(ebranche.asc$ind %in% pro.quiSontFond)), ] if(dim(ebranche.asc)[1]==0) stop("No branching possible, all probands are founders.") else gen = gen.genealogy(ebranche.asc) gen.validationAsc(gen) return(gen) } gen.children = function(gen, individuals, ...) { if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour = gen.detectionErreur(gen = gen, individuals = individuals, check = c(1, 13), ...) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen individuals = retour$individuals PositionEnfantDesMeres <- match(gen$mother, individuals) PositionEnfantDesPeres <- match(gen$father, individuals) EnfantDesMere <- gen$ind[(1:length(PositionEnfantDesMeres))[!is.na(PositionEnfantDesMeres)]] EnfantDesPere <- gen$ind[(1:length(PositionEnfantDesPeres))[!is.na(PositionEnfantDesPeres)]] Enfants <- unique(c(EnfantDesMere, EnfantDesPere)) return(Enfants) } gen.meangendepth = function(gen, pro = 0, type = "MEAN", ...) { if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour <- gen.detectionErreur(gen = gen, pro = pro, typecomp = type, check = c(1, 5, 17)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen <- retour$gen pro <- retour$pro type <- retour$typecomp if(type == "IND") { tableau <- sapply(pro, function(x, gen) GLPriv.entropie3V(gen$ind, gen$father, gen$mother, pro = x), gen = gen) tableau <- data.frame(tableau) if(type == "IND") dimnames(tableau)[[1]] <- as.character(paste("Ind", as.character(pro))) dimnames(tableau)[[2]] <- "Exp.Gen.Depth" return(tableau) } else if(type == "MEAN") return(GLPriv.entropie3V(gen$ind, gen$father, gen$mother, pro = pro)) } gen.founder = function(gen, ...) { if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour = gen.detectionErreur(gen = gen, ..., check = 1) if(retour$erreur == TRUE) return(retour$messageErreur) gen = retour$gen return(gen$ind[gen$father == 0 & gen$mother == 0]) } gen.half.founder = function(gen, ...) { if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour = gen.detectionErreur(gen = gen, ..., check = 1) if(retour$erreur == TRUE) return(retour$messageErreur) gen = retour$gen return(gen$ind[(gen$father != 0 & gen$mother == 0) | (gen$father == 0 & gen$mother != 0)]) } gen.sibship = function(gen, individuals, halfSibling = TRUE, ...) { if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour = gen.detectionErreur(gen = gen, individuals = individuals, halfSibling = halfSibling, check = c(1, 13, 14), ...) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen individuals = retour$individuals halfSibling = retour$halfSibling if(halfSibling == TRUE) { PositionProband = match(individuals, gen$ind) Meres <- gen$mother[PositionProband] Peres <- gen$father[PositionProband] MaskMere <- Meres != 0 MaskPere <- Peres != 0 Meres <- (Meres/MaskMere)[!is.na(Meres/MaskMere)] Peres <- (Peres/MaskPere)[!is.na(Peres/MaskPere)] sibshipMo <- gen.children(gen, individuals = Meres) sibshipFa <- gen.children(gen, individuals = Peres) sibshipAndProband <- unique(c(sibshipMo, sibshipFa)) temp <- match(sibshipAndProband, individuals) sibship <- sibshipAndProband[(1:length(temp))[is.na(temp)]] return(sibship) } else { PositionProband = match(individuals, gen$ind) Meres <- gen$mother[PositionProband] Peres <- gen$father[PositionProband] MaskMere <- Meres != 0 MaskPere <- Peres != 0 Meres <- (Meres/MaskMere)[!is.na(Meres/MaskMere)] Peres <- (Peres/MaskPere)[!is.na(Peres/MaskPere)] temp1 <- match(gen$mother, Meres) temp2 <- match(gen$father, Peres) PositionsibshipAndProband <- temp1 * temp2 sibshipSameFaMoAndProband <- gen$ind[(1:length(PositionsibshipAndProband))[!is.na(PositionsibshipAndProband)]] temp <- match(sibshipSameFaMoAndProband, individuals) sibship <- sibshipSameFaMoAndProband[(1:length(temp))[is.na(temp)]] return(sibship) } } gen.f = function(gen, pro, depthmin= (gen.depth(gen)-1), depthmax= (gen.depth(gen)-1)) { if(missing(pro)) pro = gen.pro(gen) retour = gen.detectionErreur(gen = gen, pro = pro, depthmin = depthmin, depthmax = depthmax, print.it = FALSE, named = TRUE, check = c(3, 5, 20, 18, 10)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen pro = retour$pro depthmin = retour$depthmin depthmax = retour$depthmax named = retour$named ecart <- as.integer(depthmax) - as.integer(depthmin) + 1 tmp <- double(length(pro) * ecart) .Call("SPLUSFS", [email protected], pro, length(pro), depthmin, depthmax, tmp, FALSE, specialsok = TRUE) dim(tmp) <- c(length(pro), ecart) dimnames(tmp) <- list(pro, NULL) tmp = drop(tmp) return(invisible(GLmulti(tmp, depth = as.integer(depthmin:depthmax)))) } gen.genealogy = function(ped, autoComplete=FALSE, ...) { if(class(ped) != "GLgen") { if(dim(ped)[2]==4 && sum(colnames(ped)==c("X1","X2","X3","X4"))==4) { print("No column names given. Assuming <ind>, <father>, <mother> and <sex>") colnames(ped) <- c("ind", "father", "mother", "sex") } if(sum(c("ind","father","mother","sex") %in% colnames(ped)) < 4){ stop(paste(paste(c("ind","father","mother","sex")[grep(FALSE,c("ind","father","mother","sex") %in% colnames(ped))]), "not in table columns.",collapse="")) } if(autoComplete & !all(is.element(ped[ped[,"father"]!=0,"father"], ped[,"ind"]))) { pereManquant <- unique(ped[grep(FALSE, is.element(ped[,"father"], ped[,"ind"])),"father"]) pereManquant <- pereManquant[-grep("^0$",pereManquant)] ajout <- matrix(c(pereManquant, rep(0, (2*length(pereManquant))), rep(1,length(pereManquant))), byrow=FALSE, ncol=4) colnames(ajout) <- colnames(ped) ped <- rbind(ped, ajout) } if(autoComplete & !all(is.element(ped[ped[,"mother"]!=0,"mother"], ped[,"ind"]))) { mereManquante <- unique(ped[grep(FALSE, is.element(ped[,"mother"], ped[,"ind"])),"mother"]) mereManquante <- mereManquante[-grep("^0$",mereManquante)] ajout <- matrix(c(mereManquante, rep(0, (2*length(mereManquante))), rep(2,length(mereManquante))), byrow=FALSE, ncol=4) colnames(ajout) <- colnames(ped) ped <- rbind(ped, ajout) } } retour = gen.detectionErreur(gen = ped, check = 1, ...) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen tmp2 <- NULL if(!is.null(gen$sex)) { tmp <- factor(gen$sex, levels = c("H", "h", 1, "F", "f", 2)) tmp2 <- as(tmp, "integer") tmp2[tmp2 == 2 | tmp2 == 3] <- 1 tmp2[tmp2 == 4 | tmp2 == 5 | tmp2 == 6] <- 2 } n <- .Call("SPLUSCALLCreerObjetGenealogie", gen$ind, gen$father, gen$mother, tmp2) return(new("GLgen", .Data = n, Date = date())) } gen.lineages = function(ped, pro = 0, maternal = TRUE, ...) { gen = gen.genealogy(ped, ...) retour = gen.detectionErreur(gen = gen, pro = pro, check = c(3, 36)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen pro = retour$pro if(sum(pro == 0)) data.ind = gen.pro(gen) else data.ind = pro if(maternal == TRUE) { ped$father = rep(0, length(ped$father)) } else { ped$mother = rep(0, length(ped$mother)) } genMouP = gen.genealogy(ped, ...) lig.parent.lst = c(data.ind) for(i in 1:gen.depth(gen)) { data.ind = unlist(gen.parent(genMouP, data.ind)) lig.parent.lst = c(lig.parent.lst, data.ind) } gen = gen.genealogy(ped[(ped$ind %in% lig.parent.lst), ], ...) return(gen) } gen.genout = function(gen, sorted = FALSE) { retour = gen.detectionErreur(gen = gen, sorted = sorted, check = c(3, 4)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen sorted = retour$sorted taille <- gen.noind(gen) v <- list(ind = integer(taille), father = integer(taille), mother = integer(taille), sex = integer(taille)) param = .Call("SPLUSOutgen", [email protected], v$ind, v$father, v$mother, v$sex, sorted) v <- list(ind = param$ind, father = param$father, mother = param$mother, sex = param$sex) return(invisible(data.frame(v))) } gen.implex = function(gen, pro = 0, genNo = -1, type = "MEAN", onlyNewAnc = FALSE, ...) { if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour <- gen.detectionErreur(gen = gen, pro = pro, genNo = genNo, typecomp = type, named = TRUE, check = c(1, 5, 16, 17, 10)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen <- retour$gen pro <- retour$pro genNo <- retour$genNo named <- retour$named type <- retour$typecomp if(onlyNewAnc == FALSE) fctApp <- GLPriv.implex3V else fctApp <- gen.implex3V if(type == "IND" | type == "MEAN") { tableau = sapply(pro, function(x, gen, genNo, fctApp, named) { fctApp(gen$ind, gen$father, gen$mother, pro = x, genNo = genNo, named = named) } , gen = gen, genNo = genNo, fctApp = fctApp, named = named) if(is.null(dim(tableau))) tableau <- t(as.matrix(tableau)) if(type == "MEAN") tableau = data.frame(apply(tableau, 1, mean)) names(tableau) <- "implex" if(type == "IND") dimnames(tableau)[[2]] <- as.character(paste("Ind", as.character(pro))) dimnames(tableau)[[1]] <- as.character(genNo) return(data.frame(tableau)) } else if(type == "ALL") return(fctApp(gen$ind, gen$father, gen$mother, pro = pro, genNo = genNo, named = named)) } gen.implexVar = function(gen, pro = 0, onlyNewAnc = FALSE, genNo = -1, ...) { if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour = gen.detectionErreur(gen = gen, pro = pro, genNo = genNo, named = TRUE, check = c(1, 5, 16, 10)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen pro = retour$pro genNo = retour$genNo named = retour$named if(onlyNewAnc == FALSE) fctApp <- GLPriv.implex3V else fctApp <- gen.implex3V facteurCorr = 1 tableau = sapply(pro, function(x, gen, fctApp, genNo, named) { fctApp(gen$ind, gen$father, gen$mother, pro = x, genNo = genNo, named = named) }, gen = gen, fctApp = fctApp, genNo = genNo, named = named) if(is.null(dim(tableau))) tableau <- t(as.matrix(tableau)) tableau = data.frame(apply(tableau, 1, var) * facteurCorr) dimnames(tableau)[[1]] <- as.character(genNo) dimnames(tableau)[[2]] <- "implex.var" return(tableau) } gen.max = function(gen, individuals) { retour = gen.detectionErreur(gen = gen, individuals = individuals, ancestors = 0, named = TRUE, check = c(3, 13, 10)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen individuals = retour$individuals named = retour$named nPro = length(individuals) ret = integer(nPro) .Call("SPLUSnumeroGen", [email protected], as.integer(individuals), nPro, ret) names(ret) <- individuals return(ret) } gen.min = function(gen, individuals) { retour = gen.detectionErreur(gen = gen, individuals = individuals, ancestors = 0, named = TRUE, check = c(3,13,10)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen individuals = retour$individuals named = retour$named nPro = length(individuals) ret = integer(nPro) .Call("SPLUSnumGenMin", [email protected], as.integer(individuals), nPro, ret) names(ret) <- individuals return(ret) } gen.mean = function(gen, individuals) { retour = gen.detectionErreur(gen = gen, individuals = individuals, ancestors = 0, named = TRUE, check = c(3,13,10)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen individuals = retour$individuals named = retour$named nPro = length(individuals) ret = double(nPro) .Call("SPLUSnumGenMoy", [email protected], as.integer(individuals), nPro, ret) names(ret) <- individuals return(ret) } gen.nochildren = function(gen, individuals) { retour = gen.detectionErreur(gen = gen, individuals = individuals, named = TRUE, check = c(3, 13, 10)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen individuals = retour$individuals named = retour$named ret <- integer(length(individuals)) .Call("SPLUSChild", [email protected], individuals, length(individuals), ret, specialsok = TRUE) names(ret) <- individuals return(ret) } gen.nowomen = function(gen) { retour = gen.detectionErreur(gen = gen, check = 3) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen if([email protected][12] == -1) return(NA) return([email protected][9] - [email protected][12]) } gen.nomen = function(gen) { retour = gen.detectionErreur(gen = gen, check = 3) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen if([email protected][12] == -1) return(NA) return([email protected][12]) } gen.noind = function(gen) { retour = gen.detectionErreur(gen = gen, check = c(3)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen return([email protected][9]) } gen.occ = function(gen, pro = 0, ancestors = 0, typeOcc = "IND", ...) { if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour = gen.detectionErreur(gen, pro = pro, ancestors = ancestors, check = c(1, 5, 11), ...) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen pro = retour$pro ancestors = retour$ancestors if(is(pro, "GLgroup")) { occurences <- matrix(0, nrow = length(ancestors), ncol = length(pro)) for(i in 1:length(pro)) occurences[, i] <- GLPrivOcc(gen, pro = pro[[i]], ancestors = ancestors) dimnames(occurences) <- list(ancestors, names(pro)) return(occurences) } else { occurences <- matrix(0, nrow = length(ancestors), ncol = length(pro)) for(i in 1:length(pro)) occurences[, i] <- GLPrivOcc(gen, pro = pro[i], ancestors = ancestors) dimnames(occurences) <- list(ancestors, pro) if(typeOcc == "IND") return(occurences) else if(typeOcc == "TOTAL") { dfResult.occtot = data.sum(as.data.frame(occurences)) dimnames(dfResult.occtot)[[1]] <- dimnames(occurences)[[1]] dimnames(dfResult.occtot)[[2]] <- c("nb.occ") return(dfResult.occtot) } else print("Please choose between \"IND\" and \"TOTAL\" for the variable typeOcc.") } } gen.parent = function(gen, individuals, output = "FaMo", ...) { if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour = gen.detectionErreur(gen = gen, individuals = individuals, output = output, check = c(1, 13, 15), ...) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen individuals = retour$individuals output = retour$output PositionProband = match(individuals, gen$ind) Meres <- gen$mother[PositionProband] Peres <- gen$father[PositionProband] Meres <- Meres[!is.na(Meres)] Peres <- Peres[!is.na(Peres)] Meres <- unique(Meres) Peres <- unique(Peres) if(output == "FaMo") return(list(Fathers=Peres[Peres > 0], Mothers=Meres[Meres > 0])) else if(output == "Fa") return(Peres[Peres > 0]) else if(output == "Mo") return(Meres[Meres > 0]) } gen.phiOver = function(phiMatrix, threshold) { if(!is.matrix(phiMatrix)) return("erreur on doit avoir une matrice") n = dim(phiMatrix)[1] phiMatrix[phiMatrix >= 0.5] = 0 phiMatrix[lower.tri(phiMatrix)] = 0 ind = dimnames(phiMatrix)[[1]] indices = matrix(rep(1:n, each = n), n, n) ran = indices[phiMatrix >= threshold] col = t(indices)[phiMatrix >= threshold] if(is.null(ind)) ind = 1:n else ind = as.numeric(ind) data.frame(line = ran, column = col, pro1 = ind[ran], pro2 = ind[col], kinship = phiMatrix[phiMatrix >= threshold]) } gen.phiMean = function(phiMatrix) { retour = gen.detectionErreur(matricephi = phiMatrix, named = TRUE, check = c(28, 10)) if(retour$erreur == TRUE) stop(retour$messageErreur) phiMatrix = retour$matricephi named = retour$named if("matrix" %in% class(phiMatrix)) mean(phiMatrix[phiMatrix < 0.5]) else GLapplyPhi(phiMatrix, function(x) mean(x[x < 0.5]), named = named) } gen.phi = function(gen, pro, depthmin = (gen.depth(gen)-1), depthmax = (gen.depth(gen)-1), MT = FALSE) { if(missing(pro)) pro = gen.pro(gen) if( depthmin<0 | depthmin>(gen.depth(gen)-1) | depthmax<0 | depthmax>(gen.depth(gen)-1) ) stop("depthmin and depthmax must be between 0 and (gen.depth(gen)-1)") retour = gen.detectionErreur( gen=gen, pro=pro, depthmin=depthmin, depthmax=depthmax, print.it=FALSE, named=TRUE, check=c(3,5,20,18,10)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = retour$gen pro = retour$pro depthmin = retour$depthmin depthmax = retour$depthmax named = retour$named if(MT) { ecart <- as.integer(depthmax) - as.integer(depthmin) + 1 np <- length(pro) npp <- length(pro) * length(pro) rmatrix <- double(ecart * npp) moyenne <- double(ecart) .Call("SPLUSPhisMT", [email protected], pro, length(pro), as.integer(depthmin), as.integer(depthmax), moyenne, rmatrix, FALSE, specialsok=TRUE) } else { liste = list() j = 1 for(i in depthmin:depthmax) { depthmintmp = i depthmaxtmp = i ecart <- as.integer(depthmaxtmp) - as.integer(depthmintmp) + 1 np <- length(pro) npp <- length(pro) * length(pro) rmatrix <- double(ecart * npp) moyenne <- double(ecart) print.it=FALSE .Call("SPLUSPhis", [email protected], pro, length(pro), depthmintmp, depthmaxtmp, moyenne, rmatrix, print.it, specialsok = TRUE) dim(rmatrix) <- c(np, np, ecart) dimnames(rmatrix) <- list(pro, pro, NULL) rmatrix <- drop(rmatrix) liste[[j]] = rmatrix j = j + 1 } sortie.lst = c() for(i in 1:length(liste)) sortie.lst = c(sortie.lst, liste[[i]]) ecart <- as.integer(depthmax) - as.integer(depthmin) + 1 np <- length(pro) npp <- length(pro) * length(pro) rmatrix <- double(ecart * npp) rmatrix <- sortie.lst } dim(rmatrix) <- c(np, np, ecart) dimnames(rmatrix) <- list(pro, pro, NULL) rmatrix <- drop(rmatrix) return(invisible(GLmulti(rmatrix, depth = as.integer(depthmin:depthmax)))) } gen.depth = function(gen) { return(depth(gen)) } gen.pro = function(gen, ...) { if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour = gen.detectionErreur(gen = gen, check = 1, ...) if(retour$erreur) return(retour$messageErreur) gen = retour$gen return(sort(gen$ind[is.na(match(gen$ind, c(gen$father, gen$mother)))])) } gen.rec = function(gen, pro = 0, ancestors = 0, ...) { if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour = gen.detectionErreur(gen = gen, pro = pro, ancestors = ancestors, check = c(1, 5, 11), ...) if(retour$erreur == TRUE) stop(retour$messageErreur) gen = gen.genealogy(retour$gen) pro = retour$pro ancestors = retour$ancestors if(is(pro, "GLgroup")) { nombreAncetre <- length(ancestors) nombreGroupe <- length(pro) rec <- matrix(0, nrow = nombreAncetre, ncol = nombreGroupe) for(i in 1:nombreGroupe) { contr <- t(gen.gc(gen, pro[[i]], ancestors)) rec[, i] <- (contr > 0) %*% rep(1, dim(contr)[2]) } dimnames(rec) <- list(ancestors, names(pro)) return(rec) } else { contr <- t(gen.gc(gen, pro, ancestors)) recouv <- (contr > 0) %*% rep(1, dim(contr)[2]) return(recouv) } } gen.meangendepthVar = function(gen, pro = 0, type = "MEAN", ...) { if(is(gen, "vector")) if(length(list(...)) != 2) stop("Invalid '...' parameter : 'father' and 'mother' parameter names are obligatory") retour <- gen.detectionErreur(gen = gen, pro = pro, typecomp = type, check = c(1, 5, 17)) if(retour$erreur == TRUE) stop(retour$messageErreur) gen <- retour$gen pro <- retour$pro type <- retour$typecomp if(type == "IND") { tableau <- sapply(pro, function(x, gen, pro, genNo, T) GLPriv.variance3V(gen$ind, gen$father, gen$mother, pro = x), gen = gen, pro = pro) tableau <- data.frame(tableau) if(type == "IND") dimnames(tableau)[[1]] <- as.character(paste("Ind", as.character(pro))) dimnames(tableau)[[2]] <- "Mean.Gen.Depth" return(tableau) } else if(type == "MEAN") return(GLPriv.variance3V(gen$ind, gen$father, gen$mother, pro = pro)) }
dendextend_options_env <- new.env() dendextend_options <- local({ options <- list() function(option, value) { if (missing(option)) { return(options) } if (missing(value)) { options[[option]] } else { options[[option]] <<- value } } }, envir = dendextend_options_env) assign_dendextend_options <- function() { dendextend_options("warn", FALSE) } remove_dendextend_options <- function() { }
Err = new.env() Err$msg = "" Err$prefix = "ypssc" Err$tab = " " Err$msgDash = " - " Err$fullprefix = "" Err$funcType = "" Err$msgType = "" Err$msgColon = " : " Err$lenOfLine = 50 Err$boxLen = 60 Err$checkAndWriteMsg = function() { Err$checkMsg() Err$writeMsg() } Err$checkMsg = function() { if( is.character(Err$msg) ) { Err$msgType = "character" } else if( is.double(Err$msg) | is.integer(Err$msg) ) { Err$msgType = "double" } else { stop( paste("Please provide either character/string or double/integer message for ", Err$funcType, sep = ""), call. = FALSE) } } Err$writeMsg = function() { Err$msg = gsub("\n", " \n ", Err$msg) if( Err$prefix == "" ) { Err$fullprefix = paste( Err$tab, Err$funcType, Err$msgColon, sep = "" ) } else { Err$fullprefix = paste( Err$tab, Err$prefix, Err$msgDash, Err$funcType, Err$msgColon, sep = "" ) } if( Err$msgType == "character" ) { lines = Err$getListOfLines(Err$msg) for( i in 1:length(lines) ) { msg = paste(Err$fullprefix, lines[i], sep = "") writeLines(msg) } } else { if( Err$msg < 0 ) { stop( paste("Please provide non-negetive integer.", funcType, sep = ""), call. = FALSE) } else if( Err$msg == 0 ) { writeLines("") } else { for( i in 1:Err$msg ) { writeLines(Err$fullprefix) } } } } Err$getListOfLines = function(text) { words = unlist( strsplit(text, " ") ) lines = c() l = 0; w = 0 while( w < length(words) ) { l = l + 1 w = w + 1 if( words[w] == "\n" ) { lines[l] = ""; next} else{ lines[l] = words[w]} while( nchar(lines[l]) <= Err$lenOfLine & w < length(words) ) { w = w + 1 if( words[w] == "\n" ) { break } else{ lines[l] = paste( lines[l], words[w], sep = " " ) } } } return(lines) } Err$help = function() { prefixCurrent = Err$prefix Err$prefix = "Err" tab = Err$tab Err$box( paste("Usage:", "\n", "\n", tab, "Set Prefix (optional):", "\n", "\n", tab, tab, "Err$prefix = 'Shashank'", "\n", "\n", tab, "Methods for displaying Notes, Warnings, Fatal error", "\n", tab, tab, "Err$note('your text')", "\n", tab, tab, "Err$warn('your text')", "\n", tab, tab, "Err$abort('your text')", "\n", sep = "") ) Err$prefix = prefixCurrent } Err$note = function(msg) { Err$msg = msg; Err$funcType = "NOTE"; Err$checkAndWriteMsg() msg = 15 } Err$warn = function(msg) { Err$msg = msg; Err$funcType = "WARNING"; Err$checkAndWriteMsg() } Err$abort = function(msg) { Err$note(0) Err$msg = msg; Err$funcType = "FATAL"; Err$checkAndWriteMsg() Err$note(0) Err$msg = "Aborting..."; Err$funcType = "FATAL"; Err$checkAndWriteMsg() Err$note(0) Err$note(0) exit() } Err$box = function(msg) { Err$note(0) Err$note( paste0( rep(">", Err$boxLen), collapse = '' ) ) Err$note(1) Err$note( msg ) Err$note(1) Err$note( paste0( rep("<", Err$boxLen), collapse = '' ) ) Err$note(0) } Err$reset = function() { Err$prefix = "ypssc" }
summary.ustyc <- function(object,...) { results <- c(nrow(object$df), ifelse(is.null(object$month),"All",object$month), ifelse(is.null(object$year),"All",object$year), object$updated) names(results) <- c("rows","month","year","updated") results }
test.lmFit <- function() { x <- regSim(model = "LM3", n = 50) lmfit <- regFit(Y ~ X1 + X2 + X3, data = x, use = "lm") print(lmfit) summary(lmfit) fitted(lmfit) slot(lmfit, "fitted") residuals(lmfit) slot(lmfit, "residuals") coef(lmfit) formula(lmfit) predict(lmfit) return() } test.rlmFit <- function() { x <- regSim(model = "LM3", n = 50) rlmfit <- regFit(Y ~ X1 + X2 + X3, data = x, use = "rlm") print(rlmfit) summary(rlmfit) fitted(rlmfit) slot(rlmfit, "fitted") residuals(rlmfit) slot(rlmfit, "residuals") coef(rlmfit) formula(rlmfit) predict(rlmfit) head(rlmfit@fit$model) return() } test.glmFit <- function() { x <- regSim(model = "LM3", n = 50) glmfit <- regFit(Y ~ X1 + X2 + X3, data = x, use = "glm") print(glmfit) summary(glmfit) print(glmfit@fit) summary(glmfit@fit) fitted(glmfit) slot(glmfit, "fitted") residuals(glmfit) slot(glmfit, "residuals") coef(glmfit) formula(glmfit) predict(glmfit) return() } test.gamFit <- function() { x <- regSim(model = "GAM3", n = 50) gamfit <- regFit(Y ~ s(X1) + s(X2) + X3, data = x, use = "gam") print(gamfit) summary(gamfit) print(gamfit@fit) summary(gamfit@fit) fitted(gamfit) slot(gamfit, "fitted") residuals(gamfit) slot(gamfit, "residuals") coef(gamfit) formula(gamfit) predict(gamfit) gamfit@fit$terms return() } test.pprFit <- function() { x <- regSim(model = "LM3", n = 50) pprfit <- regFit(Y ~ X1 + X2 + X3, data = x, use = "ppr") ppr <- ppr(Y ~ X1 + X2 + X3, data = x, nterms = 2) print(pprfit) summary(pprfit) print(pprfit@fit) summary(pprfit@fit) fitted(pprfit) slot(pprfit, "fitted") residuals(pprfit) slot(pprfit, "residuals") coef(pprfit) formula(pprfit) predict(pprfit) pprfit@fit$terms return() } if (FALSE) { test.nnetFit <- function() { x <- regSim(model = "LM3", n = 50) nnetfit <- regFit(Y ~ X1 + X2 + X3, data = x, use = "nnet") print(nnetfit) summary(nnetfit) print(nnetfit@fit) summary(nnetfit@fit) fitted(nnetfit) slot(nnetfit, "fitted") residuals(nnetfit) slot(nnetfit, "residuals") coef(nnetfit) formula(nnetfit) predict(nnetfit) nnetfit@fit$terms return() } } test.polymarsFit <- function() { x <- regSim(model = "LM3", n = 50) polymarsfit <- regFit(Y ~ X1 + X2 + X3, data = x, use = "polymars") print(polymarsfit) summary(polymarsfit) fitted(polymarsfit) slot(polymarsfit, "fitted") residuals(polymarsfit) slot(polymarsfit, "residuals") coef(polymarsfit) formula(polymarsfit) predict(polymarsfit) polymarsfit@fit$terms return() }
ebpLMMne <- function(YS, fixed.part, division, reg, con, backTrans, thetaFun, L) { N = nrow(reg) random.part = paste("(1|", paste(division), ")") model <- formula(paste("YS", "~", fixed.part, "+", random.part)) regS <- subset(reg, con == 1) regR <- subset(reg, con == 0) weights = rep(1, N) mEst <- lmer(model, data.frame(YS, regS)) Zobj <- Zfun(model, reg) Z <- Zobj$Z ZBlockNames <- Zobj$ZBlockNames vNames <- make.unique(Zfun(model, reg)$vNames,sep = ".") colnames(Z) <- vNames X <- model.matrix(formula(paste("~", fixed.part)), reg) ZS <- getME(mEst, name = "Z") vSNames <- make.unique(colnames(ZS),sep = ".") colnames(ZS) <- vSNames sigmaR = sigma(mEst) sigma2R = sigmaR ^ 2 S2v = as.numeric(VarCorr(mEst)[1]) Sv = sqrt(S2v) beta <- mEst@beta Xbeta <- X %*% beta XS <- getME(mEst, name = "X") vS <- as.vector(getME(mEst, name = "b")) vSDF <- data.frame(vSNames, vS) eS <- residuals(mEst) ZR <- Z[(con == 0),vSNames] XR <- model.matrix(formula(paste("~", fixed.part)), regR) R <- diag(sigma2R, nrow = nrow(regS), ncol = nrow(regS)) G <- sigma(mEst) ^ 2 * crossprod(getME(mEst, "Lambdat")) div = eval(parse(text = paste(paste( "reg$", paste(division), sep = "" )))) Ysim = matrix(NA, nrow = N, ncol = L) Ysim[(con == 1),] = YS divS = div[con == 1] div = as.factor(div) divS = as.factor(divS) con0 <- (con == 0) D = nlevels(div) i = 1 while (i <= D) { con_divS <- (divS == levels(div)[i]) con_div <- (div == levels(div)[i]) nd <- sum(con_divS) Nd <- sum(con_div) if (Nd > nd) { if (nd == 0) { Ysim[con_div,] <- Xbeta[con_div,] + replicate(L, c(matrix( rep(rnorm(1, 0, Sv), Nd), nrow = 1, byrow = T ))) + matrix(rnorm(L * Nd, 0, sigmaR), ncol = L) } else { Ysim[(con_div & con0),] <- matrix(rep(( as.matrix(Xbeta[(con_div & con0),]) + matrix(S2v, Nd - nd, nd) %*% solve(matrix(S2v, nd, nd) + sigma2R * diag(nd)) %*% as.matrix(YS[con_divS] - Xbeta[(con_div & (con == 1)),]) ), L), ncol = L) + replicate(L, c(matrix( rep(rnorm(1, 0, Sv), (Nd - nd)), nrow = 1, byrow = T ))) + matrix(rnorm(L * (Nd - nd), 0, sigmaR), ncol = L) } } i = i + 1 } if (is.null(backTrans)) { YbackTranssim <- Ysim } else { YbackTranssim <- backTrans(Ysim) } thetaP <- sapply(1:L, function(i) { thetaFun(YbackTranssim[, i]) }) thetaP <- rowMeans(matrix(thetaP, ncol = L)) outl <- list( thetaP = thetaP, beta = beta, Xbeta = Xbeta, sigma2R = sigma2R, R = R, G = G, model = model, mEst = mEst, YS = YS, reg = reg, con = con, regS = regS, regR = regR, weights = weights, Z = Z, ZBlockNames = ZBlockNames, X = X, ZS = ZS, XR = XR, ZR = ZR, eS = eS, vS = vSDF, fixed.part = fixed.part, random.part = random.part, division = division, backTrans = backTrans, thetaFun = thetaFun, L = L ) class(outl) = "ebpLMMne" return(outl) }
web.tsd <- function() { if (!requireNamespace("shiny", quietly = TRUE)) { stop("shiny package is absent; Please install it first") } getFromNamespace("runApp", ns="shiny")(appDir = system.file("shiny", package="embryogrowth"), launch.browser =TRUE) }
BOOL <- c(TRUE, FALSE) AGE <- c('0-11','12-15','16+') NUMHOUSEHOLD <- as.character(1:4) HOUSEHOLDTYPE <- c( 'partners, no children', 'partners with children', 'partners with children and others', 'partners with others', 'single parent with children', 'single parent with children and others', 'other') GENDER <- c('male','female') MARITALSTATUS <- c( 'married', 'divorced', 'widowed', 'never married') RELATION <- c( 'child', 'parent', 'parent in law', 'sibling', 'sibling in law', 'grandchild', 'other, family', 'other, not family') PARTNERRELATION <- c( 'spouse', 'partner', 'not partner') WORKENVIRONMENTS <- c('none','single','multiple') HOURSPERWEEK <- c('0-4','5-11','12-29','30+') COMPANYOWNER <- c('self','partner','in-laws') COMPANYCAT <- c( 'agro', 'energy/water', 'construction', 'education', 'healthcare', 'government', 'culture, sports, tourism', 'horeca', 'trade/retail', 'finacial', 'transport and communication', 'service', 'industry', 'other') PROFESSIONS <- c( 'teacher/instructor', 'agro', 'science, math', 'technical', 'transport', 'medical', 'business administration', 'law, management', 'horeca, wellness', 'language, cultural', 'social', 'other') WANTWORK <-c('no','yes','found','cant') age_ap %in% AGE interview %in% BOOL if ( age_ap == '0-11' ) proxyavailable %in% BOOL if ( age_ap == '12-15') permission %in% BOOL if ( proxyavailable ) interview if ( permission ) interview if ( age_ap == "16+" ) interview if (interview) numhousehold %in% NUMHOUSEHOLD if (interview) householdtype %in% HOUSEHOLDTYPE if (interview) respondentinhhcore %in% BOOL if (numhousehold == '1') householdtype == 'other' if ( numhousehold == '2' ) householdtype %in% c( 'partners, no children', 'partners with others', 'single parent with children','other') if ( numhousehold %in% '3' ) householdtype %in% c( 'partners with children', 'partners with others', 'single parent with children', 'single parent with children and others', 'other') if (interview) gender_1 %in% GENDER if (interview) age_1 %in% AGE if (respondentinhhcore) age_1 == '16+' if (interview) maritalstatus_1 %in% MARITALSTATUS if ( age_1 %in% c('0-11','12-15') ) maritalstatus_1 == 'never married' if ( numhousehold %in% as.character(2:4) ) gender_2 %in% GENDER if ( numhousehold %in% as.character(2:4) ) relation_2 %in% c(PARTNERRELATION,RELATION) if (relation_2 == 'spouse') maritalstatus_1 == 'married' if (householdtype %in% c( 'single parent with children', 'single parent with children and others')) relation_2 %in% RELATION if (householdtype %in% grep('partners',HOUSEHOLDTYPE,value=TRUE)) relation_2 %in% PARTNERRELATION if ( numhousehold %in% as.character(2:4) & householdtype == 'single parent with children') relation_2 == 'child' if (numhousehold %in% as.character(3:4) & householdtype == 'single parent with children' ) relation_3 == 'child' if (numhousehold == '4' & householdtype == 'single parent with children' ) relation_4 == 'child' if (numhousehold %in% as.character(3:4) & householdtype == 'partners with children') relation_3 == 'child' if (numhousehold == '4' & householdtype == 'partners with children') relation_4 == 'child' if ( numhousehold %in% as.character(3:4) ) gender_3 %in% GENDER if ( numhousehold %in% as.character(3:4) ) age_3 %in% AGE if ( numhousehold %in% as.character(3:4) ) relation_3 %in% RELATION if ( numhousehold == '4' ) gender_4 %in% GENDER if ( numhousehold == '4' ) age_4 %in% AGE if ( numhousehold == '4' ) relation_4 %in% RELATION workbox %in% BOOL if ( !interview ) !workbox if ( interview & age_ap == '16+' ) workbox if (workbox) haspayedjob %in% BOOL if ( !haspayedjob ) owncompany %in% BOOL if ( !owncompany ) familycompany %in% BOOL haswork %in% BOOL if ( haspayedjob ) haswork if (!haspayedjob & owncompany ) haswork if (!haspayedjob & familycompany ) haswork if ( !haspayedjob & !owncompany & !familycompany ) !haswork if ( haspayedjob ) workhours %in% HOURSPERWEEK if ( haswork ) workenvironments %in% WORKENVIRONMENTS if ( familycompany ) workenvironments %in% WORKENVIRONMENTS if ( haswork ) employee %in% BOOL if ( familycompany ) employee %in% BOOL if ( !employee & haswork ) companyowner %in% COMPANYOWNER if ( companyowner == 'self' ) companycat %in% COMPANYCAT if ( owncompany ) companycat %in% COMPANYCAT if (employee) profession %in% PROFESSIONS if (!employee & familycompany ) profession %in% PROFESSIONS if ( companyowner %in% c('partner','in-laws')) profession %in% PROFESSIONS unemploymentbox %in% BOOL if (!isemployee & age_ap == '16+' ) unemploymentbox if (workhours %in% c('0-4','5-11')) unemploymentbox if (unemploymentbox) wantwork %in% WANTWORK if (wantwork == 'found') willwork %in% HOURSPERWEEK if (wantwork == 'cant' ) diffwork %in% BOOL if (wantwork == 'yes' & !haswork) wantworkhrs %in% HOURSPERWEEK if (wantwork=='yes' & workhours %in% c('0-4','5-11') ) want12hrowncompany %in% BOOL if (wantwork=='yes' & wantworkhrs %in% c('12-29','30+')) want12hrowncompany %in% BOOL
as.character.mtc.hy.prior <- function(x, ...) { type <- x[['type']] distr <- x[['distr']] args <- x[['args']] expr <- if (distr == "dhnorm") { paste0("dnorm", "(", paste(args, collapse=", "), ") T(0,)") } else { paste0(distr, "(", paste(args, collapse=", "), ")") } if (type == "std.dev") { paste0("sd.d ~ ", expr, "\ntau.d <- pow(sd.d, -2)") } else if (type == "var") { paste0("var.d ~ ", expr, "\nsd.d <- sqrt(var.d)\ntau.d <- 1 / var.d") } else { paste0("tau.d ~ ", expr, "\nsd.d <- sqrt(1 / tau.d)") } } mtc.hy.prior <- function(type, distr, ...) { stopifnot(class(type) == "character") stopifnot(length(type) == 1) stopifnot(type %in% c('std.dev', 'var', 'prec')) obj <- list(type=type, distr=distr, args=list(...)) class(obj) <- "mtc.hy.prior" obj } hy.lor.outcomes <- c('mortality', 'semi-objective', 'subjective') hy.lor.comparisons <- c('pharma-control', 'pharma-pharma', 'non-pharma') hy.lor.mu <- matrix( c(-4.06, -3.02, -2.13, -4.27, -3.23, -2.34, -3.93, -2.89, -2.01), ncol=3, nrow=3, dimnames=list(hy.lor.outcomes, hy.lor.comparisons)) hy.lor.sigma <- matrix( c(1.45, 1.85, 1.58, 1.48, 1.88, 1.62, 1.51, 1.91, 1.64), ncol=3, nrow=3, dimnames=list(hy.lor.outcomes, hy.lor.comparisons)) mtc.hy.empirical.lor <- function(outcome.type, comparison.type) { stopifnot(outcome.type %in% hy.lor.outcomes) stopifnot(comparison.type %in% hy.lor.comparisons) mtc.hy.prior("var", "dlnorm", hy.lor.mu[outcome.type, comparison.type], signif(hy.lor.sigma[outcome.type, comparison.type]^-2, digits=3)) }
metacum <- function(x, pooled, sortvar) { chkclass(x, "meta") x <- updateversion(x) k.all <- length(x$TE) if (k.all < 2) { warning("Nothing calculated (minimum number of studies: 2).") return(invisible(NULL)) } if (!missing(pooled)) pooled <- setchar(pooled, c("fixed", "random")) else if (!x$fixed & x$random) pooled <- "random" else pooled <- "fixed" mf <- match.call() error <- try(sortvar <- eval(mf[[match("sortvar", names(mf))]], as.data.frame(x, stringsAsFactors = FALSE), enclos = sys.frame(sys.parent())), silent = TRUE) if (class(error) == "try-error") { xd <- x$data sortvar <- eval(mf[[match("sortvar", names(mf))]], xd, enclos = NULL) if (isCol(x$data, ".subset")) sortvar <- sortvar[x$data$.subset] } sort <- !is.null(sortvar) if (sort && (length(sortvar) != k.all)) stop("Number of studies in object 'x' and argument 'sortvar' ", "have different length.") if (!sort) sortvar <- 1:k.all o <- order(sortvar) n.e <- x$n.e[o] n.c <- x$n.c[o] n <- x$n[o] event.e <- x$event.e[o] event.c <- x$event.c[o] event <- x$event[o] mean.e <- x$mean.e[o] mean.c <- x$mean.c[o] mean <- x$mean[o] sd.e <- x$sd.e[o] sd.c <- x$sd.c[o] sd <- x$sd[o] time.e <- x$time.e[o] time.c <- x$time.c[o] time <- x$time[o] cor <- x$cor[o] TE <- x$TE[o] seTE <- x$seTE[o] if (length(x$incr) > 1) incr <- x$incr[o] else if (!is.null(x$incr)) incr <- rep_len(x$incr, k.all) else incr <- x$incr if (!is.null(x$exclude)) exclude <- x$exclude[o] else exclude <- rep_len(FALSE, k.all) ncum <- cumsum(!exclude) studlab <- x$studlab[o] slab <- character(k.all) for (i in 1:k.all) slab[i] <- paste0("Adding ", studlab[i], " (k=", ncum[i], ")") slab <- c(slab, "Pooled estimate") studlab <- c(rev(rev(slab)[-1]), " ", rev(slab)[1]) res.i <- matrix(NA, ncol = 21, nrow = k.all) add.i <- matrix(NA, ncol = 3, nrow = k.all) for (i in 1:k.all) { sel <- 1:i if (length(incr) > 1) incr.i <- incr[sel] else incr.i <- incr if (inherits(x, "metabin")) m <- metabin(event.e[sel], n.e[sel], event.c[sel], n.c[sel], exclude = exclude[sel], method = x$method, sm = x$sm, incr = incr.i, allincr = x$allincr, addincr = x$addincr, allstudies = x$allstudies, MH.exact = x$MH.exact, RR.Cochrane = x$RR.Cochrane, Q.Cochrane = x$Q.Cochrane, model.glmm = if (!is.null(x$model.glmm)) x$model.glmm else "UM.FS", level.ma = x$level.ma, hakn = x$hakn, adhoc.hakn = x$adhoc.hakn, method.tau = x$method.tau, tau.preset = x$tau.preset, TE.tau = x$TE.tau, keepdata = FALSE, warn = FALSE, control = x$control) if (inherits(x, "metacont")) m <- metacont(n.e[sel], mean.e[sel], sd.e[sel], n.c[sel], mean.c[sel], sd.c[sel], exclude = exclude[sel], sm = x$sm, pooledvar = x$pooledvar, level.ma = x$level.ma, hakn = x$hakn, adhoc.hakn = x$adhoc.hakn, method.tau = x$method.tau, tau.preset = x$tau.preset, TE.tau = x$TE.tau, keepdata = FALSE, warn = FALSE, control = x$control) if (inherits(x, "metacor")) m <- metacor(cor[sel], n[sel], exclude = exclude[sel], sm = x$sm, null.effect = x$null.effect, level.ma = x$level.ma, hakn = x$hakn, adhoc.hakn = x$adhoc.hakn, method.tau = x$method.tau, tau.preset = x$tau.preset, TE.tau = x$TE.tau, keepdata = FALSE, control = x$control) if (inherits(x, "metagen")) m <- metagen(TE[sel], seTE[sel], exclude = exclude[sel], sm = x$sm, null.effect = x$null.effect, level.ma = x$level.ma, hakn = x$hakn, adhoc.hakn = x$adhoc.hakn, method.tau = x$method.tau, tau.preset = x$tau.preset, TE.tau = x$TE.tau, keepdata = FALSE, warn = FALSE, control = x$control) if (inherits(x,"metainc")) m <- metainc(event.e[sel], time.e[sel], event.c[sel], time.c[sel], exclude = exclude[sel], method = x$method, sm = x$sm, incr = incr.i, allincr = x$allincr, addincr = x$addincr, model.glmm = if (!is.null(x$model.glmm)) x$model.glmm else "UM.FS", level.ma = x$level.ma, hakn = x$hakn, adhoc.hakn = x$adhoc.hakn, method.tau = x$method.tau, tau.preset = x$tau.preset, TE.tau = x$TE.tau, keepdata = FALSE, warn = FALSE, control = x$control) if (inherits(x, "metamean")) m <- metamean(n[sel], mean[sel], sd[sel], exclude = exclude[sel], sm = x$sm, null.effect = x$null.effect, level.ma = x$level.ma, hakn = x$hakn, adhoc.hakn = x$adhoc.hakn, method.tau = x$method.tau, tau.preset = x$tau.preset, TE.tau = x$TE.tau, keepdata = FALSE, warn = FALSE, control = x$control) if (inherits(x, "metaprop")) m <- metaprop(event[sel], n[sel], exclude = exclude[sel], method = x$method, sm = x$sm, null.effect = x$null.effect, incr = incr.i, allincr = x$allincr, addincr = x$addincr, method.ci = x$method.ci, level.ma = x$level.ma, hakn = x$hakn, adhoc.hakn = x$adhoc.hakn, method.tau = x$method.tau, tau.preset = x$tau.preset, TE.tau = x$TE.tau, keepdata = FALSE, warn = FALSE, control = x$control) if (inherits(x, "metarate")) m <- metarate(event[sel], time[sel], exclude = exclude[sel], method = x$method, sm = x$sm, null.effect = x$null.effect, incr = incr.i, allincr = x$allincr, addincr = x$addincr, level.ma = x$level.ma, hakn = x$hakn, adhoc.hakn = x$adhoc.hakn, method.tau = x$method.tau, tau.preset = x$tau.preset, TE.tau = x$TE.tau, keepdata = FALSE, warn = FALSE, control = x$control) sel.pft <- inherits(x, "metaprop") & x$sm == "PFT" sel.irft <- inherits(x, "metarate") & x$sm == "IRFT" add.i[i, ] <- c(m$method.tau.ci, m$sign.lower.tau, m$sign.upper.tau ) if (pooled == "fixed") { res.i[i, ] <- c(m$TE.fixed, m$seTE.fixed, m$lower.fixed, m$upper.fixed, m$statistic.fixed, m$pval.fixed, m$tau2, m$lower.tau2, m$upper.tau2, m$se.tau2, m$tau, m$lower.tau, m$upper.tau, m$I2, m$lower.I2, m$upper.I2, sum(m$w.fixed, na.rm = TRUE), if (sel.pft) 1 / mean(1 / n[sel]) else NA, NA, if (sel.irft) 1 / mean(1 / time[sel]) else NA, m$Rb ) } else if (pooled == "random") { res.i[i, ] <- c(m$TE.random, m$seTE.random, m$lower.random, m$upper.random, m$statistic.random, m$pval.random, m$tau2, m$lower.tau2, m$upper.tau2, m$se.tau2, m$tau, m$lower.tau, m$upper.tau, m$I2, m$lower.I2, m$upper.I2, sum(m$w.random, na.rm = TRUE), if (sel.pft) 1 / mean(1 / n[sel]) else NA, if (x$hakn) m$df.hakn else NA, if (sel.irft) 1 / mean(1 / time[sel]) else NA, m$Rb ) } } TE.i <- res.i[, 1] seTE.i <- res.i[, 2] lower.i <- res.i[, 3] upper.i <- res.i[, 4] statistic.i <- res.i[, 5] pval.i <- res.i[, 6] tau2.i <- res.i[, 7] lower.tau2.i <- res.i[, 8] upper.tau2.i <- res.i[, 9] se.tau2.i <- res.i[, 10] tau.i <- res.i[, 11] lower.tau.i <- res.i[, 12] upper.tau.i <- res.i[, 13] I2.i <- res.i[, 14] lower.I2.i <- res.i[, 15] upper.I2.i <- res.i[, 16] weight.i <- res.i[, 17] n.harmonic.mean.i <- res.i[, 18] if (pooled == "random" & x$hakn) df.hakn.i <- res.i[, 19] t.harmonic.mean.i <- res.i[, 20] Rb.i <- res.i[, 21] method.tau.ci <- unique(add.i[, 1]) sign.lower.tau.i <- add.i[, 2] sign.upper.tau.i <- add.i[, 3] if (pooled == "fixed") { TE.s <- x$TE.fixed seTE.s <- x$seTE.fixed lower.TE.s <- x$lower.fixed upper.TE.s <- x$upper.fixed statistic.s <- x$statistic.fixed pval.s <- x$pval.fixed w.s <- sum(x$w.fixed, na.rm = TRUE) } else if (pooled == "random") { TE.s <- x$TE.random seTE.s <- x$seTE.random lower.TE.s <- x$lower.random upper.TE.s <- x$upper.random statistic.s <- x$statistic.random pval.s <- x$pval.random w.s <- sum(x$w.random, na.rm = TRUE) } res <- list(TE = c(TE.i, NA, TE.s), seTE = c(seTE.i, NA, seTE.s), lower = c(lower.i, NA, lower.TE.s), upper = c(upper.i, NA, upper.TE.s), statistic = c(statistic.i, NA, statistic.s), pval = c(pval.i, NA, pval.s), studlab = studlab, tau2 = c(tau2.i, NA, x$tau2), lower.tau2 = c(lower.tau2.i, NA, x$lower.tau2), upper.tau2 = c(upper.tau2.i, NA, x$upper.tau2), se.tau2 = c(se.tau2.i, NA, x$se.tau2), tau = c(tau.i, NA, x$tau), lower.tau = c(lower.tau.i, NA, x$lower.tau), upper.tau = c(upper.tau.i, NA, x$upper.tau), method.tau.ci = method.tau.ci, sign.lower.tau.i = c(sign.lower.tau.i, NA, x$sign.lower.tau), sign.upper.tau.i = c(sign.upper.tau.i, NA, x$sign.upper.tau), I2 = c(I2.i, NA, x$I2), lower.I2 = c(lower.I2.i, NA, x$lower.I2), upper.I2 = c(upper.I2.i, NA, x$upper.I2), Rb = c(Rb.i, NA, x$Rb), w = c(weight.i, NA, w.s), df.hakn = if (pooled == "random" & x$hakn) c(df.hakn.i, NA, x$df.hakn) else NULL, sm = x$sm, method = x$method, k = x$k, pooled = pooled, fixed = ifelse(pooled == "fixed", TRUE, FALSE), random = ifelse(pooled == "random", TRUE, FALSE), TE.fixed = NA, seTE.fixed = NA, TE.random = NA, seTE.random = NA, null.effect = x$null.effect, Q = NA, level.ma = x$level.ma, hakn = x$hakn, adhoc.hakn = x$adhoc.hakn, method.tau = x$method.tau, tau.preset = x$tau.preset, TE.tau = x$TE.tau, n.harmonic.mean = c(n.harmonic.mean.i, NA, 1 / mean(1 / n)), t.harmonic.mean = c(t.harmonic.mean.i, NA, 1 / mean(1 / time)), prediction = FALSE, backtransf = x$backtransf, pscale = x$pscale, irscale = x$irscale, irunit = x$irunit, text.fixed = x$text.fixed, text.random = x$text.random, text.predict = x$text.predict, text.w.fixed = x$text.w.fixed, text.w.random = x$text.w.random, title = x$title, complab = x$complab, outclab = x$outclab, x = x, call = match.call()) res$version <- packageDescription("meta")$Version res$x$fixed <- res$fixed res$x$random <- res$random class(res) <- c("metacum", "summary.meta", "meta") if (inherits(x, "trimfill")) class(res) <- c(class(res), "trimfill") res }
AllAzimuthStatistics <- function (azimuths, ndig = 4) { n_elements = length(azimuths) m_azimuth = MeanAzimuth(azimuths) m_module = MeanModule(azimuths) c_variance = CircularVariance(azimuths) s_deviation = CircularStandardDeviation(azimuths) vm_parameter = VonMisesParameter(azimuths) c_dispersal = CircularDispersal(azimuths) s_azimuth = SkewnessAzimuthCoefficient(azimuths) k_azimuth = KurtosisAzimuthCoefficient(azimuths) print(" ------------------------------ ") print(" CIRCULAR STATISTICS - AZIMUTHS ") print(" ------------------------------ ") print(paste(" NUMBER OF ELEMENTS =", format(round(n_elements, 0), nsmall = 0))) print(paste(" MEAN AZIMUTH =", format(round(m_azimuth, ndig), nsmall = ndig))) print(paste(" MEAN MODULE =", format(round(m_module, ndig), nsmall = ndig))) print(paste(" CIRCULAR STANDARD DEVIATION =", format(round(s_deviation, ndig), nsmall = ndig))) print(paste(" CIRCULAR VARIANCE =", format(round(c_variance, ndig), nsmall = ndig))) print(paste(" CIRCULAR DISPERSAL =", format(round(c_dispersal, ndig), nsmall = ndig))) print(paste(" VON MISES PARAMETER =", format(round(vm_parameter, ndig), nsmall = ndig))) print(paste(" SKEWNESS COEFFICIENT =", format(round(s_azimuth, ndig), nsmall = ndig))) print(paste(" KURTOSIS COEFFICIENT =", format(round(k_azimuth, ndig), nsmall = ndig))) }
print.desda <- function(x, ...) { cat("\nDescriptive Discriminant Analysis\n") cat(rep("-",33), sep="") cat("\n$power ", "discriminant power") cat("\n$values ", "table of eigenvalues") cat("\n$discrivar ", "discriminant variables") cat("\n$discor ", "correlations") cat("\n$scores ", "discriminant scores\n") cat(rep("-",33), sep="") cat("\n\n$power\n") print(format(x$power, scientific=FALSE, digits=4), print.gap=2, quote=FALSE) cat("\n\n$values\n") print(format(x$values, scientific=FALSE, digits=3), print.gap=2, quote=FALSE) cat("\n\n$discrivar\n") print(x$discrivar, print.gap=2, digits=4) cat("\n\n$discor\n") print(head(x$discor), print.gap=2, digits=4) cat("\n\n$scores\n") print(head(x$scores), print.gap=2, digits=4) cat("...\n\n") invisible(x) }
library(imagerExtra) test_that("simplest_color_balance", { notim <- 1 im <- boats gim <- grayscale(im) gim2 <- imrep(gim, 2) %>% imappend(., "z") N <- 3 s_c <- 0.1 s_bad1 <- -1 s_bad2 <- 1000 s_bad3_1 <- 60 s_bad3_2 <- 70 s_bad4 <- NULL s_bad5 <- NA s_bad6 <- "Hello, World" range_bad1 <- c(1,1,1) range_bad2 <- c(-1,1) range_bad3 <- c(NA, 255) range_badorder <- c(255, 0) expect_error(BalanceSimplest(notim, s_c, s_c)) expect_error(BalanceSimplest(gim2, s_c, s_c)) expect_error(BalanceSimplest(im, s_c, s_c)) expect_error(BalanceSimplest(gim, s_c, s_c, range = range_bad1)) expect_error(BalanceSimplest(gim, s_c, s_c, range = range_bad2)) expect_error(BalanceSimplest(gim, s_c, s_c, range = range_bad3)) expect_warning(BalanceSimplest(gim, s_c, s_c, range = range_badorder)) expect_equal(BalanceSimplest(gim, s_c, s_c), BalanceSimplest(gim, s_c, s_c, range = range_badorder)) expect_error(BalanceSimplest(gim, s_bad1, s_c)) expect_error(BalanceSimplest(gim, s_c, s_bad2)) expect_error(BalanceSimplest(gim, s_bad3_1, s_bad3_2)) expect_error(BalanceSimplest(gim, s_c, s_bad4)) expect_error(BalanceSimplest(notim, s_c, s_bad5)) expect_error(BalanceSimplest(notim, s_bad6, s_c)) })
assign_season <- function(data , season_grps = NULL , season_names = NULL , season_start = NULL , abb = TRUE) { dat <- data if(abb) { mo_nms <- month.abb } else { mo_nms <- month.name } if(!lubridate::is.POSIXt(dat)) stop('Input data is not in POSIXt format. Reformat input data.') if(!is.null(season_grps)) { if (length(season_grps) <= 1) {stop('Number of seasons is equal to 1. Assign 2 or more seasons.')} } if(!is.null(season_names)) { if(is.null(season_grps)) {stop('Season names assigned with no seasons')} if (length(season_names) != length(unique(season_names))) {stop('Season names are not unique. Assign unique season names.')} if (length(season_names) != length(season_grps)) {stop('List of seasons not equal to season names. Assign an equal number of seasons and season names')} if(abb) {warning('abb = TRUE irrelevant for user-defined seasons and season names.')} } if(is.null(season_start)) { if(!is.null(season_grps)) {season_start %in% mo_nms} else {season_start %in% season_names} } if(is.null(season_grps) & is.null(season_names)){ x <- lubridate::month(dat) x <- mo_nms[x] x <- factor(x) x <- ordered(x, mo_nms) if(!is.null(season_start)){ start <- match(c(season_start), mo_nms) x <- ordered(x, c(mo_nms[c(start:12)], mo_nms[c(1:start-1)])) } } else { x <- data.frame(month = lubridate::month(dat)) names(season_grps) <- season_names seas_nm <- unlist(lapply(1:length(season_names), function(x) rep(names(season_grps[x]),length(season_grps[[x]])))) df <- data.frame(month = unname(unlist(season_grps)), nm = seas_nm) x <- left_join(x, df) x <- factor(x[, 2]) x <- ordered(x, season_names) if(!is.null(season_start)){ start <- match(c(season_start), season_names) x <- ordered(x, c(season_names[start:length(season_names)], season_names[c(1:start-1)])) } } return(x) }
OrderByCrossover<-function(df){ if(!(requireNamespace("vegan", quietly = TRUE) &requireNamespace("bipartite", quietly = TRUE))){ warning('This function needs vegan and bipartite to be installed first') return(NULL) } co <- bipartite::compart(df) row.seq <- NULL col.seq <- NULL CompartSize = c() for(i in 1:co$n.compart){ CompartSize<-c(CompartSize,sum(abs(co$cweb) == i)) } CompartmentRank<- rank(CompartSize, ties.method = 'first') for (m in order(CompartmentRank)) { comp.member <- which(abs(co$cweb) == m, arr.ind = TRUE) rs <- unique(comp.member[, 1]) cs <- unique(comp.member[, 2]) if (length(rs) < 3 | length(cs) < 3) { row.seq <- c(row.seq, rs) col.seq <- c(col.seq, cs) } else { ca <- vegan::cca(df[rs, cs]) row.seq <- c(row.seq, rs[order(summary(ca)$sites[, 1], decreasing = TRUE)]) col.seq <- c(col.seq, cs[order(summary(ca)$species[, 1], decreasing = TRUE)]) } } return(list('PrimaryOrder'= rownames(df)[row.seq], 'SecondaryOrder' = colnames(df)[col.seq] )) }
akritas <- function(formula = NULL, data = NULL, reverse = FALSE, time_variable = "time", status_variable = "status", x = NULL, y = NULL, ...) { if (!requireNamespaces("distr6")) { stop("Package 'distr6' required but not installed.") } call <- match.call() data <- clean_train_data(formula, data, time_variable, status_variable, x, y, reverse) if (ncol(data$x) == 1) { Fhat <- distr6::Empirical$new(data$x) } else { Fhat <- distr6::EmpiricalMV$new(data$x) } return(structure(list(y = data$y, x = data$x, xnames = colnames(data$x), Fhat = Fhat, FX = Fhat$cdf(data = data$x), call = call), name = "Akritas Estimator", class = c("akritas", "survivalmodel") )) } predict.akritas <- function(object, newdata, times = NULL, lambda = 0.5, type = c("survival", "risk", "all"), distr6 = FALSE, ...) { type <- match.arg(type) unique_times <- sort(unique(object$y[, 1, drop = FALSE])) if (is.null(times)) { times <- unique_times } else { times <- sort(unique(times)) } truth <- object$y newdata <- clean_test_data(object, newdata) ord <- order(truth[, 1], decreasing = TRUE) truth <- truth[ord, ] fx_train <- object$FX[ord] surv <- C_Akritas( truth = truth, times = times, unique_times = unique_times, FX_train = fx_train, FX_predict = object$Fhat$cdf(data = newdata), lambda = lambda ) colnames(surv) <- round(times, 6) ret <- list() if (type %in% c("survival", "all")) { if (!distr6) { ret$surv <- surv } else { surv <- cbind(1, surv, 0) colnames(surv) <- round(c(0, times, max(times) + 1e-2), 6) ret$surv <- distr6::as.Distribution( 1 - surv, fun = "cdf", decorators = c("CoreStatistics", "ExoticStatistics") ) } } if (type %in% c("risk", "all")) { ret$risk <- surv_to_risk(1 - surv) } if (length(ret) == 1) { return(ret[[1]]) } else { return(ret) } }
compareLengths <- function(x, y, name.x=deparse(substitute(x), width.cutoff, nlines=1, ...), name.y=deparse(substitute(y), width.cutoff, nlines=1, ...), message0='', compFun=c('NROW', 'length'), action=c(compatible='', incompatible='warning'), length0=c('compatible', 'incompatible', 'stop'), width.cutoff=20, ...){ if((nchar(name.x)<1) || (nchar(name.y)<1)){ message0 <- paste0(message0, 'in compareLengths:') } if(nchar(name.x)<1) name.x <- 'x' if(nchar(name.y)<1) name.y <- 'y' comp <- match.arg(compFun) lenx <- do.call(comp, list(x)) if(length(lenx)!=1){ stop(message0, ' compFun[ = ', comp, '](', name.x, ') has length ', lenx, '; must be 1.') } if(!is.numeric(lenx)){ stop(message0, ' compFun[ = ', comp, '](', name.x, ') is not numeric; class = ', class(lenx)) } leny <- do.call(comp, list(y)) if(length(leny)!=1){ stop(message0, ' compFun[ = ', comp, '](', name.y, ') has length ', leny, '; must be 1.') } if(!is.numeric(leny)){ stop(message0, ' compFun[ = ', comp, '](', name.y, ') is not numeric; class = ', class(leny)) } len <- c(lenx, leny) if(lenx==leny)return(c('equal', '')) act <- match.arg(action) o <- order(len) nam <- c(name.x, name.y) res <- (len[o[2]] %% len[o[1]]) if(is.na(res)){ ms0 <- paste0(message0, ' length(', nam[o[1]], ') = 0') if(length0[1] == 'compatible'){ Ms0 <- c('compatible', ms0) if(nchar(action[1])<1){ return(Ms0) } else do.call(action[1], list(Ms0)) } else { if(length0[1]=='stop'){ stop(ms0) } Ms0 <- c('incompatible', ms0) if(nchar(action[2])<1){ return(Ms0) } else do.call(action[2], list(Ms0)) } } if(res==0){ rat <- (len[o[2]] %/% len[o[1]]) msc <- paste0(message0, ' length(', nam[o[2]], ') = ', len[o[2]], ' is ', rat, ' times length(', nam[o[1]], ') = ', len[o[1]]) Msc <- c('compatible', msc) if(nchar(action[1])<1){ return(Msc) } else do.call(action[1], list(Msc)) } msi <- paste0(message0, ' length(', nam[o[2]], ') = ', len[o[2]], ' is not a multiple of length(', nam[o[1]], ') = ', len[o[1]]) Msi <- c('incompatible', msi) if(nchar(action[2])<1){ return(Msi) } else { do.call(action[2], list(Msi[1], ': ', Msi[2])) } Msi }
library(testthat) context("fit interfaces") library(parsnip) library(rlang) source(test_path("helper-objects.R")) hpc <- hpc_data[1:150, c(2:5, 8)] f <- y ~ x rmod <- linear_reg() sprk <- 1:10 class(sprk) <- c(class(sprk), "tbl_spark") tester <- function(object, formula = NULL, data = NULL, model) parsnip:::check_interface(formula, data, match.call(expand.dots = TRUE), model) tester_xy <- function(object, x = NULL, y = NULL, model) parsnip:::check_xy_interface(x, y, match.call(expand.dots = TRUE), model) test_that('good args', { expect_equal( tester(NULL, formula = f, data = hpc, model = rmod), "formula") expect_equal(tester_xy(NULL, x = hpc, y = hpc, model = rmod), "data.frame") expect_equal( tester(NULL, f, data = hpc, model = rmod), "formula") expect_equal( tester(NULL, f, data = sprk, model = rmod), "formula") }) test_that('wrong args', { expect_error(tester_xy(NULL, x = sprk, y = hpc, model = rmod)) expect_error(tester(NULL, f, data = as.matrix(hpc[, 1:4]))) }) test_that('single column df for issue expect_error( lm1 <- linear_reg() %>% set_engine("lm") %>% fit_xy(x = mtcars[, 2:4], y = mtcars[,1, drop = FALSE]), regexp = NA ) expect_error( lm2 <- linear_reg() %>% set_engine("lm") %>% fit_xy(x = mtcars[, 2:4], y = as.matrix(mtcars)[,1, drop = FALSE]), regexp = NA ) lm3 <- linear_reg() %>% set_engine("lm") %>% fit_xy(x = mtcars[, 2:4], y = mtcars$mpg) expect_equal(coef(lm1), coef(lm3)) expect_equal(coef(lm2), coef(lm3)) }) test_that('unknown modes', { mars_spec <- set_engine(mars(), "earth") expect_error( fit(mars_spec, am ~ ., data = mtcars), "Please set the mode in the model specification." ) expect_error( fit_xy(mars_spec, x = mtcars[, -1], y = mtcars[,1]), regexp = NA ) expect_error( fit_xy(mars_spec, x = lending_club[,1:2], y = lending_club$Class), regexp = NA ) }) test_that("elapsed time parsnip mods", { lm1 <- linear_reg() %>% set_engine("lm") %>% fit_xy(x = mtcars[, 2:4], y = mtcars$mpg, control = control_parsnip(verbosity = 2L)) lm2 <- linear_reg() %>% set_engine("lm") %>% fit(mpg ~ ., data = mtcars, control = control_parsnip(verbosity = 2)) expect_output(print(lm1), "Fit time:") expect_output(print(lm2), "Fit time:") expect_true(!is.null(lm1$elapsed)) expect_true(!is.null(lm2$elapsed)) lm3 <- linear_reg() %>% set_engine("lm") %>% fit_xy(x = mtcars[, 2:4], y = mtcars$mpg) output3 <- capture.output(print(lm3)) expect_equal(sum(grepl("Fit time", output3)), 0) }) test_that('No loaded engines', { expect_error( linear_reg() %>% fit(mpg ~., data = mtcars), regexp = NA ) expect_error( cubist_rules() %>% fit(mpg ~., data = mtcars), regexp = "Please load a parsnip extension package that provides one" ) expect_error( poisson_reg() %>% fit(mpg ~., data = mtcars), regexp = "Please load a parsnip extension package that provides one" ) })
burdenPlot <- function(y, G, annotation = rep('missense',ncol(G)), title="", order='mean', legend='keep', type='lines',post=NULL,name.snp=NULL){ geno <- G; pheno <- y; geno <- t(geno); geno[which(is.na(geno))]<-9; geno.plot <- subset(geno, apply(geno,1,sum)>0) MAC <- NULL mean <- NULL carriers.value <- list() for(i in 1:dim(geno.plot)[1]){ index.carriers <- which(geno.plot[i,]>0 & geno.plot[i,]!=9) carriers.value[[i]] <- pheno[index.carriers] mean[i] <- mean(carriers.value[[i]]) MAC[i] <- length(carriers.value[[i]]) } gt.hom <-apply(geno.plot==0,1,sum) gt.het1 <-apply(geno.plot==1,1,sum) gt.hom1 <-apply(geno.plot==2,1,sum) non.missing <- apply(geno.plot!=9,1,sum) foo1 <- cbind(2*gt.hom+gt.het1, gt.het1+2*gt.hom1) MAF <- apply(foo1, 1, min)/(2*non.missing) annotation.plot <- annotation[which(apply(geno,1,sum)>0)] col <- NULL col[annotation.plot=='missense'] <- 'red' col[annotation.plot=='nonsense'] <- 'cyan' col[annotation.plot=='splice' | annotation.plot=='splice-3' | annotation.plot=='splice-5'] <- 'blue' col[annotation.plot!='missense' & annotation.plot!='nonsense' & annotation.plot!='splice-3' & annotation.plot!='splice-3' & annotation.plot!='splice'] <- 'orange' if(order=='mean'){ carriers.value <- carriers.value[order(mean)] col <- col[order(mean)] if(!is.null(post)){post <- post[order(mean)]} } if(order=='MAF'){ carriers.value <- carriers.value[order(1/MAC)] col <- col[order(1/MAC)] if(!is.null(post)){post <- post[order(1/MAC)]} } if(order=='MAF.mean'){ carriers.value <- carriers.value[order(1/MAC, mean)] col <- col[order(1/MAC, mean)] if(!is.null(post)){post <- post[order(1/MAC,mean)]} } if(order=='anno'){ carriers.value <- carriers.value[order(annotation, mean, decreasing=FALSE)] col <- col[order(annotation, mean, decreasing=FALSE)]} n.ticks <- sum(is.na(mean)==FALSE) d <- density(pheno) mdy <- max(d$y) if(is.null(post)){ plot <- plot(d$x, d$y/3, ylab=" ", xlab='Trait Value',xlim=c(min(d$x),max(d$x)),ylim=c(-mdy, mdy/3), type='l', lwd=2, col='blue', yaxt="n",xaxt="n") } else{ plot <- plot(d$x, d$y/3, ylab=" ", xlab='Posterior Probability',xlim=c(min(d$x),max(d$x)),ylim=c(-mdy, mdy/3), type='l', lwd=2, col='blue', yaxt="n",xaxt="n") } if(is.null(post)){ axis(side=1,at=seq(min(d$x),max(d$x),length.out=6),labels=signif(seq(min(d$x),max(d$x),length.out=6),2)); }else{ axis(side=1,at=seq(min(d$x),max(d$x),length.out=6),labels=seq(0,1,length.out=6)); } if(type=='points'){ points(carriers.value[[1]], -(mdy)/rep(n.ticks, times=length(carriers.value[[1]]))-5e-2, pch=20)}else{ lines(c(min(carriers.value[[1]]), max(carriers.value[[1]])), -(mdy)/rep(n.ticks, times=2)-5e-2, lty='solid', lwd=1) points(carriers.value[[1]], -(mdy)/rep(n.ticks, times=length(carriers.value[[1]]))-5e-2, pch=124,cex=.68) } if(!is.null(name.snp)){ axis(2,at=seq(-mdy/n.ticks-5e-2,-length(carriers.value)*mdy/n.ticks,length.out=length(carriers.value)),labels=name.snp[order(mean)],cex.axis=.5,las=2); } points(mean(carriers.value[[1]]), -(mdy)/n.ticks-5e-2, pch=21, col=col[1], cex=1, bg=col[1]) if(!is.null(post)){ points(post[[1]]*(max(d$x)-min(d$x))+min(d$x),-(mdy)/n.ticks-5e-2,pch=17,col='purple',cex=1,bg='purple'); } if(dim(geno.plot)[1]>1){ for(i in 2:length(carriers.value)){ if(type=='points'){ points(carriers.value[[i]], -(i*mdy)/rep(n.ticks, times=length(carriers.value[[i]]))-5e-2+((i-1)*5e-2)/(length(carriers.value)-1), pch=20)}else{ lines(c(min(carriers.value[[i]]), max(carriers.value[[i]])), -(i*mdy)/rep(n.ticks, times=2)-5e-2+((i-1)*5e-2)/(length(carriers.value)-1), lty='solid', lwd=1) points(carriers.value[[i]], -(i*mdy)/rep(n.ticks, times=length(carriers.value[[i]]))-5e-2+((i-1)*5e-2)/(length(carriers.value)-1), pch=124,cex=.68)} points(mean(carriers.value[[i]]), -(i*mdy)/n.ticks-5e-2+((i-1)*5e-2)/(length(carriers.value)-1), pch=21, col=col[i], cex=1, bg=col[i]) if(!is.null(post)){ points(post[[i]]*(max(d$x)-min(d$x))+min(d$x),-(i*mdy)/n.ticks-5e-2+((i-1)*5e-2)/(length(carriers.value)-1),pch=17,col='purple',cex=1,bg='purple'); } } } abline(h=0, col='black') if(!is.null(post)){ axis(side=1,pos=0,at=seq(min(d$x),max(d$x),length.out=6),labels=signif(seq(min(d$x),max(d$x),length.out=6),2)); text(mean(pheno)+sd(pheno)/2,-(1*mdy)/n.ticks,'Trait Value'); } segments(x0=mean(pheno), y0= -((i+1)*mdy)/n.ticks, x1=mean(pheno), y1=max(d$y/3)+1, col='blue', lty='dashed') if(legend=='keep'){ if(is.null(post)){ legend('topleft', pch=21, legend=c('missense', 'nonsense', 'splice', 'synonymous'), cex=0.85, col=c('red','cyan','blue','orange'), pt.bg=c('red','cyan','blue','orange')) } if(!is.null(post)){ legend('topleft', pch=c(21,17), legend=c('missense',expression(p[j])), cex=0.85, col=c('red','purple'), pt.bg=c('red','purple')) } } title(title) return(plot) }
NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
rmAll <- function(ask = TRUE) { env <- parent.frame() object.list <- objects(env) if ( ask ) { if (length(object.list) == 0) { print("Workspace is already empty") return( invisible(1) ) } cat("Current contents of workspace:\n") print( object.list ) full.prompt <- paste( "Remove all objects? [y/n] ",sep = " ") response <- NA while( !(response %in% c("y","n")) ) { response <- readline( full.prompt ) } if( response == "n" ) { return( invisible(0) ) } } rm( list = object.list, envir = env ) return( invisible(1) ) }
emis_hot_td <- function(veh, lkm, ef, pro_month, params, verbose = FALSE, fortran = FALSE, nt = ifelse(check_nt() == 1, 1, check_nt() / 2)) { if (any(class(veh) %in% "sf")) { if (verbose) message("converting sf to data.frame") veh <- sf::st_set_geometry(veh, NULL) } for (i in 1:ncol(veh)) { veh[, i] <- as.numeric(veh[, i]) } if (class(lkm) != "units") { stop("lkm neeeds to has class 'units' in 'km'. Please, check package '?units::set_units'") } if (units(lkm)$numerator == "m") { stop("Units of lkm is 'm' ") } if (units(lkm)$numerator == "km") { lkm <- as.numeric(lkm) } if (length(lkm) != ncol(veh)) stop("Length of 'lkm' must be the as the number of columns of 'veh'") if (is.matrix(ef) | is.data.frame(ef)) { ef <- as.data.frame(ef) if (class(ef[, 1]) != "units") { stop("columns of ef must has class 'units' in 'g/km'. Please, check ?EmissionFactors") } if (units(ef[, 1])$numerator == "g" | units(ef[, 1])$denominator == "km") { for (i in 1:ncol(veh)) { ef[, i] <- as.numeric(ef[, i]) } } if (nrow(ef) == 1) { if (verbose) message("Transforming 1 row data.frame into numeric") ef <- as.numeric(ef) } } else { if (class(ef) != "units") { stop("ef must has class 'units' in 'g/km'. Please, check ?EmissionFactors") } if (units(ef)$numerator == "g" | units(ef)$denominator == "km") { ef <- as.numeric(ef) } } if (!missing(pro_month)) { if (is.data.frame(pro_month) | is.matrix(pro_month)) { pro_month <- as.data.frame(pro_month) for (i in 1:nrow(pro_month)) { pro_month[i, ] <- pro_month[i, ] / sum(pro_month[i, ]) } } else if (is.numeric(pro_month)) { pro_month <- pro_month / sum(pro_month) } } if (!missing(pro_month)) { if (verbose) message("Estimation with monthly profile") if (length(pro_month) != 12) stop("Length of pro_month must be 12") mes <- ifelse(nchar(1:12) < 2, paste0(0, 1:12), 1:12) if (is.data.frame(ef)) { if (verbose) message("Assuming you have emission factors for each simple feature and then for each month") if (is.data.frame(pro_month) & nrow(ef) == nrow(veh)) { if (verbose) message("'pro_month' is data.frame and number of rows of 'ef' and 'veh' are equal") if (nrow(pro_month) == 1) { message("Replicating one-row matrix to match number of rows of `veh`") pro_month <- matrix(as.numeric(pro_month), nrow = nrow(veh), ncol = ncol(pro_month)) } if (nrow(ef) != nrow(veh)) stop("Number of rows of 'veh' and 'ef' must be equal") if (ncol(ef) != ncol(veh)) stop("Number of cols of `ef` and `veh` must be equal") if (length(lkm) != ncol(veh)) stop("Length of `lkm` must be equal to number of columns of `veh`") if (nrow(pro_month) != nrow(veh)) stop("Number of rows of `month` and `veh` must be equal") if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(ncol(pro_month)) lkm <- as.numeric(lkm) ef <- as.matrix(ef[, 1:ncol(veh)]) month <- as.matrix(pro_month) if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emistd2fpar.f95") a <- dotCall64::.C64( .NAME = "emistd2fpar", SIGNATURE = c( rep("integer", 3), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 8), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd2f.f95") a <- dotCall64::.C64( .NAME = "emistd2f", SIGNATURE = c( rep("integer", 3), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 7), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- data.frame(emissions = a) e <- Emissions(e) e$rows <- rep(row.names(veh), each = ncolv * pmonth) e$age <- rep(seq(1, ncolv), nrowv * pmonth) e$month <- rep(seq(1, pmonth), ncolv * nrowv) } else { e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[, k] * ef[, j] })) dfi <- as.data.frame(dfi) names(dfi) <- "emissions" dfi <- Emissions(dfi) dfi$rows <- row.names(veh) dfi$age <- rep(1:ncol(veh), each = nrow(veh)) dfi$month <- (1:length(pro_month))[k] dfi })) } } else if (is.numeric(pro_month) & nrow(ef) == nrow(veh)) { if (verbose) message("'pro_month' is numeric and number of rows of 'ef' and 'veh' are equal") if (nrow(ef) != nrow(veh)) stop("Number of rows of `ef` and `veh` must be equal") if (ncol(ef) != ncol(veh)) stop("Number of cols of `ef` and `veh` must be equal") if (length(lkm) != ncol(veh)) stop("Length of `lkm` must be equal to number of columns of `veh`") if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(length(pro_month)) lkm <- as.numeric(lkm) ef <- as.matrix(ef[, 1:ncol(veh)]) month <- as.numeric(pro_month) if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emistd1fpar.f95") a <- dotCall64::.C64( .NAME = "emistd1fpar", SIGNATURE = c( rep("integer", 3), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 8), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd1f.f95") a <- dotCall64::.C64( .NAME = "emistd1f", SIGNATURE = c( rep("integer", 3), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 7), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- data.frame(emissions = a) e <- Emissions(e) e$rows <- rep(row.names(veh), ncolv * pmonth) e$age <- rep(rep(seq(1, ncolv), each = nrowv), pmonth) e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) } else { e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[k] * ef[, j] })) dfi <- as.data.frame(dfi) names(dfi) <- "emissions" dfi <- Emissions(dfi) dfi$rows <- row.names(veh) dfi$age <- rep(1:ncol(veh), each = nrow(veh)) dfi$month <- (1:length(pro_month))[k] dfi })) } } else if (is.numeric(pro_month) & nrow(ef) == 12) { if (verbose) message("'pro_month' is numeric and you have 12 montly ef") e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[k] * ef[k, j] })) dfi <- as.data.frame(dfi) names(dfi) <- "emissions" dfi <- Emissions(dfi) dfi$rows <- row.names(veh) dfi$age <- rep(1:ncol(veh), each = nrow(veh)) dfi$month <- (1:length(pro_month))[k] dfi })) } else if (is.data.frame(pro_month) & nrow(ef) == 12 * nrow(veh)) { if (verbose) message("'pro_month' is data.frame and number of rows of 'ef' is 12*number of rows 'veh'") if (nrow(pro_month) != nrow(veh)) stop("Number of rows of 'pmonth' and 'veh' must be equal") if (length(ef2) != length(unlist(veh)) * pmonth) stop("length of `ef` and `veh`*`months` must be equal be equal") if (length(lkm) != ncol(veh)) stop("length of `lkm` must be equal to number of columns of `veh`") if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(ncol(pro_month)) lkm <- as.numeric(lkm) ef$month <- rep(1:12, each = nrow(veh)) ef2 <- split(ef[, 1:ncol(veh)], ef$month) ef2 <- as.numeric(unlist(lapply(ef2, unlist))) month <- as.matrix(pro_month) if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emistd4fpar.f95") a <- dotCall64::.C64( .NAME = "emistd4fpar", SIGNATURE = c( rep("integer", 3), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef2, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 8), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd4f.f95") a <- dotCall64::.C64( .NAME = "emistd4f", SIGNATURE = c( rep("integer", 3), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef2, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 7), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- data.frame(emissions = a) e <- Emissions(e) e$rows <- rep(row.names(veh), ncolv * pmonth) e$age <- rep(rep(seq(1, ncolv), each = nrowv), pmonth) e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) } else { ef$month <- rep(1:12, each = nrow(veh)) ef <- split(ef, ef$month) e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[, k] * ef[[k]][, j] })) dfi <- as.data.frame(dfi) names(dfi) <- "emissions" dfi <- Emissions(dfi) dfi$rows <- row.names(veh) dfi$age <- rep(1:ncol(veh), each = nrow(veh)) dfi$month <- (1:length(pro_month))[k] dfi })) } } else if (is.numeric(pro_month) & nrow(ef) == 12 * nrow(veh)) { if (verbose) message("'pro_month' is numeric and number of rows of 'ef' is 12*number of rows 'veh'") if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(length(pro_month)) ef$month <- rep(1:12, each = nrow(veh)) ef2 <- split(ef[, 1:ncol(veh)], ef$month) ef2 <- as.numeric(unlist(lapply(ef2, unlist))) lkm <- as.numeric(lkm) month <- as.numeric(pro_month) if (length(ef2) != length(unlist(veh)) * pmonth) stop("length of `ef` and `veh`*`months` must be equal be equal") if (length(lkm) != ncol(veh)) stop("length of `lkm` must be equal to number of columns of `veh`") if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emistd3fpar.f95") a <- dotCall64::.C64( .NAME = "emistd3fpar", SIGNATURE = c( rep("integer", 3), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef2, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 8), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { a <- dotCall64::.C64( .NAME = "emistd3f", SIGNATURE = c( rep("integer", 3), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef2, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 7), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- data.frame(emissions = a) e <- Emissions(e) e$rows <- rep(row.names(veh), ncolv * pmonth) e$age <- rep(rep(seq(1, ncolv), each = nrowv), pmonth) e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) } else { ef$month <- rep(1:12, each = nrow(veh)) ef <- split(ef, ef$month) e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[k] * ef[[k]][, j] })) dfi <- as.data.frame(dfi) names(dfi) <- "emissions" dfi <- Emissions(dfi) dfi$rows <- row.names(veh) dfi$age <- rep(1:ncol(veh), each = nrow(veh)) dfi$month <- (1:length(pro_month))[k] dfi })) } } else { stop("Condition is not met. Review your input data dn read the documentation, please") } if (!missing(params)) { if (!is.list(params)) stop("'params' must be a list") if (is.null(names(params))) { if (verbose) message("Adding names to params") names(params) <- paste0("P_", 1:length(params)) } for (i in 1:length(params)) { e[, names(params)[i]] <- params[[i]] } } if (verbose) cat("Sum of emissions:", sum(e$emissions), "\n") } else if (!is.data.frame(ef)) { if (verbose) message("Assuming you have the same emission factors in each simple feature") if (is.data.frame(pro_month) | is.matrix(pro_month)) { if (verbose) message("'pro_month' is data.frame and 'ef' is numeric") if (nrow(pro_month) == 1) { message("Replicating one-row matrix to match number of rows of `veh`") pro_month <- matrix(as.numeric(pro_month), nrow = nrow(veh), ncol = ncol(pro_month)) } if (length(ef) != ncol(veh)) stop("Length of `ef` and number of cols of `veh` must be equal") if (length(lkm) != ncol(veh)) stop("Length of `lkm` must be equal to number of columns of `veh`") if (nrow(pro_month) != nrow(veh)) stop("Number of rows of `month` and `veh` must be equal") if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(ncol(pro_month)) lkm <- as.numeric(lkm) ef <- as.numeric(ef) month <- as.matrix(pro_month) if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emistd6fpar.f95") a <- dotCall64::.C64( .NAME = "emistd6fpar", SIGNATURE = c( rep("integer", 3), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 8), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd6f.f95") a <- dotCall64::.C64( .NAME = "emistd6f", SIGNATURE = c( rep("integer", 3), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 7), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- data.frame(emissions = a) e <- Emissions(e) e$rows <- rep(row.names(veh), ncolv * pmonth) e$age <- rep(rep(seq(1, ncolv), each = nrowv), pmonth) e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) } else { e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[, k] * ef[j] })) dfi <- as.data.frame(dfi) names(dfi) <- "emissions" dfi <- Emissions(dfi) dfi$rows <- row.names(veh) dfi$age <- rep(1:ncol(veh), each = nrow(veh)) dfi$month <- (1:length(pro_month))[k] dfi })) } } else if (is.numeric(pro_month)) { if (verbose) message("'pro_month' is numeric and 'ef' is numeric") if (length(ef) != ncol(veh)) stop("Number of columns of 'veh' and length of 'ef' must be equal") if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(length(pro_month)) lkm <- as.numeric(lkm) month <- as.numeric(pro_month) ef <- as.numeric(ef) if (length(ef) != ncol(veh)) stop("length of `ef` and number of cols of `veh` must be equal") if (length(lkm) != ncol(veh)) stop("length of `lkm` must be equal to number of columns of `veh`") if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emistd5fpar.f95") a <- dotCall64::.C64( .NAME = "emistd5fpar", SIGNATURE = c( rep("integer", 3), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 8), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd5f.f95") a <- dotCall64::.C64( .NAME = "emistd5f", SIGNATURE = c( rep("integer", 3), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 7), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- data.frame(emissions = a) e <- Emissions(e) e$rows <- rep(row.names(veh), ncolv * pmonth) e$age <- rep(seq(1, ncolv), each = nrowv) e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) } else { e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[k] * ef[j] })) dfi <- as.data.frame(dfi) names(dfi) <- "emissions" dfi <- Emissions(dfi) dfi$rows <- row.names(veh) dfi$age <- rep(1:ncol(veh), each = nrow(veh)) dfi$month <- (1:length(pro_month))[k] dfi })) } } if (!missing(params)) { if (!is.list(params)) stop("'params' must be a list") if (is.null(names(params))) { if (verbose) message("Adding names to params") names(params) <- paste0("P_", 1:length(params)) } for (i in 1:length(params)) { e[, names(params)[i]] <- params[[i]] } } if (verbose) cat("Sum of emissions:", sum(e$emissions), "\n") } } else { if (verbose) message("Estimation without monthly profile") if (!is.data.frame(ef)) { if (verbose) message("'ef' is a numeric vector with units") if (fortran) { lkm <- as.numeric(lkm) ef <- as.numeric(ef) nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) if (length(ef) != ncol(veh)) stop("length of `ef` and number of cols of `veh` must be equal") if (length(lkm) != ncol(veh)) stop("length of `lkm` must be equal to number of columns of `veh`") if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emistd7fpar.f95") a <- dotCall64::.C64( .NAME = "emistd7fpar", SIGNATURE = c( "integer", "integer", "double", "double", "double", "integer", "double" ), nrowv = nrowv, ncolv = ncolv, veh = as.matrix(veh), lkm = lkm, ef = ef, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv), INTENT = c( "r", "r", "r", "r", "r", "r", "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd7f.f95") a <- dotCall64::.C64( .NAME = "emistd7f", SIGNATURE = c( "integer", "integer", "double", "double", "double", "double" ), nrowv = nrowv, ncolv = ncolv, veh = as.matrix(veh), lkm = lkm, ef = ef, emis = dotCall64::vector_dc("double", nrowv * ncolv), INTENT = c( "r", "r", "r", "r", "r", "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- as.data.frame(a) names(e) <- "emissions" e <- Emissions(e) e$rows <- row.names(e) e$age <- rep(1:ncol(veh), each = nrow(veh)) } else { e <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * ef[j] })) e <- as.data.frame(e) names(e) <- "emissions" e <- Emissions(e) e$rows <- row.names(e) e$age <- rep(1:ncol(veh), each = nrow(veh)) } } else { if (verbose) message("'ef' is data.frame") if (nrow(ef) != nrow(veh)) stop("Number of rows of 'ef' and 'veh' must be equal") e <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * ef[, j] })) e <- as.data.frame(e) names(e) <- "emissions" e <- Emissions(e) e$rows <- row.names(e) e$age <- rep(1:ncol(veh), each = nrow(veh)) } if (!missing(params)) { if (!is.list(params)) stop("'params' must be a list") if (is.null(names(params))) { if (verbose) message("Adding names to params") names(params) <- paste0("P_", 1:length(params)) } for (i in 1:length(params)) { e[, names(params)[i]] <- params[[i]] } } if (verbose) cat("Sum of emissions:", sum(e$emissions), "\n") } return(e) }
personDens <- function(thetas, yRange = NULL, dim.lab.cex = 0.6, dim.lab.side = 3, dim.lab.adj = 0.5,dim.names = NULL,dim.color = "black",person.points = NULL, person.range = NULL, p.point.col = "black", p.range.col = "gray70",oma = c(0, 5, 0, 5), axis.logits = "Logits",show.axis.logits = TRUE, axis.persons = "Respondents",...) { densExt <- function(densElem) { xDim <- densElem["y"][[1]] yDim <- densElem["x"][[1]] xDim <- xDim/max(xDim) densInfo <- cbind(xDim, yDim) return(densInfo) } theta.dens <- function(thetas) { densList <- apply(thetas, 2, density, na.rm = TRUE) distInfo <- lapply(densList, densExt) return(distInfo) } person.plot <- function(distInfo, yRange, xRange, p.points, p.range, p.col, r.col, dim.lab.side, dim.lab.cex, dim.lab.adj, p.cex.lab, p.font.lab, p.lwd, cex) { par(mar = c(op$mar[1], 0.2, op$mar[3], 0.1)) plot(distInfo, ylim = yRange, xlim = xRange, type = "l", axes = FALSE, ylab = "", xlab = "", cex.lab = p.cex.lab, font.lab = p.font.lab, lwd = p.lwd, col = attr(distInfo, "dim.color")) if(screen() == first) mtext(axis.persons, side = 2, line = 1, cex = 0.8, font = 3) mtext(attr(distInfo, "dim.name"), side = dim.lab.side, line = -1, cex = dim.lab.cex, font = 1, adj = dim.lab.adj) box(bty = "c") draw.range <- function(upper, lower, col) { points( c( 0,0), c(lower, upper), type = "l", lwd = 5, lend=2, col = col) } draw.point <- function(pt, col) { points(0,pt, pch = 15, cex = .6, col = col) } if(!is.null(p.range)) { p.range <- matrix(p.range,nrow = 2) lower <- p.range[1,] upper <- p.range[2,] mapply(draw.range,upper,lower,r.col) } if(!is.null(p.points)) { mapply(draw.point,p.points,p.col) } if (screen() != max(split.screen())) screen(screen() + 1) } thetas <- as.matrix(thetas) nD <- ncol(thetas) if(is.null(yRange)) yRange <- c(min(thetas),max(thetas)) xRange <- c(1, 0) distInfo <- theta.dens(thetas) if (is.null(dim.names)) { if (!is.null(names(thetas))) { dim.names <- names(thetas) } else dim.names <- c(paste("Dim", seq(1:nD), sep = "")) } if (ncol(thetas) > 1 & length(dim.color) == 1) { dim.color <- rep(dim.color, ncol(thetas)) } for (i in 1:nD) { attr(distInfo[[i]], "dim.name") <- dim.names[i] attr(distInfo[[i]], "dim.color") <- dim.color[i] } old.screens <- split.screen() split.screen(c(1, nD)) first <- screen() op <- par("mar","oma") par(oma = oma) lapply(distInfo, FUN = person.plot, yRange = yRange, xRange = xRange, p.points = person.points, p.range = person.range, p.col = p.point.col, r.col = p.range.col, dim.lab.cex = dim.lab.cex, dim.lab.side = dim.lab.side, dim.lab.adj = dim.lab.adj, p.cex.lab = 1.3, p.font.lab = 3, p.lwd = 2, cex = 1.5) if (show.axis.logits) { axis(4, las = 1, cex.axis = 0.7, font.axis = 2) } mtext(axis.logits, side = 4, line = 1.5, cex = 0.8, font = 3) curr.screens <- split.screen() new.screens <- curr.screens[!(curr.screens %in% old.screens) ] close.screen(new.screens) }
format.pval <- function (x, pv=x, digits = max(1, .Options$digits - 2), eps = .Machine$double.eps, na.form = "NA", ...) { if ((has.na <- any(ina <- is.na(pv)))) pv <- pv[!ina] r <- character(length(is0 <- pv < eps)) if (any(!is0)) { rr <- pv <- pv[!is0] expo <- floor(log10(ifelse(pv > 0, pv, 1e-50))) fixp <- expo >= -3 | (expo == -4 & digits > 1) if (any(fixp)) rr[fixp] <- format(round(pv[fixp], digits = digits), ...) if (any(!fixp)) rr[!fixp] <- format(round(pv[!fixp], digits = digits), ...) r[!is0] <- rr } if (any(is0)) { digits <- max(1, digits - 2) if (any(!is0)) { nc <- max(nchar(rr)) if (digits > 1 && digits + 6 > nc) digits <- max(1, nc - 7) sep <- if (digits == 1 && nc <= 6) "" else " " } else sep <- if(digits == 1) "" else " " r[is0] <- paste("<", format(eps, digits = digits, ...), sep = sep) } if (has.na) { rok <- r r <- character(length(ina)) r[!ina] <- rok r[ina] <- na.form } r }
commodity_symbol_fred = setDT(list( symbol = c('brent', 'wtic', 'natgas', 'goldfixam', 'goldfixpm', 'silvfixnn'), name = c('Crude Oil Brent', 'Crude Oil WTI', 'Natural Gas', 'Gold Fixing Price AM', 'Gold Fixing Price PM', 'Silver Fixing Price noon'), symbol_fred = c('DCOILBRENTEU', 'DCOILWTICO', 'DHHNGSP', 'GOLDAMGBD228NLBM', 'GOLDPMGBD228NLBM', 'SLVPRUSD') )) func_commodity_symbol = function() commodity_symbol_fred md_commodity1_fred = function(syb, from, to) { symbol=symbol_fred=.=name=value=NULL syb_fred = commodity_symbol_fred[symbol == tolower(syb), symbol_fred] if (length(syb_fred) == 0) return(NULL) dt_commo_hist = ed_fred( syb_fred, from=from, to=to, print_step=0L )[[1]][,`:=`(symbol_fred = symbol, symbol = NULL, name = NULL )][commodity_symbol_fred, on='symbol_fred', nomatch=0 ][, .(symbol, name, date, value) ][!is.na(value)] setkey(dt_commo_hist, 'date') return(dt_commo_hist) } md_commodity = function(symbol=NULL, date_range = '3y', from=NULL, to=Sys.Date(), print_step=1L, ...) { . = name = NULL syb = tolower(symbol) if (is.null(symbol)) { syb = select_rows_df(commodity_symbol_fred[,.(symbol,name)], column='symbol')[,symbol] } else if (length(symbol)==1) { syb = select_rows_df(commodity_symbol_fred[,.(symbol,name)], column='symbol', input_string=syb)[,symbol] } syb = intersect(syb, commodity_symbol_fred$symbol) ft = get_fromto(date_range, from, to, min_date = "1000-01-01", default_date_range = '3y') from = ft$f to = ft$t dat_list = load_dat_loop(syb, "md_commodity1_fred", args = list(from = from, to = to), print_step=print_step) return(dat_list) }
kql_build <- function(op) { UseMethod("kql_build") } kql_build.tbl_kusto_abstract <- function(op) { q <- flatten_query(op$ops) built_q <- lapply(q, kql_build) kql_query(built_q, src=op$src) } kql_build.op_base_local <- function(op, ...) { ident("df") } kql_build.op_base_remote <- function(op, ...) { ident(op$src$x) } kql_build.op_select <- function(op, ...) { kql_clause_select(translate_kql(!!! op$dots)) } kql_build.op_filter <- function(op, ...) { dots <- mapply(get_expr, op$dots) dot_names <- mapply(all_names, dots) tidyselect::vars_select(op$vars, !!! dot_names) translated_dots <- lapply(dots, translate_kql) built_dots <- lapply(translated_dots, build_kql) clauses <- lapply(built_dots, kql_clause_filter) clauses } kql_build.op_distinct <- function(op, ...) { if (is_empty(op$dots)) cols <- op$vars else cols <- tidyselect::vars_select(op$vars, !!! op$dots) kql_clause_distinct(ident(cols)) } kql_build.op_rename <- function(op, ...) { assigned_exprs <- mapply(get_expr, op$dots) stmts <- lapply(assigned_exprs, translate_kql) pieces <- lapply(seq_along(assigned_exprs), function(i) sprintf("%s = %s", escape(ident(names(assigned_exprs)[i])), stmts[i])) kql(paste0("project-rename ", paste0(pieces, collapse=", "))) } kql_build.op_mutate <- function(op, ...) { assigned_exprs <- mapply(get_expr, op$dots) calls <- unlist(mapply(all_calls, assigned_exprs)) calls_agg <- mapply(is_agg, calls) groups <- build_kql(escape(ident(op$groups), collapse = ", ")) all_vars <- build_kql(escape(ident(op$vars), collapse = ", ")) existing_vars <- build_kql(escape(ident(setdiff(op$vars, names(assigned_exprs))), collapse = ", ")) if (any(calls_agg)) { has_agg <- TRUE if (nchar(groups) == 0) { has_grouping <- FALSE verb <- "summarize " by <- build_kql(" by ", existing_vars) } else { has_grouping <- TRUE verb <- "as tmp | join kind=leftouter (tmp | summarize " by <- build_kql(" by ", groups) on <- build_kql(") on ", groups) project <- build_kql("\n| project ", all_vars) by <- paste0(by, on, project) } } else { has_agg <- FALSE verb <- "extend " by <- "" } stmts <- mapply(translate_kql, assigned_exprs) pieces <- lapply(seq_along(assigned_exprs), function(i) sprintf("%s = %s", escape(ident(names(assigned_exprs)[i])), stmts[i])) kql(paste0(verb, pieces, by)) } kql_build.op_arrange <- function(op, ...) { dots <- mapply(append_asc, op$dots) order_vars <- translate_kql(!!! dots) build_kql("order by ", build_kql(escape(order_vars, collapse = ", "))) } kql_build.op_summarise <- function(op, ...) { assigned_exprs <- mapply(get_expr, op$dots) stmts <- mapply(translate_kql, assigned_exprs) pieces <- lapply(seq_along(assigned_exprs), function(i) sprintf("%s = %s", escape(ident(names(assigned_exprs)[i])), stmts[i])) groups <- build_kql(escape(ident(op_grps(op)), collapse = ", ")) by <- ifelse(nchar(groups) > 0, paste0(" by ", groups), "") .strategy <- if(!is.null(op$args$.strategy)) paste0(" hint.strategy = ", op$args$.strategy) else NULL .shufflekeys <- if(!is.null(op$args$.shufflekeys)) { vars <- sapply(op$args$.shufflekeys, function(x) escape(ident(x))) paste0(" hint.shufflekey = ", vars, collapse="") } else NULL .num_partitions <- if(is.numeric(op$args$.num_partitions)) paste0(" hint.num_partitions = ", op$args$.num_partitions) else if(!is.null(op$args$.num_partitions)) stop(".num_partitions must be a number", .call=FALSE) else NULL smry_str <- paste(c("summarize", .strategy, .shufflekeys, .num_partitions, " "), collapse="") smry_clauses <- paste(pieces, collapse=", ") kql(ident_q(paste0(smry_str, smry_clauses, by))) } kql_build.op_group_by <- function(op, ...) { NULL } kql_build.op_ungroup <- function(op, ...) { NULL } kql_build.op_unnest <- function(op, ...) { if (!is.null(op$args$.id)) { with_itemindex <- build_kql("with_itemindex=", escape(ident(op$args$.id)), " ") } else { with_itemindex <- kql("") } cols_to_unnest <- unname(tidyselect::vars_select(op_vars(op), !!! op$dots)) if (is_empty(cols_to_unnest)) cols_to_unnest <- setdiff(op_vars(op), op_grps(op)) build_kql("mv-expand ", with_itemindex, build_kql(escape(ident(cols_to_unnest), collapse = ", "))) } kql_build.op_head <- function(op, ...) { n <- lapply(op$args$n, translate_kql) build_kql("take ", kql(escape(n, parens = FALSE))) } kql_build.op_join <- function(op, ...) { join_type <- op$args$type by <- op$args$by by_x <- escape(ident(by$x)) if (identical(by$x, by$y)) by_clause <- by_x else { by_y <- escape(ident(by$y)) by_clause <- kql(ident(paste0(mapply(build_by_clause, by$x, by$y), collapse = ", "))) } y_render <- kql(kql_render(kql_build(op$y))) .strategy <- if(!is.null(op$args$.strategy)) paste0(" hint.strategy = ", op$args$.strategy) else NULL .shufflekeys <- if(!is.null(op$args$.shufflekeys)) { vars <- sapply(op$args$.shufflekeys, function(x) escape(ident(x))) paste0(" hint.shufflekey = ", vars, collapse="") } else NULL .num_partitions <- if(is.numeric(op$args$.num_partitions)) paste0(" hint.num_partitions = ", op$args$.num_partitions) else if(!is.null(op$args$.num_partitions)) stop(".num_partitions must be a number", .call=FALSE) else NULL .remote <- if(!is.null(op$args$.remote)) paste0(" hint.remote = ", op$args$.remote, collapse="") else NULL kind <- switch(join_type, inner_join="inner", left_join="leftouter", right_join="rightouter", full_join="fullouter", semi_join="leftsemi", anti_join="leftanti", stop("unknown join type") ) join_str <- ident_q(paste(c("join kind = ", kind, .strategy, .shufflekeys, .num_partitions, .remote, " "), collapse="")) build_kql(join_str, "(", y_render, ") on ", by_clause) } kql_build.op_set_op <- function(op, ...) { op_type <- op$args$type y_render <- kql(kql_render(kql_build(op$y))) switch(op_type, union_all= build_kql("union kind = outer (", y_render, ")"), build_kql("union kind = inner (", y_render, ")") ) } append_asc <- function(dot) { if (inherits(quo_get_expr(dot), "name")) quo_set_expr(dot, call2(expr(asc), quo_get_expr(dot))) else if (inherits(quo_get_expr(dot), "call")) if (quo_get_expr(dot)[[1]] != expr("desc")) quo_set_expr(dot, call2(expr(asc), quo_get_expr(dot))) else dot else dot } flatten_query <- function(op, ops=list()) { if (inherits(op, "tbl_df") || inherits(op, "character")) return(ops) if (inherits(op, "tbl_kusto_abstract")) flat_op <- op$ops else flat_op <- op flat_op$vars <- op_vars(flat_op) flat_op$groups <- op_grps(flat_op) if (is_empty(ops)) new_ops <- list(flat_op) else new_ops <- c(list(flat_op), ops) if (inherits(op, "op_base")) return(new_ops) else flatten_query(flat_op$x, new_ops) } kql_clause_select <- function(select) { stopifnot(is.character(select)) if (is_empty(select)) abort("Query contains no columns") build_kql( "project ", escape(select, collapse = ", ") ) } kql_clause_distinct <- function(distinct) { stopifnot(is.character(distinct)) build_kql( "distinct ", escape(distinct, collapse = ", ") ) } kql_clause_filter <- function(where) { if (!is_empty(where)) { where_paren <- escape(where, parens = FALSE) build_kql("where ", kql_vector(where_paren, collapse = " and ")) } } kql_query <- function(ops, src) { structure( list( ops = ops, src = src ), class = "kql_query" ) } build_by_clause <- function(x, y) { sprintf("$left.%s == $right.%s", escape(ident(x)), escape(ident(y))) }
BANOVA.run <- function (l1_formula = 'NA', l2_formula = 'NA', fit = NULL, model_name = 'NA', dataX = NULL, dataZ = NULL, data = NULL, y_value = NULL, id, iter = 2000, num_trials = 1, contrast = NULL, y_lowerBound = -Inf, y_upperBound = Inf, ... ){ convert.numeric.2.factor <- function(data_vec){ levels <- unique(data_vec) dummy_condition <- (length(levels) == 2) && (0 %in% levels) && (1 %in% levels) effect_condition <- sum(levels) == 0 if (effect_condition || dummy_condition){ lvl <- as.numeric(sort(levels, decreasing = T)) data_vec <- factor(data_vec, levels = lvl, labels = lvl) } else { data_vec <- as.factor(data_vec) } return(data_vec) } check.numeric.variables <- function(y_var){ if (class(y_var) != 'numeric'){ warning("The response variable must be numeric (data class also must be 'numeric')") y_var <- as.numeric(y_var) warning("The response variable has been converted to numeric") } return(y_var) } if (!is.null(data)){ if (!is.data.frame(data)) stop("data needs to be a data frame!") } if (l1_formula == 'NA'){ stop("Formula in level 1 is missing or not correct!") }else{ single_level = F if (is(fit, "BANOVA.build")) model_name = fit$model_name if (model_name == 'Multinomial'){ if (is.null(y_value)) stop("y_value (the dependent variable) must be provided!") y <- y_value mf1 <- model.frame(formula = l1_formula, data = dataX[[1]]) }else{ mf1 <- model.frame(formula = l1_formula, data = data) y <- model.response(mf1) } if (model_name %in% c('Normal', 'T')){ y <- check.numeric.variables(y) }else if (model_name %in% c('Poisson', 'Binomial', 'Bernoulli', 'Multinomial', 'ordMultinomial')){ if (class(y) != 'integer'){ warning("The response variable must be integers (data class also must be 'integer')..") y <- as.integer(as.character(y)) warning("The response variable has been converted to integers..") } if (model_name == 'ordMultinomial'){ DV_sort <- sort(unique(y)) n_categories <- length(DV_sort) if (n_categories < 3) stop('The number of categories must be greater than 2!') if (DV_sort[1] != 1 || DV_sort[n_categories] != n_categories) stop('Check if response variable follows categorical distribution!') n.cut <- n_categories - 1 } if (model_name == 'Multinomial'){ DV_sort <- sort(unique(y)) n_categories <- length(DV_sort) if (n_categories < 3) stop('The number of categories must be greater than 2!') if (DV_sort[1] != 1 || DV_sort[n_categories] != n_categories) stop('Check if response variable follows categorical distribution!') } } else if (model_name == "multiNormal") { if (is.null(ncol(y))) stop('The number of dependent variables must be greater than 1!') if (is.null(colnames(y))) stop(paste0('Please, specify the names of dependent variables!\n', 'See Examples in help(BANOVA.run) for the expected specification of the dependent variables.')) num_dv <- ncol(y) for (l in 1:num_dv){ y[,l] <- check.numeric.variables(y[,l]) } } else if (model_name == 'truncNormal'){ y <- check.numeric.variables(y) if (y_lowerBound > y_upperBound){ stop(paste0("The lower bound should be below upper bound!\n", "Current lower bound of y is ", y_lowerBound, ", and upper bound is ", y_upperBound)) } if (y_lowerBound == y_upperBound){ stop(paste0("The lower bound should be different from upper bound!\n", "Current lower bound of y is ", y_lowerBound, ", and upper bound is ", y_upperBound)) } no_lower_bound = 0 no_upper_bound = 0 if (y_lowerBound == -Inf) no_lower_bound = 1 if (y_upperBound == Inf) no_upper_bound = 1 if (no_lower_bound == 1 & no_upper_bound == 1){ stop(paste0("If the dependent variable is unbounded, please use Normal distributoin!\n", "Current lower bound of y is ", y_lowerBound, ", and upper bound is ", y_upperBound)) } min_y <- min(y) max_y <- max(y) if (min_y < y_lowerBound){ stop(paste0("At least one value of the dependent variable exceeds the specified lower bound!\n", "The lowest value of y is ", min_y, ", while specified lower bound is ", y_lowerBound)) } if (max_y > y_upperBound){ stop(paste0("At least one value of the dependent variable exceeds the specified upper bound!\n", "The highest value of y is ", max_y, ", while specified lower bound is ", y_upperBound)) } three_sd_y <- 3*sd(y) if(y_lowerBound!=(-Inf) && y_lowerBound<(min_y-three_sd_y)){ warning("The specified lower bound is more than three standard deviations away from the lowest value of y.\nThis may cause problems with initialization of starting values in the MCMC chains.") } if(y_upperBound!=(Inf) && y_upperBound>(max_y+three_sd_y)){ warning("The specified upper bound is more than three standard deviations away from the highest value of y.\nThis may cause problems with initialization of starting values in the MCMC chains.") } } else{ stop(model_name, " is not supported currently!") } } if (is.character(id) && length(id) == 1){ if (id %in% colnames(data)) old_id = data[, id] else stop(id, ' is not found in the input data, please assign values directly!') }else{ if (model_name != 'Multinomial') { stop('id ambiguous!') }else{ old_id = id } } if (l2_formula == 'NA'){ single_level = T if (is(fit, "BANOVA.build")){ fit_single_level = fit$single_level if (single_level != fit_single_level) stop("Please check the single level settings(T/F)!") } if (model_name == "Multinomial"){ for (i in 1:length(dataX)) for (j in 1:ncol(dataX[[i]])){ if(class(dataX[[i]][,j]) != 'factor' && class(dataX[[i]][,j]) != 'numeric' && class(dataX[[i]][,j]) != 'integer') stop("data class must be 'factor', 'numeric' or 'integer'") if ((class(dataX[[i]][,j]) == 'numeric' | class(dataX[[i]][,j]) == 'integer') & length(unique(dataX[[i]][,j])) <= 3){ dataX[[i]][,j] <- convert.numeric.2.factor(dataX[[i]][,j]) warning("Within-subject variables(levels <= 3) have been converted to factors") } } n <- length(dataX) uni_id <- unique(old_id) num_id <- length(uni_id) new_id <- rep(0, length(old_id)) for (i in 1:length(old_id)) new_id[i] <- which(uni_id == old_id[i]) id <- new_id dMatrice <- multi.design.matrix(l1_formula, l2_formula, dataX = dataX, id = id) X_new <- array(0, dim = c(n, n_categories, ncol(dMatrice$X_full[[1]]))) for (i in 1:n_categories){ X_new[,i,] <- dMatrice$X_full[[i]] } pooled_data_dict <- list(N = dim(X_new)[1], J = dim(X_new)[3], n_cat = dim(X_new)[2], X = X_new, y = y) if (!is(fit, "BANOVA.build")){ fit <- get_BANOVA_stan_model(model_name, single_level) }else{ model_name <- fit$model_name single_level <- fit$single_level } stan.fit <- rstan::sampling(fit$stanmodel, data = pooled_data_dict, iter=iter, ...) fit_beta <- rstan::extract(stan.fit, permuted = T) R2 = NULL tau_ySq = NULL beta1_dim <- dim(fit_beta$beta1) beta1_names <- c() for (i in 1:beta1_dim[2]) beta1_names <- c(beta1_names, paste("beta1_",i, sep = "")) samples_l1_param <- array(0, dim = c(beta1_dim[1], beta1_dim[2]), dimnames = list(NULL, beta1_names)) for (i in 1:beta1_dim[2]) samples_l1_param[, i] <- fit_beta$beta1[, i] samples_l2_sigma_param = NA samples_cutp_param = array(dim = 0) cat('Constructing ANOVA/ANCOVA tables...\n') dMatrice$Z <- array(1, dim = c(1,1), dimnames = list(NULL, ' ')) attr(dMatrice$Z, 'assign') <- 0 attr(dMatrice$Z, 'varNames') <- " " samples_l2_param <- NULL anova.table <- list() for (i in 1:n_categories) anova.table[[i]] <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X_full[[i]], samples_l1_param, error = pi^2/6, multi = T, n_cat = n_categories, choice = i-1, y_val = y_value, model = model_name) coef.tables <- table.coefficients(samples_l1_param, beta1_names, colnames(dMatrice$Z), colnames(dMatrice$X_full[[1]]), attr(dMatrice$Z, 'assign') + 1, attr(dMatrice$X_full[[1]], 'assign'), samples_cutp_param ) pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$Z, 'varNames'), l2_names = attr(dMatrice$X_full[[1]], 'varNames')) conv <- conv.geweke.heidel(samples_l1_param, colnames(dMatrice$Z), colnames(dMatrice$X_full[[1]])) }else{ data_colnames <- colnames(data) var_names <- colnames(mf1)[-1] for (i in 1:ncol(data)){ if (data_colnames[i] %in% var_names){ if(class(data[,i]) != 'factor' && class(data[,i]) != 'numeric' && class(data[,i]) != 'integer') stop("data class must be 'factor', 'numeric' or 'integer'") if ((class(data[,i]) == 'numeric' | class(data[,i]) == 'integer') & length(unique(data[,i])) <= 3){ data[,i] <- convert.numeric.2.factor(data[,i]) warning("Variables(levels <= 3) have been converted to factors") } } } n <- nrow(data) uni_id <- unique(old_id) num_id <- length(uni_id) new_id <- rep(0, length(old_id)) for (i in 1:length(old_id)) new_id[i] <- which(uni_id == old_id[i]) id <- new_id dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id, contrast = contrast) if (model_name == "Binomial"){ trials <- num_trials if (length(trials) == 1) trials <- rep(num_trials, n) if (length(trials) != n) stop('The length of num_trials must be equal to the number of observations!') if (sum(y > num_trials, na.rm = T) > 0) stop('The number of trials is less than observations!') pooled_data_dict <- list(N = nrow(dMatrice$X), J = ncol(dMatrice$X), trials = trials, X = dMatrice$X, y = y) }else if (model_name == "ordMultinomial"){ pooled_data_dict <- list(cat = n.cut + 1, N = nrow(dMatrice$X), J = ncol(dMatrice$X), X = dMatrice$X, Z = dMatrice$Z, y = y) }else if (model_name == 'multiNormal'){ pooled_data_dict <- list(L = num_dv, N = nrow(dMatrice$X), J = ncol(dMatrice$X), X = dMatrice$X, y = y) }else if (model_name == 'truncNormal'){ pooled_data_dict <- list(L = y_lowerBound, U = y_upperBound, no_lower_bound = no_lower_bound, no_upper_bound = no_upper_bound, N = nrow(dMatrice$X), J = ncol(dMatrice$X), X = dMatrice$X, y = y) }else{ pooled_data_dict <- list(N = nrow(dMatrice$X), J = ncol(dMatrice$X), X = dMatrice$X, y = y) } if (!is(fit, "BANOVA.build")){ fit <- get_BANOVA_stan_model(model_name, single_level) }else{ model_name <- fit$model_name single_level <- fit$single_level } stan.fit <- rstan::sampling(fit$stanmodel, data = pooled_data_dict, iter=iter, ...) fit_beta <- rstan::extract(stan.fit, permuted = T) if (model_name != "multiNormal"){ R2 = NULL if (!is.null(fit_beta$r_2)){ R2 <- mean(fit_beta$r_2) R2 <- round(R2, 4) } tau_ySq = NULL beta1_dim <- dim(fit_beta$beta1) beta1_names <- c() for (i in 1:beta1_dim[2]) beta1_names <- c(beta1_names, paste("beta1_",i, sep = "")) samples_l1_param <- array(0, dim = c(beta1_dim[1], beta1_dim[2]), dimnames = list(NULL, beta1_names)) for (i in 1:beta1_dim[2]) samples_l1_param[, i] <- fit_beta$beta1[, i] samples_l2_sigma_param = NA if (model_name == 'Poisson'){ samples_l2_sigma_param <- 0 } samples_cutp_param = array(dim = 0) if (model_name == 'ordMultinomial'){ c_dim <- dim(fit_beta$c_trans) c_names <- c() for (i in 2:c_dim[2]) c_names <- c(c_names, paste("c",i, sep = "_")) samples_cutp_param <- array(0, dim = c(c_dim[1], c_dim[2] - 1), dimnames = list(NULL, c_names)) for (i in 2:c_dim[2]) samples_cutp_param[, i-1] <- fit_beta$c_trans[,i] } cat('Constructing ANOVA/ANCOVA tables...\n') dMatrice$Z <- array(1, dim = c(1,1), dimnames = list(NULL, ' ')) attr(dMatrice$Z, 'assign') <- 0 attr(dMatrice$Z, 'varNames') <- " " samples_l2_param <- NULL if (model_name == 'Poisson'){ anova.table <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X, samples_l1_param, y_val = array(y, dim = c(length(y), 1)), error = pi^2/3, model = model_name) }else if (model_name %in% c('Normal', 'T', 'truncNormal')){ anova.table <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X, samples_l1_param, array(y, dim = c(length(y), 1)), model = model_name) if (!is.null(fit_beta$tau_ySq)){ tau_ySq <- mean(fit_beta$tau_ySq) } }else if (model_name == 'Bernoulli' || model_name == 'Binomial'){ anova.table <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X, samples_l1_param, y_val = array(y, dim = c(length(y), 1)), error = pi^2/3, num_trials = num_trials, model = model_name) tau_ySq = pi^2/3 }else if (model_name == 'ordMultinomial'){ anova.table <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X, samples_l1_param, y_val = array(y, dim = c(length(y), 1)), error = pi^2/6, model = model_name) tau_ySq = pi^2/6 } coef.tables <- table.coefficients(samples_l1_param, beta1_names, colnames(dMatrice$Z), colnames(dMatrice$X), attr(dMatrice$Z, 'assign') + 1, attr(dMatrice$X, 'assign') + 1, samples_cutp_param ) pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$Z, 'varNames'), l2_names = attr(dMatrice$X, 'varNames')) conv <- conv.geweke.heidel(samples_l1_param, colnames(dMatrice$Z), colnames(dMatrice$X)) mf2 <- NULL class(conv) <- 'conv.diag' cat('Done.\n') } else { dMatrice$Z <- array(1, dim = c(1,1), dimnames = list(NULL, ' ')) attr(dMatrice$Z, 'assign') <- 0 attr(dMatrice$Z, 'varNames') <- " " mlvResult <- results.BANOVA.mlvNormal(fit_beta, dep_var_names = colnames(y), dMatrice, single_level) mf2 = NULL } } }else{ if (model_name == "Multinomial"){ if (is.null(dataX) || is.null(dataZ)) stop("dataX or dataZ must be specified!") mf1 <- model.frame(formula = l1_formula, data = dataX[[1]]) mf2 <- model.frame(formula = l2_formula, data = dataZ) for (i in 1:ncol(dataZ)){ if(class(dataZ[,i]) != 'factor' && class(dataZ[,i]) != 'numeric' && class(dataZ[,i]) != 'integer') stop("data class must be 'factor', 'numeric' or 'integer'") if ((class(dataZ[,i]) == 'numeric' | class(dataZ[,i]) == 'integer') & length(unique(dataZ[,i])) <= 3){ dataZ[,i] <- convert.numeric.2.factor(dataZ[,i]) warning("Between-subject variables(levels <= 3) have been converted to factors") } } for (i in 1:length(dataX)) for (j in 1:ncol(dataX[[i]])){ if(class(dataX[[i]][,j]) != 'factor' && class(dataX[[i]][,j]) != 'numeric' && class(dataX[[i]][,j]) != 'integer') stop("data class must be 'factor', 'numeric' or 'integer'") if ((class(dataX[[i]][,j]) == 'numeric' | class(dataX[[i]][,j]) == 'integer') & length(unique(dataX[[i]][,j])) <= 3){ dataX[[i]][,j] <- convert.numeric.2.factor(dataX[[i]][,j]) warning("Within-subject variables(levels <= 3) have been converted to factors") } } n <- nrow(dataZ) uni_id <- unique(old_id) num_id <- length(uni_id) new_id <- rep(0, length(old_id)) for (i in 1:length(old_id)) new_id[i] <- which(uni_id == old_id[i]) id <- new_id dMatrice <- multi.design.matrix(l1_formula, l2_formula, dataX = dataX, dataZ = dataZ, id = id) X_new <- array(0, dim = c(n, n_categories, ncol(dMatrice$X_full[[1]]))) for (i in 1:n_categories){ X_new[,i,] <- dMatrice$X_full[[i]] } pooled_data_dict <- list(N = dim(X_new)[1], J = dim(X_new)[3], n_cat = dim(X_new)[2], M = nrow(dMatrice$Z), K = ncol(dMatrice$Z), X = X_new, Z = dMatrice$Z, id = id, y = y) }else{ if (is.null(data)) stop("data must be specified!") mf2 <- model.frame(formula = l2_formula, data = data) data_colnames <- colnames(data) var_names <- c(colnames(mf1), colnames(mf2))[-1] for (i in 1:ncol(data)){ if (data_colnames[i] %in% var_names){ if(class(data[,i]) != 'factor' && class(data[,i]) != 'numeric' && class(data[,i]) != 'integer') stop("data class must be 'factor', 'numeric' or 'integer'") if ((class(data[,i]) == 'numeric' | class(data[,i]) == 'integer') & length(unique(data[,i])) <= 3){ data[,i] <- convert.numeric.2.factor(data[,i]) warning("Variables(levels <= 3) have been converted to factors") } } } n <- nrow(data) uni_id <- unique(old_id) num_id <- length(uni_id) new_id <- rep(0, length(old_id)) for (i in 1:length(old_id)) new_id[i] <- which(uni_id == old_id[i]) id <- new_id dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id, contrast = contrast) if (model_name == "Binomial"){ trials <- num_trials if (length(trials) == 1) trials <- rep(num_trials, n) if (length(trials) != n) stop('The length of num_trials must be equal to the number of observations!') if (sum(y > num_trials, na.rm = T) > 0) stop('The number of trials is less than observations!') pooled_data_dict <- list(N = nrow(dMatrice$X), J = ncol(dMatrice$X), M = nrow(dMatrice$Z), K = ncol(dMatrice$Z), trials = trials, X = dMatrice$X, Z = dMatrice$Z, id = id, y = y) }else if(model_name == 'ordMultinomial'){ pooled_data_dict <- list(cat = n.cut + 1, N = nrow(dMatrice$X), J = ncol(dMatrice$X), M = nrow(dMatrice$Z), K = ncol(dMatrice$Z), X = dMatrice$X, Z = dMatrice$Z, id = id, y = y) }else if(model_name == 'multiNormal'){ pooled_data_dict <- list(L = num_dv, N = nrow(dMatrice$X), J = ncol(dMatrice$X), M = nrow(dMatrice$Z), K = ncol(dMatrice$Z), X = dMatrice$X, Z = dMatrice$Z, id = id, y = y) }else if (model_name == 'truncNormal'){ pooled_data_dict <- list(L = y_lowerBound, U = y_upperBound, no_lower_bound = no_lower_bound, no_upper_bound = no_upper_bound, N = nrow(dMatrice$X), J = ncol(dMatrice$X), M = nrow(dMatrice$Z), K = ncol(dMatrice$Z), X = dMatrice$X, Z = dMatrice$Z, id = id, y = y) }else{ pooled_data_dict <- list(N = nrow(dMatrice$X), J = ncol(dMatrice$X), M = nrow(dMatrice$Z), K = ncol(dMatrice$Z), X = dMatrice$X, Z = dMatrice$Z, id = id, y = y) } } if (!is(fit, "BANOVA.build")){ fit <- get_BANOVA_stan_model(model_name, single_level) }else{ model_name <- fit$model_name single_level <- fit$single_level } stan.fit <- rstan::sampling(fit$stanmodel, data = pooled_data_dict, iter=iter, verbose=TRUE, ...) fit_beta <- rstan::extract(stan.fit, permuted = T) if (model_name != "multiNormal"){ R2 = NULL if (!is.null(fit_beta$r_2)){ R2 <- mean(fit_beta$r_2) R2 <- round(R2, 4) } tau_ySq = NULL if (model_name %in% c('Normal', 'T', 'truncNormal')){ if (!is.null(fit_beta$tau_ySq)){ tau_ySq <- mean(fit_beta$tau_ySq) } }else if (model_name == 'Bernoulli' || model_name == 'Binomial'){ tau_ySq = pi^2/3 }else if (model_name == 'ordMultinomial' || model_name == 'Multinomial'){ tau_ySq = pi^2/6 }else{ tau_ySq = 0 } beta1_dim <- dim(fit_beta$beta1) beta2_dim <- dim(fit_beta$beta2) beta1_names <- c() for (i in 1:beta1_dim[2]) for (j in 1:beta1_dim[3]) beta1_names <- c(beta1_names, paste("beta1_",i,"_",j, sep = "")) samples_l1_param <- array(0, dim = c(beta1_dim[1], beta1_dim[2]*beta1_dim[3]), dimnames = list(NULL, beta1_names)) for (i in 1:beta1_dim[2]) for (j in 1:beta1_dim[3]) samples_l1_param[, (i-1) * beta1_dim[3] + j] <- fit_beta$beta1[, i, j] beta2_names <- c() for (i in 1:beta2_dim[3]) for (j in 1:beta2_dim[2]) beta2_names <- c(beta2_names, paste("beta2_",i,"_",j, sep = "")) samples_l2_param <- array(0, dim = c(beta2_dim[1], beta2_dim[2]*beta2_dim[3]), dimnames = list(NULL, beta2_names)) for (i in 1:beta2_dim[3]) for (j in 1:beta2_dim[2]) samples_l2_param[, (i-1) * beta2_dim[2] + j] <- fit_beta$beta2[, j, i] samples_l2_sigma_param = NA if (model_name == 'Poisson'){ tau_beta1Sq_dim <- dim(fit_beta$tau_beta1Sq) tau_beta1Sq_names <- c() for (i in 1:tau_beta1Sq_dim[2]) tau_beta1Sq_names <- c(tau_beta1Sq_names, paste("tau_beta1Sq",i, sep = "_")) samples_l2_sigma_param <- array(0, dim = c(tau_beta1Sq_dim[1], tau_beta1Sq_dim[2]), dimnames = list(NULL, tau_beta1Sq_names)) for (i in 1:tau_beta1Sq_dim[2]) samples_l2_sigma_param[, i] <- sqrt(fit_beta$tau_beta1Sq[,i]) } samples_cutp_param = array(dim = 0) if (model_name == 'ordMultinomial'){ c_dim <- dim(fit_beta$c_trans) c_names <- c() for (i in 2:c_dim[2]) c_names <- c(c_names, paste("c",i, sep = "_")) samples_cutp_param <- array(0, dim = c(c_dim[1], c_dim[2] - 1), dimnames = list(NULL, c_names)) for (i in 2:c_dim[2]) samples_cutp_param[, i-1] <- fit_beta$c_trans[,i] } cat('Constructing ANOVA/ANCOVA tables...\n') if (model_name == 'Multinomial'){ anova.table <- table.ANCOVA(samples_l1_param, dMatrice$X_full[[1]], dMatrice$Z, samples_l2_param, l1_error = tau_ySq) coef.tables <- table.coefficients(samples_l2_param, beta2_names, colnames(dMatrice$X_full[[1]]), colnames(dMatrice$Z), attr(dMatrice$X_full[[1]], 'assign'), attr(dMatrice$Z, 'assign') + 1, samples_cutp_param) pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$X_full[[1]], 'varNames'), l2_names = attr(dMatrice$Z, 'varNames')) conv <- conv.geweke.heidel(samples_l2_param, colnames(dMatrice$X_full[[1]]), colnames(dMatrice$Z)) }else{ anova.table <- table.ANCOVA(samples_l1_param, dMatrice$X, dMatrice$Z, samples_l2_param, l1_error = tau_ySq) coef.tables <- table.coefficients(samples_l2_param, beta2_names, colnames(dMatrice$X), colnames(dMatrice$Z), attr(dMatrice$X, 'assign') + 1, attr(dMatrice$Z, 'assign') + 1, samples_cutp_param) pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$X, 'varNames'), l2_names = attr(dMatrice$Z, 'varNames')) conv <- conv.geweke.heidel(samples_l2_param, colnames(dMatrice$X), colnames(dMatrice$Z)) } class(conv) <- 'conv.diag' cat('Done.\n') } else { mlvResult <- results.BANOVA.mlvNormal(fit_beta, dep_var_names = colnames(y), dMatrice) } } if (model_name == 'Multinomial'){ sol <- list(anova.table = anova.table, coef.tables = coef.tables, pvalue.table = pvalue.table, conv = conv, dMatrice = dMatrice, samples_l1_param = samples_l1_param, samples_l2_param = samples_l2_param, samples_l2_sigma_param = samples_l2_sigma_param, samples_cutp_param = samples_cutp_param, data = data, dataX = dataX, dataZ = dataZ, mf1 = mf1, mf2 = mf2, n_categories = n_categories, model_code = fit$stanmodel@model_code, single_level = single_level, stan_fit = stan.fit, R2 = R2, tau_ySq = tau_ySq, model_name = paste('BANOVA', model_name, sep = "."), contrast = contrast, new_id = new_id, old_id = old_id) }else if (model_name == "multiNormal"){ sol <- list(anova.table = mlvResult$combined.anova, coef.tables = mlvResult$combined.coef, pvalue.table = mlvResult$combined.pvalue, conv = mlvResult$combined.conv, correlation.matrix = mlvResult$correlation.matrix, covariance.matrix = mlvResult$covariance.matrix, test.standard.deviations.of.dep.var = mlvResult$dep_var_sd, test.residual.correlation = mlvResult$dep_var_corr, dMatrice = dMatrice, samples_l1_param = mlvResult$combined.samples.l1, samples_l2_param = mlvResult$combined.samples.l2, samples_l2_sigma_param = NA, samples_cutp_param = array(dim = 0), data = data, num_trials = num_trials, mf1 = mf1, mf2 = mf2, model_code = fit$stanmodel@model_code, single_level = single_level, stan_fit = stan.fit, R2 = mlvResult$R2, tau_ySq = mlvResult$tau_ySq, model_name = paste('BANOVA', model_name, sep = "."), contrast = contrast, new_id = new_id, old_id = old_id, samples_l1.list = mlvResult$samples_l1.list, samples_l2.list = mlvResult$samples_l2.list, anova.tables.list = mlvResult$anova.tables.list, coef.tables.list = mlvResult$coef.tables.list, pvalue.tables.list = mlvResult$pvalue.tables.list, conv.list = mlvResult$conv.list, num_depenent_variables = mlvResult$num_depenent_variables, names_of_dependent_variables = mlvResult$names_of_dependent_variables) } else { sol <- list(anova.table = anova.table, coef.tables = coef.tables, pvalue.table = pvalue.table, conv = conv, dMatrice = dMatrice, samples_l1_param = samples_l1_param, samples_l2_param = samples_l2_param, samples_l2_sigma_param = samples_l2_sigma_param, samples_cutp_param = samples_cutp_param, data = data, num_trials = num_trials, mf1 = mf1, mf2 = mf2, model_code = fit$stanmodel@model_code, single_level = single_level, stan_fit = stan.fit, R2 = R2, tau_ySq = tau_ySq, model_name = paste('BANOVA', model_name, sep = "."), contrast = contrast, new_id = new_id, old_id = old_id) } sol$call <- match.call() class(sol) <- "BANOVA" sol } get_BANOVA_stan_model <- function(model, single_level) { if (model == 'NA') stop("a model name must be provided!") if (single_level) name <- paste('single', 'BANOVA.RData', sep = '_') else name <- 'BANOVA.RData' stanmodel <- tryCatch({ model_file <- system.file('libs', Sys.getenv('R_ARCH'), name, package = 'BANOVA', mustWork = TRUE) load(model_file) if(single_level) obj <- paste(model, 'Normal_stanmodel_1', sep = '_') else obj <- paste(model, 'Normal_stanmodel', sep = '_') stanm <- eval(parse(text = obj)) stanm }, error = function(cond) { compile_BANOVA_stan_model(model, single_level) }) return(stanmodel) } compile_BANOVA_stan_model <- function(model, single_level) { if (single_level) name <- paste('stan/single_', model, '.stan', sep = '') else name <- paste('stan/',model, '_Normal.stan', sep = '') model <- BANOVA.model(model, single_level) stanmodel <- BANOVA.build(model) return(stanmodel) }
removeRedundant <- function(E){ m <- as.mip(E) A <- -getA(m$E) b <- getb(m$E) keep <- rep(TRUE, nrow(A)) names(keep) <- rownames(A) sapply(seq_len(nrow(A)),function(r){ m1 <- m m1$E <- m1$E[keep,] m1$objfn <- A[r,] lps <- as.lp.mip(m1) statuscode <- solve(lps) o <- -1*get.objective(lps) keep[r] <<- (b[r] <= o) c(o=o, t=b[r]) }) structure(E[names(keep)[keep],], removed=E[names(keep)[!keep],]) }
library("RUnit") library("gdata") intUnk <- 9999 xInt <- as.integer(c(NA, 1:2, NA, 5, 6, 7, 8, 9)) xIntUnk <- as.integer(c(intUnk, 1:2, intUnk, 5, 6, 7, 8, 9)) xIntUnkTest <- xIntUnk %in% intUnk numUnk <- 0 xNum <- c(9999, NA, 1.5, NA, 5, 6, 7, 8, 9) xNumUnk <- c(9999, 0, 1.5, 0, 5, 6, 7, 8, 9) xNumUnkTest <- xNumUnk %in% numUnk chaUnk <- "notAvail" chaUnk1 <- "-" xCha <- c("A", "B", NA, "C", NA, "-", "7", "8", "9") xChaUnk <- c("A", "B", chaUnk, "C", chaUnk, "-", "7", "8", "9") xChaUnk1 <- c("A", "B", chaUnk1, "C", chaUnk1, "-", "7", "8", "9") xChaUnkTest <- xChaUnk %in% chaUnk xChaUnk1Test <- xChaUnk %in% chaUnk1 facUnk <- "notAvail" facUnk1 <- "NA" xFac <- factor(c("A", "0", 0, "NA", "NA", intUnk, numUnk, "-", NA)) xFacUnk <- factor(c("A", "0", 0, "NA", "NA", intUnk, numUnk, "-", facUnk)) xFacUnk1 <- factor(c("A", "0", 0, "NA", "NA", intUnk, numUnk, "-", facUnk1)) xFacUnkTest <- c(0, 0, 0, 0, 0, 0, 0, 0, 1) xFacUnkTest <- as.logical(xFacUnkTest) xFacUnk1Test <- c(0, 0, 0, 1, 1, 0, 0, 0, 1) xFacUnk1Test <- as.logical(xFacUnk1Test) xFac1 <- factor(c("A", "0", 0, NA, NA, intUnk, numUnk, "-", NA)) facLev <- "A" xFacUnkLev <- factor(c("A", "0", 0, "NA", "NA", intUnk, numUnk, "-", "A")) xFacUnkLevTest <- c(1, 0, 0, 0, 0, 0, 0, 0, 1) xFacUnkLevTest <- as.logical(xFacUnkLevTest) dateUnk <- as.Date("2006-08-14") tmp <- as.Date("2006-08-15") xDate <- c(tmp, NA) xDateUnk <- c(tmp, dateUnk) xDateTest <- c(FALSE, TRUE) xDate1Unk <- c(tmp, dateUnk, NA) xDate1Test <- c(FALSE, TRUE, FALSE) POSIXltUnk <- strptime("2006-08-14", format="%Y-%m-%d") tmp <- strptime("2006-08-15", format="%Y-%m-%d") xPOSIXlt <- c(tmp, NA) xPOSIXltUnk <- c(tmp, POSIXltUnk) xPOSIXltTest <- c(FALSE, TRUE) xPOSIXlt1Unk <- c(tmp, POSIXltUnk, NA) xPOSIXlt1Test <- c(FALSE, TRUE, FALSE) POSIXctUnk <- as.POSIXct(strptime("2006-08-14 01:01:01", format="%Y-%m-%d %H:%M:%S")) tmp <- as.POSIXct(strptime("2006-08-15 01:01:01", format="%Y-%m-%d %H:%M:%S")) xPOSIXct <- c(tmp, NA) xPOSIXctUnk <- c(tmp, POSIXctUnk) xPOSIXctTest <- xPOSIXltTest xPOSIXct1Unk <- c(tmp, POSIXctUnk, NA) xPOSIXct1Test <- xPOSIXlt1Test xList <- list(xInt, xCha, xNum, xFac) xListN <- list(int=xInt, cha=xCha, num=xNum, fac=xFac) xListUnk <- list(xIntUnk, xChaUnk, xNumUnk, xFacUnk) xListUnkTest <- list(xIntUnkTest, xChaUnkTest, xNumUnkTest, xFacUnkTest) xListNUnk <- list(int=xIntUnk, cha=xChaUnk, num=xNumUnk, fac=xFacUnk) xListNUnkTest <- list(int=xIntUnkTest, cha=xChaUnkTest, num=xNumUnkTest, fac=xFacUnkTest) xDF <- as.data.frame(xListN) xDF$cha <- as.character(xDF$cha) xDFUnk <- as.data.frame(xListNUnk) xDFUnk$cha <- as.character(xDFUnk$cha) xDFUnkTest <- as.data.frame(xListNUnkTest) unkC <- c(intUnk, chaUnk, numUnk, facUnk) unkL <- list(intUnk, chaUnk, numUnk, facUnk) unkLN <- list(num=numUnk, cha=chaUnk, fac=facUnk, int=intUnk) unkLMN <- list(cha=chaUnk, int=intUnk, num=c(intUnk, numUnk), fac=c(chaUnk1, facUnk)) xListMNUnkF <- list(int=as.integer(c(9999, 1, 2, 9999, 5, 6, 7, 8, 9)), cha=c("A", "B", "notAvail", "C", "notAvail", "-", "7", "8", "9"), num=c(9999, 0, 1.5, 0, 5, 6, 7, 8, 9), fac=factor(c("A", "0", "0", "NA", "NA", 9999, "0", "-", "notAvail"))) xListMNUnkFTest <- list(int=c(1, 0, 0, 1, 0, 0, 0, 0, 0), cha=c(0, 0, 1, 0, 1, 0, 0, 0, 0), num=c(1, 1, 0, 1, 0, 0, 0, 0, 0), fac=c(0, 0, 0, 0, 0, 0, 0, 1, 1)) xListMNUnkFTest <- lapply(xListMNUnkFTest, as.logical) xListMNF <- list(int=as.integer(c(NA, 1, 2, NA, 5, 6, 7, 8, 9)), cha=c("A", "B", NA, "C", NA, "-", "7", "8", "9"), num=c(NA, NA, 1.5, NA, 5, 6, 7, 8, 9), fac=factor(c("A", "0", "0", "NA", "NA", "9999", "0", NA, NA))) xDFMUnkF <- as.data.frame(xListMNUnkF) xDFMUnkF$cha <- as.character(xDFMUnkF$cha) xDFMUnkFTest <- as.data.frame(xListMNUnkFTest) xDFMF <- as.data.frame(xListMNF) xDFMF$cha <- as.character(xDFMF$cha) unk1 <- 555555 xListUnk1 <- list(as.integer(c(unk1, 1, 2, unk1, 5, 6, 7, 8, 9)), c("A", "B", unk1, "C", unk1, "-", "7", "8", "9"), c(9999, unk1, 1.5, unk1, 5, 6, 7, 8, 9), factor(c("A", "0", "0", "NA", "NA", "9999", "0", "-", unk1))) xListUnk1Test <- lapply(xListUnk1, function(x) x %in% unk1) xListNUnk1 <- xListUnk1 names(xListNUnk1) <- c("int", "cha", "num", "fac") xDFUnk1 <- as.data.frame(xListNUnk1) xDFUnk1$cha <- as.character(xDFUnk1$cha) xDFUnk1Test <- as.data.frame(xListUnk1Test) names(xDFUnk1Test) <- names(xListNUnk1) unkC2 <- c(0, "notAvail") xListUnk2 <- list(as.integer(c(unkC2[1], 1, 2, unkC2[1], 5, 6, 7, 8, 9)), c("A", "B", unkC2[2], "C", unkC2[2], "-", "7", "8", "9"), c(9999, as.numeric(unkC2[1]), 1.5, as.numeric(unkC2[1]), 5, 6, 7, 8, 9), factor(c("A", "0", "0", "NA", "NA", "9999", "0", "-", unkC2[2]))) xListNUnk2 <- xListUnk2 names(xListNUnk2) <- c("int", "cha", "num", "fac") xDFUnk2 <- as.data.frame(xListNUnk2) xDFUnk2$cha <- as.character(xDFUnk2$cha) xListUnk2Test <- xListUnk2 xListUnk2Test[[1]] <- xListUnk2Test[[1]] %in% unkC2[1] xListUnk2Test[[2]] <- xListUnk2Test[[2]] %in% unkC2[2] xListUnk2Test[[3]] <- xListUnk2Test[[3]] %in% unkC2[1] xListUnk2Test[[4]] <- xListUnk2Test[[4]] %in% unkC2[2] xListNUnk2Test <- xListUnk2Test names(xListNUnk2Test) <- names(xListNUnk2) xDFUnk2Test <- as.data.frame(xListNUnk2Test) unkL2 <- as.list(unkC2) unkLN2 <- unkL2[c(2, 1)] names(unkLN2) <- c("cha", "int") xListUnk2a <- list(as.integer(c(NA, 1, 2, NA, 5, 6, 7, 8, 9)), c("A", "B", unkLN2[[2]], "C", unkLN2[[2]], "-", "7", "8", "9"), c(9999, NA, 1.5, NA, 5, 6, 7, 8, 9), factor(c("A", "0", "0", "NA", "NA", "9999", "0", "-", unkLN2[[2]]))) xListUnk2aTest <- xListUnk2a xListUnk2aTest[[1]] <- xListUnk2aTest[[1]] %in% unkLN2[1] xListUnk2aTest[[2]] <- xListUnk2aTest[[2]] %in% unkLN2[2] xListUnk2aTest[[3]] <- xListUnk2aTest[[3]] %in% unkLN2[1] xListUnk2aTest[[4]] <- xListUnk2aTest[[4]] %in% unkLN2[2] xList2a <- list(xListUnk2a[[1]], c("A", "B", NA, "C", NA, "-", "7", "8", "9"), xListUnk2a[[3]], factor(c("A", NA, NA, "NA", "NA", 9999, NA, "-", NA))) matUnk <- 9999 mat <- matrix(1:25, nrow=5, ncol=5) mat[1, 2] <- NA; mat[1, 4] <- NA; mat[2, 2] <- NA; mat[3, 2] <- NA; mat[3, 5] <- NA; mat[5, 4] <- NA; matUnk1 <- mat matUnk1[1, 2] <- matUnk; matUnk1[1, 4] <- matUnk; matUnk1[2, 2] <- matUnk; matUnk1[3, 2] <- matUnk; matUnk1[3, 5] <- matUnk; matUnk1[5, 4] <- matUnk; matUnkTest <- matUnk1Test <- is.na(mat) matUnk2Test <- matUnkTest | mat == 1 D1 <- "notAvail" unkLND1 <- list(.default=D1) xListUnkD1 <- list(as.integer(c(NA, 1:2, NA, 5, 6, 7, 8, 9)), c("A", "B", D1, "C", D1, "-", "7", "8", "9"), c(9999, NA, 1.5, NA, 5, 6, 7, 8, 9), factor(c("A", "0", 0, "NA", "NA", intUnk, numUnk, "-", D1))) xListUnkD1Test <- lapply(xListUnkD1, function(x) x %in% D1) xListD1 <- xList xListNUnkD1 <- xListUnkD1 xListNUnkD1Test <- xListUnkD1Test names(xListNUnkD1) <- names(xListNUnkD1Test) <- names(xListNUnk1) xListND1 <- xListN DSO2 <- c("notAvail", 5678) unkLNDSO2 <- as.list(DSO2) names(unkLNDSO2) <- c(".default", "someOther") xListUnkDSO2 <- list(as.integer(c(NA, 1:2, NA, 5, 6, 7, 8, 9)), c("A", "B", DSO2[1], "C", DSO2[1], "-", "7", "8", "9"), c(9999, NA, 1.5, NA, 5, 6, 7, 8, 9), factor(c("A", "0", 0, "NA", "NA", intUnk, numUnk, "-", DSO2[2]))) xListUnkDSO2Test <- lapply(xListUnkDSO2, function(x) x %in% DSO2) unkLND3 <- list(.default="notAvail", num=0, int=9999) xListNUnkD3 <- list(int=as.integer(c(unkLND3[[3]], 1:2, unkLND3[[3]], 5, 6, 7, 8, 9)), cha=c("A", "B", unkLND3[[1]], "C", unkLND3[[1]], "-", "7", "8", "9"), num=c(9999, unkLND3[[2]], 1.5, unkLND3[[2]], 5, 6, 7, 8, 9), fac=factor(c("A", "0", 0, "NA", "NA", intUnk, numUnk, "-", unkLND3[[1]]))) xListNUnkD3Test <- xListNUnkD3 xListNUnkD3Test$int <- xListNUnkD3Test$int %in% unkLND3[[3]] xListNUnkD3Test$cha <- xListNUnkD3Test$cha %in% unkLND3[[1]] xListNUnkD3Test$num <- xListNUnkD3Test$num %in% unkLND3[[2]] xListNUnkD3Test$fac <- xListNUnkD3Test$fac %in% unkLND3[[1]] unkLND2E <- list(.default="notAvail", 9999) test.isUnknown <- function() { checkIdentical(isUnknown(xIntUnk, unknown=as.integer(intUnk)), xIntUnkTest) checkIdentical(isUnknown(xIntUnk, unknown=intUnk), xIntUnkTest) checkIdentical(isUnknown(xNumUnk, unknown=numUnk), xNumUnkTest) checkIdentical(isUnknown(xNumUnk, unknown=as.integer(numUnk)), xNumUnkTest) checkIdentical(isUnknown(xChaUnk, unknown=chaUnk), xChaUnkTest) checkIdentical(isUnknown(xFacUnk, unknown=facUnk), xFacUnkTest) checkIdentical(isUnknown(xIntUnk, unknown=unkC), xIntUnkTest) checkIdentical(isUnknown(xIntUnk, unknown=unkL), xIntUnkTest) checkIdentical(isUnknown(xFacUnk1, unknown=facUnk1), xFacUnk1Test) facNA <- factor(c("0", 1, 2, 3, NA, "NA")) facNATest <- c(FALSE, FALSE, FALSE, FALSE, TRUE, FALSE) checkIdentical(isUnknown(facNA), facNATest) checkIdentical(isUnknown(xDateUnk, unknown=dateUnk), xDateTest) checkIdentical(isUnknown(xDate1Unk, unknown=dateUnk), xDate1Test) checkIdentical(isUnknown(xPOSIXltUnk, unknown=POSIXltUnk), xPOSIXltTest) checkIdentical(isUnknown(xPOSIXlt1Unk, unknown=POSIXltUnk), xPOSIXlt1Test) checkIdentical(isUnknown(xPOSIXctUnk, unknown=POSIXctUnk), xPOSIXctTest) checkIdentical(isUnknown(xPOSIXct1Unk, unknown=POSIXctUnk), xPOSIXct1Test) checkIdentical(isUnknown(xListUnk, unknown=unkC), xListUnkTest) checkIdentical(isUnknown(xDFUnk, unknown=unkC), xDFUnkTest) checkIdentical(isUnknown(xListUnk, unknown=unkL), xListUnkTest) checkIdentical(isUnknown(xDFUnk, unknown=unkL), xDFUnkTest) checkIdentical(isUnknown(xListNUnk, unknown=unkLN), xListNUnkTest) checkIdentical(isUnknown(xDFUnk, unknown=unkLN), xDFUnkTest) checkIdentical(isUnknown(xListMNUnkF, unknown=unkLMN), xListMNUnkFTest) checkIdentical(isUnknown(xDFMUnkF, unknown=unkLMN), xDFMUnkFTest) checkIdentical(isUnknown(xListUnk1, unknown=unk1), xListUnk1Test) checkIdentical(isUnknown(xDFUnk1, unknown=unk1), xDFUnk1Test) checkIdentical(isUnknown(xListUnk2, unknown=unkC2), xListUnk2Test) checkIdentical(isUnknown(xDFUnk2, unknown=unkC2), xDFUnk2Test) checkIdentical(isUnknown(xListUnk2, unknown=unkL2), xListUnk2Test) checkIdentical(isUnknown(xDFUnk2, unknown=unkL2), xDFUnk2Test) checkIdentical(isUnknown(x=xListUnkD1, unknown=unkLND1), xListUnkD1Test) checkIdentical(isUnknown(x=xListUnkDSO2, unknown=unkLNDSO2), xListUnkDSO2Test) checkIdentical(isUnknown(x=xListNUnkD1, unknown=unkLND1), xListNUnkD1Test) checkIdentical(isUnknown(x=xListNUnkD3, unknown=unkLND3), xListNUnkD3Test) checkException(isUnknown(x=xListNUnk, unknown=unkLND2E)) checkIdentical(isUnknown(x=mat, unknown=NA), matUnkTest) checkIdentical(isUnknown(x=matUnk1, unknown=matUnk), matUnkTest) checkIdentical(isUnknown(x=matUnk1, unknown=c(1, matUnk)), matUnk2Test) } test.unknownToNA <- function() { checkIdentical(unknownToNA(xIntUnk, as.integer(intUnk)), xInt) checkIdentical(unknownToNA(xIntUnk, intUnk), xInt) checkIdentical(unknownToNA(xNumUnk, numUnk), xNum) checkIdentical(unknownToNA(xNumUnk, as.integer(numUnk)), xNum) checkIdentical(unknownToNA(xChaUnk, chaUnk), xCha) checkIdentical(unknownToNA(xChaUnk, chaUnk), xCha) checkIdentical(unknownToNA(xFacUnk, facUnk), xFac) checkIdentical(unknownToNA(xIntUnk, unknown=unkC), xInt) checkIdentical(unknownToNA(xIntUnk, unknown=unkL), xInt) checkIdentical(unknownToNA(xFacUnk1, unknown=facUnk1), xFac1) facNA <- factor(c("0", 1, 2, 3, NA, "NA")) facNATest <- factor(c("0", 1, 2, 3, NA, NA)) checkIdentical(unknownToNA(x=facNA, unknown="NA"), facNATest) checkIdentical(unknownToNA(xDateUnk, unknown=dateUnk), xDate) checkIdentical(unknownToNA(xPOSIXctUnk, unknown=POSIXctUnk), xPOSIXct) tmp_unknownToNA <- unknownToNA(xPOSIXltUnk, unknown=POSIXltUnk) tmp_xPOSIXlt <- xPOSIXlt tmp_unknownToNA$gmtoff <- NULL tmp_xPOSIXlt$gmtoff <- NULL isdst.unknown <- unique( c(which(is.na(tmp_unknownToNA$isdst) | tmp_unknownToNA$isdst==-1 ) ) , c(which(is.na(tmp_xPOSIXlt$isdst) | tmp_xPOSIXlt$isdst==-1 ) ) ) checkIdentical(tmp_unknownToNA$isdst[!isdst.unknown], tmp_xPOSIXlt$isds[!isdst.unknown]) tmp_unknownToNA$isdst <- NULL tmp_xPOSIXlt$isdst <- NULL checkIdentical(tmp_unknownToNA, tmp_xPOSIXlt) checkIdentical(unknownToNA(xListUnk, unknown=unkC), xList) checkIdentical(unknownToNA(xDFUnk, unknown=unkC), xDF) checkIdentical(unknownToNA(xListUnk, unknown=unkL), xList) checkIdentical(unknownToNA(xDFUnk, unknown=unkL), xDF) checkIdentical(unknownToNA(xListNUnk, unknown=unkLN), xListN) checkIdentical(unknownToNA(xDFUnk, unknown=unkLN), xDF) checkIdentical(unknownToNA(xListMNUnkF, unknown=unkLMN), xListMNF) checkIdentical(unknownToNA(xDFMUnkF, unknown=unkLMN), xDFMF) checkIdentical(unknownToNA(xListUnk1, unknown=unk1), xList) checkIdentical(unknownToNA(xDFUnk1, unknown=unk1), xDF) checkIdentical(unknownToNA(xListUnk2, unknown=unkC2), xList) checkIdentical(unknownToNA(xDFUnk2, unknown=unkC2), xDF) checkIdentical(unknownToNA(xListUnk2, unknown=unkL2), xList) checkIdentical(unknownToNA(xDFUnk2, unknown=unkL2), xDF) checkException(unknownToNA(xListUnk2a, unknown=unkLN2)) checkIdentical(unknownToNA(xListNUnk2, unknown=unkL2), xListN) checkException(unknownToNA(xListNUnk2, unknown=unkLN2)) checkIdentical(unknownToNA(xDFUnk2, unknown=unkL2), xDF) checkException(unknownToNA(xDFUnk2, unknown=unkLN2)) checkIdentical(unknownToNA(x=xListUnkD1, unknown=unkLND1), xListD1) checkIdentical(unknownToNA(x=xListUnkDSO2, unknown=unkLNDSO2), xList) checkIdentical(unknownToNA(x=xListNUnkD1, unknown=unkLND1), xListND1) checkIdentical(unknownToNA(x=xListNUnkD3, unknown=unkLND3), xListN) checkException(unknownToNA(x=xListNUnk, unknown=unkLND2E)) checkEquals(unknownToNA(x=matUnk1, unknown=matUnk), mat) } test.NAToUnknown <- function() { checkIdentical(NAToUnknown(xInt, as.integer(intUnk)), xIntUnk) checkIdentical(NAToUnknown(xInt, intUnk), xIntUnk) checkIdentical(NAToUnknown(xNum, numUnk), xNumUnk) checkIdentical(NAToUnknown(xNum, as.integer(numUnk)), xNumUnk) checkIdentical(NAToUnknown(xCha, chaUnk), xChaUnk) checkIdentical(NAToUnknown(xCha, chaUnk), xChaUnk) checkIdentical(NAToUnknown(xFac, facUnk), xFacUnk) checkException(NAToUnknown(xInt, unknown=unkC)) checkException(NAToUnknown(xInt, unknown=unkL)) checkException(NAToUnknown(xCha, unknown=chaUnk1)) checkIdentical(NAToUnknown(xCha, unknown=chaUnk1, force=TRUE), xChaUnk1) checkException(NAToUnknown(xFac, unknown=facLev)) checkIdentical(NAToUnknown(xFac, unknown=facLev, force=TRUE), xFacUnkLev) checkIdentical(NAToUnknown(xFac, unknown=facUnk1, force=TRUE), xFacUnk1) facNA <- factor(c("0", 1, 2, 3, NA, NA)) facNATest <- factor(c("0", 1, 2, 3, "NA", "NA")) checkIdentical(NAToUnknown(x=facNA, unknown="NA"), facNATest) checkIdentical(NAToUnknown(xDate, unknown=dateUnk), xDateUnk) checkIdentical(NAToUnknown(xPOSIXct, unknown=POSIXctUnk), xPOSIXctUnk) tmp_NAToUnknown <- NAToUnknown(xPOSIXlt, unknown=POSIXltUnk) tmp_xPOSIXltUnk <- xPOSIXltUnk tmp_NAToUnknown$gmtoff <- NULL tmp_xPOSIXltUnk$gmtoff <- NULL isdst.unknown <- unique( c(which(is.na(tmp_NAToUnknown$isdst) | tmp_NAToUnknown$isdst==-1 ) ) , c(which(is.na(tmp_xPOSIXltUnk$isdst) | tmp_xPOSIXltUnk$isdst==-1 ) ) ) checkIdentical(tmp_NAToUnknown$isdst[!isdst.unknown], tmp_xPOSIXltUnk$isds[!isdst.unknown]) tmp_NAToUnknown$isdst <- NULL tmp_xPOSIXltUnk$isdst <- NULL checkIdentical(tmp_NAToUnknown, tmp_xPOSIXltUnk) checkIdentical(NAToUnknown(xList, unknown=unkC), xListUnk) checkIdentical(NAToUnknown(xDF, unknown=unkC), xDFUnk) checkIdentical(NAToUnknown(xList, unknown=unkL), xListUnk) checkIdentical(NAToUnknown(xDF, unknown=unkL), xDFUnk) checkIdentical(NAToUnknown(xListN, unknown=unkLN), xListNUnk) checkIdentical(NAToUnknown(xDF, unknown=unkLN), xDFUnk) checkException(NAToUnknown(xListN, unknown=unkLMN)) checkException(NAToUnknown(xDF, unknown=unkLMN)) checkIdentical(NAToUnknown(xList, unknown=unk1), xListUnk1) checkIdentical(NAToUnknown(xDF, unknown=unk1), xDFUnk1) checkIdentical(NAToUnknown(xList, unknown=unkC2), xListUnk2) checkIdentical(NAToUnknown(xDF, unknown=unkC2), xDFUnk2) checkIdentical(NAToUnknown(xList, unknown=unkL2), xListUnk2) checkIdentical(NAToUnknown(xDF, unknown=unkL2), xDFUnk2) checkException(NAToUnknown(xList, unknown=unkLN2)) checkIdentical(NAToUnknown(xListN, unknown=unkL2), xListNUnk2) checkException(NAToUnknown(xListN, unknown=unkLN2)) checkIdentical(NAToUnknown(xDF, unknown=unkL2), xDFUnk2) checkException(NAToUnknown(xDF, unknown=unkLN2)) checkIdentical(NAToUnknown(x=xList, unknown=unkLND1), xListUnkD1) checkIdentical(NAToUnknown(x=xList, unknown=unkLNDSO2), xListUnkDSO2) checkIdentical(NAToUnknown(x=xListN, unknown=unkLND1), xListNUnkD1) checkIdentical(NAToUnknown(x=xListN, unknown=unkLND3), xListNUnkD3) checkException(NAToUnknown(x=xListN, unknown=unkLND2E)) checkEquals(NAToUnknown(x=mat, unknown=matUnk), matUnk1) }
ar <- function (x, aic = TRUE, order.max = NULL, method = c("yule-walker","burg", "ols", "mle", "yw"), na.action = na.fail, series = deparse(substitute(x)), ...) { res <- switch(match.arg(method), yw =, "yule-walker" = ar.yw(x, aic = aic, order.max = order.max, na.action = na.action, series = series, ...), "burg" = ar.burg(x, aic = aic, order.max = order.max, na.action = na.action, series = series, ...), "ols" = ar.ols(x, aic = aic, order.max = order.max, na.action = na.action, series = series, ...), "mle" = ar.mle(x, aic = aic, order.max = order.max, na.action = na.action, series = series, ...) ) res$call <- match.call() res } ar.yw <- function(x, ...) UseMethod("ar.yw") ar.yw.default <- function (x, aic = TRUE, order.max = NULL, na.action = na.fail, demean = TRUE, series = NULL, ...) { if(is.null(series)) series <- deparse(substitute(x)) ists <- is.ts(x) x <- na.action(as.ts(x)) if(ists) xtsp <- tsp(x) xfreq <- frequency(x) x <- as.matrix(x) if(!is.numeric(x)) stop("'x' must be numeric") if(anyNA(x)) stop("NAs in 'x'") nser <- ncol(x) if (demean) { xm <- colMeans(x) x <- sweep(x, 2L, xm, check.margin=FALSE) } else xm <- rep.int(0, nser) n.used <- nrow(x) order.max <- if (is.null(order.max)) min(n.used - 1L, floor(10 * log10(n.used))) else round(order.max) if (order.max < 1L) stop("'order.max' must be >= 1") else if (order.max >= n.used) stop("'order.max' must be < 'n.used'") xacf <- acf(x, type = "covariance", lag.max = order.max, plot = FALSE, demean = demean)$acf if(nser > 1L) { snames <- colnames(x) A <- B <- array(0, dim = c(order.max + 1L, nser, nser)) A[1L, , ] <- B[1L, , ] <- diag(nser) EA <- EB <- xacf[1L, , , drop = TRUE] partialacf <- array(dim = c(order.max, nser, nser)) xaic <- numeric(order.max + 1L) solve.yw <- function(m) { betaA <- betaB <- 0 for (i in 0L:m) { betaA <- betaA + A[i + 1L, , ] %*% xacf[m + 2L - i, , ] betaB <- betaB + B[i + 1L, , ] %*% t(xacf[m + 2L - i, , ]) } KA <- -t(qr.solve(t(EB), t(betaA))) KB <- -t(qr.solve(t(EA), t(betaB))) EB <<- (diag(nser) - KB %*% KA) %*% EB EA <<- (diag(nser) - KA %*% KB) %*% EA Aold <- A Bold <- B for (i in seq_len(m + 1L)) { A[i + 1L, , ] <<- Aold[i + 1L, , ] + KA %*% Bold[m + 2L - i, , ] B[i + 1L, , ] <<- Bold[i + 1L, , ] + KB %*% Aold[m + 2L - i, , ] } } cal.aic <- function() { det <- abs(prod(diag(qr(EA)$qr))) return(n.used * log(det) + 2 * m * nser * nser) } cal.resid <- function() { resid <- array(0, dim = c(n.used - order, nser)) for (i in 0L:order) resid <- resid + x[(order - i + 1L):(n.used - i), , drop = FALSE] %*% t(ar[i + 1L, , ]) return(rbind(matrix(NA, order, nser), resid)) } order <- 0L for (m in 0L:order.max) { xaic[m + 1L] <- cal.aic() if (!aic || xaic[m + 1L] == min(xaic[seq_len(m + 1L)])) { ar <- A order <- m var.pred <- EA * n.used/(n.used - nser * (m + 1L)) } if (m < order.max) { solve.yw(m) partialacf[m + 1L, , ] <- -A[m + 2L, , ] } } xaic <- setNames(xaic - min(xaic), 0L:order.max) resid <- cal.resid() if(order) { ar <- -ar[2L:(order + 1L), , , drop = FALSE] dimnames(ar) <- list(seq_len(order), snames, snames) } else ar <- array(0, dim = c(0L, nser, nser), dimnames = list(NULL, snames, snames)) dimnames(var.pred) <- list(snames, snames) dimnames(partialacf) <- list(seq_len(order.max), snames, snames) colnames(resid) <- colnames(x) } else { if (xacf[1L] == 0) stop("zero-variance series") r <- as.double(drop(xacf)) z <- .Fortran(C_eureka, as.integer(order.max), r, r, coefs = double(order.max^2), vars = double(order.max), double(order.max)) coefs <- matrix(z$coefs, order.max, order.max) partialacf <- array(diag(coefs), dim = c(order.max, 1L, 1L)) var.pred <- c(r[1L], z$vars) xaic <- n.used * log(var.pred) + 2 * (0L:order.max) + 2 * demean maic <- min(aic) xaic <- setNames(if(is.finite(maic)) xaic - min(xaic) else ifelse(xaic == maic, 0, Inf), 0L:order.max) order <- if (aic) (0L:order.max)[xaic == 0L] else order.max ar <- if (order) coefs[order, seq_len(order)] else numeric() var.pred <- var.pred[order + 1L] var.pred <- var.pred * n.used/(n.used - (order + 1L)) resid <- if(order) c(rep.int(NA, order), embed(x, order + 1L) %*% c(1, -ar)) else as.vector(x) if(ists) { attr(resid, "tsp") <- xtsp attr(resid, "class") <- "ts" } } res <- list(order = order, ar = ar, var.pred = var.pred, x.mean = drop(xm), aic = xaic, n.used = n.used, order.max = order.max, partialacf = partialacf, resid = resid, method = "Yule-Walker", series = series, frequency = xfreq, call = match.call()) if(nser == 1L && order) res$asy.var.coef <- solve(toeplitz(drop(xacf)[seq_len(order)]))*var.pred/n.used class(res) <- "ar" res } print.ar <- function(x, digits = max(3L, getOption("digits") - 3L), ...) { cat("\nCall:\n", deparse(x$call), "\n\n", sep = "") nser <- NCOL(x$var.pred) if(nser > 1L) { res <- x[c("ar", if(!is.null(x$x.intercept)) "x.intercept", "var.pred")] res$ar <- aperm(res$ar, c(2L,3L,1L)) print(res, digits = digits) } else { if(x$order) { cat("Coefficients:\n") coef <- setNames(round(drop(x$ar), digits = digits), seq_len(x$order)) print.default(coef, print.gap = 2L) } if(!is.null(xint <- x$x.intercept) && !is.na(xint)) cat("\nIntercept: ", format(xint, digits = digits), " (", format(x$asy.se.coef$x.mean, digits = digits), ") ", "\n", sep = "") cat("\nOrder selected", x$order, " sigma^2 estimated as ", format(x$var.pred, digits = digits)) cat("\n") } invisible(x) } predict.ar <- function(object, newdata, n.ahead = 1L, se.fit = TRUE, ...) { if (n.ahead < 1L) stop("'n.ahead' must be at least 1") if(missing(newdata)) { newdata <- eval.parent(parse(text=object$series)) if (!is.null(nas <- object$call$na.action)) newdata <- eval.parent(call(nas, newdata)) } nser <- NCOL(newdata) ar <- object$ar p <- object$order st <- tsp(as.ts(newdata))[2L] dt <- deltat(newdata) xfreq <- frequency(newdata) tsp(newdata) <- NULL class(newdata) <- NULL if(NCOL(ar) != nser) stop("number of series in 'object' and 'newdata' do not match") n <- NROW(newdata) if(nser > 1L) { if(is.null(object$x.intercept)) xint <- rep.int(0, nser) else xint <- object$x.intercept x <- rbind(sweep(newdata, 2L, object$x.mean, check.margin = FALSE), matrix(rep.int(0, nser), n.ahead, nser, byrow = TRUE)) pred <- if(p) { for(i in seq_len(n.ahead)) { x[n+i,] <- ar[1L,,] %*% x[n+i-1L,] + xint if(p > 1L) for(j in 2L:p) x[n+i,] <- x[n+i,] + ar[j,,] %*% x[n+i-j,] } x[n + seq_len(n.ahead), ] } else matrix(xint, n.ahead, nser, byrow = TRUE) pred <- pred + matrix(object$x.mean, n.ahead, nser, byrow = TRUE) colnames(pred) <- colnames(object$var.pred) if(se.fit) { warning("'se.fit' not yet implemented for multivariate models") se <- matrix(NA, n.ahead, nser) } } else { if(is.null(object$x.intercept)) xint <- 0 else xint <- object$x.intercept x <- c(newdata - object$x.mean, rep.int(0, n.ahead)) if(p) { for(i in seq_len(n.ahead)) x[n+i] <- sum(ar * x[n+i - seq_len(p)]) + xint pred <- x[n + seq_len(n.ahead)] if(se.fit) { psi <- .Call(C_ar2ma, ar, n.ahead - 1L) vars <- cumsum(c(1, psi^2)) se <- sqrt(object$var.pred*vars)[seq_len(n.ahead)] } } else { pred <- rep.int(xint, n.ahead) if (se.fit) se <- rep.int(sqrt(object$var.pred), n.ahead) } pred <- pred + rep.int(object$x.mean, n.ahead) } pred <- ts(pred, start = st + dt, frequency = xfreq) if(se.fit) list(pred = pred, se = ts(se, start = st + dt, frequency = xfreq)) else pred } ar.mle <- function (x, aic = TRUE, order.max = NULL, na.action = na.fail, demean = TRUE, series = NULL, ...) { if(is.null(series)) series <- deparse(substitute(x)) ists <- is.ts(x) if (!is.null(dim(x))) stop("MLE only implemented for univariate series") x <- na.action(as.ts(x)) if(anyNA(x)) stop("NAs in 'x'") if(!is.numeric(x)) stop("'x' must be numeric") if(ists) xtsp <- tsp(x) xfreq <- frequency(x) x <- as.vector(x) n.used <- length(x) order.max <- if (is.null(order.max)) min(n.used-1L, 12L, floor(10 * log10(n.used))) else round(order.max) if (order.max < 0L) stop ("'order.max' must be >= 0") else if (order.max >= n.used) stop("'order.max' must be < 'n.used'") if (aic) { coefs <- matrix(NA, order.max+1L, order.max+1L) var.pred <- numeric(order.max+1L) xaic <- numeric(order.max+1L) xm <- if(demean) mean(x) else 0 coefs[1, 1L] <- xm var0 <- sum((x-xm)^2)/n.used var.pred[1L] <- var0 xaic[1L] <- n.used * log(var0) + 2 * demean + 2 + n.used + n.used * log(2 * pi) for(i in seq_len(order.max)) { fit <- arima0(x, order=c(i, 0L, 0L), include.mean=demean) coefs[i+1L, seq_len(i+demean)] <- fit$coef[seq_len(i+demean)] xaic[i+1L] <- fit$aic var.pred[i+1L] <- fit$sigma2 } xaic <- setNames(xaic - min(xaic), 0L:order.max) order <- (0L:order.max)[xaic == 0L] ar <- coefs[order+1L, seq_len(order)] x.mean <- coefs[order+1L, order+1L] var.pred <- var.pred[order+1L] } else { order <- order.max fit <- arima0(x, order=c(order, 0L, 0L), include.mean=demean) coefs <- fit$coef if(demean) { ar <- coefs[-length(coefs)] x.mean <- coefs[length(coefs)] } else { ar <- coefs x.mean <- 0 } var.pred <- fit$sigma2 xaic <- structure(0, names=order) } resid <- if(order) c(rep(NA, order), embed(x - x.mean, order+1L) %*% c(1, -ar)) else x - x.mean if(ists) { attr(resid, "tsp") <- xtsp attr(resid, "class") <- "ts" } res <- list(order = order, ar = ar, var.pred = var.pred, x.mean = x.mean, aic = xaic, n.used = n.used, order.max = order.max, partialacf = NULL, resid = resid, method = "MLE", series = series, frequency = xfreq, call = match.call()) if(order) { xacf <- acf(x, type = "covariance", lag.max = order, plot=FALSE)$acf res$asy.var.coef <- solve(toeplitz(drop(xacf)[seq_len(order)])) * var.pred/n.used } class(res) <- "ar" res } ar.ols <- function (x, aic = TRUE, order.max = NULL, na.action = na.fail, demean = TRUE, intercept = demean, series = NULL, ...) { if(is.null(series)) series <- deparse(substitute(x)) rescale <- TRUE ists <- is.ts(x) x <- na.action(as.ts(x)) if(anyNA(x)) stop("NAs in 'x'") if(ists) xtsp <- tsp(x) xfreq <- frequency(x) x <- as.matrix(x) if(!is.numeric(x)) stop("'x' must be numeric") n.used <- nrow(x) nser <- ncol(x) iser <- seq_len(nser) if(rescale) { sc <- sqrt(drop(apply(x, 2L, var))) sc[sc == 0] <- 1 x <- x/rep.int(sc, rep.int(n.used, nser)) } else sc <- rep.int(1, nser) order.max <- if (is.null(order.max)) min(n.used-1L, floor(10 * log10(n.used))) else round(order.max) if (order.max < 0L) stop("'order.max' must be >= 0") if (order.max >= n.used) stop("'order.max' must be < 'n.used'") order.min <- if (aic) 0L else order.max varE <- seA <- A <- vector("list", order.max - order.min + 1L) xaic <- rep.int(Inf, order.max - order.min + 1L) det <- function(x) max(0, prod(diag(qr(x)$qr))*(-1)^(ncol(x)-1)) if(demean) { xm <- colMeans(x) x <- sweep(x, 2L, xm, check.margin=FALSE) } else xm <- rep.int(0, nser) for (m in order.min:order.max) { y <- embed(x, m+1L) if(intercept) { if (m) X <- cbind(rep.int(1,nrow(y)), y[, (nser+1L):ncol(y)]) else X <- as.matrix(rep.int(1, nrow(y))) } else { if (m) X <- y[, (nser+1L):ncol(y)] else X <- matrix(0, nrow(y), 0) } Y <- t(y[, iser]) N <- ncol(Y) XX <- t(X)%*%X rank <- qr(XX)$rank if (rank != nrow(XX)) { warning(paste("model order: ", m, "singularities in the computation of the projection matrix", "results are only valid up to model order", m - 1L), domain = NA) break } P <- if(ncol(XX) > 0) solve(XX) else XX A[[m - order.min + 1L]] <- Y %*% X %*% P YH <- A[[m - order.min + 1L]] %*% t(X) E <- (Y - YH) varE[[m - order.min + 1L]] <- tcrossprod(E)/N varA <- P %x% (varE[[m - order.min + 1L]]) seA[[m - order.min+1L]] <- if(ncol(varA) > 0) sqrt(diag(varA)) else numeric() xaic[m - order.min+1L] <- n.used*log(det(varE[[m-order.min+1L]])) + 2*nser*(nser*m+intercept) } m <- if(aic) which.max(xaic == min(xaic)) + order.min - 1L else order.max y <- embed(x, m+1L) AA <- A[[m - order.min + 1L]] if(intercept) { xint <- AA[, 1L] ar <- AA[, -1L] X <- if(m) cbind(rep.int(1,nrow(y)), y[, (nser+1L):ncol(y)]) else as.matrix(rep.int(1, nrow(y))) } else { X <- if(m) y[, (nser+1L):ncol(y)] else matrix(0, nrow(y), 0L) xint <- NULL ar <- AA } Y <- t(y[, iser, drop = FALSE]) YH <- AA %*% t(X) E <- drop(rbind(matrix(NA, m, nser), t(Y - YH))) maic <- min(aic) xaic <- setNames(if(is.finite(maic)) xaic - min(xaic) else ifelse(xaic == maic, 0, Inf), order.min:order.max) dim(ar) <- c(nser, nser, m) ar <- aperm(ar, c(3L,1L,2L)) ses <- seA[[m - order.min + 1L]] if(intercept) { sem <- ses[iser] ses <- ses[-iser] } else sem <- rep.int(0, nser) dim(ses) <- c(nser, nser, m) ses <- aperm(ses, c(3L,1L,2L)) var.pred <- varE[[m - order.min + 1L]] if(nser > 1L) { snames <- colnames(x) dimnames(ses) <- dimnames(ar) <- list(seq_len(m), snames, snames) dimnames(var.pred) <- list(snames, snames) names(sem) <- colnames(E) <- snames } if(ists) { attr(E, "tsp") <- xtsp attr(E, "class") <- "ts" } if(rescale) { xm <- xm * sc if(!is.null(xint)) xint <- xint * sc aa <- outer(sc, 1/sc) if(nser > 1L && m) for(i in seq_len(m)) ar[i,,] <- ar[i,,]*aa var.pred <- var.pred * drop(outer(sc, sc)) E <- E * rep.int(sc, rep.int(NROW(E), nser)) sem <- sem*sc if(m) for(i in seq_len(m)) ses[i,,] <- ses[i,,]*aa } res <- list(order = m, ar = ar, var.pred = var.pred, x.mean = xm, x.intercept = xint, aic = xaic, n.used = n.used, order.max = order.max, partialacf = NULL, resid = E, method = "Unconstrained LS", series = series, frequency = xfreq, call = match.call(), asy.se.coef = list(x.mean = sem, ar=drop(ses))) class(res) <- "ar" res } ar.yw.mts <- function (x, aic = TRUE, order.max = NULL, na.action = na.fail, demean = TRUE, series = NULL, var.method = 1L, ...) { if (is.null(series)) series <- deparse(substitute(x)) if (ists <- is.ts(x)) xtsp <- tsp(x) x <- na.action(as.ts(x)) if (anyNA(x)) stop("NAs in 'x'") if (ists) xtsp <- tsp(x) xfreq <- frequency(x) x <- as.matrix(x) nser <- ncol(x) n.used <- nrow(x) if (demean) { x.mean <- colMeans(x) x <- sweep(x, 2L, x.mean, check.margin=FALSE) } else x.mean <- rep(0, nser) order.max <- if (is.null(order.max)) floor(10 * log10(n.used)) else floor(order.max) if (order.max < 1L) stop("'order.max' must be >= 1") xacf <- acf(x, type = "cov", plot = FALSE, lag.max = order.max)$acf z <- .C(C_multi_yw, aperm(xacf, 3:1), as.integer(n.used), as.integer(order.max), as.integer(nser), coefs = double((1L + order.max) * nser * nser), pacf = double((1L + order.max) * nser * nser), var = double((1L + order.max) * nser * nser), aic = double(1L + order.max), order = integer(1L), as.integer(aic)) partialacf <- aperm(array(z$pacf, dim = c(nser, nser, order.max + 1L)), 3:1)[-1L, , , drop = FALSE] var.pred <- aperm(array(z$var, dim = c(nser, nser, order.max + 1L)), 3:1) xaic <- setNames(z$aic - min(z$aic), 0:order.max) order <- z$order resid <- x if (order > 0) { ar <- -aperm(array(z$coefs, dim = c(nser, nser, order.max + 1L)), 3:1)[2L:(order + 1L), , , drop = FALSE] for (i in 1L:order) resid[-(1L:order), ] <- resid[-(1L:order),] - x[(order - i + 1L):(n.used - i), ] %*% t(ar[i, , ]) resid[1L:order, ] <- NA } else ar <- array(dim = c(0, nser, nser)) var.pred <- var.pred[order + 1L, , , drop = TRUE] * n.used/(n.used - nser * (demean + order)) if (ists) { attr(resid, "tsp") <- xtsp attr(resid, "class") <- c("mts", "ts") } snames <- colnames(x) colnames(resid) <- snames dimnames(ar) <- list(seq_len(order), snames, snames) dimnames(var.pred) <- list(snames, snames) dimnames(partialacf) <- list(1L:order.max, snames, snames) res <- list(order = order, ar = ar, var.pred = var.pred, x.mean = x.mean, aic = xaic, n.used = n.used, order.max = order.max, partialacf = partialacf, resid = resid, method = "Yule-Walker", series = series, frequency = xfreq, call = match.call()) class(res) <- "ar" return(res) } ar.burg <- function(x, ...) UseMethod("ar.burg") ar.burg.default <- function (x, aic = TRUE, order.max = NULL, na.action = na.fail, demean = TRUE, series = NULL, var.method = 1L, ...) { if(is.null(series)) series <- deparse(substitute(x)) if (ists <- is.ts(x)) xtsp <- tsp(x) x <- na.action(as.ts(x)) if(anyNA(x)) stop("NAs in 'x'") if (ists) xtsp <- tsp(x) xfreq <- frequency(x) x <- as.vector(x) if (demean) { x.mean <- mean(x) x <- x - x.mean } else x.mean <- 0 n.used <- length(x) order.max <- if (is.null(order.max)) min(n.used-1L, floor(10 * log10(n.used))) else floor(order.max) if (order.max < 1L) stop("'order.max' must be >= 1") else if (order.max >= n.used) stop("'order.max' must be < 'n.used'") xaic <- numeric(order.max + 1L) z <- .Call(C_Burg, x, order.max) coefs <- matrix(z[[1L]], order.max, order.max) partialacf <- array(diag(coefs), dim = c(order.max, 1L, 1L)) var.pred <- if(var.method == 1L) z[[2L]] else z[[3L]] if (any(is.nan(var.pred))) stop("zero-variance series") xaic <- n.used * log(var.pred) + 2 * (0L:order.max) + 2 * demean maic <- min(aic) xaic <- setNames(if(is.finite(maic)) xaic - min(xaic) else ifelse(xaic == maic, 0, Inf), 0L:order.max) order <- if (aic) (0L:order.max)[xaic == 0] else order.max ar <- if (order) coefs[order, 1L:order] else numeric() var.pred <- var.pred[order + 1L] resid <- if(order) c(rep(NA, order), embed(x, order+1L) %*% c(1, -ar)) else x if(ists) { attr(resid, "tsp") <- xtsp attr(resid, "class") <- "ts" } res <- list(order = order, ar = ar, var.pred = var.pred, x.mean = x.mean, aic = xaic, n.used = n.used, order.max = order.max, partialacf = partialacf, resid = resid, method = ifelse(var.method==1L,"Burg","Burg2"), series = series, frequency = xfreq, call = match.call()) if(order) { xacf <- acf(x, type = "covariance", lag.max = order, plot = FALSE)$acf res$asy.var.coef <- solve(toeplitz(drop(xacf)[seq_len(order)]))*var.pred/n.used } class(res) <- "ar" res } ar.burg.mts <- function (x, aic = TRUE, order.max = NULL, na.action = na.fail, demean = TRUE, series = NULL, var.method = 1L, ...) { if (is.null(series)) series <- deparse(substitute(x)) if (ists <- is.ts(x)) xtsp <- tsp(x) x <- na.action(as.ts(x)) if (anyNA(x)) stop("NAs in 'x'") if (ists) xtsp <- tsp(x) xfreq <- frequency(x) x <- as.matrix(x) nser <- ncol(x) n.used <- nrow(x) if (demean) { x.mean <- colMeans(x) x <- sweep(x, 2L, x.mean, check.margin = FALSE) } else x.mean <- rep(0, nser) order.max <- if (is.null(order.max)) floor(10 * log10(n.used)) else floor(order.max) z <- .C(C_multi_burg, as.integer(n.used), resid = as.double(x), as.integer(order.max), as.integer(nser), coefs = double((1L + order.max) * nser * nser), pacf = double((1L + order.max) * nser * nser), var = double((1L + order.max) * nser * nser), aic = double(1L + order.max), order = integer(1L), as.integer(aic), as.integer(var.method)) partialacf <- aperm(array(z$pacf, dim = c(nser, nser, order.max + 1L)), 3:1)[-1L, , , drop = FALSE] var.pred <- aperm(array(z$var, dim = c(nser, nser, order.max + 1L)), 3:1) xaic <- setNames(z$aic - min(z$aic), 0:order.max) order <- z$order ar <- if (order) -aperm(array(z$coefs, dim = c(nser, nser, order.max + 1L)), 3:1)[2L:(order + 1L), , , drop = FALSE] else array(dim = c(0, nser, nser)) var.pred <- var.pred[order + 1L, , , drop = TRUE] resid <- matrix(z$resid, nrow = n.used, ncol = nser) if (order) resid[seq_len(order), ] <- NA if (ists) { attr(resid, "tsp") <- xtsp attr(resid, "class") <- "mts" } snames <- colnames(x) colnames(resid) <- snames dimnames(ar) <- list(seq_len(order), snames, snames) dimnames(var.pred) <- list(snames, snames) dimnames(partialacf) <- list(seq_len(order.max), snames, snames) res <- list(order = order, ar = ar, var.pred = var.pred, x.mean = x.mean, aic = xaic, n.used = n.used, order.max = order.max, partialacf = partialacf, resid = resid, method = ifelse(var.method == 1L, "Burg", "Burg2"), series = series, frequency = xfreq, call = match.call()) class(res) <- "ar" return(res) }
this_session <- new.env() on_load<-function() { this_session <<- new.env() options(stringsAsFactors = FALSE) } default_server <- function() { return("https://prism.peermodelsnetwork.com/route/") } make_url <- function(model_name, base_url, type=c("call","tmp","info"), async=FALSE) { if(substring(base_url,nchar(base_url))=="/") base_url <- substring(base_url,1,nchar(base_url)-1) if(length(grep(pattern="/route",x=base_url))>0) { if(type=="call") { out <- paste0(base_url,"/",model_name,"/run") if (async) {out <- paste0(base_url,"/",model_name,"/async/run")} } if(type=="tmp") { out <- paste0(base_url,"/",model_name,"/tmp") } if(type=="info") { out <- paste0(base_url,"/",model_name,"") } } else { if(type=="call") { out <- paste0(base_url,"/library/", model_name, "/R/gateway/json") if (async) {out <- paste0(base_url,"/library/", model_name, "/R/gatewayasync/json")} } if(type=="tmp") { out <- paste0(base_url,"/tmp") } if(type=="info") { out <- paste0(base_url,"/library/", model_name, "/info") } } return(out) } get_session <- function() { as.list(this_session) } reset_session <- function() { rm(list=ls(this_session),envir = this_session) } handshake <- function(model_name, server=default_server()) { address <- make_url(model_name, base_url = server, type = "info") res<-GET(address) message(res) found <- content(res)[[1]] == 100 if (found) { message ("Model available for cloud access") return (TRUE) } else { message ("Model not found on the server") return (FALSE) } } get_default_input<-function(model_name=NULL, api_key=NULL, server=NULL) { if(is.null(model_name)) model_name <- this_session$model_name if(is.null(api_key)) api_key <- this_session$api_key if(is.null(server)) server <- this_session$server if(is.null(server)) server <- default_server() this_session$server <- server url <- make_url(model_name,server,"call") default_inputs <- prism_call(func="prism_get_default_input", base_url = url, api_key = api_key) this_session$model_name <- model_name this_session$api_key <- api_key this_session$server <- server return(default_inputs) } process_input<-function(inp) { if(length(inp)==0) return(list()) if(canbe_prism_input(inp)) return(to_prism_input(inp)) out<-list() if(is.list(inp)) { out<-list() for(i in 1:length(inp)) { nm<-names(inp[i]) element<-inp[[i]] if(canbe_prism_input(element)) out[[i]]<-to_prism_input(element) else { if(is.list(inp[[nm]])) out[[nm]]<-process_input(inp[[nm]]) else out[[nm]]<-inp[[nm]] } names(out[i])<-nm } return(out) } else return(inp) } unprocess_input<-function(inp) { if(inherits(inp,"prism_input")) return(inp$value) out<-list() for(nm in names(inp)) { if(inherits(inp[[nm]],"prism_input")) out[[nm]]<-inp[[nm]]$value else { if(is.list(inp[[nm]])) out[[nm]]<-unprocess_input(inp[[nm]]) else out[[nm]]<-inp[[nm]] } } return(out) } get_plots<-function() { if(is.null(this_session$output_list)) this_session$output_list <- get_output_object_list() plots <- filter_output_object_list(this_session$output_list,"graphics") out<-list() counter<-1; for(obj in plots) { source<-paste(this_session$urlObj,this_session$output_location,"/",obj,sep="") out[[counter]]<-prism_output(type="graphics/url",source = source) counter<-counter+1 } return(out) } draw_plots<-function(plot_number=NULL) { if(is.null(this_session$output_list)) this_session$output_list<-get_output_object_list() plots<-filter_output_object_list(this_session$output_list,"graphics") if(!is.null(plot_number)) plots<-plots[plot_number] for(obj in plots) { par(new=F) plt_data<-get_output_object(object=obj) plot.new() img <- as.raster(plt_data) rasterImage(img,0,0,1,1) } } model_run<-function(model_name=NULL, model_input=NULL, api_key = NULL, server = NULL, async=FALSE) { if(is.null(model_name)) model_name <- this_session$model_name if(is.null(api_key)) api_key <- this_session$api_key if(is.null(server)) server <- this_session$server if(is.null(server)) server <- default_server() address <- make_url(model_name, server, "call", async = async) res<-prism_call("prism_model_run", base_url = address, model_input=model_input, api_key = api_key) this_session$output_location<-this_session$last_location this_session$api_key<-api_key this_session$server <- server this_session$current_model <- model_name this_session$output_list <- NULL return(res) } prism_call<-function(func, base_url, api_key = NULL, ...) { call <- base_url if(is.null(api_key)) api_key <- this_session$api_key message(paste0("Calling server at ", call)) arg <- list(func=func,param=...) request <- NULL request <- POST(call, add_headers('x-prism-auth-user'=api_key), body=toJSON(arg), content_type_json()) if(request$status_code!=200 && request$status_code!=201) { message(paste("Error:"),rawToChar(as.raw(strtoi(request$content, 16L)))) this_session$last_call_status <- request$last_status_code return(NULL) } this_session$last_location <- request$headers$'x-ocpu-session' if(!is.null(api_key)) this_session$api_key <- api_key res <- content(request)[[1]] if (!validate(as.character(res))) {stop("Non-standard response received from server.")} if (is.numeric(res)) { stop(res) } else { res<-fromJSON(res) } return(res) } get_output_object_list<-function(location=this_session$output_location) { url <- paste0(make_url(this_session$model_name, this_session$server, type="tmp"),"/",location) message(paste0("Calling server at ", url)) response <- NULL response <- GET(url, add_headers('x-prism-auth-user'=this_session$api_key)) if(response$status_code!=200 && response$status_code!=201) stop(paste("Error:"),rawToChar(as.raw(strtoi(response$content, 16L)))) str<-content(response) con<-textConnection(str) lines<-readLines(con) close(con) return(lines) } filter_output_object_list<-function(object_list,type="") { if(type=="") return(object_list) return(object_list[which(substring(object_list,1,nchar(type))==type)]) } get_output_object<-function(location=this_session$output_location,object) { url <- paste0(make_url(this_session$model_name,this_session$server,"tmp"),"/", location,"/",object) res<-content(GET(url, add_headers('x-prism-auth-user'=this_session$api_key))) return(res) } get_async_results <- function(model_name = NULL, token = NULL, api_key = NULL, server = NULL) { if(is.null(token)) stop("Async job token not provided") if(is.null(model_name)) model_name <- this_session$model_name if(is.null(api_key)) api_key <- this_session$api_key if(is.null(server)) server <- this_session$server if(is.null(server)) server <- default_server() address <- make_url(model_name, server, "call") res <- prism_call("prism_get_async_results", base_url = address, api_key = api_key, token=token) return(res) }
y.out=as.factor(sample(c("a", "b", "c"), 50, TRUE) ) x1=rexp(50) x2=runif(50) library(partDSA) y.out.test=as.factor(sample(c("a", "b", "c"), 100, TRUE) ) x1.test=rexp(100) x2.test=runif(100) model2<-partDSA(x=data.frame(x1,x2),y=y.out,x.test=data.frame(x1=x1.test,x2=x2.test),y.test=y.out.test) model4<-partDSA(x=data.frame(x1,x2),y=y.out,control=DSA.control(missing="no",cut.off.growth=2)) print(model4) data("GBSG2", package = "TH.data") mdl1<-partDSA(x=data.frame(GBSG2[,c(1:8)]),y=as.factor(GBSG2$cens),control=DSA.control(cut.off.growth=5,loss.function="gini",minsplit=30,minbuck=10)) print(mdl1)
knitr::opts_chunk$set(collapse = TRUE, comment = " library(blink) data(RLdata500) head(RLdata500) X.c <- RLdata500[c("by","bm","bd")] X.c <- as.matrix(RLdata500[,"bd"],ncol=1) p.c <- ncol(X.c) X.s <- as.matrix(RLdata500[-c(2,4,7)]) p.s <- ncol(X.s) file.num <- rep(c(1,2,3),c(200,150,150)) a <-1 b <- 999 d <- function(string1,string2){adist(string1,string2)} c <- 1 library(knitr) library(blink) library(plyr) Sys.setenv(TMPDIR="/tmp/") configure.vars="TMPDIR=/tmp/" lam.gs <- rl.gibbs(file.num=file.num,X.s=X.s,X.c=X.c,num.gs=2,a=a,b=b,c=c,d=d, M=500) estLink <- lam.gs estPopSize <- apply(estLink , 1, function(x) {length(unique(x))}) plot(density(estPopSize),xlim=c(300,500),main="",lty=1, "Observed Population Size", ylim= c(0,1)) abline(v=450,col="red") abline(v=mean(estPopSize),col="black",lty=2) mean(estPopSize) sd(estPopSize)
color_chart <- function(colors = grDevices::colors(), ncol = NULL, use.names = NULL, text.size = 2, text.color = NULL, grid.color = "white") { force(colors) len.colors <- length(colors) if (is.null(ncol)) { ncol <- max(trunc(sqrt(len.colors)), 1L) } if (is.null(use.names)) { use.names <- ncol < 8 } nrow <- len.colors %/% ncol if (len.colors %% ncol != 0) { nrow <- nrow + 1 } color.names <- names(colors) if (length(color.names) != length(colors)) { color.names <- colors } if (len.colors < ncol*nrow) { colors[(len.colors + 1):(ncol*nrow)] <- NA color.names[(len.colors + 1):(ncol*nrow)] <- "" } if (is.null(text.color)) { text.color <- black_or_white(colors) } colors.df <- data.frame(color = colors, color.names = color.names, text.color = text.color, x = rep(1:ncol, nrow), y = rep(nrow:1, rep(ncol, nrow)), idx = ifelse(is.na(colors), "", format(seq_along(colors), trim = TRUE, width = 3)) ) p <- ggplot(colors.df, aes_(~x, ~y, fill = ~color)) if (use.names) { p <- p + aes_(label = ~color.names) } else { p <- p + aes_(label = ~idx) } p <- p + geom_tile(color = grid.color) + scale_fill_identity() + geom_text(size = text.size, aes_(color = ~text.color)) + scale_color_identity() p + theme_void() } black_or_white <- function(colors, threshold = 0.45){ if (!length(colors)) return(character()) threshold <- trunc(threshold * 255) lum <- function(colors) { sapply(colors, function(x) { y <- grDevices::col2rgb(x) sum(y * c(1.5, 2.5, 1)) / 5 }, USE.NAMES = FALSE) } ifelse(lum(colors) > threshold, "black", "white") }
plot.TrialLevelIT <- function(x, Xlab.Trial, Ylab.Trial, Main.Trial, Par=par(oma=c(0, 0, 0, 0), mar=c(5.1, 4.1, 4.1, 2.1)),...) { Object <- x if (missing(Xlab.Trial)) {Xlab.Trial <- expression(paste("Treatment effect on the Surrogate endpoint ", (alpha[i])))} if (missing(Ylab.Trial)) {Ylab.Trial <- expression(paste("Treatment effect on the True endpoint ",(beta[i])))} if (missing(Main.Trial)) {Main.Trial <- c("Trial-level surrogacy")} dev.new() par=Par plot(Object$Alpha.Vector, Object$Beta.Vector, xlab=Xlab.Trial, ylab=Ylab.Trial, main=Main.Trial, ...) abline(lm(Object$Beta.Vector ~ Object$Alpha.Vector)) }
packageMRAN <- function(package = "cholera", date = NULL, check.package = TRUE, multi.core = TRUE) { cores <- multiCore(multi.core) if (check.package) package <- checkPackage(package) ymd <- logDate(date, repository = "MRAN") mran.url <- "https://cran.microsoft.com/snapshot/" root.url <- paste0(mran.url, ymd) if (ymd < as.Date("2017-07-08")) { mac.url.suffix <- "/bin/macosx/mavericks/contrib/r-release/" } else if (ymd >= as.Date("2017-07-08")) { mac.url.suffix <- "/bin/macosx/el-capitan/contrib/r-release/" } src <- data.frame(extension = '.tar.gz', url = paste0(root.url, "/src/contrib")) mac <- data.frame(extension = '.tgz', url = paste0(root.url, mac.url.suffix)) win <- data.frame(extension = '.zip', url = paste0(root.url, "/bin/windows/contrib/r-release/")) arguments <- list(src = src, mac = mac, win = win) out <- parallel::mclapply(arguments, function(x) { pkgData(x$url, x$extension, ymd, package) }, mc.cores = cores) if (!is.null(package)) { out <- do.call(rbind, out) out$type <- row.names(out) row.names(out) <- NULL } else { names(out) <- names(arguments) } out } pkgData <- function(url, extension, ymd, package = package) { web_page <- mreadLines(url) pkg.sel <- grepl(extension, web_page, fixed = TRUE) pkg.data <- gsub("<.*?>", "", web_page[pkg.sel]) pkg.data <- gsub("\\s+", " ", pkg.data) pkg.data <- strsplit(pkg.data, " ") if (!is.null(package)) { pkg.match <- grepl(package, pkg.data, fixed = TRUE) if (sum(pkg.match) == 0) { stop("Not on MRAN (on date). Try adding 3 or 4 days to date.", call. = FALSE) } else if (sum(pkg.match) == 1) { pkg.data <- pkg.data[pkg.match] } else if (sum(pkg.match) > 1) { pkg.data <- pkg.data[pkg.match] pkg.nms <- vapply(pkg.data, function(x) { tmp <- unlist(strsplit(x[1], extension)) unlist(strsplit(tmp, "_"))[1] }, character(1L)) pkg.data <- pkg.data[pkg.nms == package] } } out <- lapply(pkg.data, function(x) { tmp <- unlist(strsplit(x[1], extension)) nm.ver <- unlist(strsplit(tmp, "_")) mo.id <- vapply(month.abb, function(m) grepl(m, x[2]), logical(1L)) mo <- which(mo.id) mo <- ifelse(mo < 10, paste0("0", mo), mo) dt <- unlist(strsplit(x[2], "-")) dt[2] <- mo dt <- paste(rev(dt), collapse = "-") dt <- as.POSIXlt(dt, tz = "GMT") data.frame(package = nm.ver[1], version = nm.ver[2], size = as.numeric(x[4]), timestamp = dt, snapshot = ymd) }) do.call(rbind, out) }
test_that("mlpca_e() compute mlpca for case e error (correlated errors, with a different covariance matrix for each row, but no error correlation between the rows)", { library(RMLPCA) data(data_clean_e) data(data_error_e) data(cov_e) data(data_cleaned_mlpca_e) data_noisy <- data_clean_e + data_error_e results <- RMLPCA::mlpca_e( X = data_noisy, Cov = cov_e, p = 1 ) data_cleaned_mlpca <- results$U %*% results$S %*% t(results$V) expect_equal(data_cleaned_mlpca, data_cleaned_mlpca_e) })
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(tidyxl) library(dplyr) library(tidyr) examples <- system.file("extdata/examples.xlsx", package = "tidyxl") glimpse(xlsx_validation(examples)[1, ]) as.data.frame(xlsx_validation(examples)) rules <- xlsx_validation(examples) cells <- filter(xlsx_cells(examples), row >= 106, col == 1) rules cells inner_join(rules, cells, by = c("sheet" = "sheet", "ref" = "address")) unrange <- function(x) { limits <- cellranger::as.cell_limits(x) rows <- seq(limits$ul[1], limits$lr[1]) cols <- seq(limits$ul[2], limits$lr[2]) rowcol <- expand.grid(rows, cols) cell_addrs <- cellranger::cell_addr(rowcol[[1]], rowcol[[2]]) cellranger::to_string(cell_addrs, fo = "A1", strict = FALSE) } unnest_ref <- function(x, ref) { UseMethod("unnest_ref") } unnest_ref.default <- function(x, ref_col = ref) { stopifnot(is.character(x), length(x) == 1L) refs <- unlist(strsplit(x, ",", fixed = TRUE)) unlist(lapply(refs, unrange)) } unrange("A121:A122") unnest_ref("A115,A121:A122") unnest_ref.data.frame <- function(x, ref_col) { ref <- rlang::enquo(ref_col) x[[rlang::quo_name(ref)]] <- lapply(x[[rlang::quo_name(ref)]], unnest_ref) tidyr::unnest(x, rlang::UQ(ref)) } (nested_rule <- slice(rules, 7)) unnest_ref(nested_rule, ref)
rm(list = ls()) s <- search()[-1] s <- s[-match(c("package:base", "package:stats", "package:graphics", "package:grDevices", "package:utils", "package:datasets", "package:methods", "Autoloads"), s)] if (length(s) > 0) sapply(s, detach, character.only = TRUE) if (!file.exists("tables")) dir.create("tables") if (!file.exists("figures")) dir.create("figures") set.seed(290875) options(prompt = "R> ", continue = "+ ", width = 63, show.signif.stars = FALSE, SweaveHooks = list(leftpar = function() par(mai = par("mai") * c(1, 1.05, 1, 1)), bigleftpar = function() par(mai = par("mai") * c(1, 1.7, 1, 1)))) HSAURpkg <- require("HSAUR3") if (!HSAURpkg) stop("cannot load package ", sQuote("HSAUR3")) rm(HSAURpkg) a <- Sys.setlocale("LC_ALL", "C") book <- TRUE refs <- cbind(c("AItR", "DAGD", "SI", "CI", "ANOVA", "MLR", "GLM", "DE", "RP", "GAM", "SA", "ALDI", "ALDII", "SIMC", "MA", "PCA", "MDS", "CA"), 1:18) ch <- function(x) { ch <- refs[which(refs[,1] == x),] if (book) { return(paste("Chapter~\\\\ref{", ch[1], "}", sep = "")) } else { return(paste("Chapter~", ch[2], sep = "")) } } if (file.exists("deparse.R")) source("deparse.R") setHook(packageEvent("lattice", "attach"), function(...) { lattice.options(default.theme = function() standard.theme("pdf", color = FALSE)) }) book <- FALSE data("Smoking_Mueller1940", package = "HSAUR3") toLatex(HSAURtable(Smoking_Mueller1940), caption = paste("Smoking and lung cancer case-control study by M\\\"uller (1940).", "The smoking intensities were defined by the number of", "cigarettes smoked daily:", "1-15 (moderate), 16-25 (heavy), 26-35 (very heavy),", "and more than 35 (extreme)."), label = "BI-Smoking_Mueller1940-tab") x <- as.table(Smoking_SchairerSchoeniger1944[, c("Lung cancer", "Healthy control")]) toLatex(HSAURtable(x, xname = "Smoking_SchairerSchoeniger1944"), caption = paste("Smoking and lung cancer case-control study by Schairer and Sch\\\"oniger (1944). Cancer other than lung cancer omitted.", "The smoking intensities were defined by the number of", "cigarettes smoked daily:", "1-5 (moderate), 6-10 (medium), 11-20 (heavy),", "and more than 20 (very heavy)."), label = "BI-Smoking_SchairerSchoeniger1944-tab") data("Smoking_Wassink1945", package = "HSAUR3") toLatex(HSAURtable(Smoking_Wassink1945), caption = paste("Smoking and lung cancer case-control study by Wassink (1945).", "Smoking categories correspond to the categories used by M\\\"uller (1940)."), label = "BI-Smoking_Wassink1945-tab") data("Smoking_DollHill1950", package = "HSAUR3") x <- as.table(Smoking_DollHill1950[,,"Male", drop = FALSE]) toLatex(HSAURtable(x, xname = "Smoking_DollHill1950"), caption = paste("Smoking and lung cancer case-control study (only males) by Doll and Hill (1950).", "The labels for the smoking categories give the number of cigarettes smoked every day."), label = "BI-Smoking_DollHill1950-tab") library("coin") set.seed(29) independence_test(Smoking_Mueller1940, teststat = "quad", distribution = approximate(100000)) ssc <- c(0, 1 + 14 / 2, 16 + 9 / 2, 26 + 9 / 2, 40) independence_test(Smoking_Mueller1940, teststat = "quad", scores = list(Smoking = ssc), distribution = approximate(100000)) eci <- function(model) cbind("Odds (Ratio)" = exp(coef(model)), exp(confint(model))) smoking <- ordered(rownames(Smoking_Mueller1940), levels = rownames(Smoking_Mueller1940)) contrasts(smoking) <- "contr.treatment" eci(glm(Smoking_Mueller1940 ~ smoking, family = binomial())) K <- diag(nlevels(smoking) - 1) K[lower.tri(K)] <- 1 contrasts(smoking) <- rbind(0, K) eci(glm(Smoking_Mueller1940 ~ smoking, family = binomial())) xSS44 <- as.table(Smoking_SchairerSchoeniger1944[, c("Lung cancer", "Healthy control")]) ap <- approximate(100000) pvalue(independence_test(xSS44, teststat = "quad", distribution = ap)) pvalue(independence_test(Smoking_Wassink1945, teststat = "quad", distribution = ap)) xDH50 <- as.table(Smoking_DollHill1950[,, "Male"]) pvalue(independence_test(xDH50, teststat = "quad", distribution = ap)) (M <- rbind(Smoking_Mueller1940[1:2,], colSums(Smoking_Mueller1940[3:5,]))) SS <- Smoking_SchairerSchoeniger1944[, c("Lung cancer", "Healthy control")] (SS <- rbind(SS[1,], colSums(SS[2:3,]), colSums(SS[4:5,]))) (W <- rbind(Smoking_Wassink1945[1:2,], colSums(Smoking_Wassink1945[3:4,]))) DH <- Smoking_DollHill1950[,, "Male"] (DH <- rbind(DH[1,], colSums(DH[2:3,]), colSums(DH[4:6,]))) smk <- c("Nonsmoker", "Moderate smoker", "Heavy smoker") x <- expand.grid(Smoking = ordered(smk, levels = smk), Diagnosis = factor(c("Lung cancer", "Control")), Study = c("Mueller1940", "SchairerSchoeniger1944", "Wassink1945", "DollHill1950")) x$weights <- c(as.vector(M), as.vector(SS), as.vector(W), as.vector(DH)) contrasts(x$Smoking) <- "contr.treatment" x <- x[rep(1:nrow(x), x$weights),] models <- lapply(levels(x$Study), function(s) glm(Diagnosis ~ Smoking, data = x, family = binomial(), subset = Study == s)) names(models) <- levels(x$Study) eci(models[["Mueller1940"]]) eci(models[["SchairerSchoeniger1944"]]) mM40_SS44 <- glm(Diagnosis ~ 0 + Study + Smoking, data = x, family = binomial(), subset = Study %in% c("Mueller1940", "SchairerSchoeniger1944")) eci(mM40_SS44) eci(models[["Wassink1945"]]) mM40_SS44_W45 <- glm(Diagnosis ~ 0 + Study + Smoking, data = x, family = binomial(), subset = Study %in% c("Mueller1940", "SchairerSchoeniger1944", "Wassink1945")) eci(mM40_SS44_W45) eci(models[["DollHill1950"]]) m_all <- glm(Diagnosis ~ 0 + Study + Smoking, data = x, family = binomial()) eci(m_all) r <- eci(m_all) xM <- round(r["SmokingModerate smoker", 2:3], 1) xH <- round(r["SmokingHeavy smoker", 2:3], 1) K <- diag(nlevels(x$Smoking) - 1) K[lower.tri(K)] <- 1 contrasts(x$Smoking) <- rbind(0, K) eci(glm(Diagnosis ~ 0 + Study + Smoking, data = x, family = binomial())) y <- xtabs(~ Study + Smoking + Diagnosis, data = x) ntrtM <- margin.table(y, 1:2)[,"Moderate smoker"] nctrl <- margin.table(y, 1:2)[,"Nonsmoker"] ptrtM <- y[,"Moderate smoker","Lung cancer"] pctrl <- y[,"Nonsmoker","Lung cancer"] ntrtH <- margin.table(y, 1:2)[,"Heavy smoker"] ptrtH <- y[,"Heavy smoker","Lung cancer"] library("rmeta") meta.MH(ntrt = ntrtM, nctrl = nctrl, ptrt = ptrtM, pctrl = pctrl) meta.MH(ntrt = ntrtH, nctrl = nctrl, ptrt = ptrtH, pctrl = pctrl)
VarBiplot <- function(bi1, bi2, b0=0, xmin = -3, xmax = 3, ymin = -3, ymax = 3, label = "Point", mode = "a", CexPoint = 0.8, PchPoint = 1, Color = "blue", ticks = c(-3, -2.5, -2, -1.5, -1, -0.5, 0.5, 1, 1.5, 2, 2.5, 3), ticklabels = round(ticks, digits = 2), tl = 0.03, ts = "Complete", Position="Angle", AddArrow=FALSE, ...) { b1 = bi1/(bi1^2 + bi2^2) b2 = bi2/(bi1^2 + bi2^2) b = b2/b1 x1 = xmin y1 = b * xmin if ((y1 > ymin - 0.001) & (y1 < ymax + 0.001)) if ((x1 * b1 + y1 * b2) < 0) ini = c(x1, y1) else { final = c(x1, y1) markerpos = 2 angle = 0 } x1 = xmax y1 = b * xmax if ((y1 > ymin - 0.001) & (y1 < ymax + 0.001)) if ((x1 * b1 + y1 * b2) < 0) ini = c(x1, y1) else { final = c(x1, y1) markerpos = 4 angle = 0 } x1 = ymin/b y1 = ymin if ((x1 > xmin) & (x1 < xmax)) if ((x1 * b1 + y1 * b2) < 0) ini = c(x1, y1) else { final = c(x1, y1) markerpos = 4 angle = 270 } x1 = ymax/b y1 = ymax if ((x1 > xmin) & (x1 < xmax)) if ((x1 * b1 + y1 * b2) < 0) ini = c(x1, y1) else { final = c(x1, y1) markerpos = 4 angle = 90 } if (mode == "p") { points(bi1, bi2, pch = 16, col = Color, cex = CexPoint, ...) c1 = bi1 c2 = bi2 if (bi1 < 0) markerpos = 2 else markerpos = 4 angle = 0 } if (mode == "a") { arrows(0, 0, bi1, bi2, length = 0.1, angle = 20, col = Color, ...) c1 = bi1 c2 = bi2 if (bi1 < 0) markerpos = 2 else markerpos = 4 angle = 0 } if (mode == "ah") { arrows(0, 0, bi1, bi2, length = 0.1, angle = 20, col = Color, ...) lines(rbind(c(0, 0), final), col = Color, lty=3, ...) c1 = final[1] c2 = final[2] } if (mode == "b") { lines(rbind(ini, final), col = Color, ...) arrows(0, 0, bi1, bi2, length = 0.1, angle = 20, col = Color, lwd=2 , ...) c1 = final[1] c2 = final[2] } if (mode == "h") { lines(rbind(c(0, 0), final), col = Color, ...) c1 = final[1] c2 = final[2] } if (mode == "s") { if (ts == "BoxPlot") { lty = 3 } else { lty = 1 } lines(rbind(ini, final), col = Color, lwd = 1, lty = lty, ...) c1 = final[1] c2 = final[2] ang = atan(bi2/bi1) * 180/pi k = length(ticks) M = cbind((ticks - b0) * b1, (ticks - b0) * b2) deltax <- tl * sin(ang * pi/180) deltay <- tl * cos(ang * pi/180) Mn <- cbind(M[, 1] + deltax, M[, 2] - deltay) for (i in 1:k) { if (InBox(M[i, 1], M[i, 2], xmin, xmax, ymin, ymax)) { lines(rbind(M[i, 1:2], Mn[i, 1:2]), col = Color, lwd = 1, ...) text(Mn[i, 1], Mn[i, 2], ticklabels[i], pos = 1, offset = 0.2, cex = 0.5, srt = ang, col = Color, ...) } } if (ts == "BoxPlot") { points(M[3, 1], M[3, 2], pch = 16, col = Color, ...) lines(rbind(M[2, ], M[4, ]), col = Color, lwd = 2, lty = 1, ...) } } if (AddArrow) arrows(0, 0, bi1, bi2, length = 0.1, angle = 20, col = Color, lwd = 2, ...) if (Position == 'Angle'){ angle=atan(bi2/bi1) * 180/pi if (bi1 < 0) markerpos = 2 else markerpos = 4 } text(c1, c2, label, cex = CexPoint, pos = markerpos, offset = 0.2, srt = angle, col = Color, ...) }
coxRegressionResiduals = function(time,event,datCovariates=NULL) { if (eval(parse(text= '!require("survival")'))) stop("This function requires package survival. Please install it first."); if ( length(time) != length(event) ) { stop("Error: The length of the vector event is unequal to the length of the time vector. In R language: length(time) != length(event)") } if ( is.null(datCovariates) ){ coxmodel=eval(parse(text = "survival:::coxph(Surv(time, event) ~ 1 , na.action = na.exclude)")); } if ( !is.null(datCovariates) ){ if ( dim(as.matrix(datCovariates))[[1]] !=length(event) ) stop("Error: the number of rows of the input matrix datCovariates is unequal to the number of observations specified in the vector event. In R language: dim(as.matrix(datCovariates))[[1]] !=length(event)") coxmodel=eval(parse( text = paste("survival:::coxph(Surv(time, event) ~ . , data=datCovariates,", "na.action = na.exclude, model = TRUE)"))); } datResiduals=data.frame(martingale=residuals(coxmodel,type="martingale"), deviance=residuals(coxmodel,type="deviance")) datResiduals }
idx_second <- seq( ymd_hms("2017-01-01 00:00:01"), ymd_hms("2017-01-01 00:00:05"), by = 1 ) dat_x <- tibble( date_time = idx_second, value = 1 ) tsbl1 <- as_tsibble(dat_x, index = date_time) test_that("illegal input in index_by()", { expect_identical(group_vars(tsbl1 %>% index_by()), "date_time") expect_error(tsbl1 %>% index_by("date_time"), "Unsupported index type:") expect_error(tsbl1 %>% index_by(date_time = date_time), "be overwritten.") expect_error( tsbl1 %>% index_by(as.Date(date_time), yearmonth(date_time)), "only accepts one expression or empty." ) }) test_that("From seconds to higher date", { res1 <- tsbl1 %>% index_by(date_min = ceiling_date(date_time, unit = "min")) %>% summarise(value = sum(value)) expect_equal( as_tibble(res1), tibble(date_min = ymd_hm("2017-01-01 00:01"), value = 5) ) res2 <- tsbl1 %>% index_by(date_min = ceiling_date(date_time, unit = "hour")) %>% summarise(value = sum(value)) expect_equal( as_tibble(res2), tibble(date_min = ymd_h("2017-01-01 01"), value = 5) ) res3 <- tsbl1 %>% index_by(date_min = floor_date(date_time, unit = "day")) %>% summarise(value = sum(value)) expect_equal( as_tibble(res3), tibble(date_min = ymd_h("2017-01-01 0"), value = 5) ) }) idx_day <- seq.Date(ymd("2017-01-01"), ymd("2017-01-20"), by = 4) dat_x <- tibble( date = idx_day, value = 1 ) tsbl2 <- as_tsibble(dat_x, index = date) test_that("From Date to year-week, year-month, year-quarter and year", { res0 <- tsbl2 %>% index_by(yrwk = yearweek(date)) %>% summarise(value = sum(value)) expect_equal( as_tibble(res0), tibble(yrwk = yearweek(ymd(idx_day[-4])), value = c(1, 1, 2, 1)) ) res1 <- tsbl2 %>% index_by(yrmth = yearmonth(date)) %>% summarise(value = sum(value)) expect_equal( as_tibble(res1), tibble(yrmth = yearmonth(ymd("2017-01-01")), value = 5) ) res2 <- tsbl2 %>% index_by(yrqtr = yearquarter(date)) %>% summarise(value = sum(value)) expect_equal( as_tibble(res2), tibble(yrqtr = yearquarter(ymd("2017-01-01")), value = 5) ) res3 <- tsbl2 %>% index_by(yr = year(date)) %>% summarise(value = sum(value)) expect_equal( as_tibble(res3), tibble(yr = year(ymd("2017-01-01")), value = 5) ) res4 <- res1 %>% index_by(yrqtr = yearquarter(yrmth)) %>% summarise(value = sum(value)) expect_equal(res2, res4) res5 <- res2 %>% index_by(yr = year(yrqtr)) %>% summarise(value = sum(value)) expect_equal(res3, res5) }) dat_x <- tibble( date = rep(idx_day, 2), group = rep(letters[1:2], each = 5), value = rep(1:2, each = 5) ) tsbl3 <- as_tsibble(dat_x, key = group, index = date) test_that("index_by() with group_by()", { res1 <- tsbl3 %>% group_by(group) %>% index_by(yrmth = yearmonth(date)) %>% summarise(value = sum(value)) expect_s3_class(res1, "tbl_ts") expect_equal( as_tibble(res1), tibble( group = c("a", "b"), yrmth = yearmonth(ymd("2017-01-01")), value = c(5L, 10L) ) ) }) tsbl4 <- tsibble( date = rep(idx_day, 2), group = rep(letters[1:2], each = 5), value1 = rep(1:2, each = 5), value2 = rnorm(10), value3 = rnorm(10), key = group, index = date ) test_that("summarise() with across()", { ts_if <- tsbl4 %>% index_by(date2 = yearmonth(date)) %>% summarise(across(where(is.numeric), mean)) expect_s3_class(ts_if[["date2"]], "yearmonth") expect_named(ts_if, c("date2", "value1", "value2", "value3")) expect_equal(nrow(ts_if), 1) ts_at <- tsbl4 %>% index_by(date2 = yearmonth(date)) %>% summarise(across(c("value1", "value3"), mean)) expect_s3_class(ts_at[["date2"]], "yearmonth") expect_named(ts_at, c("date2", "value1", "value3")) expect_equal(nrow(ts_at), 1) }) test_that("scoped variants with group_by()", { ts_if <- tsbl4 %>% group_by(group) %>% index_by(yrmth = yearmonth(date)) %>% summarise(across(where(is.numeric), mean)) expect_named(ts_if, c("group", "yrmth", "value1", "value2", "value3")) expect_equal(nrow(ts_if), 2) ts_at <- tsbl4 %>% group_by(group) %>% index_by(yrmth = yearmonth(date)) %>% summarise(across(c("value1", "value3"), mean)) expect_named(ts_at, c("group", "yrmth", "value1", "value3")) expect_equal(nrow(ts_at), 2) tbl <- tourism %>% group_by(Region, State) %>% index_by(Year = year(Quarter)) %>% summarise(across(where(is.numeric), mean)) expect_named(tbl, c("Region", "State", "Year", "Trips")) }) test_that("index_by() with pedestrian", { ped_idx <- pedestrian %>% index_by(yrmth = yearmonth(Date)) expect_s3_class(ped_idx, "grouped_ts") expect_identical(index2(ped_idx), rlang::sym("yrmth")) expect_named(ped_idx, c(names(pedestrian), "yrmth")) ped_fil <- ped_idx %>% filter(Date_Time == min(Date_Time)) ped_ref <- as_tibble(pedestrian) %>% group_by(yrmth = yearmonth(Date)) %>% filter(Date_Time == min(Date_Time)) expect_equal(ped_fil, ped_ref, ignore_attr = TRUE) ped_ren <- ped_fil %>% rename(yrmth2 = yrmth) expect_identical(index2(ped_ren), rlang::sym("yrmth2")) ped_sum <- ped_ren %>% summarise(Total = sum(Count)) expect_named(ped_sum, c("yrmth2", "Total")) expect_identical(index(ped_sum), rlang::sym("yrmth2")) expect_identical(index2(ped_sum), index(ped_sum)) ped_sum2 <- ped_ren %>% group_by(Sensor) %>% summarise(Total = sum(Count)) expect_named(ped_sum2, c("Sensor", "yrmth2", "Total")) expect_identical(index(ped_sum2), rlang::sym("yrmth2")) expect_identical(index2(ped_sum2), index(ped_sum2)) expect_identical(groups(ped_sum2), list()) ped_mut <- pedestrian %>% index_by(Date) %>% mutate(ttl = sum(Count), prop = Count / ttl) expect_identical(group_vars(ped_mut), "Date") ped_sum3 <- ped_mut %>% summarise(ttl_prop = sum(prop)) expect_equal(format(interval(ped_sum3)), "1D") }) test_that("index_by() with lambda expression", { expect_identical( pedestrian %>% index_by(yrmth = ~ yearmonth(.)), pedestrian %>% index_by(yrmth = yearmonth(Date_Time)) ) })
probcure <- function(x, t, d, dataset, x0, h, local = TRUE, conflevel = 0L, bootpars = if (conflevel == 0 && !missing(h)) NULL else controlpars()) { dfr <- if (missing(dataset)) na.omit(data.frame(x, t, d)) else na.omit(dataset[, c(deparse(substitute(x)), deparse(substitute(t)), deparse(substitute(d)))]) names(dfr) <- c("x", "t", "d") dfr$x <- as.numeric(dfr$x) dfr$t <- as.numeric(dfr$t) dfr$d <- as.integer(dfr$d) nrow <- dim(dfr)[1] ordx0 <- order(x0) x0 <- as.numeric(x0[ordx0]) lx0 <- length(x0) if (!local && missing(h)) warning("Option 'local = FALSE' overridden: with missing 'h' a local bootstrap bandwidth is computed") if (missing(h)) { sm <- bootpars$hsmooth h <- if (sm > 1) probcurehboot(x, t, d, dfr, x0, bootpars)$hsmooth else probcurehboot(x, t, d, dfr, x0, bootpars)$h } else { if (local) { if (lx0 != length(h)) stop("When 'local = TRUE', 'x0' and 'h' must have the same length") h <- as.numeric(h[ordx0]) } else { h <- as.numeric(h) } } lh <- length(h) if (conflevel < 0 | conflevel > 1) stop("'conflevel' must be a number between 0 and 1") dfr <- dfr[order(dfr$t, 1 - dfr$d),] q <- .Call("probcurenp0", dfr$t, dfr$x, dfr$d, nrow, x0, lx0, h, lh, local, PACKAGE = "npcure") if (!local) { names(q) <- paste("h", as.character(round(h, 8)), sep = "") q <- as.list(q) } if (conflevel > 0) { B <- bootpars$B fpilot <- bootpars$fpilot if (is.null(fpilot)) { pilot <- hpilot(dfr$x, x0, bootpars$nnfrac) } else pilot <- do.call(fpilot, c(list(x0 = x0), bootpars$dots)) band <- .Call("probcurenp0confband", dfr$t, dfr$x, dfr$d, nrow, x0, lx0, h, lh, 1 - (1 - conflevel)/2, B, pilot, q, local, PACKAGE = "npcure") if (local) names(band) <- c("lower", "upper") else { names(band) <- paste("h", as.character(round(h, 8)), sep = "") for (i in 1:lh) { names(band[[i]]) <- c("lower", "upper") } } structure(list(type = "cure", local = local, h = h, x0 = x0, q = q, conf = band, conflevel = conflevel), class = "npcure") } else structure(list(type = "cure", local = local, h = h, x0 = x0, q = q), class = "npcure") }
check_valid_app <- function(x, ...) { checkmate::check_string( x, min.chars = 30, pattern = "^[a-zA-Z0-9]{30}$", ... ) } test_valid_app <- checkmate::makeTestFunction(check_valid_app) assert_valid_app <- checkmate::makeAssertionFunction(check_valid_app)
filter_county_poly <- function(...) { input <- unlist(list(...)) counties <- input %>% standardize_county_names() %>% lapply(function(x) { if (x %in% wdnr.gis::wi_counties$county) { wdnr.gis::wi_counties[wdnr.gis::wi_counties$county == x, ] } else { return(NULL) } }) county_chk <- unlist(lapply(counties, is.null)) if (any(county_chk)) { if (any(!county_chk)) { warning("One or more counties may be missing") return(do.call("rbind", counties)) } else { stop("Are you sure that's a county in Wisconsin?") } } else { return(do.call("rbind", counties)) } }
plot.BTLLasso <- function(x, plots_per_page = 1, ask_new = TRUE, rescale = FALSE, which = "all", equal.ranges = FALSE, x.axis = c("loglambda", "lambda"), rows = NULL, subs.X = NULL, subs.Z1 = NULL, main.Z2 = "Obj-spec. Covariates", ...) { op <- par(no.readonly = TRUE) if(length(x$lambda)==1){ stop("Only one tuning parameter, nothing to plot!") } x.axis <- match.arg(x.axis) if (x.axis == "lambda") { norm <- x$lambda norm.range <- rev(range(norm)) x.axis.name <- expression(lambda) } if (x.axis == "loglambda") { norm <- log(x$lambda + 1) norm.range <- rev(range(norm)) x.axis.name <- expression(log(lambda + 1)) } m <- x$Y$m n.theta <- x$design$n.theta n.order <- x$design$n.order n.intercepts <- x$design$n.intercepts if (n.intercepts > 0) { n.intercepts <- n.intercepts + 1 } p.X <- x$design$p.X p.Z1 <- x$design$p.Z1 p.Z2 <- x$design$p.Z2 labels <- x$Y$object.names coefs <- x$coefs.repar y.range <- NA if(equal.ranges){ y.range <- range(coefs) } coef.plot <- c() index.plots <- c() index.num <- 1 all.labs <- c() all.mains <- c() all.subs <- c() if (n.order > 0) { order.effects <- coefs[, (n.theta + 1):(n.theta + n.order)] coef.plot <- cbind(coef.plot, order.effects) index.plots <- c(index.plots, rep(index.num,n.order)) index.num <- index.num+1 if(n.order>1){ all.labs <- c(all.labs,labels) }else{ all.labs <- c(all.labs,"") } all.mains <- c(all.mains, x$control$name.order) all.subs <- c(all.subs, "") } if (n.intercepts > 0) { intercepts <- coefs[, (n.theta + n.order + 1):(n.theta + n.order + n.intercepts), drop = FALSE] coef.plot <- cbind(coef.plot, intercepts) index.plots <- c(index.plots, rep(index.num, n.intercepts)) index.num <- index.num+1 all.labs <- c(all.labs,labels) all.mains <- c(all.mains, "Intercepts") all.subs <- c(all.subs, "") } if (p.X > 0) { gamma.X <- coefs[, (n.theta + n.order + n.intercepts + 1):(n.theta + n.order + n.intercepts + p.X * m), drop = FALSE] if (rescale) { gamma.X <- t(t(gamma.X)/rep(x$design$sd.X, each = m)) } coef.plot <- cbind(coef.plot, gamma.X) index.plots <- c(index.plots, rep(index.num:(index.num+p.X-1), each=m)) index.num <- index.num+p.X all.labs <- c(all.labs,rep(labels,p.X)) all.mains <- c(all.mains, x$design$vars.X) all.subs <- c(all.subs, subs.X) } if (p.Z1 > 0) { gamma.Z1 <- coefs[, (n.theta + n.order + n.intercepts + p.X * m + 1):(n.theta + n.order + n.intercepts + p.X * m + p.Z1 * m), drop = FALSE] if (rescale) { gamma.Z1 <- t(t(gamma.Z1)/rep(x$design$sd.Z1, each = m)) } coef.plot <- cbind(coef.plot, gamma.Z1) index.plots <- c(index.plots, rep(index.num:(index.num+p.Z1-1), each=m)) index.num <- index.num+p.Z1 all.labs <- c(all.labs,rep(labels,p.Z1)) all.mains <- c(all.mains, x$design$vars.Z1) all.subs <- c(all.subs, subs.Z1) } if (p.Z2 > 0) { gamma.Z2 <- coefs[, (n.theta + n.order + n.intercepts + p.X * m + p.Z1 * m + 1):(n.theta + n.order + n.intercepts + p.X * m + p.Z1 * m + p.Z2), drop = FALSE] if (rescale) { gamma.Z2 <- t(t(gamma.Z2)/x$design$sd.Z2) } coef.plot <- cbind(coef.plot, gamma.Z2) index.plots <- c(index.plots, rep(index.num, p.Z2)) index.num <- index.num+1 all.labs <- c(all.labs,x$design$vars.Z2) all.mains <- c(all.mains, main.Z2) all.subs <- c(all.subs, "") } n.plots <- index.num-1 suppressWarnings(if(which=="all"){ which <- 1:n.plots }) pages <- ceiling(length(which)/plots_per_page) if (is.null(rows)) { rows <- floor(sqrt(plots_per_page)) } cols <- ceiling(plots_per_page/rows) plots_on_page <- 0 pages_done <- 0 par(mfrow=c(rows, cols)) for(u in 1:n.plots){ if(u %in% which){ plot.comp(u, norm, coef.plot, index.plots, all.labs, all.mains, all.subs, y.range, x.axis.name, x$criterion, norm.range, ...) plots_on_page <- plots_on_page+1 if(plots_on_page==plots_per_page & pages_done<(pages-1)){ plots_on_page <- 0 pages_done <- pages_done+1 if(interactive() & ask_new) {readline("Press enter for next plot!")} par(mfrow=c(rows, cols)) } } } par(op) } plot.comp <- function(u, norm, coef.plot, index.plots, all.labs, all.mains, all.subs, y.range, x.axis.name, criterion, norm.range, ...){ if (!is.null(criterion)) { x.axis.min <- norm[which.min(criterion)] } index.u <- which(index.plots==u) l.u <- length(index.u) cur.coef <- coef.plot[,index.u,drop=FALSE] final.u <- cur.coef[nrow(cur.coef),] if(is.na(y.range)){ y.range.u <- range(cur.coef) }else{ y.range.u <- y.range } plot(norm, cur.coef[,1], ylim = y.range.u, type = "l", main = "", ylab = "estimates", xlab = x.axis.name, xlim = norm.range, frame.plot = FALSE, lwd=par()$lwd, ...) if(l.u>1){ for (uu in 2:l.u) { lines(norm, cur.coef[, uu], lwd=par()$lwd) } } title(main = all.mains[u], line = 1.2) mtext(all.subs[u], side = 3, line = 0.2, cex = par()$cex) if (!is.null(criterion)) { segments( x.axis.min, min(y.range.u), x.axis.min, max(y.range.u) , col=2,lty=2,lwd=par()$lwd) } x.lab1 <- norm[length(norm)]-abs(diff(range(norm)))*0.02 x.lab2 <- norm[length(norm)]-abs(diff(range(norm)))*0.005 y.lab1 <- final.u y.lab2 <- spread.labs(y.lab1, 1.2*strheight("A")) text( x.lab1, y.lab2, all.labs[index.u],pos=4) segments( x.lab2, y.lab1, x.lab1, y.lab2 ,col="gray") }
print.mcp1 <- function(x,...) { cat("Call:\n") print(x$call) cat("\n") df <- x$comp gnames1 <- x$fnames[x$comp[,1]] gnames2 <- x$fnames[x$comp[,2]] rownames(df) <- paste(gnames1, gnames2, sep = " vs. ") if (ncol(df) > 6) { if (colnames(df)[7] == "crit") { sig <- ifelse(abs(x$comp[,6]) > x$comp[,7], TRUE, FALSE) df <- round(df, 5) df <- data.frame(df, sig) colnames(df)[6] <- "test" print(df[,-c(1:2)]) } else { print(as.data.frame(round(df[,-c(1:2)], 5))) } } else { print(as.data.frame(round(df[,-c(1:2)], 5))) } cat("\n") }
Model.Counts <- function(parameter,model.type,model.name,link,covariates.matrix.mean, covariates.matrix.scalef,offset.mean,offset.scalef, fixed.b,vnmax) { if (model.type=="mean only") { output <- Model.Faddy(parameter,model.name,link,covariates.matrix.mean, offset.mean,fixed.b,vnmax) } if (model.type=="mean and scale-factor") { if ((model.name=="general") | (model.name=="general fixed b")) { output <- Model.FaddyJMV.general(parameter,link,covariates.matrix.mean, covariates.matrix.scalef,offset.mean, offset.scalef,fixed.b,vnmax) } if (model.name=="limiting") { output <- Model.FaddyJMV.limiting(parameter,link,covariates.matrix.mean, covariates.matrix.scalef,offset.mean, offset.scalef,vnmax) } } return(output) }
library(dplyr) library(ggplot2) library(HTSSIP) padj_cutoff = 0.1 physeq_S2D2_l physeq = physeq_S2D2_l[[1]] physeq physeq %>% sample_data %>% .$Substrate %>% table df_res = heavy_SIP(physeq, ex="Substrate=='12C-Con'", comparison='H-v-H', hypo_test='binary') df_res %>% head(n=3) df_res$statistic %>% table physeq_rep3 physeq_rep3 %>% sample_data %>% head(n=3) df_res = heavy_SIP(physeq_rep3, ex="Treatment=='12C-Con'", comparison='H-v-H', hypo_test='t-test') df_res %>% head(n=3) df_res %>% filter(padj < padj_cutoff) %>% nrow df_res$p %>% summary df_res = heavy_SIP(physeq_rep3, ex="Treatment=='12C-Con'", comparison='H-v-H', hypo_test='wilcox') df_res %>% head(n=3) df_res$p %>% summary %>% print df_res$padj %>% summary %>% print sessionInfo()
library(GALLO) data("QTLmarkers") DT::datatable(QTLmarkers, rownames = FALSE, extensions = 'FixedColumns', options = list(scrollX = TRUE)) dim(QTLmarkers) data("QTLwindows") DT::datatable(QTLwindows, rownames = FALSE, extensions = 'FixedColumns', options = list(scrollX = TRUE)) dim(QTLwindows) data("gffQTLs") DT::datatable(gffQTLs[1:100,], rownames = FALSE, extensions = 'FixedColumns', options = list(scrollX = TRUE)) dim(gffQTLs) data("gtfGenes") DT::datatable(gtfGenes[1:100,], rownames = FALSE, extensions = 'FixedColumns', options = list(scrollX = TRUE)) dim(gtfGenes) out.genes<-find_genes_qtls_around_markers(db_file=gtfGenes, marker_file=QTLmarkers, method = "gene", marker = "snp", interval = 500000, nThreads = 1) DT::datatable(out.genes, rownames = FALSE, extensions = 'FixedColumns', options = list(scrollX = TRUE)) dim(out.genes) out.qtls<-find_genes_qtls_around_markers(db_file=gffQTLs, marker_file=QTLmarkers, method = "qtl", marker = "snp", interval = 500000, nThreads = 1) DT::datatable(out.qtls, rownames = FALSE, extensions = 'FixedColumns', options = list(scrollX = TRUE)) dim(out.qtls) out.genes.unique<-out.genes[!duplicated(out.genes[c("Reference","gene_id")]),] overlap.genes<-overlapping_among_groups(file=out.genes.unique, x="Reference", y="gene_id") overlap.genes group.labels<-unique(out.genes.unique$Reference) plot_overlapping(overlap.genes, nmatrix=2, ntext=3, group=group.labels, labelcex = 1) oldpar <- par(mar=c(0.5,15,0.5,1)) plot_qtl_info(out.qtls, qtl_plot = "qtl_type", cex=1.5) par(oldpar) oldpar<-par(mar=c(5,20,1,1)) plot_qtl_info(out.qtls, qtl_plot = "qtl_name", qtl_class="Reproduction") par(oldpar) out.enrich<-qtl_enrich(qtl_db=gffQTLs, qtl_file=out.qtls, qtl_type = "Name", enrich_type = "chromosome", chr.subset = NULL, padj ="fdr",nThreads = 1) DT::datatable(out.enrich[order(out.enrich$pvalue),], rownames = FALSE, extensions = 'FixedColumns', options = list(scrollX = TRUE)) out.enrich$ID<-paste(out.enrich$QTL," - ","CHR",out.enrich$CHR,sep="") out.enrich.filtered<-out.enrich[which(out.enrich$adj.pval<0.05),] out.enrich.filtered$new_pval<-out.enrich.filtered$adj.pval out.enrich.filtered[which(out.enrich.filtered$new_pval<(5^-50)),"new_pval"]<-(5^-50) QTLenrich_plot(out.enrich.filtered, x="ID", pval="new_pval") out.qtls$ID<-paste(out.qtls$Name," - ","CHR",out.qtls$CHR,sep="") out.enrich.filtered<-out.enrich.filtered[ order(out.enrich.filtered$adj.pval),] out.qtls.filtered<-out.qtls[ which(out.qtls$ID%in%out.enrich.filtered$ID[1:10]),] out.qtls.filtered[which( out.qtls.filtered$Reference=="Feugang et al. (2010)"), "color_ref"]<-"purple" out.qtls.filtered[which( out.qtls.filtered$Reference== "Buzanskas et al. (2017)"), "color_ref"]<-"pink" color.grid<-c(rep("black", length(unique(out.qtls.filtered$Abbrev))), out.qtls.filtered[!duplicated(out.qtls.filtered$SNP.reference),"color_ref"]) names(color.grid)<-c(unique( out.qtls.filtered$Abbrev),unique( out.qtls.filtered$SNP.reference)) relationship_plot(qtl_file=out.qtls.filtered, x="Abbrev", y="SNP.reference", cex=1,gap=2.5,degree = 60, canvas.xlim = c(-1.5, 1.5),canvas.ylim = c(-1.5, 1.5),grid.col = color.grid)
calc_chi2 <- function(a,b,c,d, correct=T, cochrans_criteria=F){ n = a+b+c+d sums = cbind(c1 = a+c, c2 = b+d, r1 = a+b, r2 = c+d) yates_correction = if (correct) rep(T, nrow(sums)) else rep(F, nrow(sums)) if (cochrans_criteria) yates_correction = test_cochran(a,b,c,d) x = as.numeric(a)*as.numeric(d) - as.numeric(b)*as.numeric(c) x = ifelse(yates_correction, abs(x) - n/2, x) chi = n*x^2 / (as.numeric(sums[,'c1']) * as.numeric(sums[,'c2']) * as.numeric(sums[,'r1']) * as.numeric(sums[,'r2'])) ifelse(is.na(chi), 0, chi) } test_cochran <- function(a,b,c,d){ n = a+b+c+d sums = cbind(c1 = a+c, c2 = b+d, r1 = a+b, r2 = c+d) e = cbind(sums[,'c1'] / n, sums[,'c2'] / n) e = cbind(e * sums[,'r1'], e * sums[,'r2']) c1 = rowSums(e < 1) > 0 c2 = rowSums(sums < 5) > 0 c1 | c2 }