code
stringlengths
1
13.8M
source("common.r") png(file="earnings_monthly_by_currency.png", width=default_width, height=default_height, res=120) op <- par(mar=c(5,2,2,6), lty=0) res <- dbGetQuery(con, " select currency, date_trunc('month', created_at) sum_month, sum(price) from purchases where status = 1 group by sum_month, currency having sum(price) > 1 order by sum_month asc ") res$sum_month <- as.Date(res$sum_month) res <- truncate_dates(res, "sum_month") grouped <- tapply(res$sum, list(month=res$sum_month, currency=res$currency), identity) grouped[is.na(grouped)] <- 0 grouped <- floor(grouped / 100) money_cap = max(apply(grouped, 1, sum)) grouped = t(grouped) barplot(grouped, col=colors, axes=FALSE, ann=FALSE, names=format_months(unique(res$sum_month)), las=2) money_axis(money_cap) par(lty=1) legend("topleft", names(grouped[,1]), fill=colors) title(main="Seller earnings per month by currency")
snpprob_from_cross <- function(genoprobs, cross) { if(!("founder_geno" %in% names(cross))) stop("cross doesn't contain founder_geno") fg <- do.call("cbind", cross$founder_geno) mar2drop <- colnames(fg)[colSums(fg != 1 & fg != 3) > 0 | colSums(fg==1)==0 | colSums(fg==3)==0] cross <- drop_markers(cross, mar2drop) chr_pr <- names(genoprobs) chr_cross <- chr_names(cross) chr <- chr_pr[chr_pr %in% chr_cross] cross <- cross[,chr] genoprobs <- genoprobs[,chr] map <- cross$pmap if(is.null(map)) map <- cross$gmap sdp <- calc_sdp(t(do.call("cbind", cross$founder_geno))) snpinfo <- data.frame(chr=rep(chr_names(cross), n_mar(cross)), pos=unlist(map), sdp=sdp, snp=names(sdp)) mar2keep <- NULL for(i in seq_along(genoprobs)) { mar <- colnames(cross$geno[[i]]) mar <- mar[mar %in% dimnames(genoprobs)[[3]][[i]]] if(length(mar) == 0) { stop("No overlap between genoprobs and markers on chr ", names(genoprobs)[i]) } map[[i]] <- map[[i]][mar] if(inherits(genoprobs, "fst_genoprob")) { mar2keep <- c(mar2keep, mar) } else { genoprobs[[i]] <- genoprobs[[i]][,,mar,drop=FALSE] } } if(inherits(genoprobs, "fst_genoprob")) { genoprobs <- subset(genoprobs, mar=mar2keep) } snpinfo <- index_snps(map, snpinfo) genoprob_to_snpprob(genoprobs, snpinfo) }
context("test-CondBED") test_that("Whether the function gives us the correct specified length", { Data=rBED(n=100,Betax=1,Betay=1,rho=0.85) Resp=CondBED(rho=0.85,Betax=1,Betay=1,x=Data[,1]) expect_length(Resp$Conditional_Statistics$x,100)})
set_env <- function(root = NULL, new = FALSE, dev = FALSE, ...) { dots <- list(...) if ("qgis_env" %in% ls(.RQGIS_cache) && new == FALSE) { return(get("qgis_env", envir = .RQGIS_cache)) } if (Sys.info()["sysname"] == "Windows") { if (is.null(root)) { cwd <- getwd() on.exit(setwd(cwd)) osgeo <- c("C:/OSGEO4~1", "C:/OSGEO4~2") ind <- dir.exists(osgeo) osgeo <- osgeo[ind] wd <- ifelse(length(osgeo) > 0, osgeo[1], "C:/") message(sprintf("Trying to find QGIS LTR in %s", wd)) setwd(wd) raw <- "dir /s /b | %SystemRoot%\\System32\\findstr /r" cmd <- paste(raw, shQuote("bin\\\\qgis.bat$ | bin\\\\qgis-ltr.bat$")) root <- shell(cmd, intern = TRUE) if (length(root) == 0) { stop( "Sorry, we could not find QGIS on your C: drive. ", "Please specify the root to your QGIS-installation ", "manually." ) } else if (length(root) > 2) { stop( "There are several QGIS installations on your system. ", "Please choose one of them:\n", paste(unique(gsub("\\\\bin.*", "", root)), collapse = "\n") ) } else { root <- gsub("\\\\bin.*", "", root[1]) } } root <- normalizePath(root, winslash = "/") root <- gsub("/{1,}$", "", root) } if (Sys.info()["sysname"] == "Darwin") { if (is.null(root)) { message("Checking for homebrew osgeo4mac installation on your system. \n") path <- suppressWarnings( system2( "find", c("/usr/local/Cellar", "-name", "QGIS.app"), stdout = TRUE, stderr = TRUE ) ) no_homebrew <- str_detect(path, "find: /usr/local") if (is.na(no_homebrew[1])) { message(paste0( "Found no QGIS homebrew installation. ", "Checking for QGIS Kyngchaos version now." )) } if (no_homebrew == FALSE && length(path) == 1) { root <- path message("Found QGIS osgeo4mac installation. Setting environment...") } if (length(path) >= 2) { path1 <- as.numeric(regmatches(path[1], gregexpr("[0-9]+", path[1]))[[1]][3]) path2 <- as.numeric(regmatches(path[2], gregexpr("[0-9]+", path[2]))[[1]][3]) if (length(path) == 3) { path3 <- as.numeric(regmatches(path[3], gregexpr("[0-9]+", path[3]))[[1]][3]) } if (dev == TRUE && path1 > path2) { root <- path[1] message("Found QGIS osgeo4mac DEV installation. Setting environment...") } else if (dev == TRUE && path1 < path2) { root <- path[2] message("Found QGIS osgeo4mac DEV installation. Setting environment...") } else if (dev == FALSE && path1 > path2) { root <- path[2] message("Found QGIS osgeo4mac LTR installation. Setting environment...") } else if (dev == FALSE && path1 < path2) { root <- path[1] message("Found QGIS osgeo4mac LTR installation. Setting environment...") } } if (is.null(root)) { path <- system("find /Applications -name 'QGIS.app'", intern = TRUE) if (length(path) > 0) { root <- path message("Found QGIS Kyngchaos installation. Setting environment...") } } } } if (Sys.info()["sysname"] == "Linux") { if (is.null(root)) { message("Assuming that your root path is '/usr'!") root <- "/usr" } } if (Sys.info()["sysname"] == "FreeBSD") { if (is.null(root)) { message("Assuming that your root path is '/usr/local'!") root <- "/usr/local" } } qgis_env <- list(root = root) qgis_env <- c(qgis_env, check_apps(root = root, dev = dev)) assign("qgis_env", qgis_env, envir = .RQGIS_cache) if (any(grepl("/Applications", qgis_env))) { warning( paste0( "We recognized that you are using the Kyngchaos QGIS binary.\n", "Please consider installing QGIS from homebrew:", "'https://github.com/OSGeo/homebrew-osgeo4mac'.", " Run 'vignette(install_guide)' for installation instructions.\n", "The Kyngchaos installation throws some warnings during ", "processing. However, usage/outcome is not affected and you can ", "continue using the Kyngchaos installation." ) ) } qgis_env } open_app <- function(qgis_env = set_env()) { check_for_server() settings <- as.list(Sys.getenv()) if (Sys.info()["sysname"] == "Windows") { setup_win(qgis_env = qgis_env) reset_path(settings) } else if (Sys.info()["sysname"] == "Linux" | Sys.info()["sysname"] == "FreeBSD") { setup_linux(qgis_env = qgis_env) } else if (Sys.info()["sysname"] == "Darwin") { setup_mac(qgis_env = qgis_env) } tmp <- try( expr = py_run_string("app")$app, silent = TRUE ) if (!inherits(tmp, "try-error")) { stop("Python QGIS application is already running.") } py_cmd = paste0( "try:\n from pyvirtualdisplay import Display\n", " display = Display(visible=False, size=(1024, 768), color_depth=24)\n", " display.start()\n", "except:\n pass") py_run_string(py_cmd) py_run_string("import os, sys, re, webbrowser") py_run_string("from qgis.core import *") py_run_string("from osgeo import ogr") py_run_string("from PyQt4.QtCore import *") py_run_string("from PyQt4.QtGui import *") py_run_string("from qgis.gui import *") set_prefix <- paste0( "QgsApplication.setPrefixPath(r'", qgis_env$qgis_prefix_path, "', True)" ) py_run_string(set_prefix) py_run_string("QgsApplication.showSettings()") py_run_string("app = QgsApplication([], True)") py_run_string("QgsApplication.initQgis()") code <- paste0("sys.path.append(r'", qgis_env$python_plugins, "')") py_run_string(code) Sys.setlocale("LC_NUMERIC", "C") py_file <- system.file("python", "python_funs.py", package = "RQGIS") py_run_file(py_file) py_run_string("RQGIS = RQGIS()") } qgis_session_info <- function(qgis_env = set_env()) { tmp <- try(expr = open_app(qgis_env = qgis_env), silent = TRUE) suppressWarnings( out <- py_run_string("my_session_info = RQGIS.qgis_session_info()")$my_session_info ) py_run_string( "try:\n del(my_session_info)\nexcept:\ pass" ) if ((Sys.info()["sysname"] == "Linux" | Sys.info()["sysname"] == "FreeBSD") && (out$grass6 | out$grass7)) { cmd <- paste0( "find /usr ! -readable -prune -o -type f ", "-executable -iname 'grass??' -print" ) suppressWarnings({ my_grass <- system(cmd, intern = TRUE, ignore.stderr = TRUE) }) iter <- 15 while (length(my_grass) == 0 && iter > 0) { suppressWarnings({ my_grass <- try(system(cmd, intern = TRUE, ignore.stderr = TRUE), silent = TRUE) }) } if (length(my_grass) > 0) { my_grass <- lapply(seq(length(my_grass)), function(i) { version <- grep( readLines(my_grass), pattern = "grass_version = \"", value = TRUE ) version <- paste( unlist(stringr::str_extract_all(version, "\\d(\\.)?")), collapse = "" ) }) my_grass <- unlist(my_grass) grass6 <- grep("6", my_grass, value = TRUE) out$grass6 <- ifelse(length(grass6) == 0, out$grass6, grass6) grass7 <- grep("7", my_grass, value = TRUE) out$grass7 <- ifelse(length(grass7) == 0, out$grass7, grass7) } } out = out[c("qgis_version", "gdal", "grass6", "grass7", "saga", "supported_saga_versions")] if (length(out$supported_saga_versions) == 1 && out$supported_saga_versions == "") { out[names(out) != "supported_saga_versions"] } else { out } } find_algorithms <- function(search_term = NULL, name_only = FALSE, qgis_env = set_env()) { tmp <- try(expr = open_app(qgis_env = qgis_env), silent = TRUE) algs <- py_capture_output(py_run_string("processing.alglist()")) algs <- gsub("\n", "', '", algs) algs <- unlist(strsplit(algs, "', |, '")) algs <- unlist(strsplit(algs, '", ')) algs <- gsub("\\['|'\\]|'", "", algs) if (Sys.info()["sysname"] == "Windows") { algs <- gsub('\\\\|"', "", shQuote(algs)) } else { algs <- gsub('\\\\|"', "", algs) } algs <- algs[algs != ""] if (!is.null(search_term)) { algs <- grep(search_term, algs, value = TRUE) } if (name_only) { algs <- gsub(".*>", "", algs) } algs } get_usage <- function(alg = NULL, intern = FALSE, qgis_env = set_env()) { tmp <- try(expr = open_app(qgis_env = qgis_env), silent = TRUE) out <- py_capture_output(py_run_string(sprintf("processing.alghelp('%s')", alg))) out <- gsub("^\\[|\\]$|'", "", out) out <- gsub(", ", "\n", out) if (intern) { out } else { cat(gsub("\\\\t", "\t", out)) } } get_options <- function(alg = "", intern = FALSE, qgis_env = set_env()) { tmp <- try(expr = open_app(qgis_env = qgis_env), silent = TRUE) out <- py_capture_output(py_run_string( sprintf("processing.algoptions('%s')", alg) )) out <- gsub("^\\[|\\]$|'", "", out) out <- gsub(", ", "\n", out) if (intern) { out } else { cat(gsub("\\\\t", "\t", out)) } } open_help <- function(alg = "", qgis_env = set_env()) { tmp <- try(expr = open_app(qgis_env = qgis_env), silent = TRUE) algs <- find_algorithms(name_only = TRUE, qgis_env = qgis_env) if (!alg %in% algs) { stop("The specified algorithm ", alg, " does not exist.") } if (grepl("grass", alg)) { open_grass_help(alg) } else { algName <- alg url = py_run_string(sprintf("url = RQGIS.open_help('%s')", algName))$url browseURL(url) } } get_args_man <- function(alg = "", options = TRUE, qgis_env = set_env()) { tmp <- try(expr = open_app(qgis_env = qgis_env), silent = TRUE) algs <- find_algorithms(name_only = TRUE, qgis_env = qgis_env) if (!alg %in% algs) { stop("The specified algorithm ", alg, " does not exist.") } args <- py_run_string( sprintf( "algorithm_params = RQGIS.get_args_man('%s')", alg ) )$algorithm_params if (options && length(args$vals[args$opts]) > 0) { args$vals[args$opts] <- "0" msg <- paste(paste0(args$params[args$opts], ": 0"), collapse = "\n") message( "Choosing default values for following parameters:\n", msg, "\n", "See get_options('", alg, "') for all available options." ) } py_run_string( "try:\n del(algorithm_params)\nexcept:\ pass" ) out <- as.list(args$vals) names(out) <- args$params out } pass_args <- function(alg, ..., params = NULL, NA_flag = -99999, qgis_env = set_env()) { dots <- list(...) if (!is.null(params) && (length(dots) > 0)) { stop(paste( "Use either QGIS parameters as R arguments,", "or as a parameter argument list object, but not both" )) } if (length(dots) > 0) { params <- dots } dups <- duplicated(names(params)) if (any(dups)) { stop( "You have specified following parameter(s) more than once: ", paste(names(params)[dups], collapse = ", ") ) } suppressMessages( params_all <- get_args_man(alg, options = TRUE) ) ind <- setdiff(names(params), names(params_all)) if (length(ind) > 0) { stop( paste(sprintf("'%s'", ind), collapse = ", "), " is/are (an) invalid function argument(s). \n\n", sprintf("'%s'", alg), " allows following function arguments: ", paste(sprintf("'%s'", names(params_all)), collapse = ", ") ) } params_2 <- params_all params_2[names(params)] <- params params <- params_2 rm(params_2) args <- py_run_string( sprintf( "algorithm_params = RQGIS.get_args_man('%s')", alg ) )$algorithm_params ind_2 <- args$params[args$opts] %in% ind if (any(ind_2)) { msg <- paste(paste0(args$params[args$opts][ind_2], ": 0"), collapse = "\n") message( "Choosing default values for following parameters:\n", msg, "\n", "See get_options('", alg, "') for all available options." ) } opts <- py_run_string(sprintf("opts = RQGIS.get_options('%s')", alg))$opts opts <- lapply(opts, function(x) { data.frame(name = x, number = 0:(length(x) - 1), stringsAsFactors = FALSE) }) int <- intersect(names(params), names(opts)) ls_1 <- lapply(int, function(x) { if (grepl("saga:", alg)) { saga_test <- gsub("\\[\\d\\] ", "", opts[[x]]$name) } else { saga_test <- opts[[x]]$name } if (params[[x]] %in% c(opts[[x]]$name, saga_test)) { opts[[x]][ opts[[x]]$name == params[[x]] | saga_test == params[[x]], "number" ] } else { test <- suppressWarnings(try(as.numeric(params[[x]]), silent = TRUE)) if (!is.na(test)) { if (!test %in% opts[[x]]$number) { stop( x, " only accepts these values: ", paste(opts[[x]]$number, collapse = ", "), "\nYou specified: ", test ) } } params[[x]] } }) params[int] <- ls_1 out <- py_run_string(sprintf("out = RQGIS.get_args_man('%s')", alg))$out params[!out$output] <- save_spatial_objects( params = params[!out$output], type_name = out$type_name, NA_flag = NA_flag ) params[out$output] <- lapply(params[out$output], function(x) { if (basename(x) != "None" && dirname(x) == ".") { tmp = normalizePath(getwd(), winslash = "/") tmp = gsub("^\\\\\\\\", "//", tmp) file.path(tmp, x) } else if (basename(x) != "None") { normalizePath(dirname(x), winslash = "/", mustWork = TRUE) tmp = normalizePath(x, winslash = "/", mustWork = FALSE) gsub("^\\\\\\\\", "//", tmp) } else { x } }) ind = out$type_name == "extent" & (params == "\"None\"" | params == "None") if (any(ind)) { ext <- get_extent( params = params[!out$output], type_name = out$type_name[!out$output] ) params[ind] <- paste(ext, collapse = ",") } params <- params[names(params_all)] check <- py_run_string(sprintf( "check = RQGIS.check_args('%s', %s)", alg, py_unicode(r_to_py(unlist(params))) ))$check if (length(check) > 0) { stop(sprintf( "Invalid argument value '%s' for parameter '%s'\n", check, names(check) )) } py_run_string( "try:\n del(out, opts, check)\nexcept:\ pass" ) params } run_qgis <- function(alg = NULL, ..., params = NULL, load_output = FALSE, show_output_paths = TRUE, NA_flag = -99999, qgis_env = set_env()) { tmp <- try(expr = open_app(qgis_env = qgis_env), silent = TRUE) if (alg == "qgis:vectorgrid") { stop("Please use qgis:creategrid instead of qgis:vectorgrid!") } if (grepl("^qgis\\:selectby", alg)) { stop(paste( "The 'Select by' operations of QGIS are interactive.", "Please use 'grass7:v.extract' instead." )) } params <- pass_args(alg, ..., params = params, NA_flag = NA_flag, qgis_env = qgis_env) vals <- vapply(params, function(x) { tmp <- unlist(strsplit(as.character(x), "")) tmp <- tmp[tmp != "\""] tmp <- paste(tmp, collapse = "") ifelse(grepl("True|False|None", tmp), tmp, shQuote(tmp)) }, character(1)) args <- paste(vals, collapse = ", ") py_run_string(paste("args = ", r_to_py(args))) py_run_string(paste0("params = ", py_unicode(r_to_py(names(params))))) py_run_string("params = dict((x, y) for x, y in zip(params, args))") cmd <- paste(sprintf("res = processing.runalg('%s', params)", alg)) msg <- py_capture_output(py_run_string(cmd)) if (grepl("Unable to execute algorithm|Error", msg)) { stop(msg) } res <- py_run_string("res")$res if (show_output_paths) { print(res) } if (msg != "") { message(msg) } py_run_string( "try:\n del(res, args, params)\nexcept:\ pass" ) if (load_output) { out_names <- py_run_string( sprintf("out_names = RQGIS.get_args_man('%s')", alg) )$out_names out_names <- out_names$params[out_names$output] py_run_string( "try:\n del(out_names)\nexcept:\ pass" ) params_out <- params[out_names] out_files <- params_out[params_out != "None"] ls_1 <- lapply(out_files, function(x) { if (!file.exists(x)) { stop("Unfortunately, QGIS did not produce: ", x) } capture.output({ test <- try(expr = read_sf(x), silent = TRUE) }) if (inherits(test, "try-error")) { raster(x) } else { test } }) if (length(ls_1) == 1) { ls_1[[1]] } else { ls_1 } } }
sobolrep <- function(model=NULL, factors, N, tail=TRUE, conf=0.95, nboot=0, nbrep=1, total=FALSE, ...) { if (is.character(factors)) { X.labels <- factors d <- length(X.labels) } else if (factors%%1==0 & factors>0) { d <- factors X.labels <- paste("X", 1:d, sep = "") } else { stop("invalid argument 'factors', expecting a positive integer or a character string vector (names).") } if (N%%1!=0 | N<=0) { stop("invalid argument 'N', expecting a positive integer.") } if (conf < 0 | conf > 1) { stop("invalid argument 'conf', expecting a value in ]0,1[.") } if (!is.logical(tail)) { stop("invalid argument 'tail', expecting a boolean.") } if(nboot%%1!=0 | nboot<0){ stop("invalid argument 'nboot', expecting a positive integer or zero.") } if(!is.logical(total)){ stop("invalid argument 'total', expecting a boolean.") } if(N>=(d-1)^2){ if (sqrt(N)%%1==0) { if (numbers::isPrime(sqrt(N))){ q <- sqrt(N) } else if (length(unique(primeFactors(sqrt(N))))==1){ q <- sqrt(N) } else { if (tail){ q <- numbers::previousPrime(sqrt(N)) N <- q^2 } else { q <- numbers::nextPrime(sqrt(N)) N <- q^2 } warning("The value entered for N is not the square of a prime number. It has been replaced by: ",paste(q^2)) } } if (sqrt(N)%%1!=0) { if (tail){ q <- numbers::previousPrime(sqrt(N)) N <- q^2 } else { q <- numbers::nextPrime(sqrt(N)) N <- q^2 } warning("The value entered for N is not the square of a prime number. It has been replaced by: ",paste(q^2)) } } if(N<d^2){ q <- numbers::nextPrime(d) N <- q^2 warning("The value entered for N is not satisfying the constraint N >= (d-1)^2. It has been replaced by: ",paste(q^2)) } doe <- matrix(NA,nrow=N,ncol=2*d) perm <- replicate(2*d,sample(q)) doe0a <- addelman_const(d,q,choice="U") doe0b <- addelman_const(d,q,choice="W") mat_rand <- matrix(runif(d*q),nrow=q,ncol=d) for (i in 1:d) { p1 <- perm[doe0a[,i],i] p2 <- perm[doe0b[,i],d+i] doe[,c(i,d+i)] <- (c(p1,p2)-mat_rand[c(p1,p2),i])/q } loop_index <- t(combn(d,2)) RP <- matrix(NA,nrow=N,ncol=d+nrow(loop_index)) for(ind in 1:d){ p1 <- order(doe[,ind]) p2 <- order(doe[,d+ind]) RP[,ind] <- p2[order(p1)] } for(ind in 1:nrow(loop_index)){ p1 <- do.call(base::order,as.data.frame(doe[,loop_index[ind,]])) p2 <- do.call(base::order,as.data.frame(doe[,d+loop_index[ind,]])) RP[,d+ind] <- p2[order(p1)] } rm(perm,doe0a,doe0b,mat_rand,p1,p2,loop_index) X <- rbind(doe[,1:d],doe[,(d+1):(2*d)]) if(total){ perm <- replicate(d,sample(N)) doetot <- matrix(runif(N*d),nrow=N,ncol=d) for (i in 1:d){ p1 <- perm[,i] doetot[,i] <- (p1-doetot[p1,i])/N } index <- seq(1,d) + seq(0,d-1)*d X0 <- matrix(c(rep(doe[,(d+1):(2*d)],d)),ncol=d^2) X0[,index] <- doetot Xtot <- matrix(X0[,c(outer(seq(1,d^2,by=d),seq(0,d-1),'+'))],ncol=d) X <- rbind(X, Xtot) rm(perm,doetot,p1,X0,index) } x <- list(model=model, factors=factors, X=X, RP=RP, N=N, order=t, conf=conf, tail=tail, nboot=nboot, nbrep=nbrep, total=total, call=match.call()) class(x) <- "sobolrep" if (!is.null(x$model)) { response(x, ...) tell(x, ...) } return(x) } repeat.sobolrep <- function(Ord, RP, mat_rep = NULL, pow_init=NULL){ new_RP <- matrix(0,ncol=ncol(RP),nrow=nrow(RP)) d <- ncol(RP) q <- sqrt(nrow(RP)) for(ind in 1:d){ p1 <- RP[,ind] col_Ord <- matrix(Ord[,ind],ncol=q) new_col <- c(apply(col_Ord,2,sample)) map <- setNames(new_col,c(col_Ord)) new_RP[,ind] <- unname(map[as.character(p1)]) } return(new_RP) } estim.sobolrep <- function(data, i = 1 : nrow(data), RP, d, I, ...){ res <- cpp_get_indices(data, RP, I, i, d) out <- c(unlist(res)) return(out) } estimtotal.sobolrep <- function(data, i = 1 : nrow(data), ...){ ST <- cpp_get_total_indices(data, i) return(ST) } tell.sobolrep <- function(x, y = NULL, ...){ id <- deparse(substitute(x)) if (! is.null(y)) { x$y <- y } else if (is.null(x$y)) { stop("y not found") } X2 <- x$X[(x$N+1):(2*x$N),] Ord <- apply(X2,2,base::order) RP <- x$RP d <- x$factors nbrep <- x$nbrep total <- x$total if(total){ fulldata <- matrix(x$y,ncol=d+2) data <- fulldata[,1:2] datatot <- fulldata[,2:(d+2)] } else{ data <- matrix(x$y,ncol=2) } S0 <- 0 Sb <- 0 S2b <- 0 S20 <- 0 timm <- as.numeric(Sys.time()) seed_val <- ((timm-floor(timm))) * 1e8 I <- t(combn(d,2)) for(rep in 1:nbrep){ new_RP <- cbind(repeat.sobolrep(Ord,RP[,1:d]),RP[,(d+1):ncol(RP)]) if (x$nboot == 0){ indices <- data.frame(original = estim.sobolrep(data=data, RP=new_RP, d=d, I=I)) Sb <- data.frame("original"=indices[1:d,]) + Sb S2b <- data.frame("original"=indices[(d+1):nrow(indices),]) + S2b } else{ set.seed(seed_val) S.boot <- boot(data=data, estim.sobolrep, R = x$nboot, RP=new_RP, d=d, I=I) Sb <- as.matrix(S.boot$t[,1:d]) + Sb S0 <- S.boot$t0[1:d] + S0 S2b <- as.matrix(S.boot$t[,(d+1):ncol(RP)]) + S2b S20 <- S.boot$t0[(d+1):ncol(RP)] + S20 } set.seed(NULL) } if (x$nboot == 0){ x$S <- Sb/nbrep x$S2 <- S2b/nbrep } else{ S.boot$t <- cbind(Sb, S2b)/x$nbrep S.boot$t0 <- c(S0, S20)/x$nbrep indices <- bootstats(S.boot, x$conf, "bias corrected") x$S <- indices[1:d,] x$S2 <- indices[(d+1):nrow(indices),] } if(total){ if (x$nboot == 0){ x$T <- data.frame("original"=estimtotal.sobolrep(datatot)) } else{ ST.boot <- boot(datatot, estimtotal.sobolrep, R = x$nboot) x$T <- bootstats(ST.boot, x$conf, "bias corrected") } } x$V <- var(data[,1]) rownames <- paste("X",1:d,sep="") rownames2 <- paste("X",apply(t(combn(d,2)),1,paste,collapse=""),sep= "") rownames(x$S) <- rownames rownames(x$S2) <- rownames2 if(total){ rownames(x$T) <- rownames } assign(id, x, parent.frame()) } print.sobolrep <- function(x, ...) { cat("\nCall:\n", deparse(x$call), "\n", sep = "") if(x$total){ cat("\nModel runs:", x$N*(x$factors+2), "\n") } else{ cat("\nModel runs:", 2*x$N, "\n") } if (!is.null(x$y)) { cat("\nModel variance:\n") print(x$V) cat("\nFirst-order indices:\n") print(x$S) cat("\nClosed second-order indices:\n") print(x$S2) if(x$total){ cat("\nTotal-effect indices:\n") print(x$T) } } } plot.sobolrep <- function(x, ylim = c(0, 1), choice, ...) { if (!is.null(x$y)) { if (choice==1){ nodeplot(x$S, ylim = ylim, ...) legend(x = "topright", legend = c("First-order indices")) } if (choice==2){ nodeplot(x$S2, ylim = ylim, ...) legend(x = "topright", legend = c("Second-order indices")) } if (choice==3 & x$total){ nodeplot(x$T, ylim = ylim, ...) legend(x = "topright", legend = c("Total-effect indices")) } } }
NULL expect_true <- function(object, info = NULL, label = NULL) { act <- quasi_label(enquo(object), label, arg = "object") act$val <- as.vector(act$val) expect_waldo_constant(act, TRUE, info = info) } expect_false <- function(object, info = NULL, label = NULL) { act <- quasi_label(enquo(object), label, arg = "object") act$val <- as.vector(act$val) expect_waldo_constant(act, FALSE, info = info) } expect_null <- function(object, info = NULL, label = NULL) { act <- quasi_label(enquo(object), label, arg = "object") expect_waldo_constant(act, NULL, info = info) } expect_waldo_constant <- function(act, constant, info) { comp <- waldo_compare(act$val, constant, x_arg = "actual", y_arg = "expected") expect( identical(act$val, constant), sprintf( "%s is not %s\n\n%s", act$lab, deparse(constant), paste0(comp, collapse = "\n\n") ), info = info, trace_env = caller_env() ) invisible(act$val) }
renderLineChart <- function(expr, env=parent.frame(), quoted=FALSE) { func = NULL shiny::installExprFunction(expr, "func", env, quoted) function() { dataframe <- func() mapply(function(col, name) { values <- mapply(function(val, i) { list(x = i, y = val) }, col, 1:nrow(dataframe), SIMPLIFY=FALSE, USE.NAMES=FALSE) list(key = name, values = values) }, dataframe, names(dataframe), SIMPLIFY=FALSE, USE.NAMES=FALSE) } }
ind.oneway.second <- function(m, sd, n, unbiased=TRUE, contr=NULL, sig.level=.05, digits=3){ if(length(n)==1){ n <- rep(n, length(m)) } if(unbiased==FALSE){ sd <- ssd2sd(n,sd) } k <- length(m) Xg <- sum(n*m)/sum(n) dfb <- k - 1 dfw <- sum(n) - k MSb <- sum(n * (m - Xg)^2)/(k-1) MSw <- sum((n-1)*sd^2)/dfw SSb <- dfb * MSb SSw <- dfw * MSw SSt <- SSb + SSw f.value <- MSb/MSw anova.table <- data.frame(matrix(NA,ncol=4, nrow=3)) rownames(anova.table) <- c("Between (A)", "Within", "Total") colnames(anova.table) <- c("SS", "df", "MS", "F") anova.table$SS <- c(SSb, SSw,SSt) anova.table$df <- c(dfb, dfw, dfb+dfw) anova.table$MS <- c(MSb,MSw,NA) anova.table$F <- c(f.value, NA,NA) class(anova.table) <- c("anova", "data.frame") anova.table <- round(anova.table, digits) etasq <- SSb / SSt delta.lower <- delta.upper <- numeric(length(etasq)) delta.lower <- try(FNONCT(f.value, dfb, dfw, prob=1-sig.level/2), silent=TRUE) delta.upper <- try(FNONCT(f.value, dfb, dfw, prob=sig.level/2), silent=TRUE) if(is.character(delta.lower)){ delta.lower <- 0 } etasq.lower <- delta.lower / (delta.lower + dfb + dfw + 1) etasq.upper <- delta.upper / (delta.upper + dfb + dfw + 1) omegasq <- (SSb - dfb * MSw)/(SSt + MSw) sosb_L <- SSt * etasq.lower msw_L <- (SSt - sosb_L)/dfw omegasq.lower <- (sosb_L - (dfb*msw_L))/(SSt+msw_L) sosb_U <- SSt * etasq.upper msw_U <- (SSt - sosb_U)/dfw omegasq.upper <- (sosb_U - (dfb*msw_U))/(SSt+msw_U) omnibus.es <- round(c(etasq=etasq, etasq.lower=etasq.lower, etasq.upper=etasq.upper), digits) temp <- combinations(k,2) cont1 <- matrix(0, nrow=nrow(temp),ncol=k) cont1.lab <- rep(0,nrow(temp)) for(i in 1:nrow(temp)){ cont1[i, temp[i,1]] <- 1 cont1[i, temp[i,2]] <- -1 cont1.lab[i] <- paste(temp[i,1],"-",temp[i,2], sep="") rownames(cont1) <- cont1.lab } if(!is.null(contr)){ if(is.vector(contr)){ cont1 <- t(as.matrix(contr)) }else{ cont1 <- contr } } psi <- colSums(t(cont1) * as.vector(m)) SSpsi <- (psi^2)/colSums(t(cont1^2) / as.vector(n)) nmat <- matrix(n, nrow=nrow(cont1), ncol=length(n), byrow=TRUE) psi.std <- sqrt(MSw * rowSums(cont1 ^ 2/nmat)) psi.lower <- psi + psi.std * qt(sig.level/2, dfw) psi.upper <- psi + psi.std * qt(sig.level/2, dfw, lower.tail=FALSE) raw.contrasts <- round(data.frame(mean.diff=psi, lower=psi.lower, upper=psi.upper, std=psi.std), digits) rownames(raw.contrasts) <- rownames(cont1) gpsi <- psi/sqrt(MSw) gpsi.std <- sqrt(rowSums(cont1 ^ 2/nmat)) gpsi.lower <- gpsi + gpsi.std * qt(sig.level/2, dfw) gpsi.upper <- gpsi + gpsi.std * qt(sig.level/2, dfw, lower.tail=FALSE) standardized.contrasts <- round(data.frame(es=gpsi, lower=gpsi.lower, upper=gpsi.upper, std=gpsi.std), digits) rownames(standardized.contrasts) <- rownames(cont1) c.delta <- c(.10, .25, .4) criterion.power <- round(power.f(sig.level=sig.level, u=dfb, n=sum(n)/k,delta=c.delta), digits) names(criterion.power) <- c("small", "medium", "large") output <- list(anova.table=anova.table, omnibus.es=omnibus.es, raw.contrasts=raw.contrasts, standardized.contrasts = standardized.contrasts, power=criterion.power) return(output) }
rm(list=ls()) setwd("C:/Users/Tom/Documents/Kaggle/Facebook/Data") library(data.table) targetDate <- "23-05-2016" blockTarget <- c("train","test")[1] dir.create(file.path(getwd(), targetDate), showWarnings = FALSE) distanceConstantX <- 2.5 distanceId <- which(distanceConstantX==c(1, 2.5, 4, 7, 12, 30)) xBlockSize <- c(0.2,0.25,0.5,0.4,0.5,1)[distanceId] nbXBlocks <- 10/xBlockSize - 1 yBlockSize <- c(0.2,0.1,0.1,0.05,0.04,0.025)[distanceId] nbYBlocks <- 10/yBlockSize - 1 nbBlocks <- nbXBlocks*nbYBlocks if(blockTarget=="train"){ train <- readRDS(paste0("../Downsampling/",targetDate,"/summary.rds")) } else{ train <- readRDS("train.rds") } targetFolder <- file.path(getwd(), targetDate, blockTarget) dir.create(targetFolder, showWarnings = FALSE) for(blockId in 1:nbBlocks){ cat("Processing block",blockId,"of",nbBlocks,"\n") xStart <- xBlockSize * ((blockId-1) %% nbXBlocks) xMin <- xStart-(xStart==0) xMax <- xStart + 2*xBlockSize + 1e-6 yStart <- floor((blockId-1)/nbXBlocks)*yBlockSize yMin <- yStart-(yStart==0) yMax <- yStart + 2*yBlockSize + 1e-6 block <- train[x>xMin & x<=xMax & y>yMin & y<=yMax] savePath <- file.path(targetFolder, paste0(nbBlocks," - ", xStart, " - ", yStart, ".rds")) saveRDS(block, savePath) }
setMethod("simulate", "yuima.multimodel", function(object, nsim=1, seed=NULL, xinit, true.parameter, space.discretized=FALSE, increment.W=NULL, increment.L=NULL, method="euler", hurst, methodfGn="WoodChan", sampling, subsampling, ...){ tmpsamp <- NULL if(missing(sampling)){ tmpsamp <- setSampling(...) } else { tmpsamp <- sampling } tmpyuima <- setYuima(model=object, sampling=tmpsamp) out <- simulate(tmpyuima, nsim=nsim, seed=seed, xinit=xinit, true.parameter=true.parameter, space.discretized=space.discretized, increment.W=increment.W, increment.L=increment.L, method=method, hurst=hurst,methodfGn=methodfGn, subsampling=subsampling) return(out) }) aux.simulate.multimodel<-function(object, nsim, seed, xinit, true.parameter, space.discretized, increment.W, increment.L,method, hurst=0.5,methodfGn, sampling, subsampling, Initial, Terminal, n, delta, grid, random, sdelta, sgrid, interpolation){ if(is(object@model@measure$df,"yuima.law")&& is.null(increment.L)){ samp<- object@sampling randomGenerator<-object@model@measure$df if(samp@regular){ tForMeas<-samp@delta NumbIncr<-samp@n[1] if(missing(true.parameter)){ eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) }else{ measureparam<-true.parameter[object@model@parameter@measure] eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) } Noise<- rand(object = randomGenerator, n=NumbIncr, param=measureparam) }else{ tForMeas<-diff(samp@grid[[1]]-samp@Initial) my.InternalFunforLevy<-function(tForMeas, randomGenerator, true.parameter,object){ if(missing(true.parameter)){ eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) }else{ measureparam<-true.parameter[object@model@parameter@measure] eval(parse(text= paste0("measureparam$", object@[email protected]," <- tForMeas",collapse=""))) } Noise<- rand(object = randomGenerator, n=samp@n[1], param=measureparam) } Noise<-sapply(X=tForMeas, FUN=my.InternalFunforLevy, randomGenerator=randomGenerator, true.parameter=true.parameter, object=object) } increment.L=Noise if(is(object@model@measure$df,"yuima.law")&&!is.null(increment.L)){ dummy<-object dummy@model@measure$df <- expression() if(missing(xinit)){ res<- aux.simulate.multimodel(object=dummy, nsim, xinit=object@model@xinit ,seed, true.parameter, space.discretized, increment.W, increment.L = t(increment.L), method, hurst, methodfGn, sampling=object@sampling) }else{ res<- aux.simulate.multimodel(object=dummy, nsim, xinit, seed, true.parameter, space.discretized, increment.W, increment.L = increment.L, method, hurst, methodfGn, sampling=object@sampling) } res@model <- object@model if(missing(subsampling)) return(res) return(subsampling(res, subsampling)) } } yuima <- object samp <- object@sampling if(missing(yuima)){ yuima.warn("yuima object is missing.") return(NULL) } tmphurst<-yuima@model@hurst if(!missing(hurst)){ yuima@model@hurst=hurst } if (is.na(yuima@model@hurst)){ yuima.warn("Specify the hurst parameter.") return(NULL) } tmpsamp <- NULL if(is.null(yuima@sampling)){ if(missing(sampling)){ tmpsamp <- setSampling(Initial = Initial, Terminal = Terminal, n = n, delta = delta, grid = grid, random = random, sdelta=sdelta, sgrid=sgrid, interpolation=interpolation) } else { tmpsamp <- sampling } } else { tmpsamp <- yuima@sampling } yuima@sampling <- tmpsamp sdeModel <- yuima@model Terminal <- yuima@sampling@Terminal[1] n <- yuima@sampling@n[1] r.size <- [email protected] d.size <- [email protected] if(missing(xinit)){ xinit <- sdeModel@xinit } else { if(length(xinit) != d.size){ if(length(xinit)==1){ xinit <- rep(xinit, d.size) } else { yuima.warn("Dimension of xinit variables missmatch.") return(NULL) } } } xinit <- as.expression(xinit) par.len <- length(sdeModel@parameter@all) if(missing(true.parameter) & par.len>0){ true.parameter <- vector(par.len, mode="list") for(i in 1:par.len) true.parameter[[i]] <- 0 names(true.parameter) <- sdeModel@parameter@all } yuimaEnv <- new.env() if(par.len>0){ for(i in 1:par.len){ pars <- sdeModel@parameter@all[i] for(j in 1:length(true.parameter)){ if( is.na(match(pars, names(true.parameter)[j]))!=TRUE){ assign(sdeModel@parameter@all[i], true.parameter[[j]],yuimaEnv) } } } } if(space.discretized){ if(r.size>1){ warning("Space-discretized EM cannot be used for multi-dimentional models. Use standard method.") space.discretized <- FALSE } if(length([email protected])){ warning("Space-discretized EM is for only Wiener Proc. Use standard method.") space.discretized <- FALSE } } if(!missing(increment.W) & !is.null(increment.W)){ if(space.discretized == TRUE){ yuima.warn("Parameter increment must be invalid if space.discretized=TRUE.") return(NULL) }else if(dim(increment.W)[1] != r.size){ yuima.warn("Length of increment's row must be same as yuima@[email protected].") return(NULL) }else if(dim(increment.W)[2] != n){ yuima.warn("Length of increment's column must be same as sampling@n[1].") return(NULL) } } if(!missing(increment.L) & !is.null(increment.L)){ if(space.discretized == TRUE){ yuima.warn("Parameter increment must be invalid if space.discretized=TRUE.") return(NULL) }else if(dim(increment.L)[1] != length(yuima@[email protected][[1]]) ){ yuima.warn("Length of increment's row must be same as yuima@[email protected].") return(NULL) }else if(dim(increment.L)[2] != n){ yuima.warn("Length of increment's column must be same as sampling@n[1].") return(NULL) } } yuimaEnv$dL <- increment.L if(space.discretized){ yuima@data <- space.discretized(xinit, yuima, yuimaEnv) yuima@model@hurst<-tmphurst return(yuima) } delta <- samp@delta if(missing(increment.W) | is.null(increment.W)){ if( sdeModel@hurst!=0.5 ){ grid<-sampling2grid(yuima@sampling) isregular<-yuima@sampling@regular if((!isregular) || (methodfGn=="Cholesky")){ dW<-CholeskyfGn(grid, sdeModel@hurst,r.size) yuima.warn("Cholesky method for simulating fGn has been used.") } else { dW<-WoodChanfGn(grid, sdeModel@hurst,r.size) } } else { delta<-samp@delta if(!is.Poisson(sdeModel)){ dW <- rnorm(n * r.size, 0, sqrt(delta)) dW <- matrix(dW, ncol=n, nrow=r.size,byrow=TRUE) } else { dW <- matrix(0,ncol=n,nrow=1) } } } else { dW <- increment.W } if(is(sdeModel,"yuima.multimodel")&&!is(sdeModel@measure$df,"yuima.law")){ if(length([email protected])==1){ if([email protected]=="CP"){ intens <- as.character(sdeModel@measure$intensity) dens <- as.character(sdeModel@measure$df$expr) dumCP <- setPoisson(intensity = intens, df = dens, dimension = length([email protected][[1]])) dummSamp <- yuima@sampling samp <- setSampling(Initial = dummSamp@Initial, Terminal = dummSamp@Terminal, n = dummSamp@n) traj <- simulate(object = dumCP, sampling = samp, true.parameter = true.parameter) Incr.levy <- diff(traj@[email protected][[1]]) if(length(traj@[email protected])>1){ for(i in c(2:length(traj@[email protected]))){ Incr.levy<-cbind(Incr.levy,diff(traj@[email protected][[i]])) } } }else{ dummSamp <- yuima@sampling samp <- setSampling(Initial = dummSamp@Initial, Terminal = dummSamp@Terminal, n = dummSamp@n) xinitCode <- yuima@model@xinit dimJumpCoeff <- length(yuima@[email protected][[1]]) dumjumpCoeff <- matrix(as.character(diag(rep(1,dimJumpCoeff))),dimJumpCoeff,dimJumpCoeff) Dumsolve.variable<-paste0("MyLevyDum",c(1:dimJumpCoeff)) if(!is(sdeModel@measure$df,"yuima.law")){ LevyMod <- setMultiModel(drift=rep("0",dimJumpCoeff), diffusion = NULL, jump.coeff = dumjumpCoeff, df = as.character(sdeModel@measure$df$expr), measure.type = [email protected], solve.variable = Dumsolve.variable) }else{ LevyMod <- setModel(drift=rep("0",dimJumpCoeff), diffusion = NULL, jump.coeff = dumjumpCoeff, measure = sdeModel@measure, measure.type = [email protected], solve.variable = Dumsolve.variable) } yuimaLevy <- setYuima(model=LevyMod, sampling = samp) yuimaLevy@model@dimension <- dimJumpCoeff traj<- simCode(xinit=xinitCode,yuima = yuimaLevy, env=yuimaEnv) Incr.levy <- diff(traj@[email protected][[1]]) if(length(traj@[email protected])>1){ for(i in c(2:length(traj@[email protected]))){ Incr.levy<-cbind(Incr.levy,diff(traj@[email protected][[i]])) } } } }else{ if(any([email protected]=="CP")){ intens <- as.character(sdeModel@measure$intensity) dens <- as.character(sdeModel@measure$df$expr) numbLev <- length([email protected]) posCPindex <- c(1:numbLev)[[email protected]%in%"CP"] CPmeasureComp <- paste0(dens,"[,c(",toString(posCPindex),")]") intens <- as.character(sdeModel@measure$intensity) dumCP <- setPoisson(intensity = intens, df = CPmeasureComp, dimension = length(posCPindex)) dummSamp <- yuima@sampling samp <- setSampling(Initial = dummSamp@Initial, Terminal = unique(dummSamp@Terminal), n = unique(dummSamp@n)) trajCP <- simulate(object = dumCP, sampling = samp, true.parameter = true.parameter) dimJumpCoeff <- length(yuima@[email protected]) dumjumpCoeff <- matrix(as.character(diag(rep(1,dimJumpCoeff))),dimJumpCoeff,dimJumpCoeff) Dumsolve.variable <- paste0("MyLevyDum",c(1:dimJumpCoeff)) dummy.measure.code <- as.character(sdeModel@measure$df$expr) LevyMod <- setMultiModel(drift=rep("0",dimJumpCoeff), diffusion = NULL, jump.coeff = dumjumpCoeff, df = dummy.measure.code, measure.type = "code", solve.variable = Dumsolve.variable) yuimaLevy <- setYuima(model=LevyMod, sampling = samp) yuimaLevy@model@dimension <- dimJumpCoeff trajcode<- simCode(xinit=rep("0",length=dimJumpCoeff), yuima = yuimaLevy, env=yuimaEnv) countCP <- 0 countcode <- 0 if(yuima@[email protected][1]=="CP"){ Incr.levy <- as.matrix(as.numeric(diff(trajCP@[email protected][[1]]))) countcode <- countcode+1 }else{ if(yuima@[email protected][1]=="code"){ Incr.levy <- as.matrix(as.numeric(diff(trajcode@[email protected][[1]]))) countCP <- countCP+1 } } if(length(yuima@[email protected])>1){ for(i in c(2:length(yuima@[email protected]))){ if(yuima@[email protected][i]=="CP"){ Incr.levy<-cbind(Incr.levy,as.numeric(diff(trajCP@[email protected][[(i-countCP)]]))) countcode <- countcode+1 }else{ if(yuima@[email protected][i]=="code"){ Incr.levy <- cbind(Incr.levy,as.numeric(diff(trajcode@[email protected][[i]]))) countCP <- countCP+1 } } } } } } } if(!is.null(increment.L)) Incr.levy<-t(increment.L) assign("dL",t(Incr.levy),envir=yuimaEnv) sim <- Multi.Euler(xinit,yuima,dW,env=yuimaEnv) yuima@[email protected]<-as.list(numeric(length=length([email protected]))) for(i in 1:length(yuima@[email protected])){ yuima@[email protected][[i]]<[email protected][[i]] index(yuima@[email protected][[i]]) <- yuima@sampling@grid[[1]] } yuima@[email protected] <- [email protected] yuima@model@xinit <- xinit yuima@model@hurst <-tmphurst if(missing(subsampling)) return(yuima) subsampling(yuima, subsampling) } simCode <- function(xinit,yuima,env){ sdeModel<-yuima@model modelstate <- [email protected] modeltime <- [email protected] Terminal <- yuima@sampling@Terminal[1] Initial <- yuima@sampling@Initial[1] dimension <- yuima@model@dimension dummy.val <- numeric(dimension) if(length(xinit) != dimension) xinit <- rep(xinit, dimension)[1:dimension] if(length(unique(as.character(xinit)))==1 && is.numeric(tryCatch(eval(xinit[1],envir=env),error=function(...) FALSE))){ dX_dummy<-xinit[1] dummy.val<-eval(dX_dummy, envir=env) if(length(dummy.val)==1){ dummy.val<-rep(dummy.val,dimension) } for(i in 1:length(modelstate)){ assign(modelstate[i],dummy.val[i] ,envir=env) } } else { for(i in 1:dimension){ dummy.val[i] <- eval(xinit[i], envir=env) } } JP <- eval([email protected][[1]], envir=env) mu.size <- length(JP) dummyList<-as.list(env) lgth.meas<-length(yuima@model@parameter@measure) if(lgth.meas>1){ for(i in c(2:lgth.meas)){ idx.dummy<-yuima@model@parameter@measure[i] assign(idx.dummy,as.numeric(dummyList[idx.dummy])) } } if(!is(sdeModel@measure$df,"yuima.law")){ dumStringMeas <- toString(sdeModel@measure$df$expr) dumStringMeas1 <- substr(x=dumStringMeas, start=2,stop=nchar(x = dumStringMeas)) dumStringMeas2 <- paste0("r",dumStringMeas1) tmpMeas2 <- strsplit(x=dumStringMeas2,split="") posMeas2 <- match("(" , tmpMeas2[[1]])[1] dumStringMeas3 <- substr(x=dumStringMeas2, start=1,stop=(posMeas2-1)) a<-deparse(args(eval(parse(text=dumStringMeas3))))[1] b<-gsub("^function (.+?)","(",a) b1 <- substr(x=b,start =1, stop=(nchar(b)-1)) FinalMeasRandn<-paste0(dumStringMeas3,b1) dummyvarMaes <- all.vars(parse(text=FinalMeasRandn)) posDum<- match(c([email protected],sdeModel@parameter@measure),dummyvarMaes) if(length(posDum)+1!=length(dummyvarMaes)){ yuima.stop("too input variables in the random number function") } deltaVar <- dummyvarMaes[-posDum] F <- suppressWarnings(parse(text=gsub("^r(.+?)\\(.+?,", "r\\1(mu.size*N_sharp,", parse(text=FinalMeasRandn), perl=TRUE))) F.env <- new.env(parent=env) N_sharp <- unique(yuima@sampling@n) TrueDelta <- unique(yuima@sampling@delta) assign(deltaVar, TrueDelta, envir=F.env) assign("mu.size", mu.size, envir=F.env) assign("N_sharp", N_sharp, envir=F.env) randJ <- eval(F, envir=F.env) randJ <- rbind(dummy.val, randJ) }else{ TrueDelta <- unique(yuima@sampling@delta) randJ<- env$dL } RANDLevy <- apply(randJ,2,cumsum) tsX <- zoo(x=RANDLevy) yuimaData <- setYuima(data=setData(tsX, delta=TrueDelta)) return(yuimaData) } Multi.Euler<-function(xinit,yuima,dW,env){ sdeModel<-yuima@model modelstate <- [email protected] modeltime <- [email protected] V0 <- sdeModel@drift V <- sdeModel@diffusion r.size <- [email protected] d.size <- [email protected] Terminal <- yuima@sampling@Terminal[1] n <- yuima@sampling@n[1] dL <- env$dL if(length(unique(as.character(xinit)))==1 && is.numeric(tryCatch(eval(xinit[1],env),error=function(...) FALSE))){ dX_dummy<-xinit[1] dummy.val<-eval(dX_dummy, env) if(length(dummy.val)==1){dummy.val<-rep(dummy.val,length(xinit))} for(i in 1:length(modelstate)){ assign(modelstate[i],dummy.val[i] ,env) } dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(xinit)){ dX[i] <- dummy.val[i] } }else{ dX_dummy <- xinit if(length(modelstate)==length(dX_dummy)){ for(i in 1:length(modelstate)) { if(is.numeric(tryCatch(eval(dX_dummy[i],env),error=function(...) FALSE))){ assign(modelstate[i], eval(dX_dummy[i], env),env) }else{ assign(modelstate[i], 0, env) } } }else{ yuima.warn("the number of model states do not match the number of initial conditions") return(NULL) } dX<-vector(mode="numeric",length(dX_dummy)) for(i in 1:length(dX_dummy)){ dX[i] <- eval(dX_dummy[i], env) } } delta <- Terminal/n has.drift <- sum(as.character(sdeModel@drift) != "(0)") var.in.diff <- is.logical(any(match(unlist(lapply(sdeModel@diffusion, all.vars)), [email protected]))) p.b <- function(t, X=numeric(d.size)){ for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) if(has.drift){ tmp <- matrix(0, d.size, r.size+1) for(i in 1:d.size){ tmp[i,1] <- eval(V0[i], env) for(j in 1:r.size){ tmp[i,j+1] <- eval(V[[i]][j],env) } } } else { tmp <- matrix(0, d.size, r.size) if(!is.Poisson(sdeModel)){ for(i in 1:d.size){ for(j in 1:r.size){ tmp[i,j] <- eval(V[[i]][j],env) } } } } return(tmp) } X_mat <- matrix(0, d.size, n+1) X_mat[,1] <- dX if(has.drift){ dW <- rbind( rep(1, n)*delta , dW) } if(!length([email protected])){ if(var.in.diff & (!is.Poisson(sdeModel))){ for( i in 1:n){ dX <- dX + p.b(t=i*delta, X=dX) %*% dW[, i] X_mat[,i+1] <- dX } }else{ sde.tics <- seq(0, Terminal, length=(n+1)) sde.tics <- sde.tics[2:length(sde.tics)] X_mat[, 1] <- dX for(i in 1:length(modelstate)){ assign(modelstate[i], dX[i]) } assign(modeltime, sde.tics) t.size <- length(sde.tics) if(has.drift){ pbdata <- matrix(0, d.size*(r.size+1), t.size) for(i in 1:d.size){ pbdata[(i-1)*(r.size+1)+1, ] <- eval(V0[i], env) for(j in 1:r.size){ pbdata[(i-1)*(r.size+1)+j+1, ] <- eval(V[[i]][j], env) } } dim(pbdata)<-(c(r.size+1, d.size*t.size)) }else{ pbdata <- matrix(0, d.size*r.size, t.size) if(!is.Poisson(sdeModel)){ for(i in 1:d.size){ for(j in 1:r.size){ pbdata[(i-1)*r.size+j, ] <- eval(V[[i]][j], env) } } } dim(pbdata)<-(c(r.size, d.size*t.size)) } pbdata <- t(pbdata) for( i in 1:n){ if(!is.Poisson(sdeModel)) dX <- dX + pbdata[((i-1)*d.size+1):(i*d.size), ] %*% dW[, i] X_mat[, i+1] <- dX } } tsX <- ts(data=t(X_mat), deltat=delta , start=0) }else{ JP <- [email protected] mu.size <- length(JP) p.b.j <- function(t, X=numeric(d.size)){ for(i in 1:length(modelstate)){ assign(modelstate[i], X[i], env) } assign(modeltime, t, env) j.size <- length(JP[[1]]) tmp <- matrix(0, mu.size, j.size) for(i in 1:mu.size){ for(j in 1:j.size){ tmp[i,j] <- eval(JP[[i]][j],env) } } return(tmp) } dZ <- dL for(i in 1:n){ assign([email protected], dZ[,i], env) if([email protected]){ dZ[,i] <- 1 } tmp.j <- p.b.j(t=i*delta, X=dX) dX <- dX + p.b(t=i*delta, X=dX) %*% dW[, i] +tmp.j %*% dZ[,i] X_mat[, i+1] <- dX } tsX <- ts(data=t(X_mat), deltat=delta, start=0) } yuimaData <- setData(original.data=tsX) return(yuimaData) }
segmentByGFLars <- function(Y, K, weights=defaultWeights(nrow(Y)), epsilon=1e-9, verbose=FALSE){ if (!is.matrix(Y) || !is.numeric(Y)){ stop("Argument 'Y' should be a numeric matrix.\nPlease see 'doGFLars' for using GFLars directly on a data.frame or a numeric vector") } if (any(is.na(Y))) { stop("Missing values are not handled by the current implementation of group fused LARS") } rownames(Y) <- NULL n <- as.numeric(nrow(Y)) p <- dim(Y)[2] if (missing(K)) { stop("Please provide argument 'K'") } if (K>=n) { stop("Too many breakpoints are required") } if (is.null(weights)) { weights <- defaultWeights(n) } res.meansignal <- colMeans(Y); res.lambda <- numeric(K); res.bkp <- numeric(K) res.value <- list() res.c <- matrix(NA, n-1, K); Y <- sweep(Y, 2, colMeans(Y)) AS <- numeric(0) c <- leftMultiplyByXt(Y=Y, w=weights, verbose=verbose) for (ii in 1:K){ cNorm <- rowSums(c^2) res.c[, ii] <- cNorm bigcHat <- max(cNorm) if (verbose) { print(paste('optimize LARS : ', ii)) } if (ii==1) { AS <- which.max(cNorm) res.bkp[ii] <- AS } I <- order(AS) AS <- AS[I] w <- leftMultiplyByInvXAtXA(n, AS, matrix(c[AS,], ncol=p), weights, verbose=verbose) a <- multiplyXtXBySparse(n=n, ind=AS, val=w, w=weights, verbose=verbose) a1 <- bigcHat - rowSums(a^2) u <- a*c a2 <- bigcHat - rowSums(u) a3 <- bigcHat - cNorm gammaTemp = matrix(NA, n-1, 2); subset <- which(a1 > epsilon) delta <- a2[subset]^2 - a1[subset]*a3[subset] delta.neg <- subset[which(delta<0)] delta.pos <- subset[which(delta>=0)] gammaTemp[delta.neg, 1] <- NA; gammaTemp[delta.pos, 1] <- (a2[delta.pos]+sqrt(delta[which(delta>=0)]))/a1[delta.pos]; gammaTemp[delta.neg, 2] <- NA; gammaTemp[delta.pos, 2] <- (a2[delta.pos]-sqrt(delta[which(delta>=0)]))/a1[delta.pos]; subset <- which((a1 <= epsilon) & (a2 > epsilon)) gammaTemp[subset, ] = a3[subset] / (2*a2[subset]) maxg <- max(gammaTemp, na.rm=TRUE)+1; subset <- which((a1 <= epsilon) & (a2 <= epsilon)); gammaTemp[subset, ] <- maxg; gammaTemp[AS, ] <- maxg; gamma <- min(gammaTemp, na.rm=TRUE) idx <- which.min(gammaTemp) nexttoadd <- 1 + (idx-1) %% (n-1); res.lambda[ii] <- sqrt(bigcHat); res.value[[ii]] <- matrix(numeric(ii*p), ncol = p) res.value[[ii]][I,] <- gamma*w; if (ii>1){ res.value[[ii]][1:(ii-1),] <- res.value[[ii]][1:(ii-1),] + res.value[[ii-1]]; } if (ii<K){ AS <- c(AS,nexttoadd) res.bkp[ii+1] <- nexttoadd; c <- c-gamma*a; } } list( bkp=res.bkp, lambda=res.lambda, mean=res.meansignal, value=res.value, c=res.c) }
NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL tabular2 <- function(df, ...) { df<-data.frame(df$m,df$q,df$c,df$f,df$h) stopifnot(is.data.frame(df)) align <- function(x) if (is.numeric(x)) "r" else "l" col_align <- vapply(df, align, character(1)) cols <- lapply(df, format, ...) contents <- do.call("paste", c(cols, list(sep = " \\tab ", collapse = "\\cr\n "))) x <- paste("\\tabular{", paste(col_align, collapse = ""), "}{\n ", contents, "\n}\n", sep = "") cat(x) }
logistic_fun <- function(Dose, E0 = 0, EC50 = 50, Emax = 1, rc = 5) { E0 + Emax / (1 + exp((EC50 - Dose) / rc)) } logisticFun <- logistic_fun
nnfromvertex <- function(X, what=c("dist", "which"), k=1) { stopifnot(is.lpp(X)) what <- match.arg(what, several.ok=TRUE) nX <- npoints(X) nv <- nvertices(domain(X)) if(length(k) == 0) stop("k is an empty vector") else if(length(k) == 1) { if(k != round(k) || k <= 0) stop("k is not a positive integer") } else { if(any(k != round(k)) || any(k <= 0)) stop(paste("some entries of the vector", sQuote("k"), "are not positive integers")) } k <- as.integer(k) kmax <- max(k) nnd <- matrix(Inf, nrow=nv, ncol=kmax) nnw <- matrix(NA_integer_, nrow=nv, ncol=kmax) colnames(nnd) <- colnames(nnw) <- 1:kmax if(nX > 0) { ii <- which(!duplicated(X)) uX <- X[ii] coUX <- coords(uX)[, c("seg", "tp")] coUX$lab <- ii oo <- with(coUX, order(seg, tp)) coUXord <- coUX[oo, , drop=FALSE] seg <- coUXord$seg tp <- coUXord$tp L <- domain(X) nv <- nvertices(L) ns <- nsegments(L) seglen <- lengths_psp(as.psp(L)) from <- L$from to <- L$to huge <- sum(seglen) tol <- max(sqrt(.Machine$double.eps), diameter(Frame(L))/2^20) kmaxcalc <- min(nX, kmax) z <- vnnFind(seg, tp, ns, nv, from, to, seglen, huge, tol, kmax=kmaxcalc) vnndist <- z$vnndist vnnwhich <- z$vnnwhich vnnwhich <- coUXord$lab[vnnwhich] nnd[, 1:kmaxcalc] <- vnndist nnw[, 1:kmaxcalc] <- vnnwhich } nnd <- nnd[,k, drop=TRUE] nnw <- nnw[,k, drop=TRUE] if(identical(what, "dist")) return(nnd) if(identical(what, "which")) return(nnw) return(cbind(data.frame(dist=nnd), data.frame(which=nnw))) } vnnFind <- function(seg, tp, ns, nv, from, to, seglen, huge, tol, kmax=1) { nX <- length(seg) from0 <- from - 1L to0 <- to - 1L seg0 <- seg - 1L if(kmax == 1) { z <- .C(SL_Clinvwhichdist, np = as.integer(nX), sp = as.integer(seg0), tp = as.double(tp), nv = as.integer(nv), ns = as.integer(ns), from = as.integer(from0), to = as.integer(to0), seglen = as.double(seglen), huge = as.double(huge), tol = as.double(tol), dist = as.double(numeric(nv)), which = as.integer(integer(nv)), PACKAGE="spatstat.linnet") } else { z <- .C(SL_linvknndist, kmax = as.integer(kmax), nq = as.integer(nX), sq = as.integer(seg0), tq = as.double(tp), nv = as.integer(nv), ns = as.integer(ns), from = as.integer(from0), to = as.integer(to0), seglen = as.double(seglen), huge = as.double(huge), tol = as.double(tol), dist = as.double(numeric(kmax * nv)), which = as.integer(integer(kmax * nv)), PACKAGE="spatstat.linnet") } vnndist <- z$dist vnnwhich <- z$which + 1L vnnwhich[vnnwhich == 0] <- NA if(kmax > 1) { vnndist <- matrix(vnndist, ncol=kmax, byrow=TRUE) vnnwhich <- matrix(vnnwhich, ncol=kmax, byrow=TRUE) } return(list(vnndist=vnndist, vnnwhich=vnnwhich)) }
is_installed <- function(..., .stop = FALSE) { x <- c(...) ip <- utils::installed.packages() yn <- x %in% ip if (sum(!yn) > 0 && .stop) { msg <- pmsg( "This function requires the following packages: ", paste(x[!yn], collapse = ", "), print = FALSE ) stop(msg, call. = FALSE) } invisible(set_names(yn, x)) }
create_temp_state_filename <- function() { beastier::get_beastier_tempfilename( pattern = "beast2_", fileext = ".xml.state" ) }
library(uwot) context("perplexity") iris10_nn10 <- dist_nn(dist(iris10), k = 10) P_symm <- matrix(c( 0.000000e+00, 0.0022956859, 0.0022079944, 0.0004763074, 4.338953e-02, 1.822079e-02, 0.002913239, 0.0413498285, 5.184416e-05, 0.004134502, 2.295686e-03, 0.0000000000, 0.0188919615, 0.0129934442, 1.089032e-03, 5.689921e-04, 0.002131646, 0.0048261793, 6.996252e-03, 0.050676976, 2.207994e-03, 0.0188919615, 0.0000000000, 0.0444964580, 2.464225e-03, 5.935835e-04, 0.040353636, 0.0027720360, 1.111298e-02, 0.013673490, 4.763074e-04, 0.0129934442, 0.0444964580, 0.0000000000, 5.466455e-04, 2.771325e-04, 0.018028275, 0.0005761904, 3.389471e-02, 0.014363302, 4.338953e-02, 0.0010890318, 0.0024642250, 0.0005466455, 0.000000e+00, 1.831834e-02, 0.006393040, 0.0329052015, 5.372241e-05, 0.002356628, 1.822079e-02, 0.0005689921, 0.0005935835, 0.0002771325, 1.831834e-02, 0.000000e+00, 0.001326343, 0.0110122168, 1.065771e-05, 0.001168212, 2.913239e-03, 0.0021316462, 0.0403536359, 0.0180282748, 6.393040e-03, 1.326343e-03, 0.000000000, 0.0059083283, 4.862680e-03, 0.002656313, 4.134983e-02, 0.0048261793, 0.0027720360, 0.0005761904, 3.290520e-02, 1.101222e-02, 0.005908328, 0.0000000000, 2.982247e-04, 0.012212476, 5.184416e-05, 0.0069962518, 0.0111129834, 0.0338947056, 5.372241e-05, 1.065771e-05, 0.004862680, 0.0002982247, 0.000000e+00, 0.004150755, 4.134502e-03, 0.0506769759, 0.0136734904, 0.0143633019, 2.356628e-03, 1.168212e-03, 0.002656313, 0.0122124758, 4.150755e-03, 0.000000000 ) * 10, nrow = 10, byrow = TRUE) res <- perplexity_similarities( perplexity = 4, verbose = FALSE, nn = find_nn(iris10, k = 10, method = "fnn", metric = "euclidean", n_threads = 0, verbose = FALSE ) )$matrix expect_true(Matrix::isSymmetric(res)) expect_equal(as.matrix(res), P_symm, tol = 1e-5, check.attributes = FALSE) Psymm9 <- matrix( c( 0, 0.1111, 0.1112, 0.1110, 0.1116, 0.1113, 0.1112, 0.1115, 0.1106, 0.1112, 0.1111, 0, 0.1113, 0.1113, 0.1110, 0.1107, 0.1112, 0.1112, 0.1112, 0.1114, 0.1112, 0.1113, 0, 0.1113, 0.1112, 0.1106, 0.1114, 0.1112, 0.1112, 0.1113, 0.1110, 0.1113, 0.1113, 0, 0.1110, 0.1105, 0.1114, 0.1111, 0.1113, 0.1114, 0.1116, 0.1110, 0.1112, 0.1110, 0, 0.1113, 0.1113, 0.1115, 0.1106, 0.1111, 0.1113, 0.1107, 0.1106, 0.1105, 0.1113, 0, 0.1105, 0.1111, 0.1103, 0.1105, 0.1112, 0.1112, 0.1114, 0.1114, 0.1113, 0.1105, 0, 0.1113, 0.1112, 0.1112, 0.1115, 0.1112, 0.1112, 0.1111, 0.1115, 0.1111, 0.1113, 0, 0.1108, 0.1114, 0.1106, 0.1112, 0.1112, 0.1113, 0.1106, 0.1103, 0.1112, 0.1108, 0, 0.1111, 0.1112, 0.1114, 0.1113, 0.1114, 0.1111, 0.1105, 0.1112, 0.1114, 0.1111, 0 ), byrow = TRUE, nrow = 10 ) res <- perplexity_similarities( perplexity = 9, verbose = FALSE, nn = find_nn(iris10, k = 10, method = "fnn", metric = "euclidean", n_threads = 0, verbose = FALSE ) )$matrix expect_true(Matrix::isSymmetric(res)) expect_equal(as.matrix(res), Psymm9, tol = 1e-4, check.attributes = FALSE) P_symm_6nn <- matrix(c( 0, 0, 0.004227396, 0, 0.038581602, 0.016370215, 0.003972948, 0.037491042, 0, 0.007253571, 0, 0, 0.020541010, 0.01457322, 0, 0, 0, 0.008117719, 0.008608916, 0.043891243, 0.004227396, 0.020541010, 0, 0.04314614, 0.004242199, 0, 0.036275982, 0.004791681, 0.010952319, 0.015666352, 0, 0.014573224, 0.043146139, 0, 0, 0, 0.018725165, 0, 0.032811238, 0.015644628, 0.038581602, 0, 0.004242199, 0, 0, 0.016370215, 0.010365583, 0.031963895, 0, 0.003730662, 0.016370215, 0, 0, 0, 0.016370215, 0, 0.002795087, 0.011902114, 0, 0.002562369, 0.003972948, 0, 0.036275982, 0.01872517, 0.010365583, 0.002795087, 0, 0.006321792, 0.004717900, 0.003609179, 0.037491042, 0.008117719, 0.004791681, 0, 0.031963895, 0.011902114, 0.006321792, 0, 0, 0.015406444, 0, 0.008608916, 0.010952319, 0.03281124, 0, 0, 0.004717900, 0, 0, 0.004370167, 0.007253571, 0.043891243, 0.015666352, 0.01564463, 0.003730662, 0.002562369, 0.003609179, 0.015406444, 0.004370167, 0 ) * 10, nrow = 10, byrow = TRUE) res <- perplexity_similarities( perplexity = 4, verbose = FALSE, nn = find_nn(iris10, k = 6, method = "fnn", metric = "euclidean", n_threads = 0, verbose = FALSE ) )$matrix expect_true(Matrix::isSymmetric(res)) expect_equal(as.matrix(res), P_symm_6nn, tol = 1e-5, check.attributes = FALSE) P_row <- matrix(c( 0.000000e+00, 0.03254778, 0.04322171, 0.009522236, 4.179712e-01, 1.389888e-02, 0.03932256, 0.3802648571, 1.633620e-04, 0.06308741, 1.336594e-02, 0.00000000, 0.21654628, 0.163906282, 4.387114e-03, 4.819686e-08, 0.02029701, 0.0618376045, 2.029701e-02, 0.49936271, 9.381792e-04, 0.16129295, 0.00000000, 0.400023323, 9.381792e-04, 7.502536e-16, 0.29552576, 0.0143118438, 7.811162e-03, 0.11915861, 3.912338e-06, 0.09596260, 0.48990584, 0.000000000, 3.912338e-06, 1.913538e-19, 0.09596260, 0.0009992458, 1.842071e-01, 0.13295484, 4.498193e-01, 0.01739352, 0.04834632, 0.010928997, 0.000000e+00, 1.584988e-02, 0.07694327, 0.3403719404, 2.009270e-04, 0.04014584, 3.505169e-01, 0.01137979, 0.01187167, 0.005542650, 3.505169e-01, 0.000000e+00, 0.02652673, 0.2200679860, 2.131340e-04, 0.02336422, 1.894222e-02, 0.02233591, 0.51154696, 0.264602894, 5.091753e-02, 1.331050e-07, 0.00000000, 0.0834805843, 1.155348e-02, 0.03662029, 4.467317e-01, 0.03468598, 0.04112888, 0.010524562, 3.177321e-01, 1.763500e-04, 0.03468598, 0.0000000000, 1.925167e-05, 0.11431520, 8.735213e-04, 0.11962802, 0.21444851, 0.493687059, 8.735213e-04, 2.023140e-08, 0.08570012, 0.0059452421, 0.000000e+00, 0.07884399, 1.960264e-02, 0.51417681, 0.15431120, 0.154311203, 6.986716e-03, 2.081749e-08, 0.01650597, 0.1299343209, 4.171117e-03, 0.00000000 ), nrow = 10, byrow = TRUE) expected_sigmas <- c(0.3252233, 0.2679755, 0.1817380, 0.1751287, 0.3280264, 0.4861266, 0.2463306, 0.2422687, 0.3463065, 0.2411619) resp <- calc_row_probabilities_parallel(t(iris10_nn10$dist), perplexity = 4, n_threads = 0, ret_sigma = TRUE ) res <- resp$matrix res <- nn_to_sparse(iris10_nn10$idx, as.vector(t(res)), self_nbr = TRUE, max_nbr_id = nrow(iris10_nn10$idx) ) expect_equal(as.matrix(res), P_row, tol = 1e-5, check.attributes = FALSE) expect_equal(sqrt(resp$sigma), expected_sigmas, tol = 1e-5) res <- calc_row_probabilities_parallel(t(iris10_nn10$dist), perplexity = 4, n_threads = 1 )$matrix res <- nn_to_sparse(iris10_nn10$idx, as.vector(t(res)), self_nbr = TRUE, max_nbr_id = nrow(iris10_nn10$idx) ) expect_equal(as.matrix(res), P_row, tol = 1e-5, check.attributes = FALSE) iris_dup <- duplicated(x2m(iris)) uiris <- iris[!iris_dup, ] normiris <- scale(x2m(uiris), center = TRUE, scale = FALSE) normiris <- normiris / max(abs(normiris)) Prow_iris_p150_k50_rowSums <- c( 1.064902, 1.01981, 1.022902, 1.00269, 1.058712, 0.959587, 1.020604, 1.072308, 0.918501, 1.035426, 1.010711, 1.055485, 1.00664, 0.874596, 0.840662, 0.782034, 0.960034, 1.065464, 0.91116, 1.029154, 1.016113, 1.041956, 0.94594, 1.038197, 1.010267, 1.021842, 1.064241, 1.060124, 1.058187, 1.030837, 1.03162, 1.022887, 0.938471, 0.876479, 1.042369, 1.031878, 0.992018, 1.047312, 0.93035, 1.069906, 1.057901, 0.766783, 0.954321, 1.030951, 0.977892, 1.013204, 1.025217, 1.012253, 1.028178, 1.065557, 0.84282, 1.103245, 0.981218, 0.927567, 1.190567, 1.135817, 1.11851, 0.745579, 1.074413, 0.892972, 0.717667, 1.111475, 0.84308, 1.285817, 0.884184, 0.949937, 1.078251, 1.009963, 0.930185, 0.96844, 1.107436, 1.031162, 1.161345, 1.165258, 1.076716, 1.029794, 1.008188, 1.173165, 1.26895, 0.857554, 0.919873, 0.887521, 1.015009, 1.200669, 0.958936, 0.979149, 1.070616, 0.946976, 1.019518, 0.987791, 1.007625, 1.257148, 1.038777, 0.754076, 1.078727, 1.049221, 1.098134, 1.148382, 0.74274, 1.084166, 0.819342, 1.072723, 0.958094, 1.101275, 1.036348, 0.744063, 0.689913, 0.811003, 0.896867, 0.781658, 1.162044, 1.199109, 1.110908, 0.923403, 0.831603, 1.055974, 1.167772, 0.662894, 0.653821, 0.899437, 1.003726, 0.952751, 0.705241, 1.281862, 1.039594, 0.882058, 1.306628, 1.290206, 1.09357, 0.864005, 0.824926, 0.663579, 1.063836, 1.242015, 0.843297, 0.769286, 0.907494, 1.14366, 1.252945, 1.073047, 1.022525, 0.951965, 0.977462, 0.941184, 1.050544, 1.128182, 1.230836, 0.925821, 1.158545 ) Prow_niris_p150_k50_betas <- c( 5.885742, 5.736816, 5.197266, 5.471191, 5.71875, 5.699707, 5.451172, 6.242188, 4.727051, 5.95459, 5.53418, 6.278809, 5.412598, 3.991699, 4.12207, 4.150879, 4.842285, 6.005859, 5.578369, 5.635254, 6.838379, 5.978516, 4.450684, 7.612305, 7.321289, 6.594238, 6.863281, 6.144043, 6.030762, 6.04248, 6.217285, 6.470703, 4.745117, 4.282471, 6.104004, 5.433594, 5.414551, 5.560547, 4.568359, 6.307129, 5.703125, 4.453369, 4.664551, 7.005859, 6.844238, 5.671875, 5.775879, 5.260254, 5.626465, 5.994629, 13.903809, 19.361816, 17.199951, 10.595215, 21.495117, 19.960938, 22.048828, 6.962402, 17.828125, 9.40918, 6.223511, 18.996094, 11.31665, 26.000977, 9.661377, 15.227539, 18.856934, 12.867676, 20.546875, 9.992432, 22.505859, 16.000977, 23.277344, 24.697266, 18.488281, 16.779785, 17.730957, 23.207031, 25.374023, 8.538818, 8.724121, 8.112671, 12.005859, 23.245605, 16.113281, 19.423828, 17.885254, 19.319336, 13.402344, 11.15625, 15.037109, 24.227539, 12.86377, 6.838623, 14.530762, 14.649414, 15.500977, 20.317383, 7.972168, 14.302246, 8.755371, 19.519531, 9.589355, 18.270508, 11.995361, 4.407959, 11.406738, 6.748779, 14.204102, 6.195068, 22.625977, 21.842773, 14.548828, 17.580078, 15.902832, 15.451172, 19.606445, 3.676147, 3.610718, 18.935059, 10.456055, 18.219238, 4.096863, 26.099609, 12.159668, 8.970703, 27.116211, 26.008301, 15.51416, 11.36377, 7.287109, 4.036987, 14.57373, 25.604492, 17.268066, 5.501221, 11.135986, 19.822266, 25.111816, 14.611328, 11.272705, 15.021484, 9.565918, 9.592529, 15.895508, 22.691895, 22.258789, 13.867188, 22.583008 ) res <- perplexity_similarities( perplexity = 50, n_threads = 0, verbose = FALSE, ret_sigma = TRUE, nn = find_nn(normiris, k = 149, method = "fnn", metric = "euclidean", n_threads = 0, verbose = FALSE ) ) expect_equal(Matrix::rowSums(res$matrix), Prow_iris_p150_k50_rowSums, tol = 1e-6) expect_equal(1 / res$sigma, Prow_niris_p150_k50_betas, tol = 1e-6) res <- perplexity_similarities( perplexity = 50, n_threads = 1, verbose = FALSE, nn = find_nn(normiris, k = 149, method = "fnn", metric = "euclidean", n_threads = 1, verbose = FALSE ) )$matrix expect_equal(Matrix::rowSums(res), Prow_iris_p150_k50_rowSums, tol = 1e-6)
eval.func.1D<-function(func,N,support=NULL,g=1,std=1,distr=FALSE, M=NULL,sig=NULL,p=NULL,a=0.5,b=0.5,d=2) { if (func=="gauss"){ norma<-(2*pi)^(-1/2) funni<-function(t){ fu<-exp(-t^2/2); return( norma*fu ) } } if (func=="polynomial"){ support<-c(-std,std) norma<-(2*(1-1/(g+1)))^(-1) funni<-function(t){ fu<-1-abs(t)^g; return( norma*fu ) } } if (func=="student"){ norma<-gamma((g+1)/2)/((g*pi)^(1/2)*gamma(g/2)) funni<-function(t){ fu<-(1+t^2/g)^(-(g+1)/2); return( norma*fu ) } } if (func=="exponential"){ norma<-1/2 funni<-function(t){ fu<-exp(-abs(t)); return( norma*fu ) } } if (func=="exponential"){ norma<-1/2 funni<-function(t){ fu<-exp(-abs(t)); return( norma*fu ) } } if (func=="mixt"){ funni<-function(t){ mixnum<-length(p) val<-0 for (mi in 1:mixnum){ evapoint<-(t-M[mi])/sig[mi] val<-val+p[mi]*evanor(evapoint)/sig[mi] } return( val ) } } if (func=="hat"){ normavak<-((2*pi)^d*(a^(-d)-b))^(-1) norma<-normavak*(2*pi)^((d-1)/2) funni<-function(t){ fu<-a^(1-d)*exp(-a^2*t^2)-b*exp(-t^2/2); return( norma*fu ) } } if (is.null(support)) support<-c(-1,1) value<-matrix(0,N,1) step<-(support[2]-support[1])/N lowsuppo<-support[1] if (!distr){ for (i in 1:N){ inde<-i t<-lowsuppo+step*inde-step/2 value[i]<-funni(t/std)/std } } else{ inde<-1 t<-lowsuppo+step*inde-step/2 value[1]<-step*funni(t/std)/std for (i in 2:N){ inde<-i t<-lowsuppo+step*inde-step/2 value[i]<-value[i-1]+step*funni(t/std)/std } } index<-seq(1:N) len<-length(index) down<-matrix(0,len,1) high<-matrix(0,len,1) down[,1]<-index-1 high[,1]<-index res<-list( value=value, down=down,high=high, support=support,N=N) return(res) }
coefMer <- getS3method("coef", "merMod") coef.rlmerMod <- function(object, ...) { val <- coefMer(object, ...) class(val) <- "coef.rlmerMod" val } extractAIC.rlmerMod <- function(fit, scale = 0, k = 2, ...) stop("AIC is not defined for rlmerMod objects") family.rlmerMod <- function(object, ...) gaussian() fitted.rlmerMod <- getS3method("fitted", "merMod") fixef.rlmerMod <- function(object, ...) structure(object@beta, names = dimnames(.X(object))[[2]]) getFixedFormula <- function(form) { form[[3]] <- if (is.null(nb <- nobars(form[[3]]))) 1 else nb form } formula.rlmerMod <- getS3method("formula", "merMod") isREML.rlmerMod <- function(x, ...) .isREML(x, ...) isGLMM.rlmerMod <- function(x, ...) FALSE isLMM.rlmerMod <- function(x, ...) TRUE isNLMM.rlmerMod <- function(x, ...) FALSE logLik.rlmerMod <- function(object, REML = NULL, ...) stop("log-likelihood is not defined for rlmerMod objects") model.frame.rlmerMod <- getS3method("model.frame", "merMod") model.matrix.rlmerMod <- function(object, ...) .X(object) terms.rlmerMod <- getS3method("terms", "merMod") .prt.resids <- function(resids, digits, title="Scaled residuals:", ...) { cat(title,"\n") rq <- setNames(zapsmall(quantile(resids), digits + 1L), c("Min", "1Q", "Median", "3Q", "Max")) print(rq, digits=digits, ...) cat("\n") } .prt.call <- function(call, long=TRUE) { if (!is.null(cc <- call$formula)) cat("Formula:", deparse(cc),"\n") if (!is.null(cc <- call$data)) cat(" Data:", deparse(cc), "\n") if (!is.null(cc <- call$weights)) cat("Weights:", deparse(cc), "\n") if (!is.null(cc <- call$offset)) cat(" Offset:", deparse(cc), "\n") if (long && length(cc <- call$control) && !identical((dc <- deparse(cc)), "lmerControl()")) cat("Control:", dc, "\n") if (!is.null(cc <- call$subset)) cat(" Subset:", deparse(asOneSidedFormula(cc)[[2]]),"\n") } .prt.VC <- function(varcor, digits, comp, formatter=format, ...) { cat("Random effects:\n") fVC <- if(missing(comp)) formatVC(varcor, digits=digits, formatter=formatter) else formatVC(varcor, digits=digits, formatter=formatter, comp=comp) print(fVC, quote = FALSE, digits = digits, ...) } .prt.grps <- function(ngrps, nobs) { cat(sprintf("Number of obs: %d, groups: ", nobs)) cat(paste(paste(names(ngrps), ngrps, sep = ", "), collapse = "; ")) cat("\n") } setMethod("show", "rlmerMod", function(object) print.rlmerMod(object)) globalVariables("forceSymmetric", add=TRUE) vcov.rlmerMod <- getS3method("vcov", "merMod") vcov.summary.rlmerMod <- function(object, correlation = TRUE, ...) { if(is.null(object$vcov)) stop("logic error in summary of rlmerMod object") object$vcov } VarCorrMer <- getS3method("VarCorr", "merMod") VarCorr.rlmerMod <- function(x, ...) { val <- VarCorrMer(x, ...) class(val) <- "VarCorr.rlmerMod" val } VarCorr.summary.rlmerMod <- function(x, ...) x$varcor print.VarCorr.rlmerMod <- getS3method("print", "VarCorr.merMod") formatVC <- function(varcor, digits = max(3, getOption("digits") - 2), comp = "Std.Dev.", formatter = format, useScale = attr(varcor, "useSc"), ...) { c.nms <- c("Groups", "Name", "Variance", "Std.Dev.") avail.c <- c.nms[-(1:2)] if(anyNA(mcc <- pmatch(comp, avail.c))) stop("Illegal 'comp': ", comp[is.na(mcc)]) nc <- length(colnms <- c(c.nms[1:2], (use.c <- avail.c[mcc]))) if(length(use.c) == 0) stop("Must *either* show variances or standard deviations") reStdDev <- c(lapply(varcor, attr, "stddev"), if(useScale) list(Residual = unname(attr(varcor, "sc")))) reLens <- lengths(reStdDev) nr <- sum(reLens) reMat <- array('', c(nr, nc), list(rep.int('', nr), colnms)) reMat[1+cumsum(reLens)-reLens, "Groups"] <- names(reLens) reMat[,"Name"] <- c(unlist(lapply(varcor, colnames)), if(useScale) "") if(any("Variance" == use.c)) reMat[,"Variance"] <- formatter(unlist(reStdDev)^2, digits = digits, ...) if(any("Std.Dev." == use.c)) reMat[,"Std.Dev."] <- formatter(unlist(reStdDev), digits = digits, ...) if (any(reLens > 1)) { maxlen <- max(reLens) recorr <- lapply(varcor, attr, "correlation") corr <- do.call(rbind, lapply(recorr, function(x) { x <- as.matrix(x) dig <- max(2, digits - 2) cc <- format(round(x, dig), nsmall = dig) cc[!lower.tri(cc)] <- "" nr <- nrow(cc) if (nr >= maxlen) return(cc) cbind(cc, matrix("", nr, maxlen-nr)) }))[, -maxlen, drop = FALSE] if (nrow(corr) < nrow(reMat)) corr <- rbind(corr, matrix("", nrow(reMat) - nrow(corr), ncol(corr))) colnames(corr) <- c("Corr", rep.int("", max(0L, ncol(corr)-1L))) cbind(reMat, corr) } else reMat } weights.rlmerMod <- function(object, ...) { object@resp$weights } reFormHack <- function(re.form,ReForm,REForm,REform) { if (!missing(ReForm)) { message(shQuote("re.form")," is now preferred to ",shQuote("ReForm")) return(ReForm) } if (!missing(REForm)) { message(shQuote("re.form")," is now preferred to ",shQuote("REForm")) return(REForm) } if (!missing(REform)) { message(shQuote("re.form")," is now preferred to ",shQuote("REform")) return(REform) } re.form } predict.rlmerMod <- function(object, newdata=NULL, re.form=NULL, ReForm, REForm, REform, terms=NULL, type=c("link","response"), allow.new.levels=FALSE, na.action=na.pass, ...) { REform <- reFormHack(re.form,ReForm,REForm,REform) if (length(list(...)>0)) warning("unused arguments ignored") if (isLMM(object) && !missing(type)) warning("type argument ignored for linear mixed models") fit.na.action <- attr(object@frame,"na.action") type <- match.arg(type) if (!is.null(terms)) stop("terms functionality for predict not yet implemented") form_orig <- formula(object) if (is.null(newdata) && is.null(REform)) { if (isLMM(object) || isNLMM(object)) { pred <- fitted(object) } else { pred <- switch(type,response=object@resp$mu, link=object@resp$eta) } if (!is.null(fit.na.action)) { pred <- napredict(fit.na.action,pred) } return(pred) } else { X_orig <- getME(object, "X") if (is.null(newdata)) { X <- X_orig } else { RHS <- formula(object,fixed.only=TRUE)[-2] Terms <- terms(object,fixed.only=TRUE) X <- model.matrix(RHS, mfnew <- model.frame(delete.response(Terms), newdata, na.action=na.action), contrasts.arg=attr(X_orig,"contrasts")) } pred <- drop(X %*% fixef(object)) offset <- rep(0, nrow(X)) tt <- terms(object) if (!is.null(off.num <- attr(tt, "offset"))) { for (i in off.num) offset <- offset + eval(attr(tt,"variables")[[i + 1]], newdata) } if (!is.null(frOffset <- attr(object@frame,"offset"))) offset <- offset + eval(frOffset, newdata) pred <- pred+offset if (is.null(REform)) { REform <- form_orig[-2] } if (is.language(REform)) { na.action.name <- deparse(match.call()$na.action) if (!is.null(newdata) && na.action.name %in% c("na.exclude","na.omit")) { if (length(nadrop <- attr(mfnew,"na.action"))>0) { newdata <- newdata[-nadrop,] } } re <- ranef(object) if(is.null(newdata)) rfd <- object@frame else rfd <- newdata ReTrms <- mkReTrms(findbars(REform[[2]]), rfd) if (!allow.new.levels && any(sapply(ReTrms$flist,function(x) any(is.na(x))))) stop("NAs are not allowed in prediction data for grouping variables unless allow.new.levels is TRUE") unames <- unique(sort(names(ReTrms$cnms))) for (i in all.vars(REform[[2]])) { newdata[[i]] <- factor(newdata[[i]]) } Rfacs <- setNames(lapply(unames,function(x) factor(eval(parse(text=x),envir=newdata))), unames) new_levels <- lapply(Rfacs,function(x) levels(droplevels(factor(x)))) levelfun <- function(x,n) { if (any(!new_levels[[n]] %in% rownames(x))) { if (!allow.new.levels) stop("new levels detected in newdata") newx <- as.data.frame(matrix(0,nrow=length(new_levels[[n]]),ncol=ncol(x), dimnames=list(new_levels[[n]],names(x)))) newx[rownames(x),] <- x x <- newx } if (any(!rownames(x) %in% new_levels[[n]])) { x <- x[rownames(x) %in% new_levels[[n]],,drop=FALSE] } x } re_x <- mapply(levelfun,re,names(re),SIMPLIFY=FALSE) re_new <- list() if (any(!names(ReTrms$cnms) %in% names(re))) stop("grouping factors specified in REform that were not present in original model") for (i in seq_along(ReTrms$cnms)) { rname <- names(ReTrms$cnms)[i] if (any(!ReTrms$cnms[[rname]] %in% names(re[[rname]]))) stop("random effects specified in REform that were not present in original model") re_new[[i]] <- re_x[[rname]][,ReTrms$cnms[[rname]]] } re_newvec <- unlist(lapply(re_new,t)) if(!is.null(newdata)) pred <- pred + drop(as.matrix(re_newvec %*% ReTrms$Zt)) } if (isGLMM(object) && type=="response") { pred <- object@resp$family$linkinv(pred) } if (is.null(newdata) && !is.null(fit.na.action)) { pred <- napredict(fit.na.action,pred) } else { pred <- napredict(na.action,pred) } return(pred) } } forceCopy <- function(x) deepcopy(x)
getXYmat <- function(DF, xyTopLeft=TRUE, relPOA=TRUE, center=FALSE) { if(!is.data.frame(DF)) { stop("DF must be a data frame") } DF <- setNames(DF, tolower(names(DF))) dfNames <- names(DF) needsXY1 <- c("point.x", "point.y") needsXY2 <- c("x", "y") wantsAIM <- c("aim.x", "aim.y") hasXY1 <- needsXY1 %in% dfNames hasXY2 <- needsXY2 %in% dfNames hasAIM <- wantsAIM %in% dfNames if(!xor(all(hasXY1), all(hasXY2))) { stop("Coordinates must be named either x, y or point.x, point.y") } if(("z" %in% dfNames) && ("point.z" %in% dfNames)) { stop("Coordinates must be named either z or point.z") } if(!all(hasAIM) && relPOA) { warning(c("The data frame is missing variable(s)\n", paste(wantsAIM[!hasAIM], collapse=" "), "\n", "Point of Aim is assumed to be in (0,0)")) relPOA <- FALSE } if(all(hasXY2)) { dfNames <- names(DF) dfNames[dfNames %in% "x"] <- "point.x" dfNames[dfNames %in% "y"] <- "point.y" dfNames[dfNames %in% "z"] <- "point.z" warning("Variables x, y were renamed to point.x, point.y") names(DF) <- dfNames } centerOne <- function(x) { x$aim.x <- mean(x$point.x) x$aim.y <- mean(x$point.y) if(hasName(x, "point.z")) { x$aim.z <- mean(x$point.z) } x } DF <- if(center) { if(hasName(DF, "series")) { DFspl <- split(DF, DF$series, drop=TRUE) DFL <- lapply(DFspl, centerOne) do.call("rbind", DFL) } else { centerOne(DF) } } else { DF } if(!relPOA && !center) { DF$aim.x <- 0 DF$aim.y <- 0 if("point.z" %in% dfNames) { DF$aim.z <- 0 } } if(!hasName(DF, "aim.x") || !hasName(DF, "aim.y")) { DF$aim.x <- 0 DF$aim.y <- 0 } x <- DF$point.x - DF$aim.x y <- if(xyTopLeft) { -(DF$point.y - DF$aim.y) } else { DF$point.y - DF$aim.y } z <- if("point.z" %in% dfNames) { DF$point.z - DF$aim.z } else { NULL } return(cbind(x, y, z)) }
fillgvp <- function(x, method = "linear", n = 4) { if(dim(x)[1] == 0) { stop("Dimension of data-set must be higher than 0.") } names <- c("glucose") names <- match(names, names(x)) if(any(is.na(names))) { stop("Name of data-set must be glucose.") } if(all(is.na(x$glucose))) { stop("Variable glucose must be non-NA value.") } if(!is.numeric(x$glucose)) { stop("Variable glucose must be numeric.") } if(method != "linear" && method != "cubic") { stop("method must be linear or cubic.") } if(!is.numeric(n)) { stop("n must be numeric.") } if(n < 0) { stop("n must be positive values.") } position <- is.na(x$glucose) na.before <- dim(x[position,])[1] if(method == "linear") { x$glucose <- round(na.approx(x$glucose, maxgap = n, na.rm = F), digits = 0) } else if(method == "cubic") { x$glucose <- round(na.spline(x$glucose, maxgap = n, na.rm = F), digits = 0) } position <- is.na(x$glucose) na.after <- na.before - dim(x[position,])[1] message(paste(na.before, "NA glucose values in dataset before filling.")) message(paste(na.after, "NA glucose values filled.")) message(paste(dim(x[position,])[1], "NA glucose values in dataset after filling.")) return(x) }
context("site") test_that("rmarkdown::render_site", { skip_on_cran() site_dir <- tempfile() dir.create(site_dir) files <- c("_site.yml", "index.Rmd", "tech-docs.Rmd", "404.md", "accessibility.md", "LICENSE.md", "NEWS.md", "README.md", "images", "favicon") file.copy(file.path("site", files), site_dir, recursive = TRUE) capture.output(rmarkdown::render_site(site_dir)) html_files <- c("index.html", "tech-docs.html", "404.html", "accessibility.html", "LICENSE.html", "NEWS.html") html_files <- file.path(site_dir, "docs", html_files) expect_true(all(file.exists(html_files))) moved <- c("site_libs", "favicon", "images") expect_true(all(file.exists(file.path(site_dir, "docs", moved)))) })
strangle.bls = function(S,K1,K2,r,t,sd,plot=FALSE){ all=list(S,K1,K2,r,t,sd,plot) if(any(lapply(all,is.null)==T)) stop("Cannot input any variables as NULL.") if(any(lapply(all,length) != 1)==T) stop("All inputs must be of length 1.") num2=list(S,K1,K2,r,t,sd) na.num2=num2[which(lapply(num2,is.na)==F)] if(any(lapply(na.num2,is.numeric)==F)) stop("S, K1, K2, r, t, and sd must be numeric.") nalist=list(S,K1,K2,r,t,sd,plot) if(any(lapply(nalist,is.na)==T)) stop("Cannot input any variables as NA.") stopifnot(is.logical(plot)) NA.Neg=array(c(S,K1,K2,r,t,sd)) NA.Neg.Str=c("S","K1","K2","r","t","sd") app=apply(NA.Neg,1,is.na) na.s=which(app==F & NA.Neg<=0) if(length(na.s)>0) {errs=paste(NA.Neg.Str[na.s],collapse=" & ") stop(cat("Error: '",errs, "' must be positive real number(s).\n"))} na.s2=which(app==F & NA.Neg==Inf) if(length(na.s2)>0) {errs=paste(NA.Neg.Str[na.s2],collapse=" & ") stop(cat("Error: '",errs, "' cannot be infinite.\n"))} if(K1>=K2) stop("K1 must be less than K2.") if(K2<=S | K1>=S) stop("K2 must be > S and K1 must be < S") d1 = (log(S/K1)+(r+sd^2/2)*t)/(sd*sqrt(t)) d2 = d1 - sd * sqrt(t) putP = K1*exp(-r*t) * pnorm(-d2) - S*pnorm(-d1) d1 = (log(S/K2)+(r+sd^2/2)*t)/(sd*sqrt(t)) d2 = d1 - sd * sqrt(t) callP = S*pnorm(d1) - K2*exp(-r*t)*pnorm(d2) stock=unique(round(seq(0,K1,length.out=6))) stock=c(stock,round(seq(K1,K2,length.out=4))) stock=c(stock,round(seq(K2,K2+K1,length.out=6))) stock=unique(stock) stock2=unique(round(c(seq(0,K1,length.out=6),seq(K2,K2+K1,length.out=6)))) payoff=rep(0,length(stock)) profit=rep(0,length(stock)) for(i in 1:length(stock)){ if(stock[i]<=K1) payoff[i]=K1-stock[i] if(stock[i]>=K2) payoff[i]=stock[i]-K2 if(stock[i]<K2 & stock[i]>K1) payoff[i]=0 profit[i]=payoff[i]+(-callP-putP)*exp(r*t) } if(plot==T){ plot(stock,profit,type="l",xlab="Stock Price",main="Strangle\nPayoff and Profit",ylab="$", ylim=c(min(profit,payoff),max(profit,payoff)),xaxt='n',yaxt='n',col="steelblue",lwd=2) lines(stock,payoff,lty=2,lwd=2,col="firebrick") abline(h=0,lty=2,col="gray") y=round(seq(min(payoff,profit),max(payoff,profit),length.out=8)) axis(2,at=y,labels=y,las=2) axis(1,at=if(K2-K1<7) stock2[-which(stock2==round(K2))] else stock2,las=2) legend("top",c("Profit","Payoff"),lty=c(1,2),col=c("steelblue","firebrick"),lwd=c(2,2)) } out1=data.frame(stock,payoff,profit) names(out1)=c("Stock Price","Payoff","Profit") out2=matrix(c(putP,callP,callP+putP),nrow=3) rownames(out2)=c("Put (K1)","Call (K2)","Net Cost") colnames(out2)=c("Premiums") out=list(Payoff=out1,Premiums=out2) return(out) }
library("testthat") context("test-largeBernoulli.R") suppressWarnings(RNGversion("3.5.0")) test_that("Separable covariates in logistic regression", { skip_on_cran() set.seed(666) simulant <- simulateCyclopsData(nstrata = 1, ncovars = 5, model = "logistic") successes <- simulant$outcomes$rowId[simulant$outcomes$y == 1] separable <- simulant$covariates[simulant$covariates$covariateId == 3 & simulant$covariates$rowId %in% successes,] separable$covariateId <- 6 simulant$covariates <- rbind(simulant$covariates, separable) data <- convertToCyclopsData(simulant$outcomes, simulant$covariates, modelType = "lr", addIntercept = TRUE) fit <- fitCyclopsModel(data, prior = createPrior("none")) expect_error(coef(fit), "did not converge") separability <- getUnivariableSeparability(data) expect_equal(sum(separability), 1.0) scFit <- fitCyclopsModel(data, prior = createPrior("none"), forceNewObject = TRUE, fixedCoefficients = separability) expect_equivalent(coef(scFit)[separability], 0.0) separability <- is.nan(coef(fit, ignoreConvergence = TRUE)) ecFit <- fitCyclopsModel(data, prior = createPrior("none"), forceNewObject = TRUE, fixedCoefficients = separability) expect_equivalent(coef(ecFit)[separability], 0.0) nsFit <- fitCyclopsModel(data, prior = createNonSeparablePrior(), forceNewObject = TRUE) expect_true(is.na(coef(nsFit)[7])) }) test_that("Separable covariates in cox regression", { skip_on_cran() set.seed(666) simulant <- simulateCyclopsData(nstrata = 1, ncovars = 5, model = "survival") successes <- simulant$outcomes$rowId[simulant$outcomes$y == 1] separable <- simulant$covariates[simulant$covariates$covariateId == 3 & simulant$covariates$rowId %in% successes,] separable$covariateId <- 6 simulant$covariates <- rbind(simulant$covariates, separable) data <- convertToCyclopsData(simulant$outcomes, simulant$covariates, modelType = "cox") fit <- fitCyclopsModel(data, prior = createPrior("none")) separability <- getUnivariableSeparability(data) expect_equal(sum(separability), 1.0) fit <- fitCyclopsModel(data, prior = createPrior("none"), forceNewObject = TRUE, fixedCoefficients = separability) expect_equivalent(coef(fit)[separability], 0.0) })
"pwr.2p.test" <- function (h = NULL, n = NULL, sig.level = 0.05, power = NULL, alternative = c("two.sided","less","greater")) { if (sum(sapply(list(h, n, power, sig.level), is.null)) != 1) stop("exactly one of h, n, power, and sig.level must be NULL") if (!is.null(h) && is.character(h)) h <- cohen.ES(test="p",size=h)$effect.size if (!is.null(n) && any(n < 1)) stop("number of observations in each group must be at least 1") if (!is.null(sig.level) && !is.numeric(sig.level) || any(0 > sig.level | sig.level > 1)) stop(sQuote("sig.level"), " must be numeric in [0, 1]") if (!is.null(power) && !is.numeric(power) || any(0 > power | power > 1)) stop(sQuote("power"), " must be numeric in [0, 1]") alternative <- match.arg(alternative) tside <- switch(alternative, less = 1, two.sided = 2, greater=3) if (tside == 2 && !is.null(h)) h <- abs(h) if (tside == 3) { p.body <- quote({ pnorm(qnorm(sig.level, lower = FALSE) - h * sqrt(n/2), lower = FALSE) }) } if (tside == 2) { p.body <- quote({ pnorm(qnorm(sig.level/2, lower = FALSE) - h * sqrt(n/2), lower = FALSE) + pnorm(qnorm(sig.level/2, lower = TRUE) - h * sqrt(n/2), lower = TRUE) }) } if (tside ==1) { p.body <- quote({ pnorm(qnorm(sig.level, lower = TRUE) - h * sqrt(n/2), lower = TRUE) }) } if (is.null(power)) power <- eval(p.body) else if (is.null(h)){ if(tside==2) h <- uniroot(function(h) eval(p.body) - power, c(1e-10,10))$root if(tside==1) h <- uniroot(function(h) eval(p.body) - power, c(-10,5))$root if(tside==3) h <- uniroot(function(h) eval(p.body) - power, c(-5,10))$root } else if (is.null(n)) n <- uniroot(function(n) eval(p.body) - power, c(2 + 1e-10, 1e+09))$root else if (is.null(sig.level)) sig.level <- uniroot(function(sig.level) eval(p.body) - power, c(1e-10, 1 - 1e-10))$root else stop("internal error") NOTE <- "same sample sizes" METHOD <- "Difference of proportion power calculation for binomial distribution (arcsine transformation)" structure(list(h = h, n = n, sig.level = sig.level, power = power, alternative = alternative, method = METHOD, note = NOTE), class = "power.htest") }
zmatrix <- function(partition, s, ps){ partition <- check_phypartition(tip_labels = colnames(ps$structure), partition = partition) parameters <- ps$parameters structure_matrix <- ps$structure T_bar <- ps$tbar L_j <- colSums(structure_matrix * T_bar) L_j <- L_j[match(parameters$tip_label, colnames(structure_matrix))] if (any(row.names(partition) != colnames(structure_matrix))) stop("Partition does not match phylogeny.") scaling_factor <- T_bar / L_j scaling_matrix <- diag(scaling_factor, nrow(structure_matrix)) z <- s %*% scaling_matrix colnames(z) <- row.names(z) new("similarity", similarity = z, dat_id = "phybranch", parameters = list(transform = NA, k = NA, normalise = NA, max_d = NA)) }
set_block <- function(plate, block, what, value) { if (! "well" %in% colnames(plate)) stop(dQuote("plate"), " data frame misses ", dQuote("well"), " column containing well IDs.") if (what != make.names(what)) warning("Column name not syntactically correct. See ", dQuote("?make.names"), ".") set_block_ <- function(plate, block) { plateRows <- factor(gsub("[[:digit:]]+", "", plate$well)) plateCols <- factor(as.numeric(gsub("[[:alpha:]]+", "", plate$well))) startWell <- sub("~.*", "", block) endWell <- sub(".*~", "", block) startRow <- substr(startWell, 1,1) endRow <- substr(endWell, 1,1) startCol <- as.numeric(substr(startWell, 2,3)) endCol <- as.numeric(substr(endWell, 2,3)) targetRows <- LETTERS[seq(which(LETTERS == startRow), which(LETTERS == endRow))] targetCols <- seq(startCol, endCol) plate[plateRows %in% targetRows & plateCols %in% targetCols, what] <- value plate } Reduce(set_block_, block, plate) }
Loglogistic <- R6Class("Loglogistic", inherit = SDistribution, lock_objects = F, public = list( name = "Loglogistic", short_name = "LLogis", description = "Loglogistic Probability Distribution.", packages = "actuar", initialize = function(scale = NULL, shape = NULL, rate = NULL, decorators = NULL) { super$initialize( decorators = decorators, support = PosReals$new(zero = T), type = PosReals$new(zero = T) ) }, mean = function(...) { scale <- unlist(self$getParameterValue("scale")) shape <- unlist(self$getParameterValue("shape")) return((scale * pi / shape) / sin(pi / shape)) }, mode = function(which = "all") { scale <- unlist(self$getParameterValue("scale")) shape <- unlist(self$getParameterValue("shape")) return(scale * ((shape - 1) / (shape + 1))^(1 / shape)) }, median = function() { unlist(self$getParameterValue("scale")) }, variance = function(...) { scale <- unlist(self$getParameterValue("scale")) shape <- unlist(self$getParameterValue("shape")) shapi <- pi / shape var <- rep(NaN, length(scale)) var[shape > 2] <- scale[shape > 2]^2 * ((2 * shapi[shape > 2]) / sin(2 * shapi[shape > 2]) - (shapi[shape > 2]^2) / sin(shapi[shape > 2])^2) return(var) }, skewness = function(...) { scale <- unlist(self$getParameterValue("scale")) shape <- unlist(self$getParameterValue("shape")) shapi <- pi / shape skew <- rep(NaN, length(scale)) s1 <- (2 * shapi[shape > 3]^3 * scale[shape > 3]^3) / sin(shapi[shape > 3])^3 s2 <- (6 * shapi[shape > 3]^2 * scale[shape > 3]^3) * (1 / sin(shapi[shape > 3])) * (1 / sin(2 * shapi[shape > 3])) s3 <- (3 * shapi[shape > 3] * scale[shape > 3]^3) / sin(3 * shapi[shape > 3]) skew[shape > 3] <- s1 - s2 + s3 return(skew) }, kurtosis = function(excess = TRUE, ...) { scale <- unlist(self$getParameterValue("scale")) shape <- unlist(self$getParameterValue("shape")) shapi <- pi / shape kurtosis <- rep(NaN, length(scale)) s1 <- (3 * shapi[shape > 4]^4 * scale[shape > 4]^4) / sin(shapi[shape > 4])^4 s2 <- (12 * shapi[shape > 4]^3 * scale[shape > 4]^4) * (1 / sin(shapi[shape > 4])^2) * (1 / sin(2 * shapi[shape > 4])) s3 <- (12 * shapi[shape > 4]^2 * scale[shape > 4]^4) * (1 / sin(shapi[shape > 4])) * (1 / sin(3 * shapi[shape > 4])) s4 <- (4 * shapi[shape > 4] * scale[shape > 4]^4) * (1 / sin(4 * shapi[shape > 4])) kurtosis[shape > 4] <- -s1 + s2 - s3 + s4 return(kurtosis) }, pgf = function(z, ...) { return(NaN) } ), private = list( .pdf = function(x, log = FALSE) { if (checkmate::testList(self$getParameterValue("shape"))) { mapply(actuar::dllogis, shape = self$getParameterValue("shape"), rate = self$getParameterValue("rate"), MoreArgs = list(x = x, log = log) ) } else { actuar::dllogis(x, shape = self$getParameterValue("shape"), rate = self$getParameterValue("rate"), log = log) } }, .cdf = function(x, lower.tail = TRUE, log.p = FALSE) { if (checkmate::testList(self$getParameterValue("shape"))) { mapply(actuar::pllogis, shape = self$getParameterValue("shape"), rate = self$getParameterValue("rate"), MoreArgs = list(q = x, lower.tail = lower.tail, log.p = log.p) ) } else { actuar::pllogis(x, shape = self$getParameterValue("shape"), rate = self$getParameterValue("rate"), lower.tail = lower.tail, log.p = log.p ) } }, .quantile = function(p, lower.tail = TRUE, log.p = FALSE) { if (checkmate::testList(self$getParameterValue("shape"))) { mapply(actuar::qllogis, shape = self$getParameterValue("shape"), rate = self$getParameterValue("rate"), MoreArgs = list(p = p, lower.tail = lower.tail, log.p = log.p) ) } else { actuar::qllogis(p, shape = self$getParameterValue("shape"), rate = self$getParameterValue("rate"), lower.tail = lower.tail, log.p = log.p ) } }, .rand = function(n) { if (checkmate::testList(self$getParameterValue("shape"))) { mapply(actuar::rllogis, shape = self$getParameterValue("shape"), rate = self$getParameterValue("rate"), MoreArgs = list(n = n) ) } else { actuar::rllogis(n, shape = self$getParameterValue("shape"), rate = self$getParameterValue("rate")) } }, .traits = list(valueSupport = "continuous", variateForm = "univariate") ) ) .distr6$distributions <- rbind( .distr6$distributions, data.table::data.table( ShortName = "LLogis", ClassName = "Loglogistic", Type = "\u211D+", ValueSupport = "continuous", VariateForm = "univariate", Package = "actuar", Tags = "" ) )
build <- function(pkg = ".", path = NULL, binary = FALSE, vignettes = TRUE, manual = FALSE, args = NULL, quiet = FALSE, ...) { save_all() if (!file_exists(pkg)) { stop("`pkg` must exist", call. = FALSE) } check_dots_used(action = getOption("devtools.ellipsis_action", rlang::warn)) pkgbuild::build( path = pkg, dest_path = path, binary = binary, vignettes = vignettes, manual = manual, args = args, quiet = quiet, ... ) } pkgbuild::with_debug pkgbuild::clean_dll pkgbuild::has_devel pkgbuild::find_rtools
url <- "https://github.com/oneapi-src/oneTBB/archive/refs/tags/v2021.1.1.tar.gz" owd <- setwd("src") unlink("tbb", recursive = TRUE) download.file(url, destfile = basename(url), mode = "wb") before <- list.files() untar(basename(url)) after <- list.files() folder <- setdiff(after, before) print(folder) file.rename(folder, "tbb") unlink(basename(url))
NI.D5.calc2 <- function(p.vec, Se, Sp, ordering, group.mem, a, trace = TRUE, print.time = TRUE, ...) { start.time <- proc.time() I <- ncol(group.mem) joint.p <- matrix(data = rep(p.vec, times = I), nrow = 4, ncol = I, byrow = FALSE, dimnames = list(joint.p.row.labels(ordering), as.character(1:I))) save.info <- TwoDisease.Hierarchical(joint.p = joint.p, group.mem = group.mem, Se = Se, Sp = Sp, ordering = ordering, a = 1:I, accuracy = TRUE) ind.acc1.all <- save.info$Disease1$Individual rownames(ind.acc1.all) <- ind.acc1.all[, "Individual"] check1 <- check.all.equal(ind.acc1.all, which(colnames(ind.acc1.all) == "PSp")) if (is.null(check1)) { ind.acc1 <- get.unique.index(ind.acc1.all[a,], which(colnames(ind.acc1.all) == "PSp"), rowlabel = a)[,-1] } else { ind.acc1 <- check1[,-1] } ind.acc2.all <- save.info$Disease2$Individual rownames(ind.acc2.all) <- ind.acc2.all[, "Individual"] check2 <- check.all.equal(ind.acc2.all, which(colnames(ind.acc2.all) == "PSp")) if (is.null(check2)) { ind.acc2 <- get.unique.index(ind.acc2.all[a,], which(colnames(ind.acc2.all) == "PSp"), rowlabel = a)[,-1] } else { ind.acc2 <- check2[,-1] } acc.dis1 <- save.info$Disease1$Overall acc.dis2 <- save.info$Disease2$Overall save.it <- c(I, save.info$Expt, save.info$Expt / I, acc.dis1, acc.dis2) accuracy.mat <- matrix(data = save.it[4:11], nrow = 2, ncol = 4, byrow = TRUE, dimnames = list("Disease" = 1:2, c("PSe", "PSp", "PPPV", "PNPV"))) Se.display <- matrix(data = Se, nrow = 2, ncol = 5, dimnames = list("Disease" = 1:2, "Stage" = 1:5)) Sp.display <- matrix(data = Sp, nrow = 2, ncol = 5, dimnames = list("Disease" = 1:2, "Stage" = 1:5)) if (print.time) { time.it(start.time) } list("algorithm" = "Non-informative five-stage hierarchical testing", "prob.vec" = p.vec, "Se" = Se.display, "Sp" = Sp.display, "Config" = list("Stage1" = save.it[1], "Stage2" = get.pools(group.mem[2,]), "Stage3" = get.pools(group.mem[3,]), "Stage4" = get.pools(group.mem[4,])), "p.mat" = joint.p, "ET" = save.it[2], "value" = save.it[3], "Accuracy" = list("Disease 1 Individual" = ind.acc1, "Disease 2 Individual" = ind.acc2, "Overall" = accuracy.mat)) }
NULL measurementInvariance <- function(..., std.lv = FALSE, strict = FALSE, quiet = FALSE, fit.measures = "default", baseline.model = NULL, method = "satorra.bentler.2001") { .Deprecated(msg = c("The measurementInvariance function is deprecated, and", " it will cease to be included in future versions of ", "semTools. See help('semTools-deprecated) for details.")) lavaancfa <- function(...) { lavaan::cfa(...) } dotdotdot <- list(...) if (is.null(dotdotdot$model)) stop('all lavaan() and lavOptions() arguments must', ' named, including the "model=" argument.') if (!is.null(dotdotdot$group.equal)) stop("lavaan ERROR: group.equal argument should not be used") if (names(dotdotdot)[1] == "") names(dotdotdot)[1] <- "model" res <- list() configural <- dotdotdot configural$group.equal <- "" template <- try(do.call(lavaancfa, configural), silent = TRUE) if (class(template) == "try-error") stop('Configural model did not converge.') pttemplate <- parTable(template) varnames <- unique(pttemplate$rhs[pttemplate$op == "=~"]) facnames <- unique(pttemplate$lhs[(pttemplate$op == "=~") & (pttemplate$rhs %in% varnames)]) ngroups <- max(pttemplate$group) if (ngroups <= 1) stop("Well, the number of groups is 1. Measurement", " invariance across 'groups' cannot be done.") if (std.lv) { for (i in facnames) { pttemplate <- fixParTable(pttemplate, i, "~~", i, 1:ngroups, 1) } fixloadings <- which(pttemplate$op == "=~" & pttemplate$free == 0) for (i in fixloadings) { pttemplate <- freeParTable(pttemplate, pttemplate$lhs[i], "=~", pttemplate$rhs[i], pttemplate$group[i]) } dotdotdot$model <- pttemplate res$fit.configural <- try(do.call(lavaancfa, dotdotdot), silent = TRUE) } else { res$fit.configural <- template } if (std.lv) { findloadings <- which(pttemplate$op == "=~" & pttemplate$free != 0 & pttemplate$group == 1) for (i in findloadings) { pttemplate <- constrainParTable(pttemplate, pttemplate$lhs[i], "=~", pttemplate$rhs[i], 1:ngroups) } for (i in facnames) { pttemplate <- freeParTable(pttemplate, i, "~~", i, 2:ngroups) } dotdotdot$model <- pttemplate res$fit.loadings <- try(do.call(lavaancfa, dotdotdot), silent = TRUE) } else { loadings <- dotdotdot loadings$group.equal <- c("loadings") res$fit.loadings <- try(do.call(lavaancfa, loadings), silent = TRUE) } if (std.lv) { findintcepts <- which(pttemplate$op == "~1" & pttemplate$lhs %in% varnames & pttemplate$free != 0 & pttemplate$group == 1) for (i in findintcepts) { pttemplate <- constrainParTable(pttemplate, pttemplate$lhs[i], "~1", "", 1:ngroups) } for (i in facnames) { pttemplate <- freeParTable(pttemplate, i, "~1", "", 2:ngroups) } dotdotdot$model <- pttemplate res$fit.intercepts <- try(do.call(lavaancfa, dotdotdot), silent = TRUE) } else { intercepts <- dotdotdot intercepts$group.equal <- c("loadings", "intercepts") res$fit.intercepts <- try(do.call(lavaancfa, intercepts), silent = TRUE) } if (strict) { if (std.lv) { findresiduals <- which(pttemplate$op == "~~" & pttemplate$lhs %in% varnames & pttemplate$rhs == pttemplate$lhs & pttemplate$free != 0 & pttemplate$group == 1) for (i in findresiduals) { pttemplate <- constrainParTable(pttemplate, pttemplate$lhs[i], "~~", pttemplate$rhs[i], 1:ngroups) } dotdotdot$model <- pttemplate res$fit.residuals <- try(do.call(lavaancfa, dotdotdot), silent = TRUE) for (i in facnames) { pttemplate <- fixParTable(pttemplate, i, "~1", "", 1:ngroups, 0) } dotdotdot$model <- pttemplate res$fit.means <- try(do.call(lavaancfa, dotdotdot), silent = TRUE) } else { residuals <- dotdotdot residuals$group.equal <- c("loadings", "intercepts", "residuals") res$fit.residuals <- try(do.call(lavaancfa, residuals), silent = TRUE) means <- dotdotdot means$group.equal <- c("loadings", "intercepts", "residuals", "means") res$fit.means <- try(do.call(lavaancfa, means), silent = TRUE) } } else { if (std.lv) { for (i in facnames) { pttemplate <- fixParTable(pttemplate, i, "~1", "", 1:ngroups, 0) } dotdotdot$model <- pttemplate res$fit.means <- try(do.call(lavaancfa, dotdotdot), silent = TRUE) } else { means <- dotdotdot means$group.equal <- c("loadings", "intercepts", "means") res$fit.means <- try(do.call(lavaancfa, means), silent = TRUE) } } if (!quiet) printInvarianceResult(res, fit.measures, baseline.model, method) invisible(res) } printInvarianceResult <- function(FIT, fit.measures, baseline.model, method) { NAMES <- names(FIT) nonconv <- which(sapply(FIT, class) == "try-error") if (length(nonconv)) { message('The following model(s) did not converge: \n', paste(NAMES[nonconv], sep = "\n")) FIT <- FIT[-nonconv] NAMES <- NAMES[-nonconv] } names(FIT) <- NULL lavaanLavTestLRT <- function(...) lavaan::lavTestLRT(...) TABLE <- do.call(lavaanLavTestLRT, c(FIT, list(model.names = NAMES, method = method))) if (length(fit.measures) == 1L && fit.measures == "default") { if (length(lavInspect(FIT[[1]], "test")) > 1L) { if (lavInspect(FIT[[1]], "test")[[2]]$test %in% c("satorra.bentler", "yuan.bentler")) { fit.measures <- c("cfi.robust", "rmsea.robust") } else fit.measures <- c("cfi.scaled", "rmsea.scaled") } else { fit.measures <- c("cfi", "rmsea") } } if (length(fit.measures)) { FM <- lapply(FIT, fitMeasures, fit.measures = fit.measures, baseline.model = baseline.model) FM.table1 <- sapply(fit.measures, function(x) sapply(FM, "[[", x)) if (length(FM) == 1L) { FM.table1 <- rbind( rep(as.numeric(NA), length(fit.measures)), FM.table1) } if (length(FM) > 1L) { FM.table2 <- rbind(as.numeric(NA), abs(apply(FM.table1, 2, diff))) colnames(FM.table2) <- paste(colnames(FM.table2), ".delta", sep = "") FM.TABLE <- as.data.frame(cbind(FM.table1, FM.table2)) } else { FM.TABLE <- as.data.frame(FM.table1) } rownames(FM.TABLE) <- rownames(TABLE) class(FM.TABLE) <- c("lavaan.data.frame", "data.frame") } cat("\n") cat("Measurement invariance models:\n\n") cat(paste(paste("Model", seq_along(FIT), ":", NAMES), collapse = "\n")) cat("\n\n") print(TABLE) if (length(fit.measures)) { cat("\n\n") cat("Fit measures:\n\n") print(FM.TABLE) cat("\n") return(list(anova = TABLE, fitMeasures = FM.TABLE)) } TABLE }
context("get_decon") test_that("get_decon produces an opinionated dataset", { skip_if_offline() skip_on_cran() cesR::get_decon() expect_true(exists("decon")) }) test_that("get_decon produces an error message if the decon object already exists", { skip_if_offline() skip_on_cran() expect_error(cesR::get_decon()) })
svygpg <- function(formula, design, ...) { if( length( attr( terms.formula( formula ) , "term.labels" ) ) > 1 ) stop( "convey package functions currently only support one variable in the `formula=` argument" ) UseMethod("svygpg", design) } svygpg.survey.design <- function(formula, design, sex, na.rm=FALSE,...) { if (is.null(attr(design, "full_design"))) stop("you must run the ?convey_prep function on your linearized survey design object immediately after creating it with the svydesign() function.") wagevar <- model.frame(formula, design$variables, na.action = na.pass)[[1]] mf <- model.frame(sex, design$variables, na.action = na.pass) xx <- lapply(attr(terms(sex), "variables")[-1], function(tt) model.matrix(eval(bquote(~0 + .(tt))), mf)) cols <- sapply(xx, NCOL) sex <- matrix(nrow = NROW(xx[[1]]), ncol = sum(cols)) scols <- c(0, cumsum(cols)) for (i in 1:length(xx))sex[, scols[i] + 1:cols[i]] <- xx[[i]] colnames(sex) <- do.call("c", lapply(xx, colnames)) sex <- as.matrix(sex) x <- cbind(wagevar,sex) if(na.rm){ nas<-rowSums(is.na(x)) design<-design[nas==0,] if (length(nas) > length(design$prob)){ wagevar <- wagevar[nas == 0] sex <- sex[nas==0,] } else{ wagevar[nas > 0] <- 0 sex[nas > 0,] <- 0 } } w <- 1 / design$prob ind <- names(design$prob) if(na.rm){ if (length(nas) > length(design$prob)) sex <- sex[!nas,] else sex[nas] <- 0 } col_female <- grep("female", colnames(sex)) col_male <- setdiff(1:2, col_female) INDM <- list(value = sum(sex[, col_male]*w), lin=sex[, col_male]) INDF <- list(value = sum(sex[, col_female]*w), lin=sex[, col_female]) TM <- list(value = sum(wagevar*sex[, col_male]*w), lin=wagevar*sex[, col_male]) TF <- list(value = sum(wagevar*sex[, col_female]*w), lin=wagevar*sex[, col_female]) list_all_tot <- list(INDM=INDM,INDF=INDF,TM=TM,TF=TF) IGPG <- contrastinf( quote( ( TM / INDM - TF / INDF ) / ( TM / INDM ) ) , list_all_tot ) infun <- IGPG$lin rval <- IGPG$value variance <- survey::svyrecvar(infun/design$prob, design$cluster, design$strata, design$fpc, postStrata = design$postStrata) colnames( variance ) <- rownames( variance ) <- names( rval ) <- strsplit( as.character( formula )[[2]] , ' \\+ ' )[[1]] class(rval) <- c( "cvystat" , "svystat" ) attr( rval , "var" ) <- variance attr(rval, "lin") <- infun attr( rval , "statistic" ) <- "gpg" rval } svygpg.svyrep.design <- function(formula, design, sex,na.rm=FALSE, ...) { if (is.null(attr(design, "full_design"))) stop("you must run the ?convey_prep function on your replicate-weighted survey design object immediately after creating it with the svrepdesign() function.") wage <- terms.formula(formula)[[2]] df <- model.frame(design) wage <- df[[as.character(wage)]] if(na.rm){ nas<-is.na(wage) design<-design[!nas,] df <- model.frame(design) wage <- wage[!nas] } ws <- weights(design, "sampling") design <- update(design, one = rep(1, length(wage))) mf <- model.frame(sex, design$variables, na.action = na.pass) xx <- lapply(attr(terms(sex), "variables")[-1], function(tt) model.matrix(eval(bquote(~0 + .(tt))), mf)) cols <- sapply(xx, NCOL) sex <- matrix(nrow = NROW(xx[[1]]), ncol = sum(cols)) scols <- c(0, cumsum(cols)) for (i in 1:length(xx)) sex[, scols[i] + 1:cols[i]] <- xx[[i]] colnames(sex) <- do.call("c", lapply(xx, colnames)) sex <- as.matrix(sex) ComputeGpg <- function(earn_hour, w, sex) { col_female <- grep("female", colnames(sex)) col_male <- setdiff(1:2, col_female) ind_men <- sex[, col_male] ind_fem <- sex[, col_female] med_men <- sum(ind_men * earn_hour * w)/sum(ind_men * w) med_fem <- sum(ind_fem * earn_hour * w)/sum(ind_fem * w) gpg <- (med_men - med_fem)/med_men gpg } rval <- ComputeGpg(earn_hour = wage, w = ws, sex = sex) ww <- weights(design, "analysis") qq <- apply(ww, 2, function(wi) ComputeGpg(wage, wi, sex = sex)) if(anyNA(qq))variance <- NA else variance <- survey::svrVar(qq, design$scale, design$rscales, mse = design$mse, coef = rval) variance <- as.matrix( variance ) colnames( variance ) <- rownames( variance ) <- names( rval ) <- strsplit( as.character( formula )[[2]] , ' \\+ ' )[[1]] class(rval) <- c( "cvystat" , "svrepstat" ) attr(rval, "var") <- variance attr(rval, "statistic") <- "gpg" rval } svygpg.DBIsvydesign <- function (formula, design, sex, ...){ if (!( "logical" %in% class(attr(design, "full_design"))) ){ full_design <- attr( design , "full_design" ) full_design$variables <- cbind( getvars(formula, attr( design , "full_design" )$db$connection, attr( design , "full_design" )$db$tablename,updates = attr( design , "full_design" )$updates, subset = attr( design , "full_design" )$subset), getvars(sex, attr( design , "full_design" )$db$connection, attr( design , "full_design" )$db$tablename,updates = attr( design , "full_design" )$updates, subset = attr( design , "full_design" )$subset) ) attr( design , "full_design" ) <- full_design rm( full_design ) } design$variables <- cbind( getvars(formula, design$db$connection,design$db$tablename, updates = design$updates, subset = design$subset), getvars(sex, design$db$connection, design$db$tablename,updates = design$updates, subset = design$subset) ) NextMethod("svygpg", design) }
library(testthat) context("Testing if repo command works properly") source("R/test_utils.R") test_that_template("Test template creation - various options", { wspace_dir <- get_wspace_dir() retcode <- rsuite_run(args = c("tmpl", "start", "-n", "TestTemplate1"), wd = wspace_dir) expect(retcode == 0, sprintf("Failed to create template in wspace directory(errcode %s)"), retcode) expect_true(dir.exists(file.path(wspace_dir, "TestTemplate1", "project"))) expect_true(dir.exists(file.path(wspace_dir, "TestTemplate1", "package"))) retcode <- rsuite_run(args = c("tmpl", "start", "-n", "TestTemplate2", "--prj", "--pkg"), wd = wspace_dir) expect(retcode == 0, sprintf("Failed to create template in wspace directory(errcode %s)"), retcode) expect_true(dir.exists(file.path(wspace_dir, "TestTemplate2", "project"))) expect_true(dir.exists(file.path(wspace_dir, "TestTemplate2", "package"))) retcode <- rsuite_run(args = c("tmpl", "start", "-n", "TestTemplate3", "--prj"), wd = wspace_dir) expect(retcode == 0, sprintf("Failed to create template in wspace directory(errcode %s)"), retcode) expect_true(dir.exists(file.path(wspace_dir, "TestTemplate3", "project"))) expect_false(dir.exists(file.path(wspace_dir, "TestTemplate3", "package"))) retcode <- rsuite_run(args = c("tmpl", "start", "-n", "TestTemplate4", "--pkg"), wd = wspace_dir) expect(retcode == 0, sprintf("Failed to create template in wspace directory(errcode %s)"), retcode) expect_false(dir.exists(file.path(wspace_dir, "TestTemplate4", "project"))) expect_true(dir.exists(file.path(wspace_dir, "TestTemplate4", "package"))) })
residuals.flashlight <- function(object, ...) { object <- flashlight(object, check = FALSE, ...) response(object) - predict(object) }
setClass(Class = "Single.Obs.LT.Survey", contains = "LT.Survey" ) setMethod( f="initialize", signature="Single.Obs.LT.Survey", definition=function(.Object, population, line.transect, perp.truncation){ .Object@population <- population .Object@transect <- line.transect [email protected] <- perp.truncation validObject(.Object) return(.Object) } ) setValidity("Single.Obs.LT.Survey", function(object){ return(TRUE) } ) setMethod( f="create.survey.results", signature="Single.Obs.LT.Survey", definition=function(object, dht.tables = FALSE, ...){ population <- object@population line.transect <- try(object@transect, silent = TRUE) if(class(line.transect) == "try-error"){ line.transect <- [email protected] } if(sum(population@N) >= 2000){ poss.distances <- calc.poss.detect.dists.lines.largeN(population, line.transect, perp.truncation = [email protected]) }else{ poss.distances <- calc.poss.detect.dists.lines(population, line.transect, perp.truncation = [email protected]) } n.in.covered <- poss.distances$distance dist.data <- simulate.detections(poss.distances, population@detectability) dist.data <- rename.duplicates(dist.data) all.col.names <- names(object@population@population) cov.param.names <- all.col.names[!all.col.names %in% c("object", "x", "y", "strata", "scale.param", "shape.param")] dist.data <- dist.data[,c("object", "transect.ID", "distance", "x", "y", cov.param.names)] ddf.data.obj <- new(Class = "Single.Obs.DDF.Data", data = dist.data) if(dht.tables){ region.table <- create.region.table(object, ...) sample.table <- create.sample.table(object) obs.table <- data.frame(object = dist.data$object, Sample.Label = dist.data$transect.ID) obs.table <- merge(obs.table, [email protected], by = "Sample.Label")[,c("object","Sample.Label","Region.Label")] obs.table.obj <- new(Class = "Obs.Table", data = obs.table) return(list(ddf.data = ddf.data.obj, obs.table = obs.table.obj, sample.table = sample.table, region.table = region.table, n.in.covered = n.in.covered)) }else{ return(list(ddf.data = ddf.data.obj, n.in.covered = n.in.covered)) } } )
corrector_numeric <- function (y, c_l, r_w, conm, cons, cha_num, rw_col, multsh) { warnid <- 0 y <- as.character(y) y_1 <- unlist(strsplit(y, "")) z_1 <- match(y_1, cha_num) z <- which(is.na(z_1) == FALSE) l_z <- length(z) if (l_z == 0) { z_2 <- y } else { y_2 <- y_1 y_2[z] <- " " y_2 <- paste(y_2, collapse = "") y_2 <- unlist(strsplit(y_2, " ")) y_3 <- nchar(y_2) z_2 <- as.character(y_2[which(y_3 > 0)]) z_5 <- which(z_1 > 32) if (conm == 0 && cons == 0 && (l_z + length(z_5)) >= length(z_2)) { z_3 <- match(c(1, length(y_1)), z) z_3 <- z_3[!duplicated(z_3)] z_3 <- y_1[z[z_3[!is.na(z_3)]]] z_4 <- z[-1] - z[-l_z] z_4 <- y_1[z[which(z_4 == 1)]] z_3 <- c(z_3, z_4) if(length(z_5)) { z_5 <- cha_num[z_1[z_5]] z_3 <- append(z_3, z_5) z_3 <- z_3[!duplicated(z_3)] } if (length(z_3) > 1) { tch <- "characters " } else { tch <- "character " } warning(multsh, " The cell in ", rw_col[2], r_w, " and marker ", shQuote(c_l, "sh"), " contains the unexpected ", tch, paste(shQuote(z_3, "sh"), collapse = " and "), ".", call. = FALSE, noBreaks. = TRUE) warnid <- 1 } if ((conm >= 1 || cons >= 1)) { if (l_z > 1) { tch <- "characters " } else { tch <- "character " } warning(multsh, " The cell in ", rw_col[2], r_w, " and marker ", shQuote(c_l, "sh"), " contains the unexpected ", tch, paste(shQuote(y_1[z], "sh"), collapse = " and "), ".", call. = FALSE, noBreaks. = TRUE) warnid <- 1 if (length(z_2) > 1) { warning(multsh, " The cell in ", rw_col[2], r_w, " and marker ", shQuote(c_l, "sh"), " contains multiple entries. In case of multiple rows (or multiple columns) data, inserting several entries in one cell is not recommended.", call. = FALSE, noBreaks. = FALSE) } } } if (length(z_2) == 0 ) { z_2 <- NA } else { if (is.na(z_2[1]) == FALSE) { if (nchar(z_2[1]) == 0) { z_2 <- NA } else { z_num_2 <- unlist(lapply(z_2, function(x) strsplit(x, "[.]")[[1]][1])) z_num <- floor(as.numeric(z_2)) z_real <- as.numeric(z_2) zerostarter <- which(nchar(z_num_2) != nchar(z_num)) n_z <- nchar(z_num) n_z_2 <- nchar(z_2) n0 <- z_2[zerostarter] n1 <- z_2[n_z == 1] n4 <- z_2[n_z >= 4] if (length(n1) > 0 || length(n4) > 0 || length(zerostarter) > 0) { khata <- c(n0, n1, n4) khata <- khata[!duplicated(khata)] warning(multsh, " The cell in ", rw_col[2], r_w, " and marker ", shQuote(c_l, "sh"), " contains an unusual entry ", paste(shQuote(khata, "sh"), collapse = " and "), ".", call. = FALSE, noBreaks. = TRUE) warnid <- 1 z_2 <- as.character(z_real) } } } } z_2 <- z_2[!duplicated(z_2)] list(z_2, warnid) } corrector_string <- function (y, c_l, r_w, conm, cons, cha_string, rw_col, coding, multsh) { warnid <- 0 y <- as.character(y) y_1 <- unlist(strsplit(y, "")) z_1 <- match(y_1, cha_string) z <- which(is.na(z_1) == FALSE) l_z <- length(z) if (l_z == 0) { z_2 <- y } else if (length(y) == 0) { z_2 <- NA } else { y_2 <- y_1 y_2[z] <- " " y_2 <- paste(y_2, collapse = "") y_2 <- unlist(strsplit(y_2, " ")) y_3 <- nchar(y_2) z_2 <- as.character(y_2[which(y_3 > 0)]) z_2 <- as.character(z_2[z_2 > 0]) z_5 <- which(z_1 > 32) if ((l_z + length(z_5)) >= length(z_2) && conm == 0 && cons == 0) { z_3 <- match(c(1, length(y_1)), z) z_3 <- z_3[!duplicated(z_3)] z_3 <- y_1[z[z_3[!is.na(z_3)]]] z_4 <- z[-1] - z[-l_z] z_4 <- y_1[z[which(z_4 == 1)]] z_3 <- c(z_3, z_4) if(length(z_5)) { z_5 <- cha_string[z_1[z_5]] z_3 <- append(z_3, z_5) z_3 <- z_3[!duplicated(z_3)] } if (length(z_3) > 1) { tch <- "characters " } else { tch <- "character " } warning(multsh, " The cell in ", rw_col[2], r_w, " and marker ", shQuote(c_l, "sh"), " contains the unexpected ", tch, paste(shQuote(z_3, "sh"), collapse = " and "), ".", call. = FALSE, noBreaks. = TRUE) warnid <- 1 } if ((conm >= 1 || cons >= 1)) { if (l_z > 1) { tch <- "characters " } else { tch <- "character " } warning(multsh, " The cell in ", rw_col[2], r_w, " and marker ", shQuote(c_l, "sh"), " contains the unexpected ", tch, paste(shQuote(y_1[z], "sh"), collapse = " and "), ".", call. = FALSE, noBreaks. = TRUE) warnid <- 1 if (length(z_2) > 1) { warning(multsh, " The cell in ", rw_col[2], r_w, " and marker ", shQuote(c_l, "sh"), " contains multiple entries. In case of multiple rows (or multiple columns) data, inserting several entries in one cell is not recommended.", call. = FALSE, noBreaks. = TRUE) warnid <- 1 } } } z_2 <- z_2[!duplicated(z_2)] if (length(z_2) == 0) { z_2 <- NA } else if (length(z_2) == 1) { if (is.na(z_2) == FALSE) { if (nchar(z_2) == 0) { z_2 <- NA } } } if (is.element(coding, c('1let', 'iupac', '4let')) == T) { lz <- length(z_2) z_2 <- unlist(strsplit(as.character(z_2), "")) if (length(z_2) > lz) { if (coding == '1let') { mol <- "amino acids: " } else { mol <- "SNPs: " } warning(multsh, " The cell in ", rw_col[2], r_w, " and marker ", shQuote(c_l, "sh"), " contains consecutive ", mol, shQuote(y, "sh"), ".", call. = FALSE, noBreaks. = TRUE) } } list(z_2, warnid) }
mtsframe <- function(dates, Y) UseMethod("mtsframe") mtsframe.default <- function(dates, Y) { Y = as.matrix(Y) n <- dim(Y)[1]; D <- dim(Y)[2] if(inherits(dates, "Date")==T){dates = as.Date(dates)} else {dates = dates} outputs <- list(dates = dates, Y = Y, n=n, D=D, call = match.call()) class(outputs) <- "mtsframe" return(outputs) } plot.mtsframe <- function(x, time.format="%m-%y", col = NULL, lty = NULL, main = NULL, type = NULL, pch = NULL, lwd = NULL, ylab = NULL,xlab = NULL, ylim = NULL, xlim = NULL,cex.lab=NULL, cex.axis=NULL,cex.main=NULL, ...) { matplot(x$dates, x$Y, main = if(is.null(main)){''} else {main}, col = if(is.null(col)){'black'} else {col}, lty = if(is.null(lty)){1} else {lty}, pch = if(is.null(pch)){1} else {pch}, lwd = if(is.null(lwd)){1} else {lwd}, type = if(is.null(type)){'l'} else {type}, xlab = if(is.null(xlab)){'Time'} else {xlab}, ylab = if(is.null(ylab)){''} else {ylab}, ylim = if(is.null(ylim)){ c(min(x$Y), max(x$Y)) } else {ylim}, xlim = if(is.null(xlim)){c(min(x$dates),max(x$dates))} else {xlim}, cex.lab = if(is.null(cex.lab)){1} else {cex.lab}, cex.axis = if(is.null(cex.axis)){1} else {cex.axis}, cex.main = if(is.null(cex.main)){1} else {cex.main}, xaxt="n") if(inherits(x$dates, "Date")==T){ timelabels<-format(x$dates,time.format) ; axis(1,at=x$dates,labels=timelabels,cex.axis = if(is.null(cex.axis)){1} else {cex.axis})} else { axis(1,at=x$dates,cex.axis = if(is.null(cex.axis)){1} else {cex.axis}) } }
latticeCombineGrid <- function(trellis.list, between = list(y = 0.3, x = 0.3), as.table = TRUE, ...) { stopifnot( requireNamespace("lattice"), requireNamespace("latticeExtra") ) outLayout <- function(x, y, ...) { update(c(x, y, ...), between = between, as.table = as.table) } out <- suppressWarnings(Reduce(outLayout, trellis.list)) dots = list(...) if (length(dots) > 0) { out <- do.call(update, args = append(list(object = out), dots)) } return(out) }
cluster_se_glm <- function(model, cluster){ if (class(cluster) == "factor") { cluster <- droplevels(cluster) } if (nrow(model.matrix(model)) != length(cluster)) { stop("check your data: cluster variable has different N than model - you may have observations with missing data") } M <- length(unique(cluster)) N <- length(cluster) K <- model$rank dfc <- (M/(M - 1)) * ((N - 1)/(N - K)) uj <- apply(estfun(model), 2, function(x) tapply(x, cluster, sum)) rcse.cov <- dfc * sandwich(model, meat. = crossprod(uj)/N) return(rcse.cov) } clean.names <- function(str) { x <- strsplit(str,":")[[1]] x <- gsub("[\\p{P}\\p{S}\\p{Z}]","",x,perl=T) paste(x,collapse=":") } clean.names <- Vectorize(clean.names,vectorize.args=("str"),USE.NAMES = F) amce <- function(formula, data, design="uniform", respondent.varying = NULL, subset=NULL, respondent.id=NULL, cluster=TRUE, na.ignore=FALSE, weights=NULL, baselines = NULL) { formula_user <- formula formula_char_user <- all.vars(formula) user_names <- list() user_levels <- list() for (char in formula_char_user) { user_names[[clean.names(char)]] <- char if (class(data[[char]]) == "factor") { old_names <- names(user_levels) user_levels <- c(user_levels,levels(data[[char]])) new_names <- sapply(clean.names(levels(data[[char]])),function(x) paste(clean.names(char),x,sep="")) names(user_levels) <- c(old_names,new_names) } } formula_char <- clean.names(formula_char_user) if(length(unique(formula_char)) != length(formula_char)) { stop("Error: Variable names must be unique when whitespace and meta-characters are removed. Please rename.") } y_var <- clean.names(formula_char_user[1]) orig_effects <- clean.names(attr(terms(formula_user),"term.labels")) orig_effects <- c(sort(orig_effects[!grepl(":",orig_effects)]), orig_effects[grepl(":",orig_effects)]) vars_plus <- paste(orig_effects,collapse = " + ") form <- formula(paste(c(y_var,vars_plus),collapse = " ~ ")) orig_effects <- attr(terms(form),"term.labels") full_terms <- attr(terms(formula(paste(y_var,paste(sapply(orig_effects,function(x) gsub(":","*",x)),collapse=" + "),sep=" ~ "))),"term.labels") missing_terms <- full_terms[!is.element(full_terms,orig_effects)] if (length(missing_terms > 0)) { orig_effects <- c(orig_effects,missing_terms) warning("Missing base terms for interactions added to formula") } orig_effects <- c(sort(orig_effects[!grepl(":",orig_effects)]), orig_effects[grepl(":",orig_effects)]) vars_plus <- paste(orig_effects,collapse = " + ") form <- formula(paste(c(y_var,vars_plus),collapse = "~")) orig_effects <- clean.names(attr(terms(form),"term.labels")) unique_vars <- clean.names(rownames(attr(terms(form),"factor"))[-1]) respondent_vars <- clean.names(respondent.varying) profile_vars <- unique_vars[!is.element(unique_vars,respondent_vars)] if (length(respondent_vars) > 0) { profile_effects <- unlist(sapply(orig_effects,USE.NAMES = F,function(x) { y <- strsplit(x,":")[[1]] if (!any(is.element(y,respondent_vars))) x })) resp_only <- unlist(sapply(orig_effects,USE.NAMES = F, function(x) { y <- strsplit(x,":")[[1]] if(any(is.element(y,respondent_vars))) x })) resp_mod <- unlist(sapply(resp_only,USE.NAMES = F,function(x) { y <- strsplit(x,":")[[1]] vars <- y[!is.element(y,respondent_vars)] if (length(vars) > 0) paste(vars,collapse = ":") })) resp_effects <- c(resp_mod,resp_only) } else { profile_effects <- orig_effects resp_effects <- NULL } if (!is.null(respondent.id)) respondent.id <- clean.names(respondent.id) if (!is.null(weights)) weights <- clean.names(weights) if (!is.null(baselines)) { names(baselines) <- clean.names(names(baselines)) baselines <- lapply(baselines,function(x) clean.names(x)) } colnames(data) <- clean.names(colnames(data)) var_to_check_levels <- unique(c(formula_char_user, respondent_vars, profile_vars, profile_effects, orig_effects)) for (var in var_to_check_levels) { if (class(data[[var]]) == "factor") { clean.labels <- clean.names(levels(data[[var]])) if (length(unique(clean.labels)) != length(clean.labels)) { stop (paste("Error: levels of variable", var, "are not unique when whitespace and meta-characters are removed. Please rename.")) } data[[var]] <- factor(data[[var]],levels=levels(data[[var]]), labels=clean.names(levels(data[[var]]))) } } for(var in formula_char) { if(!(var %in% colnames(data))) { stop(paste("Error:", var, "not in 'data'")) } } for (var in profile_vars) { if (class(data[[var]]) != "factor") { data[[var]] <- as.factor(data[[var]]) warning(paste(c("Warning: ",var," changed to factor"),collapse="")) } } if(na.ignore == FALSE){ for(variab in formula_char){ if (sum(is.na(data[[variab]])) != 0 ){ stop(paste("Error:", variab, "has missing values in 'data'")) } } } if (!is.null(respondent_vars)) { for (var in respondent_vars) { found <- 0 for (formulavars in formula_char) { if (var == formulavars) { found <- 1 } } if (found == 0) { stop(paste("Error:", var, "is specified in respondent.varying, but is not in the formula")) } } } if (!is.numeric(data[[y_var]]) & !is.integer(data[[y_var]])) { stop(paste("Error:", y_var, "is not numeric or integer")) } if (!is.null(baselines)) { for(var in names(baselines)) { if(!(baselines[[var]] %in% data[[var]])) { stop(paste("Error: user supplied baseline",baselines[[var]],"is not a level of",var)) } } } if(is.null(respondent.id) & cluster == TRUE) { warning("respondent.id is NULL - setting cluster to FALSE. Please specify a respondent.id variable if you want to estimate clustered standard errors") cluster <- FALSE } if (cluster == TRUE) { if (is.null(respondent.id)) { stop('Error: Must specify a respondent.id if cluster = TRUE') } else if (!(respondent.id %in% colnames(data))) { stop('Error: respondent.id not in data') } } if(!is.null(weights)) { if (!weights %in% colnames(data)) { stop('Error: weights not in data') } if(length(unique(data[[weights]])) == 1) { weights <- NULL } } if (class(design) == "conjointDesign") { names(dimnames(design$J)) <- clean.names(names(dimnames(design$J))) dimnames(design$J) <- lapply(dimnames(design$J),function(x) clean.names(x)) names(design$depend) <- clean.names(names(design$depend)) design$depend <- lapply(design$depend,function(x) clean.names(x)) for (eff in profile_vars) { if (!(eff %in% names(dimnames(design$J)))) { stop(paste("Error:", eff, "not in 'design' object")) } } for (eff in names(dimnames(design$J))) { if (!(eff %in% colnames(data))){ stop(paste("Error: attribute", eff, "in 'design' object is not in 'data'")) } else { for (lev in clean.names(levels(as.factor(data[[eff]])))) { if (!(lev %in% dimnames(design$J)[[eff]])) { stop(paste("Error: factor level", lev, "of attribute", eff, "not in 'design' object")) } } } } depend_to_check <- NULL for (var in names(design$depend)) { depend_to_check <- c(depend_to_check,design$depend[[var]]) } depend_to_check <- depend_to_check[!depend_to_check %in% var_to_check_levels] for (var in depend_to_check){ if (class(data[[var]]) == "factor") { clean.labels <- clean.names(levels(data[[var]])) if (length(unique(clean.labels)) != length(clean.labels)) { stop (paste("Error: levels of variable", var, "used as a dependency, are not unique when whitespace and meta-characters are removed. Please rename.")) } data[[var]] <- factor(data[[var]],levels=levels(data[[var]]), labels=clean.names(levels(data[[var]]))) } } } else if (design == "uniform") { design <- list() design.dim <- vector(length=length(profile_vars)) dim_list <- list() for (i in 1:length(profile_vars)) { dim_list[[i]] <- levels(factor(data[[profile_vars[i]]])) design.dim[i] <- length(dim_list[[i]]) } names(dim_list) <- profile_vars design$J <- array(1/prod(design.dim), dim=design.dim, dimnames=dim_list) design$depend <- compute_dependencies(design$J) } else { stop("Design object must be a valid character string 'uniform' or a conjointDesign object") } if (is.null(subset)) { data <- data } else { if (class(subset) == "logical") { if (length(subset) == nrow(data)) { data <- subset(data, subset) } else { warning("Warning: invalid argument to 'subset' - must be the same length as the number of rows in data") } } else { warning("Warning: invalid argument to 'subset' - must be a logical") } } if (!is.null(baselines)) { for (var in names(baselines)) { data[[var]] <- factor(data[[var]]) data[[var]] <- relevel(data[[var]], baselines[[var]]) } } if(any(profile_vars %in% names(design$depend))) { depend_vars <- c() for(eff in profile_vars[profile_vars %in% names(design$depend)]) { inter <- c() eff_all <- grep(paste(c(":",eff,"(?!_)","|",eff,":(?<!_)"),collapse=""), orig_effects,value=T,perl=T) if (length(eff_all) > 0) { eff_all <- sapply(strsplit(eff_all,":"),function(x) paste(sort(x),collapse="*")) } eff_all <- c(eff,eff_all) inter <- sapply(eff_all,USE.NAMES = F,function(x) { T_r <- design$depend[[eff]] for (t in T_r){ data[[t]] <- as.factor(data[[t]]) } T_r_d <- c(x,T_r) paste(T_r_d,collapse="*") }) depend_vars <- c(depend_vars,inter) } depend_vars <- unique(depend_vars) form_full <- formula(paste(c(form,depend_vars),collapse = " + ")) } else { form_full <- form } all_run_vars <- attr(terms(form_full),"term.labels") all_run_vars <- c(sort(all_run_vars[!grepl(":",all_run_vars)]), all_run_vars[grepl(":",all_run_vars)]) vars_plus <- paste(all_run_vars,collapse = " + ") form_full<- formula(paste(c(y_var,vars_plus),collapse = "~")) all_run_vars <- attr(terms(form_full),"term.labels") if (length(respondent_vars) > 0) { prof_only <- unlist(sapply(all_run_vars,function(x) { y <- clean.names(strsplit(x,":")[[1]]) if(!any(is.element(y,respondent_vars))) x })) prof_only_plus <- paste(prof_only,collapse = " + ") form_prof <- paste(all.vars(form_full)[1],prof_only_plus,sep=" ~ ") form_prof <- formula(form_prof) } else { form_prof <- form_full } all_prof <- clean.names(attr(terms(form_prof),"term.labels")) all_run_vars <- clean.names(all_run_vars) if (any(!is.element(all_prof,all_run_vars))) { warning("Warning: mismatch of term names between full formula and profile formula") } if (is.null(weights)) { lin.mod.prof <- lm(form_prof, data=data) if (length(respondent_vars) > 0) { lin.mod.full <- lm(form_full, data=data) } else { lin.mod.full <- NULL } } else { if (cluster) { out.design <- svydesign(ids = data[[respondent.id]], weights = data[[weights]], data=data) } else { out.design <- svydesign(ids = ~0, weights = data[[weights]], data=data) } lin.mod.prof <- svyglm(form_prof, data=data, design = out.design) if (length(respondent_vars) > 0) { lin.mod.full <- svyglm(form_full, data=data, design = out.design) } else { lin.mod.full <- NULL } } sample_size_prof <- length(lin.mod.prof$residuals) if (length(respondent.varying) > 0) { sample_size_full <- length(lin.mod.full$residuals) } else { sample_size_full <- NULL } if (is.null(weights) & cluster == TRUE) { vcov_mat_prof <- cluster_se_glm(lin.mod.prof, data[[respondent.id]]) if (length(respondent.varying) > 0) { vcov_mat_full <- cluster_se_glm(lin.mod.full, data[[respondent.id]]) } else { vcov_mat_full <- NULL } } else if (!is.null(weights)) { vcov_mat_prof <- vcov(lin.mod.prof) if (length(respondent_vars) > 0) { vcov_mat_full <- vcov(lin.mod.full) } else { vcov_mat_full <- NULL } } else { vcov_mat_prof <- vcovHC(lin.mod.prof,type="HC2") if (length(respondent.varying) > 0) { vcov_mat_full <- vcovHC(lin.mod.full,type="HC2") } else { vcov_mat_full <- NULL } } fix.vcov <- function(varprob,vcov) { if (!requireNamespace("Matrix", quietly = TRUE)){ stop("Matrix package needed for this function to work. Please install it.", call. = FALSE) } varprob2 <- Matrix(varprob,sparse=TRUE) vcov2 <- Matrix(vcov,sparse=TRUE) fix1 <- varprob2 %*% vcov2 + t(varprob2 %*% vcov2) + vcov2 vcov_vector <- matrix(as.vector(vcov2),ncol=1,nrow=length(as.vector(vcov2))) weighted_covs <- kronecker(varprob2,varprob2) %*% vcov_vector weighted_covs <- matrix(weighted_covs,nrow=nrow(vcov), ncol=ncol(vcov)) fix2 <- fix1 + weighted_covs out <- matrix(fix2,ncol=ncol(vcov),nrow=nrow(vcov)) colnames(out) <- rownames(out) <- rownames(vcov) return(out) } J_baseline <- NULL J_effect <- NULL J_call <- Quote(design$J[]) J_call <- J_call[c(1, 2, rep(3, length(dim(design$J))))] warn_i <- 0 estimates <- list() profile_effects <- c(sort(profile_effects[!grepl(":",profile_effects)]), profile_effects[grepl(":",profile_effects)]) covariance_list <- list() varprob_mat <- matrix(0,nrow(vcov_mat_prof),ncol(vcov_mat_prof)) colnames(varprob_mat) <- rownames(varprob_mat) <- colnames(vcov_mat_prof) for(i in 1:length(profile_effects)) { substrings <- strsplit(profile_effects[i], "[:*]", perl=TRUE)[[1]] all_levels <- list() all_levels_coefs <- list() for(effect in substrings) { all_levels[[effect]] <- levels(data[[effect]])[-1] all_levels_coefs[[effect]] <- sapply(all_levels[[effect]], function(x) { paste(c(effect,x), collapse="") }) } levels <- expand.grid(all_levels, stringsAsFactors = FALSE) levels <- cbind(apply(levels,1,function(x) paste(x,collapse=":")),levels) colnames(levels) <- c("name",substrings) coefs <- expand.grid(all_levels_coefs, stringsAsFactors = FALSE) coefs <- apply(coefs,1,function(x) paste(x,collapse=":")) results <- matrix(nrow=2, ncol = nrow(levels)) if (length(substrings) > 1) { rownames(results) <- c("ACIE", "Std. Error") } else { rownames(results) <- c("AMCE", "Std. Error") } colnames(results) <- coefs results[2,] <- NA all_depends <- unlist(sapply(all_prof,USE.NAMES = F,function(x) { y <- strsplit(x,":")[[1]] if (all(is.element(substrings,y))) x })) all_depends <- all_depends[-is.element(all_depends,profile_effects[i])] for(j in 1:nrow(levels)) { effect_level_coef <- coefs[j] initial_beta <- coefficients(lin.mod.prof)[effect_level_coef] if (!is.na(initial_beta) & length(substrings) > 1) { for (effect1 in substrings) { effect_base1 <- levels(data[[effect1]])[1] base.subset <- data[which(data[[effect1]] == effect_base1),] for(effect in substrings[!(substrings %in% effect1)]) { base.subset <- base.subset[which(base.subset[[effect]] == as.character(levels[j,effect])),] } if (nrow(base.subset) == 0) { initial_beta <- NA warn_i <- warn_i + 1 } } } if (!is.na(initial_beta) & length(all_depends) > 0) { J_effect_call <- J_base_call <- J_call for(effect in substrings) { base <- levels(data[[effect]])[1] effect_index <- which(names(dimnames(design$J)) == effect) J_base_call[effect_index + 2] <- base level <- levels[j,effect] J_effect_call[effect_index + 2] <- level } eval(call("<-", Quote(J_baseline), J_base_call)) eval(call("<-", Quote(J_effect), J_effect_call)) for(k in 1:length(all_depends)) { depend <- all_depends[[k]] substrings_d <- strsplit(depend,":")[[1]] substrings_d <- substrings_d[!is.element(substrings_d,substrings)] all_depend_coefs <- list() for (sub in substrings_d) { all_depend_coefs[[sub]] <- sapply(levels(data[[sub]]), function(x) paste(c(sub,x),collapse="")) } all_depend_levels <- expand.grid(all_depend_coefs) substrings_l <- strsplit(effect_level_coef,":")[[1]] for (l in length(substrings_l):1) { all_depend_levels <- cbind(rep(substrings_l[l], nrow(all_depend_levels)), all_depend_levels) } colnames(all_depend_levels)[1:length(substrings_l)] <- substrings all_depend_levels <- all_depend_levels[sort(colnames(all_depend_levels))] all_depend_level_coefs <- apply(all_depend_levels, 1, function(x) paste(x,collapse=":")) if (!(is.null(dim(J_baseline)))){ baseline_support <- apply(J_baseline,substrings_d,sum) } else { baseline_support <- J_baseline } baseline_support[baseline_support != 0] <- 1 if (!is.null(dim(J_effect))) { joint_prob <- apply(J_effect, substrings_d, sum)*baseline_support } else { joint_prob <- J_effect*baseline_support } joint_prob <- as.vector(joint_prob) names(joint_prob) <- all_depend_level_coefs all_depend_level_coefs <- all_depend_level_coefs[!is.na(lin.mod.prof$coefficients[all_depend_level_coefs])] varprob_mat[effect_level_coef,all_depend_level_coefs] <- as.numeric(joint_prob[all_depend_level_coefs])/as.numeric(sum(joint_prob)) if (length(all_depend_level_coefs)) { var_prob <- joint_prob[all_depend_level_coefs] var_prob <- as.numeric(var_prob)/as.numeric(sum(joint_prob)) depend_betas <- lin.mod.prof$coefficients[all_depend_level_coefs] initial_beta <- sum(initial_beta,var_prob*depend_betas,na.rm=T) } } } results[1,j] <- initial_beta } estimates[[profile_effects[i]]] <- results } vcov_prof <- suppressMessages(fix.vcov(varprob_mat,vcov_mat_prof)) for (i in 1:length(estimates)) { coef_names <- colnames(estimates[[i]]) variances <- sqrt(diag(vcov_prof)[coef_names]) estimates[[i]][2,] <- ifelse(is.na(estimates[[i]][1,]),NA,variances) } profile_effects_plus <- paste(profile_effects,collapse=" + ") profile_effects_form <- formula(paste(c(y_var,profile_effects_plus),collapse = " ~ ")) profile_effects_terms <- colnames(model.matrix(profile_effects_form,data)) profile_effects_terms <- profile_effects_terms[profile_effects_terms %in% colnames(vcov_mat_prof)] vcov_prof <- vcov_prof[profile_effects_terms,profile_effects_terms] if (length(respondent_vars) > 0) { conditional.estimates <- list() resp_effects <- c(sort(resp_effects[!grepl(":",resp_effects)]), resp_effects[grepl(":",resp_effects)]) covariance_list <- list() varprob_mat <- matrix(0,nrow(vcov_mat_full),ncol(vcov_mat_full)) colnames(varprob_mat) <- rownames(varprob_mat) <- colnames(vcov_mat_full) for (i in 1:length(resp_effects)) { substrings <- strsplit(resp_effects[i], "[:*]", perl=TRUE)[[1]] all_levels <- list() all_levels_coefs <- list() for(effect in substrings) { if (class(data[[effect]]) != "factor") { all_levels[[effect]] <- effect all_levels_coefs[[effect]] <- effect } else { all_levels[[effect]] <- levels(data[[effect]])[-1] all_levels_coefs[[effect]] <- sapply(all_levels[[effect]], function(x) { paste(c(effect,x), collapse="") }) } } levels <- expand.grid(all_levels, stringsAsFactors = FALSE) levels <- cbind(apply(levels,1,function(x) paste(x,collapse=":")),levels) colnames(levels) <- c("name",substrings) coefs <- expand.grid(all_levels_coefs, stringsAsFactors = FALSE) coefs <- apply(coefs,1,function(x) paste(x,collapse=":")) results <- matrix(nrow=2, ncol = nrow(levels)) rownames(results) <- c("Conditional Estimate", "Std. Error") colnames(results) <- coefs results[2,] <- NA if (any(substrings %in% profile_vars)) { all_depends <- unlist(sapply(all_run_vars,USE.NAMES = F,function(x) { y <- strsplit(x,":")[[1]] if (all(is.element(substrings,y))) x })) all_depends <- all_depends[!is.element(all_depends,resp_effects[i])] resp.other <- respondent_vars[!is.element(respondent_vars,substrings)] all_depends <- unlist(sapply(all_depends,function(x) { sub_depends <- strsplit(x,":")[[1]] if (all(!is.element(sub_depends,resp.other))) x })) } else { all_depends <- c() } for(j in 1:nrow(levels)) { effect_level_coef <- coefs[j] initial_beta <- coefficients(lin.mod.full)[effect_level_coef] if (!is.na(initial_beta)) { for (effect1 in substrings[substrings %in% profile_vars]) { effect_base1 <- levels(data[[effect1]])[1] base.subset <- data[which(data[[effect1]] == effect_base1),] for(effect in substrings[substrings %in% profile_vars][!(substrings[substrings %in% profile_vars] %in% effect1)]) { base.subset <- base.subset[which(base.subset[[effect]] == as.character(levels[j,effect])),] } if (nrow(base.subset) == 0) { initial_beta <- NA warn_i <- warn_i + 1 } } } if (!is.na(initial_beta) & length(all_depends) > 0) { J_effect_call <- J_base_call <- J_call for(effect in substrings[substrings %in% profile_vars]) { base <- levels(data[[effect]])[1] effect_index <- which(names(dimnames(design$J)) == effect) J_base_call[effect_index + 2] <- base level <- levels[j,effect] J_effect_call[effect_index + 2] <- level } eval(call("<-", Quote(J_baseline), J_base_call)) eval(call("<-", Quote(J_effect), J_effect_call)) for(k in 1:length(all_depends)) { depend <- all_depends[[k]] substrings_d <- strsplit(depend,":")[[1]] substrings_d <- substrings_d[!is.element(substrings_d,substrings)] all_depend_coefs <- list() for (sub in substrings_d) { all_depend_coefs[[sub]] <- sapply(levels(data[[sub]]), function(x) paste(c(sub,x),collapse="")) } all_depend_levels <- expand.grid(all_depend_coefs) substrings_l <- strsplit(effect_level_coef,":")[[1]] for (l in length(substrings_l):1) { all_depend_levels <- cbind(rep(substrings_l[l], nrow(all_depend_levels)), all_depend_levels) } colnames(all_depend_levels)[1:length(substrings_l)] <- substrings all_depend_levels <- all_depend_levels[sort(colnames(all_depend_levels))] all_depend_level_coefs <- apply(all_depend_levels, 1, function(x) paste(x,collapse=":")) if (!(is.null(dim(J_baseline)))) { baseline_support <- apply(J_baseline,substrings_d,sum) } else { baseline_support <- J_baseline } baseline_support[baseline_support != 0] <- 1 if (!is.null(dim(J_effect))) { joint_prob <- apply(J_effect, substrings_d, sum)*baseline_support } else { joint_prob <- J_effect*baseline_support } joint_prob <- as.vector(joint_prob) names(joint_prob) <- all_depend_level_coefs all_depend_level_coefs <- all_depend_level_coefs[!is.na(lin.mod.full$coefficients[all_depend_level_coefs])] varprob_mat[effect_level_coef,all_depend_level_coefs] <- as.numeric(joint_prob[all_depend_level_coefs])/as.numeric(sum(joint_prob)) if (length(all_depend_level_coefs)) { var_prob <- joint_prob[all_depend_level_coefs] var_prob <- as.numeric(var_prob)/as.numeric(sum(joint_prob)) depend_betas <- lin.mod.full$coefficients[all_depend_level_coefs] initial_beta <- sum(initial_beta,var_prob*depend_betas, na.rm=T) } } } results[1,j] <- initial_beta } conditional.estimates[[resp_effects[i]]] <- results } vcov_resp <- suppressMessages(fix.vcov(varprob_mat,vcov_mat_full)) for (i in 1:length(conditional.estimates)) { coef_names <- colnames(conditional.estimates[[i]]) variances <- sqrt(diag(vcov_resp)[coef_names]) conditional.estimates[[i]][2,] <- ifelse(is.na(conditional.estimates[[i]][1,]), NA, variances) } resp_effects_plus <- paste(resp_effects,collapse=" + ") resp_effects_form <- formula(paste(c(y_var,resp_effects_plus),collapse = " ~ ")) resp_effects_terms <- colnames(model.matrix(resp_effects_form,data)) resp_effects_terms <- resp_effects_terms[resp_effects_terms %in% colnames(vcov_mat_full)] vcov_resp <- vcov_resp[resp_effects_terms,resp_effects_terms] } output <- list() class(output) <- c("amce") output$estimates <- estimates output$attributes <- dimnames(design$J) output$vcov.prof <- vcov_prof output$samplesize_prof <- sample_size_prof output$formula <- form if (warn_i > 0) { warning(paste("Warning: ",warn_i," interaction levels lacked support at baseline, effects undefined unless alternative baseline is provided.")) } if (length(respondent.varying) > 0) { output$cond.estimates <- conditional.estimates output$vcov.resp <- vcov_resp output$samplesize_full <- sample_size_full output$cond.formula <- resp_effects_form } output$baselines <- list() output$continuous <- list() for (k in unique_vars) { if (class(data[[k]]) == "factor") { output$baselines[[k]] <- levels(data[[k]])[1] } else if (class(data[[k]]) == "numeric") { output$continuous[[k]] <- quantile(model.matrix(form,data)[,k], probs=c(0.25,0.5,0.75), na.rm=T) } } if (!is.null(respondent.id)) { output$numrespondents <- length(unique(data[[respondent.id]])) } else { output$numrespondents <- NULL } if (!is.null(respondent.varying)) { output$respondent.varying <- respondent_vars } else { output$respondent.varying <- NULL } if (!is.null(weights)) { output$weights <- subset(data, select = weights) } else { output$weights <- NULL } output$user.names <- user_names output$user.levels <- user_levels output$data <- data return(output) } get.conditional.effects <- function(object, conditional.levels, current.effect, current.level, mod.var) { amce_obj <- object cond.data <- amce_obj$data for (var in names(amce_obj$baselines)) { cond.data[[var]] <- amce_obj$baselines[[var]] } for (var in names(conditional.levels)) { cond.data[[var]] <- conditional.levels[[var]][1] } cond.data[[current.effect]] <- current.level orig.levels <- sapply(all.vars(amce_obj$cond.formula)[-1] [all.vars(amce_obj$cond.formula)[-1] %in% names(amce_obj$baselines)], function(x) levels(amce_obj$data[[x]]), simplify=F) cond.base <- unlist(sapply(amce_obj$respondent.varying,USE.NAMES = F, function(x) colnames(amce_obj$cond.estimates[[x]]))) cond.beta <- c(0,do.call(cbind,amce_obj$cond.estimates)[1,]) estimates.vector <- c() error.vector <- c() names.vector <- c() cov.ij <- function(var1,var2) { out <- pred_mat[var1]*pred_mat[var2]*amce_obj$vcov.resp[var1,var2] return(out) } cov.ij <- Vectorize(cov.ij,vectorize.args = c("var1","var2")) na.multiply <- function(x,y) { vec <- c(x,y) if (any(is.na(vec)) && vec[!is.na(vec)] == 0) { out <- 0 } else { out <- x*y } } na.multiply <- Vectorize(na.multiply,vectorize.args = c("x","y")) mod_vars <- strsplit(mod.var,":")[[1]] for (mod_coef in colnames(amce_obj$cond.estimates[[mod.var]])) { mod_coefs <- strsplit(mod_coef,":")[[1]] for (x in 1:length(mod_coefs)) { mod_lev <- sub(mod_vars[x],"",mod_coefs[x]) cond.data[[mod_vars[x]]] <- mod_lev } pred_mat <- model.matrix(amce_obj$cond.formula,cond.data,xlev = orig.levels) turn_off <- rep(1,ncol(pred_mat)) names(turn_off) <- colnames(pred_mat) turn_off[cond.base] <- 0 pred_mat <- pred_mat[1,]*turn_off if (!any(is.na(cond.beta))) { pred_val <- sum(pred_mat*cond.beta) } else { pred_val <- sum(na.multiply(pred_mat,cond.beta)) } if (!is.na(pred_val)) { vars <- colnames(amce_obj$vcov.resp)[2:ncol(amce_obj$vcov.resp)] all_cov <- outer(vars,vars,FUN= function(x,y) cov.ij(x,y)) pred_se <- sqrt(sum(all_cov)) } else { pred_se <- NA } estimates.vector <- c(estimates.vector,pred_val) error.vector <- c(error.vector,pred_se) names.vector <- c(names.vector,mod_coef) } names(estimates.vector) <- names(error.vector) <- names.vector out <- rbind(estimates.vector,error.vector) return(out) } summary.amce <- function(object, covariate.values=NULL, ...) { amce_obj <- object summary_results <- list() header <- c("Attribute", "Level", "Estimate", "Std. Err", "z value", "Pr(>|z|)", " ") if (!is.null(covariate.values)) { names(covariate.values) <- clean.names(names(covariate.values)) for (i in 1:length(covariate.values)) { if (!names(covariate.values)[i] %in% amce_obj$respondent.varying) { stop(paste(c("Error: variable",names(covariate.values)[i],"is not a respondent-varying characteristic in AMCE object."),collapse=" ")) } if (names(covariate.values)[i] %in% names(amce_obj$baselines)) { covariate.values[[i]] <- clean.names(covariate.values[[i]]) if (any(!covariate.values[[i]] %in% levels(amce_obj$data[[names(covariate.values)[i]]]))) { stop(paste("Error: some level(s) of variable",names(covariate.values)[i],"do not appear in data.")) } if (is.null(names(covariate.values[[i]]))) { cov.names <- sapply(covariate.values[[i]],function(x) paste(names(covariate.values)[i],x,sep="")) names(covariate.values[[i]]) <- sapply(cov.names,USE.NAMES = F, function(x) amce_obj$user.levels[x]) } } } } all_prof <- names(amce_obj$estimates) all_amce <- grep(":",all_prof,value=T,invert=T) all_acie <- grep(":",all_prof,value=T,invert=F) namce <- sum(sapply(all_amce,function(x) length(unlist(amce_obj$estimates[[x]]))/2)) summary_results[["amce"]] <- matrix(nrow= namce, ncol=length(header)) colnames(summary_results[["amce"]]) <- header summary_results[["amce"]] <- as.data.frame(summary_results[["amce"]]) amce_i <- 1 if (length(all_acie) > 0) { nacie <- sum(sapply(all_acie,function(x) length(unlist(amce_obj$estimates[[x]]))/2)) summary_results[["acie"]] <- matrix(nrow= nacie, ncol=length(header)) colnames(summary_results[["acie"]]) <- header summary_results[["acie"]] <- as.data.frame(summary_results[["acie"]]) acie_i <- 1 } baselines_amce <- c() baselines_acie <- c() names_amce <- c() names_acie <- c() for (effect in all_prof) { variates <- strsplit(effect, ":")[[1]] lev_list <- c() print_names <- c() for (var in variates) { lev_list <- c(lev_list, amce_obj$user.levels[[clean.names(paste0(var,amce_obj$baselines[[var]]))]]) print_names <- c(print_names,amce_obj$user.names[[var]]) } print_level <- paste(lev_list,sep="",collapse=":") print_effect <- paste(print_names,sep="",collapse=":") if (grepl(":",effect)) { entry_name <- "acie" baselines_acie <- c(baselines_acie,print_level) names_acie <- c(names_acie,print_effect) index <- acie_i } else { entry_name <- "amce" baselines_amce <- c(baselines_amce,print_level) names_amce <- c(names_amce, print_effect) index <- amce_i } for (p in 1:ncol(amce_obj$estimates[[effect]])) { variate_levels <- strsplit(colnames(amce_obj$estimates[[effect]])[p],":")[[1]] lev_list <- c() for (lev in variate_levels) { lev_list <- c(lev_list, amce_obj$user.levels[[lev]]) } print_level <- paste(lev_list,sep="",collapse=":") summary_results[[entry_name]][index,1] <- print_effect summary_results[[entry_name]][index,2] <- print_level summary_results[[entry_name]][index,3] <- amce_obj$estimates[[effect]][1,p] summary_results[[entry_name]][index,4] <- amce_obj$estimates[[effect]][2,p] zscr <- amce_obj$estimates[[effect]][1,p]/amce_obj$estimates[[effect]][2,p] summary_results[[entry_name]][index,5] <- zscr pval <- 2*pnorm(-abs(zscr)) summary_results[[entry_name]][index,6] <- pval if (!is.na(pval)) { if (pval < .001) { summary_results[[entry_name]][index,7] <- "***" } else if (pval < .01) { summary_results[[entry_name]][index,7] <- "**" } else if (pval < .05) { summary_results[[entry_name]][index,7] <- "*" } else { summary_results[[entry_name]][index,7] <- "" } } else { summary_results[[entry_name]][index,7] <- "" } index <- index + 1 } if (grepl(":",effect)) { acie_i <- index } else { amce_i <- index } } summary_results[["amce"]] <- as.data.frame(summary_results[["amce"]]) summary_results[["baselines_amce"]] <- data.frame("Attribute" = names_amce, "Level" = baselines_amce) if (grepl(":",effect)) { summary_results[["acie"]] <- as.data.frame(summary_results[["acie"]]) summary_results[["baselines_acie"]] <- data.frame("Attribute" = names_acie, "Level" = baselines_acie) } if (length(amce_obj$cond.estimates) > 0) { if (is.null(covariate.values)) covariate.values <- list() if (any(!amce_obj$respondent.varying %in% names(covariate.values))) { for (var in amce_obj$respondent.varying[!amce_obj$respondent.varying %in% names(covariate.values)]) { if (var %in% names(amce_obj$baselines)) { cov.vals <- colnames(amce_obj$cond.estimates[[var]]) covariate.values[[var]] <- sub(var,"",cov.vals) covariate.values[[var]] <- c(amce_obj$baselines[[var]],covariate.values[[var]]) cov.vals <- c(paste(var,amce_obj$baselines[[var]],sep=""),cov.vals) names(covariate.values[[var]]) <- sapply(cov.vals, USE.NAMES = F, function(x) amce_obj$user.levels[[x]]) } else { covariate.values[[var]] <- amce_obj$continuous[[var]] } } } tab_name_amce <- c() tab_var_amce <- c() tab_val_amce <- c() tab_name_acie <- c() tab_var_acie <- c() tab_val_acie <- c() for (effect in amce_obj$respondent.varying) { print_effect <- amce_obj$user.names[[effect]] all_req_vars <- attr(terms(amce_obj$formula),"term.labels") all_resp <- unlist(sapply(all_req_vars,function(x) { y <- strsplit(x,":")[[1]] if (any(y == effect)) x })) all_mod <- unlist(sapply(all_resp,function(x) { subs <- strsplit(x,":")[[1]] subs <- subs[is.element(subs,all_prof)] if (length(subs) > 0) paste(subs,collapse=":") })) all_mod <- unique(all_mod) if (length(all_mod) == 0) { stop(paste(c("respondent characteristic",effect,"not interacted with profile attributes, no interpretation"),collapse=" ")) } mod_amce <- grep(":",all_mod,value = T,invert = T) mod_acie <- grep(":",all_mod,value = T,invert = F) namce <- sum(sapply(mod_amce,function(x) length(unlist(amce_obj$estimates[[x]]))/2)) if (length(mod_acie) > 0) { nacie <- sum(sapply(mod_acie,function(x) length(unlist(amce_obj$estimates[[x]]))/2)) } for (i in 1:length(covariate.values[[effect]])) { cond_lev <- covariate.values[[effect]][i] if (!is.null(names(covariate.values[[effect]]))) { print_cond_lev <- names(covariate.values[[effect]])[i] } else { print_cond_lev <- covariate.values[[effect]][i] } entry_name_amce <- paste(c(effect,i,"amce"),collapse="") summary_results[[entry_name_amce]] <- matrix(NA,nrow = namce, ncol=length(header)) colnames(summary_results[[entry_name_amce]]) <- header summary_results[[entry_name_amce]] <- as.data.frame(summary_results[[entry_name_amce]]) amce_i <- 1 tab_name_amce <- c(tab_name_amce,entry_name_amce) tab_var_amce <- c(tab_var_amce, effect) tab_val_amce <- c(tab_val_amce, print_cond_lev) if (length(mod_acie) > 0) { entry_name_acie <- paste(c(effect,i,"acie"),collapse="") summary_results[[entry_name_acie]] <- matrix(NA,nrow= nacie, ncol=length(header)) colnames(summary_results[[entry_name_acie]]) <- header summary_results[[entry_name_acie]] <- as.data.frame(summary_results[[entry_name_acie]]) acie_i <- 1 tab_name_acie <- c(tab_name_acie,entry_name_acie) tab_var_acie <- c(tab_var_acie, effect) tab_val_acie <- c(tab_val_acie, print_cond_lev) } for (mod_var in all_mod) { mod_vars <- strsplit(mod_var, ":")[[1]] print_vars <- c() for (var in mod_vars) { print_vars <- c(print_vars,amce_obj$user.names[[var]]) } print_mod_var <- paste(c(print_vars),collapse=":") if (grepl(":",mod_var)) { entry_name <- entry_name_acie index <- acie_i } else { entry_name <- entry_name_amce index <- amce_i } cond.effects <- get.conditional.effects(amce_obj,covariate.values,effect,cond_lev,mod_var) for (p in 1:ncol(amce_obj$cond.estimates[[mod_var]])) { mod_coef <- colnames(amce_obj$cond.estimates[[mod_var]])[p] mod_coefs <- strsplit(mod_coef, ":")[[1]] print_levs <- c() for (v in 1:length(mod_coefs)) { print_levs <- c(print_levs, amce_obj$user.levels[[mod_coefs[v]]]) } print_mod_level <- paste(print_levs,sep="",collapse=":") cond_beta <- cond.effects[1,mod_coef] cond_se <- cond.effects[2,mod_coef] if (!is.na(cond_beta)) { zscr <- cond_beta/cond_se pval <- 2*pnorm(-abs(zscr)) } else { zscr <- pval <- NA } summary_results[[entry_name]][index,1] <- print_mod_var summary_results[[entry_name]][index,2] <- print_mod_level summary_results[[entry_name]][index,3] <- cond_beta summary_results[[entry_name]][index,4] <- cond_se summary_results[[entry_name]][index,5] <- zscr summary_results[[entry_name]][index,6] <- pval if (!is.na(cond_beta)) { if (pval < .001) { summary_results[[entry_name]][index,7] <- "***" } else if (pval < .01) { summary_results[[entry_name]][index,7] <- "**" } else if (pval < .05) { summary_results[[entry_name]][index,7] <- "*" } else { summary_results[[entry_name]][index,7] <- "" } } else { summary_results[[entry_name]][index,7] <- "" } index <- index + 1 } if (grepl(":",effect)) { acie_i <- index } else { amce_i <- index } } summary_results[[entry_name_amce]] <- as.data.frame(summary_results[[entry_name_amce]]) if (length(mod_acie) > 0) { summary_results[[entry_name_acie]] <- as.data.frame(summary_results[[entry_name_acie]]) } } } summary_results[["table_values_amce"]] <- data.frame("Table Name" = tab_name_amce, "Level Name" = tab_var_amce, "Level Value" = tab_val_amce) summary_results[["table_values_amce"]] <- apply(summary_results[["table_values_amce"]],c(1,2),function(x) as.character(x)) summary_results[["table_values_acie"]] <- data.frame("Table Name" = tab_name_acie, "Level Name" = tab_var_acie, "Level Value" = tab_val_acie) summary_results[["table_values_acie"]] <- apply(summary_results[["table_values_acie"]],c(1,2),function(x) as.character(x)) } else { summary_results[["table_values_amce"]] <- NULL summary_results[["table_values_acie"]] <- NULL } summary_results[["samplesize_estimates"]] <- amce_obj$samplesize_prof if (!is.null(amce_obj$samplesize_full)) { summary_results[["samplesize_resp"]] <- amce_obj$samplesize_full } else { summary_results[["samplesize_resp"]] <- NULL } if (!is.null(amce_obj$numrespondents)) { summary_results[["respondents"]] <- amce_obj$numrespondents } else { summary_results[["respondents"]] <- NULL } class(summary_results) <- c("summary.amce") return(summary_results) } print.summary.amce <- function(x, digits=5, ...) { summary_result <- x cat("------------------------------------------\n") cat("Average Marginal Component Effects (AMCE):\n") cat("------------------------------------------\n") print(summary_result$amce, digits=digits, row.names=F) cat("---\n") cat(paste("Number of Obs. = ", summary_result$samplesize_estimates, sep="")) cat("\n") cat("---\n") if (!is.null(summary_result$respondents)) { cat(paste("Number of Respondents = ", summary_result$respondents, sep="")) cat("\n") cat("---\n") } if (!is.null(summary_result$table_values_amce)) { if (nrow(summary_result$table_values_amce) > 0) { all.vars <- unique(summary_result$table_values_amce[,2]) for (i in 1:nrow(summary_result$table_values_amce)) { print.lev <- paste(c("Conditional AMCE's ","(", summary_result$table_values_amce[i,2], " = ", summary_result$table_values_amce[i,3]), collapse="") if (length(all.vars) > 1) { this.var <- summary_result$table_values_amce[i,2] other.vars <- all.vars[!is.element(all.vars,this.var)] for (x in other.vars) { lev <- summary_result$table_values_amce[summary_result$table_values_amce[ ,"Level.Name"] == x, "Level.Value"][1] print.lev <- paste(c(print.lev,"; ",x," = ",lev),collapse="") } } print.lev <- paste(c(print.lev,"):\n"),collapse="") cat("------------------------------------------------------------\n") cat(print.lev) cat("------------------------------------------------------------\n") print(summary_result[[summary_result$table_values_amce[i,1]]], digits=digits, row.names=F) cat("---\n") cat(paste("Number of Obs. = ", summary_result$samplesize_resp, sep="")) cat("\n") if (!is.null(summary_result$respondents)) { cat(paste("Number of Respondents = ", summary_result$respondents, sep="")) cat("\n") } cat("---\n") cat("Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05") cat("\n") cat("\n") } } } cat("Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05") cat("\n") cat("\n") cat("--------------------\n") cat("AMCE Baseline Levels:\n") cat("--------------------\n") print(summary_result$baselines_amce, row.names=F) cat("\n") cat("\n") if (!is.null(summary_result$acie)) { cat("---------------------------------------------\n") cat("Average Component Interaction Effects (ACIE):\n") cat("---------------------------------------------\n") print(summary_result$acie, digits=digits, row.names=F) cat("---\n") cat(paste("Number of Obs. = ", summary_result$samplesize_estimates, sep="")) cat("\n") if (!is.null(summary_result$respondents)) { cat(paste("Number of Respondents = ", summary_result$respondents, sep="")) cat("\n") } } if (!is.null(summary_result$table_values_acie)) { if (nrow(summary_result$table_values_acie) > 0) { for (i in 1:nrow(summary_result$table_values_acie)) { cat("------------------------------------------------------------\n") cat(paste(c("Conditional ACIE's","(",summary_result$table_values_acie[i,2],"=", summary_result$table_values_acie[i,3],"):\n"),collapse=" ")) cat("------------------------------------------------------------\n") print(summary_result[[summary_result$table_values_acie[i,1]]], digits=digits, row.names=F) cat("---\n") cat(paste("Number of Obs. = ", summary_result$samplesize_resp, sep="")) cat("\n") if (!is.null(summary_result$respondents)) { cat(paste("Number of Respondents = ", summary_result$respondents, sep="")) cat("\n") } cat("---\n") cat("Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05") cat("\n") cat("\n") } } } if (!is.null(summary_result$acie)) { cat("---\n") cat("Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05") cat("\n") cat("\n") cat("--------------------\n") cat("ACIE Baseline Levels:\n") cat("--------------------\n") print(summary_result$baselines_acie, row.names=F) cat("\n") cat("\n") } } plot.amce <- function(x, main="", xlab="Change in E[Y]", ci=.95, colors=NULL, xlim=NULL, breaks=NULL, labels=NULL, attribute.names = NULL, level.names = NULL, label.baseline = TRUE, text.size=11, text.color = "black", point.size = .5, dodge.size=0.9, plot.theme = NULL, plot.display = "all", facet.names = NULL, facet.levels = NULL, group.order = NULL,font.family = NULL,...) { amce_obj <- x ylim <- xlim pe <- NULL se <- NULL group <- NULL lower <- NULL upper <- NULL var <- NULL printvar <- NULL facet <- NULL raw_attributes <- names(amce_obj$estimates) raw_levels <- lapply(amce_obj$estimates,colnames) for (effect in names(raw_levels)) { effect_elements <- strsplit(effect, ":")[[1]] baseline_interactions <- c() for (elem in effect_elements) { base_coef <- paste(c(elem,amce_obj$baselines[[elem]]),collapse="") baseline_interactions <- c(baseline_interactions,base_coef) } interaction_str <- paste(baseline_interactions,sep="",collapse=":") raw_levels[[effect]] <- c(interaction_str, raw_levels[[effect]]) } if (ci < 1 & ci > 0) { zscr <- qnorm(1- ((1-ci)/2)) } else { cat("Invalid confidence interval -- Defaulting to 95%") zscr <- qnorm(1- ((1-.95)/2)) } if (!is.null(attribute.names)) { attribute.names <- unique(attribute.names) if (length(attribute.names) != length(raw_attributes)) { cat(paste("Error: The number of unique elements in attribute.names ", length(attribute.names), " does not match the attributes in amce object for which estimates were obtained: ", paste(raw_attributes,collapse=", "), "\n", sep="")) cat("Defaulting attribute.names to attribute names in AMCE object\n") attribute.names <- NULL } } if (!is.null(level.names)) { names(level.names) <- clean.names(names(level.names)) for (name in names(level.names)) { if (name %in% names(raw_levels)) { if (length(level.names[[name]]) != length(raw_levels[[name]])) { cat(paste("Error: level.names lengths do not match levels for attribute ", name, "\n",sep="")) cat(paste("Defaulting level.names for attribute ", name, " to level names in AMCE object", "\n",sep="")) level.names[[name]] <- NULL } } else { cat(paste("Error: level.names entry ",name," not in AMCE object. Removing level.names for attribute.","\n",sep="")) level.names[[name]] <- NULL } } } if (is.null(attribute.names)) { attribute.names <- c() for (attr in names(amce_obj$estimates)) { attr_split <- strsplit(attr,":")[[1]] attr_lookup <- paste(unlist(sapply(attr_split,function(x) amce_obj$user.names[x])), collapse=":") attribute.names <- c(attribute.names,attr_lookup) } } if (is.null(level.names)) level.names <- list() if (any(!names(raw_levels) %in% names(level.names))) { for (attr in names(raw_levels)[!names(raw_levels) %in% names(level.names)]) { attr_split <- strsplit(raw_levels[[attr]],":") level.names[[attr]] <- unlist(lapply(attr_split,function(x) paste(sapply(x,function(y) amce_obj$user.levels[y]),collapse=":"))) } } plot.display.opts <- c("all","unconditional","interaction") if (!is.element(plot.display,plot.display.opts)) { stop(paste(c("Error-- plot.display must be once of: ",paste(plot.display.opts,collapse=", ")),collapse=" ")) } if (!is.null(facet.names)) { facet.names <- clean.names(facet.names) } else if (!is.null(facet.levels)) { facet.names <- clean.names(names(facet.levels)) } if (!is.null(facet.names)) { facet.names.check <- c() for (facet.name in facet.names) { if (grepl(":",facet.name)) stop("Error-- cannot facet by interaction in current version.") if (!facet.name %in% names(amce_obj$estimates) & !facet.name %in% names(amce_obj$cond.estimates)) { stop(paste(c("Error-- cannot find facet name",facet.name,"in AMCE object output."),collapse=" ")) } else { facet.names.check <- c(facet.names.check,facet.name) } } facet.names <- facet.names.check } if ((is.null(facet.names)) & (length(amce_obj$respondent.varying) > 0) & (plot.display != "unconditional")) { facet.names <- amce_obj$respondent.varying } if (is.null(facet.names) & plot.display == "interaction") { warning("Warning: no facet name or respondent varying characteristic provided to calculate conditional estimates. Will display unconditional only") plot.display <- "unconditional" } if(plot.display == "unconditional" & !is.null(facet.names)) { warning("Warning-- plot display is set to unconditional, facet names will be ignored") facet.names <- NULL facet.levels <- NULL } if (!is.null(facet.levels)) { names(facet.levels) <- clean.names(names(facet.levels)) for (facet.name in names(facet.levels)) { if (facet.name %in% names(amce_obj$baselines)) { facet.levels[[facet.name]] <- clean.names(facet.levels[[facet.name]]) if (facet.name %in% names(amce_obj$estimates) && is.element(amce_obj$baselines[[facet.name]],facet.levels[[facet.name]])) { stop (paste(c("Error: Facet level \"",as.character(amce_obj$baselines[[facet.name]]), "\" is the baseline level of a profile varying attribute. Please provide alternative facet level or use defaults."), collapse="")) } if (is.null(names(facet.levels[[facet.name]]))) { fac.levs <- sapply(facet.levels[[facet.name]],function(x) paste(facet.name,x,sep="")) names(facet.levels[[facet.name]]) <- sapply(fac.levs, USE.NAMES = F, function(x) amce_obj$user.levels[[x]]) } } else if (is.null(names(facet.levels[[facet.name]]))) { names(facet.levels[[facet.name]]) <- as.character(facet.levels[[facet.name]]) } } } if (is.null(facet.levels)) facet.levels <- list() if (any(!facet.names %in% names(facet.levels))) { for (facet.name in facet.names[!facet.names %in% names(facet.levels)]) { if (facet.name %in% names(amce_obj$baselines)) { if (facet.name %in% names(amce_obj$estimates)) { fac.levs <- colnames(amce_obj$estimates[[facet.name]]) } else { fac.levs <- colnames(amce_obj$cond.estimates[[facet.name]]) } facet.levels[[facet.name]] <- sub(facet.name,"",fac.levs) facet.levels[[facet.name]] <- c(amce_obj$baselines[[facet.name]], facet.levels[[facet.name]]) fac.levs <- c(paste(facet.name,amce_obj$baselines[[facet.name]],sep=""),fac.levs) names(facet.levels[[facet.name]]) <- sapply(fac.levs, USE.NAMES = F,function(x) amce_obj$user.levels[[x]]) } else if (facet.name %in% names(amce_obj$continuous)) { facet.levels[[facet.name]] <- amce_obj$continuous[[facet.name]] } } } covariate.values <- list() for (var in names(facet.levels)) { if (var %in% amce_obj$respondent.varying) { covariate.values[[var]] <- facet.levels[[var]] } } d <- data.frame(pe=c(), se=c(), upper=c(), lower=c(), var=c(), printvar = c(), group=c(), facet=c()) if (plot.display != "interaction") { if (plot.display == "all") { uncond.facet.name <- "Unconditional" } else { uncond.facet.name <- NA } if (plot.display == "all" && !is.null(facet.names)) { attr_remove <- c() for (facet.name in facet.names[!is.element(facet.names, amce_obj$respondent.varying)]) { attr_remove1 <- raw_attributes[grepl(":",raw_attributes)] attr_remove1 <- attr_remove1[grepl(facet.name,attr_remove1)] attr_remove <- c(attr_remove,attr_remove1) } raw_attributes <- raw_attributes[!is.element(raw_attributes,attr_remove)] } for (i in 1:length(raw_attributes)) { attr_name <- raw_attributes[i] print_attr_name <- attribute.names[which(names(amce_obj$estimates) == raw_attributes[i])] d_head <- data.frame(pe=NA, se=NA, upper=NA, lower=NA, var= attr_name, printvar=paste(print_attr_name, ":", sep=""), group="<NA>",facet=uncond.facet.name) d <- rbind(d,d_head) for (j in 1:length(raw_levels[[attr_name]])) { level_name <- raw_levels[[attr_name]][j] print_level_name <- level.names[[attr_name]][j] if (j == 1) { if (label.baseline) { print_level_name <- paste("(Baseline = ",print_level_name,")",sep="") } d_lev <- data.frame(pe=NA, se=NA, upper=NA, lower=NA, var=level_name, printvar=paste(" ", print_level_name,sep=""), group=print_attr_name, facet=uncond.facet.name) } else { val_pe <- amce_obj$estimates[[attr_name]][1,level_name] val_se <- amce_obj$estimates[[attr_name]][2,level_name] upper_bnd <- val_pe + zscr*val_se lower_bnd <- val_pe - zscr*val_se d_lev <- data.frame(pe=val_pe, se=val_se, upper=upper_bnd, lower=lower_bnd, var=level_name, printvar=paste(" ", print_level_name,sep=""), group=print_attr_name, facet=uncond.facet.name) } d <- rbind(d,d_lev) } } } if (plot.display != "unconditional" & !is.null(facet.names)) { for (facet.name in facet.names) { print_facet_name <- amce_obj$user.names[[facet.name]] all_req_vars <- attr(terms(amce_obj$formula),"term.labels") all_mod <- unlist(sapply(all_req_vars,function(x) { y <- strsplit(x,":")[[1]] if (any(y == facet.name)) x })) all_mod <- unlist(sapply(all_mod,function(x) { subs <- strsplit(x,":")[[1]] subs <- subs[is.element(subs,names(amce_obj$estimates))] subs <- subs[subs != facet.name] if (length(subs) > 0) paste(subs,collapse=":") })) if (length(all_mod) == 0) { stop(paste(c("Error: Facet variable",facet.name,"not interacted with profile attributes"),collapse=" ")) } all_mod <- unique(all_mod) if (is.element(facet.name,names(amce_obj$estimates))) { facet.start <- 2 } else { facet.start <- 1 } for (k in facet.start:length(facet.levels[[facet.name]])) { facet_lev <- facet.levels[[facet.name]][k] if (is.element(facet.name,names(amce_obj$estimates))) { print_facet_level <- paste(c("ACIE", paste(c(print_facet_name, names(facet.levels[[facet.name]])[k]), collapse = " = ")), collapse = "\n") } else { print_facet_level <- paste(c("Conditional on",paste(c(print_facet_name, names(facet.levels[[facet.name]])[k]), collapse = " = ")), collapse = "\n") } for (mod_var in all_mod) { print_attr_name <- attribute.names[which(names(amce_obj$estimates) == mod_var)] d_head <- data.frame(pe=NA, se=NA, upper=NA, lower=NA,var=mod_var, printvar=paste(print_attr_name, ":", sep=""), group="<NA>", facet=print_facet_level) d <- rbind(d, d_head) if (facet.name %in% names(amce_obj$estimates)) { inter_coef <- paste(sort(c(mod_var,facet.name)),collapse = ":") estimate.source <- amce_obj$estimates[[inter_coef]] estimate.source <- estimate.source[,grep(paste0(facet.name, facet_lev), colnames(estimate.source))] } else { estimate.source <- get.conditional.effects(amce_obj, covariate.values, facet.name, facet_lev, mod_var) } mod_vars <- strsplit(mod_var,":")[[1]] for (p in 1:length(raw_levels[[mod_var]])) { mod_coef <- raw_levels[[mod_var]][p] mod_coefs <- strsplit(mod_coef,":")[[1]] for (lev in 1:length(mod_coefs)) { mod_lev <- sub(mod_vars[lev],"",mod_coefs[lev]) } print_level_name <- level.names[[mod_var]][p] if (p == 1) { if (label.baseline) { print_level_name <- paste("(Baseline = ",print_level_name,")",sep="") } d_lev <- data.frame(pe=NA, se=NA, upper=NA, lower=NA, var = mod_coef, printvar=paste(" ", print_level_name,sep=""), group=print_attr_name, facet= print_facet_level) } else { val_pe <- estimate.source[1,p-1] if (!is.na(val_pe)) { val_se <- estimate.source[2,p-1] upper_bnd <- val_pe + zscr*val_se lower_bnd <- val_pe - zscr*val_se } else { val_se <- upper_bnd <- lower_bnd <- NA } d_lev <- data.frame(pe=val_pe, se=val_se, upper=upper_bnd, lower=lower_bnd, var = mod_coef, printvar=paste(" ", print_level_name,sep=""), group=print_attr_name, facet=print_facet_level) } d <- rbind(d, d_lev) } } } } } else { d <- d[,-which(colnames(d) == "facet")] } if (is.null(ylim)) { max_upper <- max(d$upper, na.rm=T) + .05 min_lower <- min(d$lower, na.rm=T) - .05 ylim <- c(min_lower, max_upper) d[is.na(d)] <- max_upper + 100 } else { d[is.na(d)] <- max(ylim) + 100 } d$group[d$group == "<NA>"] <- NA if(!is.null(facet.names)) d$facet[d$facet == "<NA>"] <- NA d$var <- factor(d$var,levels=unique(d$var)[length(d$var):1]) if (!is.null(facet.names)) { d$facet <- factor(d$facet,levels=unique(d$facet)) } if (!is.null(group.order)){ n.row <- length(unique(as.character(d$var))) order.var <- vector("character", length = n.row) i <- 1 while (i<n.row){ for (j in group.order){ order.var[i] <- unique(as.character(d$var[d$var==gsub(" ","",j)])) i <- i+1 temp.d <- d temp.d$group <- gsub(" ","",temp.d$group) temp.d <- subset(temp.d, group==gsub(" ","",j)) temp.var <- unique((as.character(temp.d$var))) order.var[i:(i+length(temp.var)-1)] <- temp.var i <- i+length(temp.var) } } order.var <- rev(order.var) order.df <- data.frame(order.var, 1:length(order.var)) colnames(order.df) <- c("var", "order") d$var <- factor(d$var, levels=order.var) d <- merge(d, order.df, by.x="var", by.y="var", suffixes=c("","")) } p = ggplot(d, aes(y=pe, x=var, colour=group)) p = p + coord_flip(ylim = ylim) p = p + geom_hline(yintercept = 0,size=.5,colour="black",linetype="dotted") p = p + geom_pointrange(aes(ymin=lower,ymax=upper),position=position_dodge(width=dodge.size),size=point.size) if (!is.null(facet.names)) { p = p + facet_wrap(~ facet) } if (is.null(breaks) & is.null(labels)) { p = p + scale_y_continuous(name=xlab) } else if (is.null(breaks) & !is.null(labels)) { p = p + scale_y_continuous(name=xlab, labels=labels) } else if (!is.null(breaks) & is.null(labels)) { p = p + scale_y_continuous(name=xlab, breaks=breaks) } else if (!is.null(breaks) & !is.null(labels)) { p = p + scale_y_continuous(name=xlab, breaks=breaks, labels=labels) } if (!is.null(group.order)){ fix.xlabs.df <- d[!duplicated(d$var),] fix.xlabs <- fix.xlabs.df[order(-fix.xlabs.df$order),]$printvar } else { fix.xlabs <- as.character(d$printvar)[!duplicated(d$var)] } p = p + scale_x_discrete(name="",labels=fix.xlabs[length(fix.xlabs):1]) if (!is.null(main)) { if (main != "") { p = p + ggtitle(main) } } if (is.null(colors)) { p = p + scale_colour_discrete(" ") } else if (is.vector(colors)) { cPal <- rep(colors, ceiling(length(unique(d$group))/length(colors))) p = p + scale_colour_manual(values=cPal) } else { cat("Error: 'colors' must be a vector. Using default colors\n") p = p + scale_colour_discrete(" ") } if (is.null(plot.theme)){ theme_bw1 <- function(base_size = text.size, base_family = "") { theme_grey(base_size = base_size, base_family = base_family) %+replace% theme(axis.text.x = element_text(size = base_size*.9, colour = text.color, hjust = .5 , vjust=1),axis.text.y = element_text(size = base_size, colour = text.color, hjust = 0 , vjust=.5,family=font.family), axis.ticks = element_line(colour = "grey50"),axis.title.y = element_text(size = base_size,angle=90,vjust=.01,hjust=.1,family=font.family),plot.title = element_text(face = "bold",family=font.family),legend.position = "none") } p = p + theme_bw1() print(p) } else if (is.null(class(plot.theme))) { cat("Error: 'plot.theme' is not a valid ggplot theme object. Using default theme\n") theme_bw1 <- function(base_size = text.size, base_family = "") { theme_grey(base_size = base_size, base_family = base_family) %+replace% theme(axis.text.x = element_text(size = base_size*.9, colour = text.color, hjust = .5 , vjust=1),axis.text.y = element_text(size = base_size, colour = text.color, hjust = 0 , vjust=.5,family=font.family), axis.ticks = element_line(colour = "grey50"),axis.title.y = element_text(size = base_size,angle=90,vjust=.01,hjust=.1,family=font.family),plot.title = element_text(face = "bold",family=font.family),legend.position = "none") } p = p + theme_bw1() print(p) } else if (class(plot.theme)[1] != "theme") { cat("Error: 'plot.theme' is not a valid ggplot theme object. Using default theme\n") theme_bw1 <- function(base_size = text.size, base_family = "") { theme_grey(base_size = base_size, base_family = base_family) %+replace% theme(axis.text.x = element_text(size = base_size*.9, colour = text.color, hjust = .5 , vjust=1),axis.text.y = element_text(size = base_size, colour = text.color, hjust = 0 , vjust=.5,family=font.family), axis.ticks = element_line(colour = "grey50"),axis.title.y = element_text(size = base_size,angle=90,vjust=.01,hjust=.1,family=font.family),plot.title = element_text(face = "bold",family=font.family),legend.position = "none") } p = p + theme_bw1() print(p) } else { p = p + plot.theme print(p) } if (length(covariate.values) > 1) { resp.message <- c("Note:") for (this.var in names(covariate.values)) { resp.message <- paste(c(resp.message," For AMCE and ACIE conditional on ",this.var,", "),collapse="") other.vars <- names(covariate.values)[names(covariate.values) != this.var] other.levels <- c() for (var in other.vars) { other.levels <- c(other.levels,paste(c(var," will be held at level \"",names(covariate.values[[var]])[1],"\""),collapse = "")) } other.levels <- paste(other.levels,collapse = ", and ") resp.message <- c(resp.message,other.levels,".") resp.message <- paste(resp.message,collapse = "") } cat(resp.message,"\n") } } compute_dependencies <- function(J, tol=1e-14){ attribute_names <- names(dimnames(J)) if (length(attribute_names) == 1){ dependency_list <- list() dependency_list[[attribute_names[1]]] <- c() return(dependency_list) }else{ dependency_list <- list() for (k in attribute_names){ dependency_list[[k]] <- c() } for (i in 1:(length(attribute_names)-1)){ for(j in (i+1):length(attribute_names)){ attr1 <- attribute_names[i] attr2 <- attribute_names[j] cross_tab <- apply(J, c(attr1,attr2), sum) sums <- apply(cross_tab, 1, sum) cross_tab_std <- cross_tab/sums is_equal = TRUE r_1 <- cross_tab_std[1,] if (nrow(cross_tab_std) > 1){ for (m in 2:nrow(cross_tab_std)){ if (any(as.vector(r_1) - as.vector(cross_tab_std[m,]) > tol)){ is_equal <- FALSE } } } if (!is_equal){ dependency_list[[attr1]] <- c(dependency_list[[attr1]], attr2) dependency_list[[attr2]] <- c(dependency_list[[attr2]], attr1) } } } return(dependency_list) } } makeDesign <- function(type="file", J=NULL, filename=NULL, attribute.levels = NULL, constraints=NULL, level.probs=NULL, tol=1e-14){ design.obj <- NULL if (type == 'file'){ if (is.null(filename)){ cat("Error: Must provide a valid filename argument for type = 'file'\n") stop() } connection <- file(filename, open="r") file_lines <- readLines(connection) close(connection) attr_index <- which(file_lines == "Attributes") weight_index <- which(file_lines == "Weights") restriction_index <- which(file_lines == "Restrictions") attributes <- file_lines[(attr_index+1):(weight_index-1)] weight <- file_lines[(weight_index+1):(restriction_index-1)] if (restriction_index+1 != length(file_lines)){ constr <- file_lines[(restriction_index+1):length(file_lines)] }else{ constr <- NULL } attribute.levels <- list() for (attrstr in attributes){ attributename <- strsplit(attrstr, ":")[[1]][1] levels <- strsplit(strsplit(attrstr, ":")[[1]][2], ",")[[1]] attribute.levels[[attributename]] <- levels } level.probs <- list() for (probstr in weight){ attributename <- strsplit(probstr, ":")[[1]][1] weights <- strsplit(strsplit(probstr, ":")[[1]][2], ",")[[1]] level.probs[[attributename]] <- as.numeric(weights) } if (is.null(constr) != TRUE){ constraints <- list() for (i in 1:length(constr)){ allconstraints <- strsplit(constr[i], ";")[[1]] constraints[[i]] <- list() for (m in allconstraints){ attributename <- strsplit(m, ":")[[1]][1] constrained_levels <- strsplit(strsplit(m, ":")[[1]][2], ",")[[1]] constraints[[i]][[attributename]] <- constrained_levels } } }else{ constraints <- NULL } } if (type == 'array'){ if (sum(J) != 1){ cat("Error: Profile assignment probability array invalid: Does not sum to 1\n") }else{ design.obj$J <- J design.obj$dependence <- compute_dependencies(J) } }else if (type == 'constraints' | type == 'file'){ if (is.null(attribute.levels) | is.list(attribute.levels) != TRUE){ cat("Error: Must provide a valid list() object in attribute.levels argument for type = 'constraints'\n") } dimensions <- c() for (attr in names(attribute.levels)){ dimensions <- c(dimensions, length(attribute.levels[[attr]])) } J_mat <- array(NA, dim=dimensions, dimnames = attribute.levels) for (cstr in constraints){ constraint_names <- names(cstr) select_call <- Quote(J_mat[]) select_call <- select_call[c(1, 2, rep(3, length(dim(J_mat))))] for (f in 1:length(constraint_names)){ name <- constraint_names[f] index <- which(names(dimnames(J_mat)) == name) select_call[index+2] <- cstr[f] } eval(call("<-", select_call, 0)) } if (is.null(level.probs)){ cell_prob <- 1/sum(is.na(J_mat)) J_mat[is.na(J_mat)] <- cell_prob }else{ for (attr in names(level.probs)){ level.probs[[attr]] <- level.probs[[attr]]/sum(level.probs[[attr]]) } for (attr in names(level.probs)){ if (is.null(names(level.probs[[attr]]))){ names(level.probs[[attr]]) <- attribute.levels[[attr]] } } unconstrained_probs <- J_mat unconstrained_probs[TRUE] <- 1 for (attr in names(dimnames(J_mat))){ for (level in attribute.levels[[attr]]){ marg_prob <- level.probs[[attr]][[level]] select_call <- Quote(unconstrained_probs[]) select_call <- select_call[c(1, 2, rep(3, length(dim(J_mat))))] index <- which(names(dimnames(J_mat)) == attr) select_call[index+2] <- level eval(call("<-", select_call, eval(call("*",select_call, marg_prob)))) } } missing_prob <- sum(unconstrained_probs[is.na(J_mat)==FALSE]) increase_prob <- unconstrained_probs*1/(1-missing_prob) J_mat[is.na(J_mat)] <- increase_prob[is.na(J_mat)] } design.obj$J <- J_mat design.obj$dependence <- compute_dependencies(J_mat, tol) }else{ cat("Invalid type argument: Must be either 'file', 'array', or 'constraints") } class(design.obj) <- "conjointDesign" return(design.obj) } re.escape <- function(strings){ vals <- c("\\\\", "\\[", "\\]", "\\(", "\\)", "\\{", "\\}", "\\^", "\\$","\\*", "\\+", "\\?", "\\.", "\\|") replace.vals <- paste0("\\\\", vals) for(i in seq_along(vals)){ strings <- gsub(vals[i], replace.vals[i], strings) } strings } read.qualtrics <- function(filename,responses=NULL,covariates = NULL,respondentID = NULL,letter="F",new.format = FALSE,ranks = NULL){ qualtrics_results <- read.csv(filename, stringsAsFactors=F) if (new.format) { new.format.test <- grepl("ImportId",qualtrics_results[2,1]) if (new.format==new.format.test) { print("New qualtrics format detected.") qualtrics_results <- qualtrics_results[-2,] } else { stop("You indicate the data is of new qualtrics format, but it seems to be in old format.") return (NULL) } } if (!new.format) { new.format.test <- grepl("ImportId",qualtrics_results[2,1]) if (new.format==new.format.test) { print("Old qualtrics format detected.") } else { stop("You indicate the data is of old qualtrics format, but it seems to be in new format.") return (NULL) } } var_names <- as.character(qualtrics_results[1,]) q_names <- colnames(qualtrics_results) qualtrics_data <- qualtrics_results[2:nrow(qualtrics_results),] colnames(qualtrics_data) <- var_names respondent_index <- 1:nrow(qualtrics_data) attr_regexp <- paste(c("^",letter,"-[0-9]+-[0-9]+(?!-)"),collapse="") attr_name_cols <- grep(attr_regexp, var_names, perl=TRUE) qualtrics_data[attr_name_cols] <- lapply(qualtrics_data[attr_name_cols], function (x) sub("\\s+$", "", x)) attr_name_matrix <- matrix(unlist(strsplit(var_names[attr_name_cols],"-")),nrow=3,ncol=length(attr_name_cols)) colnames(attr_name_matrix) <- var_names[attr_name_cols] attr_name_matrix <- attr_name_matrix[2:nrow(attr_name_matrix),] attr_name_matrix <- as.data.frame(t(attr_name_matrix)) num_tasks <-unique(as.integer(attr_name_matrix[,1])) level_regexp <- paste(c("^",letter,"-[0-9]+-[0-9]+-[0-9]+"),collapse="") level_name_cols <- grep(level_regexp, var_names, perl=TRUE) num_profiles <- length(unique(do.call(rbind,strsplit(var_names[level_name_cols],"-"))[,3])) level_name_matrix <- matrix(unlist(strsplit(var_names[level_name_cols],"-")),nrow=4,ncol=length(level_name_cols)) colnames(level_name_matrix) <- var_names[level_name_cols] level_name_matrix <- level_name_matrix[2:nrow(level_name_matrix),] level_name_matrix <- as.data.frame(t(level_name_matrix)) all_attr <- c() for (attr_vec in attr_name_cols) { all_attr <- c(all_attr,qualtrics_data[,attr_vec]) } all_attr <- gsub(pattern = "\\s+$", replacement = "", all_attr) unique_attr <- unique(all_attr)[nchar(unique(all_attr)) != 0] unique_attr <- unique_attr[!is.na(unique_attr)] if (is.null(responses) & is.null(ranks)) { stop("Either responses or ranks must be non-NULL") return(NULL) } if (!is.null(responses) && length(num_tasks) != length(responses)) { stop("Error: Number of response columns doesn't equal number of tasks in data") return(NULL) } if (!is.null(ranks) && length(num_tasks) != length(ranks)/num_profiles) { stop("Error: Number of rank columns doesn't equal number of tasks times number of profiles in data") return(NULL) } if (length(attr_name_cols) == 0) { stop("Error: Cannot find any columns designating attributes and levels. Please make sure the input file originated from a Qualtrics survey designed using the Conjoint SDT") return(NULL) } for (attr_column in attr_name_cols) { if (is.null(unique(qualtrics_data[,attr_column]))) { stop(paste("Error, attribute column ", var_names[attr_column], " has no attribute names - recommend deleting this column")) } else if (unique(qualtrics_data[,attr_column])[1] == "" & length(unique(qualtrics_data[,attr_column])) == 1) { stop(paste("Error, attribute column ", var_names[attr_column], " has no attribute names - recommend deleting this column")) } } for (lev_column in level_name_cols) { if (is.null(unique(qualtrics_data[,lev_column]))) { stop(paste("Error, level column ", var_names[lev_column], " has no attribute names - recommend deleting this column")) } else if (unique(qualtrics_data[,lev_column])[1] == "" & length(unique(qualtrics_data[,lev_column])) == 1) { stop(paste("Error, level column ", var_names[lev_column], " has no attribute names - recommend deleting this column")) } } if (!is.null(respondentID)){ respondent_index <- qualtrics_data[,which(q_names %in% respondentID)] }else{ respondent_index <- 1:nrow(qualtrics_data) } if (is.character(responses[1])){ response_vars <- which(q_names %in% responses) }else{ response_vars <- responses } if (sum(grepl("[\\'\"]",unique(all_attr)))>0){ stop(paste("Error, attribute name has special characters. Some special characters are reserved for this function (if cjoint>v2.0.6) for the purpose of efficiency. If you still want to display special character in your plot, use the argument attribute.names in the plot function. See manual for more details.")) } else { if (sum(grepl("^attribute_[0-9]+$",unique(all_attr)))>0) { stop (paste("Error, attribute_[0-9]+ is reserved for the function.")) } if (sum(grepl("^selected_[0-9]+-[0-9]+$",unique(all_attr)))>0) { stop (paste("Error, selected_[0-9]+-[0-9]+ is reserved for the function.")) } } colnames(qualtrics_data)[which(q_names %in% covariates)] <- covariates out_data_set_cols <- c(which(q_names %in% respondentID), which(q_names %in% covariates), (attr_name_cols), (level_name_cols) ) out_data_dataset <- qualtrics_data[,out_data_set_cols] if (!is.null(respondentID)){ id_var_name <- colnames(out_data_dataset)[which(q_names %in% respondentID)] } else { out_data_dataset <- cbind(out_data_dataset, respondent_index) id_var_name <- "respondent_index" } num_tasks <- unique(as.integer(attr_name_matrix[,1])) num_profiles <- as.integer(unique(level_name_matrix[,2])) num_attr <- unique(as.integer(attr_name_matrix[,2])) attr_regexp <- paste(c("^",letter,"-[0-9]+-[0-9]+$"),collapse="") temp.col.index <- grep(attr_regexp,colnames(out_data_dataset), perl=TRUE) colnames(out_data_dataset)[temp.col.index] <- gsub("-","_",colnames(out_data_dataset)[temp.col.index]) level_regexp <- paste(c("^",letter,"-[0-9]+-[0-9]+-[0-9]+$"),collapse="") temp.col.index <- grep(level_regexp,colnames(out_data_dataset), perl=TRUE) colnames(out_data_dataset)[temp.col.index] <- gsub("-","_",colnames(out_data_dataset)[temp.col.index]) for (i in num_attr){ temp.cmd <- paste0("out_data_dataset['attribute_",i,"']<-","out_data_dataset['",letter,"_1_",i,"']") eval(parse(text=temp.cmd)) } temp_regexp <- paste(c("^",letter,"_[0-9]+_[0-9]+$"),collapse="") temp.col.index <- grep(temp_regexp,colnames(out_data_dataset), perl=TRUE) out_data_dataset <- out_data_dataset[,-temp.col.index] test.selected <- sum(!unique(unlist(qualtrics_data[,response_vars])) %in% c("",num_profiles))==0 if (!test.selected){ stop(paste0("Responses can only take values among (",paste(num_profiles, collapse = ","),")")) return (NULL) } if (is.null(ranks)){ for (i in num_tasks){ temp.cmd <- paste0("temp.selected","<-","qualtrics_data[,",response_vars[i],"]") eval(parse(text=temp.cmd)) for (j in num_profiles){ temp.cmd <- paste0("out_data_dataset$'selected_",j,"-",i,"'<-","ifelse(temp.selected==j,1,0)") eval(parse(text=temp.cmd)) temp.cmd <- paste0("out_data_dataset$'selected_",j,"-",i,"'[temp.selected","=='']","<-","''") eval(parse(text=temp.cmd)) } } } else { ranks_col <- which(q_names %in% ranks) for (i in num_tasks){ for (j in num_profiles){ temp.cmd <- paste0("out_data_dataset$'selected_",j,"-",i,"'<-","qualtrics_data[,",ranks_col[(i-1)*length(num_profiles)+j],"]") eval(parse(text=temp.cmd)) } } } trim <- function (x) gsub("^\\s+|\\s+$", "", x) for (i in num_attr){ temp.cmd <- paste0("out_data_dataset","<-subset(out_data_dataset, attribute_",i,"!='')") eval(parse(text=temp.cmd)) temp.cmd <- paste0("out_data_dataset['attribute_",i,"'] <- ","trim(out_data_dataset$'attribute_",i,"')") eval(parse(text=temp.cmd)) } attribute_var_names <- unique(unlist(out_data_dataset[,grep("attribute_[0-9]+$", colnames(out_data_dataset))])) attribute_var_names_label <- gsub(" ",".", attribute_var_names) for (i in num_tasks){ for (j in num_profiles){ for (r in 1:length(attribute_var_names)){ temp.cmd <- paste0("out_data_dataset['",attribute_var_names[r],"_",j,"-",i,"']<-''") eval(parse(text=temp.cmd)) temp.cmd <- paste0("out_data_dataset['",attribute_var_names[r],".rowpos_",j,"-",i,"']<-''") eval(parse(text=temp.cmd)) } } } for (i in num_tasks){ for (j in num_profiles){ for (k in num_attr){ for (r in attribute_var_names){ temp.cmd <- paste0("out_data_dataset['",r,"_",j,"-",i,"']", "[out_data_dataset['attribute_",k,"']=='",r, "']<-out_data_dataset['",letter,"_",i,"_",j,"_",k, "'][out_data_dataset['attribute_",k,"']=='",r,"']") eval(parse(text=temp.cmd)) temp.cmd <- paste0("out_data_dataset['",r,".rowpos","_",j,"-",i,"'", "][out_data_dataset['attribute_",k,"']=='",r, "']<-k") eval(parse(text=temp.cmd)) } } } } temp_regexp <- paste(c("^",letter,"_[0-9]+_[0-9]+_[0-9]+$"),collapse="") temp.col.index <- grep(temp_regexp,colnames(out_data_dataset), perl=TRUE) out_data_dataset <- out_data_dataset[,-temp.col.index] regex.temp <- paste0("^attribute","_[0-9]+","$") out_data_dataset <- out_data_dataset[,-grep(regex.temp, colnames(out_data_dataset))] regex.temp <- paste(paste0("^",re.escape(attribute_var_names),"_[0-9]+-[0-9]+","$"),collapse="|") regex.temp.2 <- paste(paste0("^",re.escape(attribute_var_names),".rowpos_[0-9]+-[0-9]+","$"),collapse="|") varying.temp <- colnames(out_data_dataset)[grep(regex.temp, colnames(out_data_dataset))] varying.temp.2 <- colnames(out_data_dataset)[grep(regex.temp.2, colnames(out_data_dataset))] varying.temp.3 <- colnames(out_data_dataset)[grep("^selected_[0-9]+-[0-9]+$", colnames(out_data_dataset))] varying.temp <- c(varying.temp, varying.temp.2, varying.temp.3) v.names.temp <- unique(gsub("-[0-9]+$","",varying.temp)) v.names.temp <- v.names.temp[order(v.names.temp)] varying.temp <- paste0(rep(v.names.temp, length(num_tasks)),"-", rep(num_tasks, each=length(v.names.temp))) out_data_dataset <- reshape(out_data_dataset, idvar = id_var_name, varying = varying.temp, sep = "-", timevar = "task", times = num_tasks, v.names = v.names.temp, new.row.names = 1:(length(num_tasks)*nrow(out_data_dataset)), direction = "long") regex.temp <- paste(paste0("^",re.escape(attribute_var_names),"_[0-9]+","$"), collapse="|") regex.temp.2 <- paste(paste0("^",re.escape(attribute_var_names),".rowpos_[0-9]+","$"), collapse="|") varying.temp <- colnames(out_data_dataset)[grep(regex.temp, colnames(out_data_dataset))] varying.temp.2 <- colnames(out_data_dataset)[grep(regex.temp.2, colnames(out_data_dataset))] varying.temp.3 <- colnames(out_data_dataset)[grep("^selected_[0-9]+$", colnames(out_data_dataset))] varying.temp <- c(varying.temp, varying.temp.2, varying.temp.3) v.names.temp <- unique(gsub("_[0-9]+$","",varying.temp)) v.names.temp <- v.names.temp[order(v.names.temp)] varying.temp <- paste0(rep(v.names.temp, length(num_profiles)),"_", rep(num_profiles, each=length(v.names.temp))) out_data_dataset <- reshape(out_data_dataset, idvar = id_var_name, varying = varying.temp, sep = "_", timevar = "profile", times = num_profiles, v.names = v.names.temp, new.row.names = 1:(length(num_profiles)*nrow(out_data_dataset)), direction = "long") colnames(out_data_dataset)<- gsub(" ",".",colnames(out_data_dataset)) for (m in attribute_var_names_label){ out_data_dataset[[m]] <- as.factor(out_data_dataset[[m]]) } colnames(out_data_dataset)[which(colnames(out_data_dataset)==id_var_name)] <- "respondent" out_data_dataset$respondentIndex <- as.factor(out_data_dataset$respondent) out_data_dataset$respondentIndex <- as.integer(out_data_dataset$respondentIndex) out_data_dataset$selected <- as.integer(out_data_dataset$selected) out_data_dataset$task <- as.integer(out_data_dataset$task) out_data_dataset$profile <- as.integer(out_data_dataset$profile) return(out_data_dataset) } read.with.qualtRics <- function(filename,responses=NULL,covariates = NULL,respondentID = NULL,letter="F",new.format = FALSE,ranks = NULL){ qualtrics_results <- filename replace.regexp <- paste0("^",letter,".[0-9]+.[0-9]+$") replace.col <- grep(replace.regexp, colnames(filename)) colnames(qualtrics_results)[replace.col] <- gsub("[.]","-",colnames(qualtrics_results)[replace.col]) replace.regexp <- paste0("^",letter,".[0-9]+.[0-9]+.[0-9]+$") replace.col <- grep(replace.regexp, colnames(filename)) colnames(qualtrics_results)[replace.col] <- gsub("[.]","-",colnames(qualtrics_results)[replace.col]) var_names <- as.character(qualtrics_results[1,]) q_names <- colnames(qualtrics_results) qualtrics_data <- qualtrics_results[2:nrow(qualtrics_results),] colnames(qualtrics_data) <- var_names respondent_index <- 1:nrow(qualtrics_data) attr_regexp <- paste(c("^",letter,"-[0-9]+-[0-9]+(?!-)"),collapse="") attr_name_cols <- grep(attr_regexp, var_names, perl=TRUE) qualtrics_data[attr_name_cols] <- lapply(qualtrics_data[attr_name_cols], function (x) sub("\\s+$", "", x)) attr_name_matrix <- matrix(unlist(strsplit(var_names[attr_name_cols],"-")),nrow=3,ncol=length(attr_name_cols)) colnames(attr_name_matrix) <- var_names[attr_name_cols] attr_name_matrix <- attr_name_matrix[2:nrow(attr_name_matrix),] attr_name_matrix <- as.data.frame(t(attr_name_matrix)) num_tasks <-unique(as.integer(attr_name_matrix[,1])) level_regexp <- paste(c("^",letter,"-[0-9]+-[0-9]+-[0-9]+"),collapse="") level_name_cols <- grep(level_regexp, var_names, perl=TRUE) num_profiles <- length(unique(do.call(rbind,strsplit(var_names[level_name_cols],"-"))[,3])) level_name_matrix <- matrix(unlist(strsplit(var_names[level_name_cols],"-")),nrow=4,ncol=length(level_name_cols)) colnames(level_name_matrix) <- var_names[level_name_cols] level_name_matrix <- level_name_matrix[2:nrow(level_name_matrix),] level_name_matrix <- as.data.frame(t(level_name_matrix)) all_attr <- c() for (attr_vec in attr_name_cols) { all_attr <- c(all_attr,qualtrics_data[,attr_vec]) } all_attr <- gsub(pattern = "\\s+$", replacement = "", all_attr) unique_attr <- unique(all_attr)[nchar(unique(all_attr)) != 0] unique_attr <- unique_attr[!is.na(unique_attr)] if (is.null(responses) & is.null(ranks)) { stop("Either responses or ranks must be non-NULL") return(NULL) } if (!is.null(responses) && length(num_tasks) != length(responses)) { stop("Error: Number of response columns doesn't equal number of tasks in data") return(NULL) } if (!is.null(ranks) && length(num_tasks) != length(ranks)/num_profiles) { stop("Error: Number of rank columns doesn't equal number of tasks times number of profiles in data") return(NULL) } if (length(attr_name_cols) == 0) { stop("Error: Cannot find any columns designating attributes and levels. Please make sure the input file originated from a Qualtrics survey designed using the Conjoint SDT") return(NULL) } for (attr_column in attr_name_cols) { if (is.null(unique(qualtrics_data[,attr_column]))) { stop(paste("Error, attribute column ", var_names[attr_column], " has no attribute names - recommend deleting this column")) } else if (unique(qualtrics_data[,attr_column])[1] == "" & length(unique(qualtrics_data[,attr_column])) == 1) { stop(paste("Error, attribute column ", var_names[attr_column], " has no attribute names - recommend deleting this column")) } } for (lev_column in level_name_cols) { if (is.null(unique(qualtrics_data[,lev_column]))) { stop(paste("Error, level column ", var_names[lev_column], " has no attribute names - recommend deleting this column")) } else if (unique(qualtrics_data[,lev_column])[1] == "" & length(unique(qualtrics_data[,lev_column])) == 1) { stop(paste("Error, level column ", var_names[lev_column], " has no attribute names - recommend deleting this column")) } } if (!is.null(respondentID)){ respondent_index <- qualtrics_data[,which(q_names %in% respondentID)] }else{ respondent_index <- 1:nrow(qualtrics_data) } if (is.character(responses[1])){ response_vars <- which(q_names %in% responses) }else{ response_vars <- responses } if (sum(grepl("[\\'\"]",unique(all_attr)))>0){ stop(paste("Error, attribute name has special characters. Some special characters are reserved for this function (if cjoint>v2.0.6) for the purpose of efficiency. If you still want to display special character in your plot, use the argument attribute.names in the plot function. See manual for more details.")) } else { if (sum(grepl("^attribute_[0-9]+$",unique(all_attr)))>0) { stop (paste("Error, attribute_[0-9]+ is reserved for the function.")) } if (sum(grepl("^selected_[0-9]+-[0-9]+$",unique(all_attr)))>0) { stop (paste("Error, selected_[0-9]+-[0-9]+ is reserved for the function.")) } } colnames(qualtrics_data)[which(q_names %in% covariates)] <- covariates out_data_set_cols <- c(which(q_names %in% respondentID), which(q_names %in% covariates), (attr_name_cols), (level_name_cols) ) out_data_dataset <- qualtrics_data[,out_data_set_cols] if (!is.null(respondentID)){ id_var_name <- colnames(out_data_dataset)[which(q_names %in% respondentID)] } else { out_data_dataset <- cbind(out_data_dataset, respondent_index) id_var_name <- "respondent_index" } num_tasks <- unique(as.integer(attr_name_matrix[,1])) num_profiles <- as.integer(unique(level_name_matrix[,2])) num_attr <- unique(as.integer(attr_name_matrix[,2])) attr_regexp <- paste(c("^",letter,"-[0-9]+-[0-9]+$"),collapse="") temp.col.index <- grep(attr_regexp,colnames(out_data_dataset), perl=TRUE) colnames(out_data_dataset)[temp.col.index] <- gsub("-","_",colnames(out_data_dataset)[temp.col.index]) level_regexp <- paste(c("^",letter,"-[0-9]+-[0-9]+-[0-9]+$"),collapse="") temp.col.index <- grep(level_regexp,colnames(out_data_dataset), perl=TRUE) colnames(out_data_dataset)[temp.col.index] <- gsub("-","_",colnames(out_data_dataset)[temp.col.index]) for (i in num_attr){ temp.cmd <- paste0("out_data_dataset['attribute_",i,"']<-","out_data_dataset['",letter,"_1_",i,"']") eval(parse(text=temp.cmd)) } temp_regexp <- paste(c("^",letter,"_[0-9]+_[0-9]+$"),collapse="") temp.col.index <- grep(temp_regexp,colnames(out_data_dataset), perl=TRUE) out_data_dataset <- out_data_dataset[,-temp.col.index] test.selected <- sum(!unique(unlist(qualtrics_data[,response_vars])) %in% c("",num_profiles))==0 if (!test.selected){ stop(paste0("Responses can only take values among (",paste(num_profiles, collapse = ","),")")) return (NULL) } if (is.null(ranks)){ for (i in num_tasks){ temp.cmd <- paste0("temp.selected","<-","qualtrics_data[,",response_vars[i],"]") eval(parse(text=temp.cmd)) for (j in num_profiles){ temp.cmd <- paste0("out_data_dataset$'selected_",j,"-",i,"'<-","ifelse(temp.selected==j,1,0)") eval(parse(text=temp.cmd)) temp.cmd <- paste0("out_data_dataset$'selected_",j,"-",i,"'[temp.selected","=='']","<-","''") eval(parse(text=temp.cmd)) } } } else { ranks_col <- which(q_names %in% ranks) for (i in num_tasks){ for (j in num_profiles){ temp.cmd <- paste0("out_data_dataset$'selected_",j,"-",i,"'<-","qualtrics_data[,",ranks_col[(i-1)*length(num_profiles)+j],"]") eval(parse(text=temp.cmd)) } } } trim <- function (x) gsub("^\\s+|\\s+$", "", x) for (i in num_attr){ temp.cmd <- paste0("out_data_dataset","<-subset(out_data_dataset, attribute_",i,"!='')") eval(parse(text=temp.cmd)) temp.cmd <- paste0("out_data_dataset['attribute_",i,"'] <- ","trim(out_data_dataset$'attribute_",i,"')") eval(parse(text=temp.cmd)) } attribute_var_names <- unique(unlist(out_data_dataset[,grep("attribute_[0-9]+$", colnames(out_data_dataset))])) attribute_var_names_label <- gsub(" ",".", attribute_var_names) for (i in num_tasks){ for (j in num_profiles){ for (r in 1:length(attribute_var_names)){ temp.cmd <- paste0("out_data_dataset['",attribute_var_names[r],"_",j,"-",i,"']<-''") eval(parse(text=temp.cmd)) temp.cmd <- paste0("out_data_dataset['",attribute_var_names[r],".rowpos_",j,"-",i,"']<-''") eval(parse(text=temp.cmd)) } } } for (i in num_tasks){ for (j in num_profiles){ for (k in num_attr){ for (r in attribute_var_names){ temp.cmd <- paste0("out_data_dataset['",r,"_",j,"-",i,"']", "[out_data_dataset['attribute_",k,"']=='",r, "']<-out_data_dataset['",letter,"_",i,"_",j,"_",k, "'][out_data_dataset['attribute_",k,"']=='",r,"']") eval(parse(text=temp.cmd)) temp.cmd <- paste0("out_data_dataset['",r,".rowpos","_",j,"-",i,"'", "][out_data_dataset['attribute_",k,"']=='",r, "']<-k") eval(parse(text=temp.cmd)) } } } } temp_regexp <- paste(c("^",letter,"_[0-9]+_[0-9]+_[0-9]+$"),collapse="") temp.col.index <- grep(temp_regexp,colnames(out_data_dataset), perl=TRUE) out_data_dataset <- out_data_dataset[,-temp.col.index] regex.temp <- paste0("^attribute","_[0-9]+","$") out_data_dataset <- out_data_dataset[,-grep(regex.temp, colnames(out_data_dataset))] regex.temp <- paste(paste0("^",re.escape(attribute_var_names),"_[0-9]+-[0-9]+","$"),collapse="|") regex.temp.2 <- paste(paste0("^",re.escape(attribute_var_names),".rowpos_[0-9]+-[0-9]+","$"),collapse="|") varying.temp <- colnames(out_data_dataset)[grep(regex.temp, colnames(out_data_dataset))] varying.temp.2 <- colnames(out_data_dataset)[grep(regex.temp.2, colnames(out_data_dataset))] varying.temp.3 <- colnames(out_data_dataset)[grep("^selected_[0-9]+-[0-9]+$", colnames(out_data_dataset))] varying.temp <- c(varying.temp, varying.temp.2, varying.temp.3) v.names.temp <- unique(gsub("-[0-9]+$","",varying.temp)) v.names.temp <- v.names.temp[order(v.names.temp)] varying.temp <- paste0(rep(v.names.temp, length(num_tasks)),"-", rep(num_tasks, each=length(v.names.temp))) out_data_dataset <- reshape(out_data_dataset, idvar = id_var_name, varying = varying.temp, sep = "-", timevar = "task", times = num_tasks, v.names = v.names.temp, new.row.names = 1:(length(num_tasks)*nrow(out_data_dataset)), direction = "long") regex.temp <- paste(paste0("^",re.escape(attribute_var_names),"_[0-9]+","$"), collapse="|") regex.temp.2 <- paste(paste0("^",re.escape(attribute_var_names),".rowpos_[0-9]+","$"), collapse="|") varying.temp <- colnames(out_data_dataset)[grep(regex.temp, colnames(out_data_dataset))] varying.temp.2 <- colnames(out_data_dataset)[grep(regex.temp.2, colnames(out_data_dataset))] varying.temp.3 <- colnames(out_data_dataset)[grep("^selected_[0-9]+$", colnames(out_data_dataset))] varying.temp <- c(varying.temp, varying.temp.2, varying.temp.3) v.names.temp <- unique(gsub("_[0-9]+$","",varying.temp)) v.names.temp <- v.names.temp[order(v.names.temp)] varying.temp <- paste0(rep(v.names.temp, length(num_profiles)),"_", rep(num_profiles, each=length(v.names.temp))) out_data_dataset <- reshape(out_data_dataset, idvar = id_var_name, varying = varying.temp, sep = "_", timevar = "profile", times = num_profiles, v.names = v.names.temp, new.row.names = 1:(length(num_profiles)*nrow(out_data_dataset)), direction = "long") colnames(out_data_dataset)<- gsub(" ",".",colnames(out_data_dataset)) for (m in attribute_var_names_label){ out_data_dataset[[m]] <- as.factor(out_data_dataset[[m]]) } colnames(out_data_dataset)[which(colnames(out_data_dataset)==id_var_name)] <- "respondent" out_data_dataset$respondentIndex <- as.factor(out_data_dataset$respondent) out_data_dataset$respondentIndex <- as.integer(out_data_dataset$respondentIndex) out_data_dataset$selected <- as.integer(out_data_dataset$selected) out_data_dataset$task <- as.integer(out_data_dataset$task) out_data_dataset$profile <- as.integer(out_data_dataset$profile) return(out_data_dataset) }
lsdm_est_logist_2pl <- function( y, theta, wgt_theta, method="L-BFGS-B", b0=NULL, a0=NULL) { y <- as.numeric(y) dist_irf_val <- function(x){ a <- x[2] b <- x[1] irf_est <- stats::plogis(a*(theta-b)) diff_irf <- y - irf_est val <- sum( diff_irf^2 * wgt_theta ) return(val) } dist_irf_grad <- function(x){ grad <- rep(0,2) a <- x[2] b <- x[1] irf_est <- stats::plogis(a*(theta-b)) diff_irf <- y - irf_est der1 <- 2*diff_irf*irf_est*(1-irf_est)*wgt_theta grad[1] <- sum( der1*a ) grad[2] <- -sum( der1*(theta-b) ) return(grad) } if (is.null(b0)){ b0 <- theta[ which.min( abs(y-0.5) ) ] par0 <- c(b0, 1) } else { par0 <- c( b0, a0) } res <- stats::optim( par=par0, fn=dist_irf_val, gr=dist_irf_grad, method=method) res <- c( res$par, sqrt(res$value) ) return(res) }
local_lifecycle_quiet <- function(frame = caller_env()) { local_options(lifecycle_verbosity = "quiet", .frame = frame) }
summary.mlnormal <- function( object, digits=4, file=NULL, ...) { CDM::osink( file=file, suffix=paste0( "__SUMMARY.Rout") ) cat("-----------------------------------------------------------------\n") sirt::sirt_summary_print_package_rsession(pack="LAM") cat( "Date of Analysis:", paste( object$s2 ), "\n" ) cat("Computation Time:", print(object$s2 - object$s1), "\n\n") sirt::sirt_summary_print_call(CALL=object$CALL) cat( object$descriptions["des_method"], "\n\n") if ( object$REML & ! ( object$vcov_REML ) ){ cat(" * Standard errors for random effects are not properly calculated! \n") cat(" * Use vcov=TRUE as an argument in 'mlnormal' if valid standard errors\n") cat(" for random effects parameters are requested.\n\n") } cat("-----------------------------------------------------------------\n") cat( "Number of observations=", object$ic$N, "\n" ) cat( "Number of clusters=", object$ic$G, "\n\n" ) cat( "Number of iterations=", object$iter, "\n\n" ) cat( "Deviance=", round( object$deviance, 2 ), "\n" ) cat( paste0( object$descriptions["log_like_verbose"] , "=" ), round( object$ic$loglike, 2 ), "\n" ) if ( object$posterior_obj$display_posterior ){ cat( "Log prior=", round( object$posterior_obj$log_prior, 2 ), "\n" ) cat( "Log posterior=", round( object$posterior_obj$log_posterior, 2 ), "\n" ) } cat("\n") cat( "Number of estimated parameters=", object$ic$np, "\n" ) cat( " Number of estimated beta parameters=", object$ic$np.beta, "\n" ) cat( " Number of estimated theta parameters=", object$ic$np.theta, "\n\n" ) if ( ! object$REML ){ cat( "AIC=", round( object$ic$AIC, 1 ), " | penalty=", round( object$ic$AIC - object$ic$deviance,2 ), " | AIC=-2*LL + 2*p \n" ) } cat("-----------------------------------------------------------------\n") cat("Beta Parameters\n") excl <- c("parm","prior") obji <- object$beta_summary mlnormal_summary_round_helper(obji, digits=digits, exclude=excl, print=TRUE) cat("-----------------------------------------------------------------\n") cat("Theta Parameters\n") obji <- object$theta_summary mlnormal_summary_round_helper(obji, digits=digits, exclude=excl, print=TRUE) CDM::csink( file=file ) }
source("setup.R") expect_error(detect_file_enc(NULL)) expect_error(detect_file_enc(NA)) expect_equal(detect_file_enc(NA_character_), NA_character_) expect_equal(detect_file_enc(character(0)), character(0)) expect_equal(detect_file_enc(""), NA_character_) expect_equal(detect_file_enc("no-exists"), NA_character_) expect_warning(detect_file_enc(""), "Can not open file ''") expect_warning(detect_file_enc("no-exists"), "Can not open file 'no-exists'") tmp <- tempfile() x <- as.raw(sample(0:255, 50)) writeBin(x, tmp) expect_equivalent(detect_file_enc(tmp), NA_character_) unlink(tmp) if (skip_os()) { exit_file("Skip tests on current OS") } res <- detect_file_enc(ex_files) expect_true(is.character(res)) expect_true(all(!is.na(res))) expect_equal(length(res), length(ex_files)) expect_equivalent(res, ex_encs)
context("Checking r_sample_logical") test_that("r_sample_logical ...",{ })
precartogramR <- function(data, method=c("gsm", "gn", "dcn", "GastnerSeguyMore", "GastnerNewman", "DougenikChrismanNiemeyer"), gridpower2=8:11, pf=1.5, verbose=FALSE) { method <- match.arg(method) if (method=="DougenikChrismanNiemeyer") method <- "dcn" if (method=="GastnerNewman") method <- "gn" if (method=="GastnerSeguyMore") method <- "gsm" if (!inherits(data, "sf")) stop(paste(deparse(substitute((data))),"not inherits from sf class")) if (is.na(sf::st_crs(data))) { warning("No coordinate reference system !\n Function proceeds assuming planar coordinates\n Remarks:\n 1. This function use planar coordinates to calculate areas and thus does not give correct answers for longitude/latitude data\n 2. Setting coordinate reference system could be a good idea, see sf::st_crs") } else { if (sf::st_is_longlat(data)) stop(paste(deparse(substitute((data))),"is an unprojected map.\n This function use planar coordinates to calculate areas and thus does not give correct answers for longitude/latitude data:\n => Use \"st_transform()\" to transform longitude/latitude coordinates to another coordinate system.")) } if (method=="dcn") { return(dist_between_vertices(data)) } else { return(grid_analysis(data, gridpower2, pf, verbose)) } }
survMC <- function(m,n,Time,Event,chains,adapt,iter,data) { if(Time!="OS"){ names(data)[names(data) == Time] <- "OS" } if(Event!="Death"){ names(data)[names(data) == Event] <- "Death" } data<-data[order(data$OS),] var1 <- colnames(data) nr <- nrow(data) data1 <- subset(data, Death == 1) u <- unique(data1$OS) if ((data$Death[nrow(data)])==0){ u1<-c(u,data$OS[nrow(data)]) } else { u1 <- u } u2 <- sort(u1) t.len<-(length(u2)-1) model_jags <- " data{ for(i in 1:N) { for(j in 1:T) { Y[i,j] <- step(obs.t[i] - t[j] + eps) dN[i, j] <- Y[i, j] * step(t[j + 1] - obs.t[i] - eps) * fail[i] } } } model{ for(i in 1:N){ betax[i,1] <- 0 for(k in 2:(p+1)){ betax[i,k] <- betax[i,k-1] + beta[k-1]*x[i,k-1] } } for(j in 1:T) { for(i in 1:N) { dN[i, j] ~ dpois(Idt[i, j]) Idt[i, j] <- Y[i, j] * exp(betax[i,p+1]) * dL0[j] } dL0[j] ~ dgamma(mu[j], c) mu[j] <- dL0.star[j] * c } c <- 0.001 r <- 0.1 for (j in 1 : T) { dL0.star[j] <- r * (t[j + 1] - t[j]) } for(k in 1:p){ beta[k] ~ dnorm(0.0,0.000001) } }" params <- c("beta","dL0") inits <- function(){list( beta = rep(0,p), dL0 = rep(0.0001,bigt))} x2 <- rep(0,nrow(data)) q <- matrix(nrow=0,ncol=5) s <- matrix(nrow=0,ncol=2) di <- matrix(nrow=0,ncol=1) for(i in m:n){ x1 <- data[(1:nrow(data)),i] x = t(rbind(x1,x2)) datafi <- list(x=x,obs.t=data$OS,t=u2,T=t.len,N=nrow(data),fail=data$Death,eps=1E-10,p=2) jags <- jags.model(textConnection(model_jags), data = datafi, n.chains = chains, n.adapt = adapt) samps <- coda.samples(jags, params, n.iter=iter) s1 <- summary(samps) stats <- s1$statistics[1,c(1:2)] s <- rbind(s,stats) quan <- s1$quantiles[1,] q <- rbind(q,quan) d = dic.samples(jags, n.iter=iter) meandeviance <- round(sum(d$deviance),2) di <- rbind(di,meandeviance) } results <- cbind(s,q) expresults <- exp(results) Variables <- names(data)[m:n] expresults <- data.frame(Variables,expresults,di) colnames(expresults)<-c("Variable","Posterior Means","SD","2.5%","25%","50%","75%","97.5%","DIC") rownames(expresults) <- NULL return(expresults) } utils::globalVariables(c("Death","N","step","obs.t","eps","fail","x1","dL0","p","bigt"))
expected <- eval(parse(text="c(\"unknown\", \"unknown\", \"unknown\", \"unknown\", \"unknown\", \"unknown\", \"unknown\", \"unknown\")")); test(id=0, code={ argv <- eval(parse(text="list(c(\"* Edit the help file skeletons in 'man', possibly combining help files for multiple functions.\", \"* Edit the exports in 'NAMESPACE', and add necessary imports.\", \"* Put any C/C++/Fortran code in 'src'.\", \"* If you have compiled code, add a useDynLib() directive to 'NAMESPACE'.\", \"* Run R CMD build to build the package tarball.\", \"* Run R CMD check to check the package tarball.\", \"\", \"Read \\\"Writing R Extensions\\\" for more information.\"))")); .Internal(`Encoding`(argv[[1]])); }, o=expected);
NULL .einfo <- setRefClass( Class = "einfo", contains = "eutil", methods = list( initialize = function(method = "GET", ...) { callSuper() perform_query(method = method, ...) if (no_errors()) { errors$check_errors(.self) } }, show_xml = function() { if (is.null(database())) { cat("List of Entrez databases\n") methods::show(xmlValue("/eInfoResult/DbList/DbName")) } else { cat(sprintf("Overview over the Entrez database %s.\n", sQuote(xmlValue("/eInfoResult/DbInfo/MenuName")))) x <- get_content("parsed") nm <- names(x) fnm <- ellipsize(paste0(names(x$Fields), collapse = "; "), offset = 10) lnm <- ellipsize(paste0(names(x$Links), collapse = "; "), offset = 9) showme <- sprintf(" %s: %s", nm, c(vapply(x[1:6], as.character, ""), fnm, lnm)) cat(showme, sep = "\n") } }, show_json = function() { methods::show(get_content("json")) }, show = function() { cat("Object of class", sQuote(eutil()), "\n") if (no_errors()) { switch(retmode(), xml = show_xml(), json = show_json()) } else { methods::show(get_error()) } } ) ) parse_einfo <- function(object) { retmode <- object$retmode() if (retmode == "xml") { x <- object$get_content("xml") if (is.null(object$database())) { xvalue(x, "/eInfoResult/DbList/DbName") } else { list( dbName = xvalue(x, "/eInfoResult/DbInfo/DbName"), MenuName = xvalue(x, "/eInfoResult/DbInfo/MenuName"), Description = xvalue(x, "/eInfoResult/DbInfo/Description"), DbBuild = xvalue(x, "/eInfoResult/DbInfo/DbBuild"), Count = xvalue(x, "/eInfoResult/DbInfo/Count", "integer"), LastUpdate = xvalue(x, "/eInfoResult/DbInfo/LastUpdate", "POSIXlt"), Fields = extract_df(x, "/eInfoResult/DbInfo/FieldList/Field/"), Links = extract_df(x, "/eInfoResult/DbInfo/LinkList/Link/") ) } } else if (retmode == "json") { jsonlite::fromJSON(object$get_content("json")) } } extract_df <- function(x, path) { nm <- unique(xname(x, paste0(path, "child::node()"))) if (!all(is.na(nm))) { nodes <- xset(x, paste0(path, "*")) list <- split(vapply(nodes, XML::xmlValue, ""), nm) tibble::as_tibble(list, validate = TRUE)[, nm] } else { tibble::tibble() } } einfo <- function(db = NULL, version = "2.0", retmode = "xml") { retmode <- match.arg(retmode, c("xml", "json")) assertthat::assert_that(is.null(db) || assertthat::is.string(db)) if (!is.null(db)) { assertthat::assert_that(is.null(version) || version == "2.0") } else { version <- NULL } .einfo(method = "GET", db = db, version = version, retmode = retmode) } setMethod("content", "einfo", function(x, as = NULL) { callNextMethod(x = x, as = as) }) setMethod("[", c(x = "einfo", i = "ANY", j = "missing"), function(x, i, j) { content(x, as = "parsed")[i] }) setMethod("[[", "einfo", function(x, i) { content(x, as = "parsed")[[i]] })
xlsx.reader <- function(data.file, filename, workbook.name) { .require.package('readxl') sheets <- readxl::excel_sheets(filename) for (sheet.name in sheets) { variable.name <- paste(workbook.name, clean.variable.name(sheet.name), sep = ".") tryCatch(assign(variable.name, data.frame(readxl::read_excel(filename, sheet = sheet.name)), envir = .TargetEnv), error = function(e) { warning(paste("The worksheet", sheet.name, "didn't load correctly.")) }) } }
run_tests <- length(strsplit(packageDescription("fwildclusterboot")$Version, "\\.")[[1]]) > 3 run_tests <- FALSE if(run_tests){ library(fwildclusterboot) library(data.table) library(tinytest) library(RStata) options("RStata.StataVersion" = 16) options("RStata.StataPath" = "\"C:\\Program Files\\Stata16\\StataIC-64\"") tol <- 0.01 save_test_data_to <- "c:/Users/alexa/Dropbox/fwildclusterboot/" save_data <- paste0(save_test_data_to, "voters.csv") set.seed(2) data1 <<- fwildclusterboot:::create_data(N = 1000, N_G1 = 20, icc1 = 0.01, N_G2 = 10, icc2 = 0.01, numb_fe1 = 10, numb_fe2 = 10, seed = 1234) fwrite(data1, save_data) lm_fit <- lm(proposition_vote ~ treatment + ideology1 + log_income + Q1_immigration + Q2_defense, data = data1) boot_lm1 <- suppressWarnings( boottest( object = lm_fit, clustid = "group_id1", bootcluster = c("group_id1", "Q1_immigration"), B = 99999, seed = 911, param = "treatment", conf_int = FALSE, sign_level = 0.05, nthreads = 4 ) ) test_1 <- " clear import delimited c:/Users/alexa/Dropbox/fwildclusterboot/voters.csv set seed 1 quietly reg proposition_vote treatment ideology1 log_income i.q1_immigration i.q2_defense, cluster(group_id1) boottest treatment, reps(99999) cluster(group_id1 ) bootcluster(group_id1 q1_immigration) nograph gen p_val = r(p) //gen conf_int = r(CI) " res <- RStata::stata(test_1, data.out = TRUE) stata_p_val <- unique(res$p_val) expect_equal(boot_lm1$p_val, stata_p_val, tol = tol) boot_lm2 <- suppressWarnings( boottest( object = lm_fit, clustid = "group_id1", bootcluster = c("group_id1", "Q1_immigration"), B = 99999, seed = 911, param = "treatment", conf_int = FALSE, sign_level = 0.10 )) test_2 <- " clear import delimited c:/Users/alexa/Dropbox/fwildclusterboot/voters.csv set seed 1 quietly reg proposition_vote treatment ideology1 log_income i.q1_immigration i.q2_defense, cluster(group_id1) boottest treatment, reps(99999) cluster(group_id1 ) bootcluster(group_id1 q1_immigration) nograph level(90) gen p_val = r(p) //gen conf_int = r(CI) " res <- RStata::stata(test_2, data.out = TRUE) stata_p_val <- unique(res$p_val) expect_equal(boot_lm2$p_val, stata_p_val, tol = tol) test_3 <- " clear import delimited c:/Users/alexa/Dropbox/fwildclusterboot/voters.csv set seed 1 quietly reg proposition_vote treatment ideology1 log_income i.q1_immigration i.q2_defense, cluster(group_id2) boottest treatment = 0.05, reps(99999) cluster(group_id1 ) bootcluster(group_id1 q1_immigration) nograph level(90) gen p_val = r(p) //gen conf_int = r(CI) " boot_lm3 <- suppressWarnings( boottest( object = lm_fit, clustid = "group_id1", bootcluster = c("group_id1", "Q1_immigration"), B = 99999, seed = 911, param = "treatment", conf_int = FALSE, sign_level = 0.10, beta0 = 0.05 )) res <- RStata::stata(test_3, data.out = TRUE) stata_p_val <- unique(res$p_val) expect_equal(boot_lm3$p_val, stata_p_val, tol = tol) boot_lm7 <- suppressWarnings( boottest( object = lm_fit, clustid = "group_id1", bootcluster = c("group_id1", "Q1_immigration","Q2_defense"), B = 99999, seed = 911, param = "treatment", conf_int = FALSE, sign_level = 0.10, type = "rademacher", impose_null = FALSE )) test_7 <- " clear import delimited c:/Users/alexa/Dropbox/fwildclusterboot/voters.csv set seed 1 quietly reg proposition_vote treatment ideology1 log_income i.q1_immigration i.q2_defense, cluster(group_id1) boottest treatment, reps(99999) cluster(group_id1 ) bootcluster(group_id1 q1_immigration q2_defense) nograph level(90) weighttype(rademacher) nonull gen p_val = r(p) //gen conf_int = r(CI) " res <- RStata::stata(test_7, data.out = TRUE) stata_p_val <- unique(res$p_val) expect_equal(boot_lm7$p_val, stata_p_val, tol= tol) skip_test <- TRUE if(skip_test){ boot_lm8 <- suppressWarnings( boottest( object = lm_fit, clustid = c("group_id1", "group_id2"), bootcluster = c("group_id1", "Q1_immigration"), B = 199999, seed = 911, param = "treatment", conf_int = FALSE, sign_level = 0.05, type = "rademacher", impose_null = FALSE )) test_8 <- " clear import delimited c:/Users/alexa/Dropbox/fwildclusterboot/voters.csv set seed 1 quietly reg proposition_vote treatment ideology1 log_income i.q1_immigration i.q2_defense, cluster(group_id1) boottest treatment, reps(199999) cluster(group_id1 group_id2) bootcluster(group_id1 q1_immigration) nograph level(95) weighttype(rademacher) nonull gen p_val = r(p) //gen conf_int = r(CI) " res <- RStata::stata(test_8, data.out = TRUE) stata_p_val <- unique(res$p_val) expect_equal(boot_lm8$p_val, stata_p_val, tol= tol) boot_lm9 <- suppressWarnings( boottest( object = lm_fit, clustid = c("group_id1", "group_id2"), bootcluster = c("group_id1", "Q2_defense"), B = 199999, seed = 911, param = "treatment", conf_int = FALSE, sign_level = 0.05, type = "rademacher", impose_null = FALSE )) test_9 <- " clear import delimited c:/Users/alexa/Dropbox/fwildclusterboot/voters.csv set seed 1 quietly reg proposition_vote treatment ideology1 log_income i.q1_immigration i.q2_defense, cluster(group_id1) boottest treatment, reps(199999) cluster(group_id1 group_id2) bootcluster(group_id1 q2_defense) nograph level(95) weighttype(rademacher) nonull gen p_val = r(p) //gen conf_int = r(CI) " res <- RStata::stata(test_9, data.out = TRUE) stata_p_val <- unique(res$p_val) expect_equal(boot_lm9$p_val, stata_p_val, tol= tol) boot_lm10 <- suppressWarnings( boottest( object = lm_fit, clustid = c("group_id1", "group_id2"), bootcluster = c("group_id1", "Q1_immigration", "Q2_defense"), B = 99999, seed = 911, param = "treatment", conf_int = FALSE, sign_level = 0.10, type = "rademacher", impose_null = FALSE )) test_10 <- " clear import delimited c:/Users/alexa/Dropbox/fwildclusterboot/voters.csv set seed 1 quietly reg proposition_vote treatment ideology1 log_income i.q1_immigration i.q2_defense, cluster(group_id1) boottest treatment, reps(99999) cluster(group_id1 group_id2) bootcluster(group_id1 q1_immigration q2_defense) nograph level(90) weighttype(rademacher) nonull gen p_val = r(p) //gen conf_int = r(CI) " res <- RStata::stata(test_10, data.out = TRUE) stata_p_val <- unique(res$p_val) expect_equal(boot_lm10$p_val, stata_p_val, tol= tol) } }
dpareto2 <- function(x, scale = 1, shape = 1) { d <- (shape*scale^shape)/((x + scale)^(shape + 1)) d[x <= 0] <- 0 d }
wilcoxTestTargetY <- function(Y, predictedOnlyX, predictedXE, verbose, ...){ residOnlyX <- abs(Y - predictedOnlyX) residXE <- abs(Y - predictedXE) diffResid <- residOnlyX-residXE testResult <- wilcox.test(diffResid, alternative="greater") pvalue <- testResult$p.value if(verbose) cat(paste("\nTest statistc: ", testResult$statistic)) if(verbose) cat(paste("\np-value: ", pvalue)) list(pvalue = pvalue) }
perm_distribution <- function(x, y, type, randomization = FALSE, n.rep = 10000) { stopifnot("'x' is missing." = !missing(x)) stopifnot("'y' is missing." = !missing(y)) stopifnot("'type' is missing." = !missing(type)) checkmate::assert_numeric(x, min.len = 5, finite = TRUE, any.missing = FALSE, null.ok = FALSE) checkmate::assert_numeric(y, min.len = 5, finite = TRUE, any.missing = FALSE, null.ok = FALSE) checkmate::assert_choice(type, choices = c("HL11", "HL12", "HL21", "HL22", "MED1", "MED2"), null.ok = FALSE) checkmate::assert_flag(randomization, na.ok = FALSE, null.ok = FALSE) checkmate::assert_count(n.rep, na.ok = FALSE, positive = TRUE, null.ok = FALSE) m <- length(x) n <- length(y) if (randomization & (n.rep > choose(m + n, m))) { stop (paste0("'n.rep' may not be larger than ", choose(m + n, m), ", the number of all splits.")) } if (!randomization) { complete <- c(x, y) splits <- gtools::combinations((m + n), m, 1:(m + n)) distribution <- apply(splits, 1, function(s) rob_perm_statistic(x = complete[s], y = complete[-s], type = type)$statistic) } else if (randomization) { splits <- replicate(n.rep, sample(c(x, y))) distribution <- apply(splits, 2, function(s) rob_perm_statistic(x = s[1:m], y = s[(m + 1):(m + n)], type)$statistic) } return(distribution) } m_est_perm_distribution <- function(x, y, psi, k, randomization = FALSE, n.rep = 10000) { stopifnot("'x' is missing." = !missing(x)) stopifnot("'y' is missing." = !missing(y)) stopifnot("'psi' is missing." = !missing(psi)) stopifnot("'k' is missing." = !missing(k)) checkmate::assert_numeric(x, min.len = 5, finite = TRUE, any.missing = FALSE, null.ok = FALSE) checkmate::assert_numeric(y, min.len = 5, finite = TRUE, any.missing = FALSE, null.ok = FALSE) checkmate::assert_choice(psi, choices = c("huber", "hampel", "bisquare"), null.ok = FALSE) checkmate::assert_numeric(k, lower = 0, len = ifelse(psi == "hampel", 3, 1), finite = TRUE, any.missing = FALSE, null.ok = FALSE) checkmate::assert_flag(randomization, na.ok = FALSE, null.ok = FALSE) checkmate::assert_count(n.rep, na.ok = FALSE, positive = TRUE, null.ok = FALSE) m <- length(x) n <- length(y) if (randomization & (n.rep > choose(m + n, m))) { stop (paste0("'n.rep' may not be larger than ", choose(m + n, m), ", the number of all splits.")) } if (!randomization) { complete <- c(x, y) splits <- gtools::combinations((m + n), m, 1:(m + n)) distribution <- apply(splits, 1, function(s) m_test_statistic(x = complete[s], y = complete[-s], psi = psi, k = k)$statistic) } else if (randomization) { splits <- replicate(n.rep, sample(c(x, y))) distribution <- apply(splits, 2, function(s) m_test_statistic(x = s[1:m], y = s[(m + 1):(m + n)], psi = psi, k = k)$statistic) } return(distribution) } calc_perm_p_value <- function(statistic, distribution, m, n, randomization, n.rep, alternative) { stopifnot("'statistic' is missing." = !missing(statistic)) stopifnot("'distribution' is missing." = !missing(distribution)) stopifnot("'m' is missing." = !missing(m)) stopifnot("'n' is missing." = !missing(n)) stopifnot("'randomization' is missing." = !missing(randomization)) stopifnot("'n.rep' is missing." = !missing(n.rep)) stopifnot("'alternative' is missing." = !missing(alternative)) checkmate::assert_number(statistic, na.ok = FALSE, finite = TRUE, null.ok = FALSE) checkmate::assert_numeric(distribution, finite = FALSE, any.missing = TRUE, null.ok = FALSE) checkmate::assert_count(m, na.ok = FALSE, positive = TRUE, null.ok = FALSE) checkmate::assert_count(n, na.ok = FALSE, positive = TRUE, null.ok = FALSE) checkmate::assert_flag(randomization, na.ok = FALSE, null.ok = FALSE) checkmate::assert_count(n.rep, na.ok = FALSE, positive = TRUE, null.ok = FALSE) checkmate::assert_choice(alternative, choices = c("two.sided", "greater", "less"), null.ok = FALSE) if (randomization & (n.rep > choose(m + n, m))) { stop (paste0("'n.rep' should not be larger than ", choose(m + n, m), ", the number of all splits.")) } A <- switch(alternative, two.sided = sum(abs(distribution) >= abs(statistic), na.rm = TRUE), greater = sum(distribution >= statistic, na.rm = TRUE), less = sum(distribution <= statistic, na.rm = TRUE) ) if (randomization & (A > n.rep)) { stop (paste0("'n.rep' needs to be at least as large as the number of observations which are at least as extreme as the observed value ", statistic, " of the test statistic.")) } if (randomization) { p.value <- statmod::permp(A, nperm = n.rep, n1 = m, n2 = n, twosided = (alternative == "two.sided"), method = "auto") } else if (!randomization) { p.value <- A / choose(m + n, m) } return(p.value) }
get_block_attributes <- function(source, block_key, host = .host.) { downlo <- basicTextGatherer() if (curlPerform(url = paste0(host, '//', source, '.', block_key, '.header'), writefunction = downlo[[1]], customrequest = 'GET') != 0) stop ('Http error status.') rexi <- '^([[:alnum:]]+):([0-9]+)*$' rexh <- '^([[:alnum:]]+):([0-9a-f]+)*$' ss <- strsplit(downlo$value(), '\n')[[1]] if (any(!grepl(rexh, ss))) stop ('Unexpected format.') ix <- which(grepl(rexi, ss)) vv <- as.numeric(gsub(rexi, '\\2', ss[ix])) names(vv) <- gsub(rexi, '\\1', ss[ix]) ll <- as.list(vv) ss <- ss[-ix] vv <- gsub(rexh, '\\2', ss) names(vv) <- gsub(rexh, '\\1', ss) c(ll, as.list(vv)) }
dwplot <- function(x, ci = .95, dodge_size = .4, vars_order = NULL, show_intercept = FALSE, margins = FALSE, model_name = "model", model_order = NULL, style = c("dotwhisker", "distribution"), by_2sd = FALSE, vline = NULL, dot_args = list(size = 1.2), whisker_args = list(size = .5), dist_args = list(alpha = .5), line_args = list(alpha = .75, size = 1), ...) { if (length(style) > 1) style <- style[[1]] if (!style %in% c("dotwhisker", "distribution")) stop("style must be dotwhisker or distribution") df <- dw_tidy(x, ci, by_2sd, margins, ...) if (!show_intercept) df <- df %>% filter(!grepl("^\\(Intercept\\)$|^\\w+\\|\\w+$", term)) estimate <- model <- conf.low <- conf.high <- term <- std.error <- n <- loc <- dens <- NULL n_vars <- length(unique(df$term)) dodge_size <- dodge_size if (model_name %in% names(df)) { dfmod <- df[[model_name]] n_models <- length(unique(dfmod)) l_models <- if(is.null(model_order)) unique(dfmod) else model_order df[[model_name]] <- factor(dfmod, levels = rev(l_models)) } else { if (length(df$term) == n_vars) { df[[model_name]] <- factor("one") n_models <- 1 } else { stop( "Please add a variable named '", model_name, "' to distinguish different models" ) } } mod_names <- unique(df[[model_name]]) if (!is.null(vars_order)) { df$term <- factor(df$term, levels = vars_order) df <- df[order(df$term),] %>% filter(!is.na(term)) } if (n_models > 1) { df <- add_NAs(df, n_models, mod_names) } var_names <- unique(df$term) df <- df %>% mutate(y_ind = n_vars - as.numeric(factor(term, levels = var_names)) + 1) y_ind <- df$y_ind if (style == "distribution") { if (nrow(df) > n_models * n_vars) { df <- df %>% select(-n,-loc,-dens) %>% distinct() } df1 <- purrr::map_dfr(1:101, function(x) df) %>% arrange(term, model) %>% group_by(term, model) %>% dplyr::mutate( n = 1:dplyr::n(), loc = estimate - 3 * std.error + (6 * std.error) / 100 * (n - 1), dens = dnorm(loc, mean = estimate, sd = std.error) + y_ind ) %>% filter(!is.na(estimate)) p <- ggplot(data = df) + vline + geom_dwdist(df1 = df1, line_args = line_args, dist_args = dist_args) + scale_y_continuous(breaks = unique(df$y_ind), labels = var_names) + guides(color = guide_legend(reverse = TRUE), fill = guide_legend(reverse = TRUE)) + ylab("") + xlab("") } else { point_args0 <- list(na.rm = TRUE) point_args <- c(point_args0, dot_args) segment_args0 <- list(na.rm = TRUE) segment_args <- c(segment_args0, whisker_args) p <- ggplot(data = df) + vline + geom_dw( df = df, point_args = point_args, segment_args = segment_args, dodge_size = dodge_size ) + guides(color = guide_legend(reverse = TRUE)) + ylab("") + xlab("") } if (n_models == 1) { p <- p + theme(legend.position = "none") } p$args <- list( dodge_size = dodge_size, vars_order = vars_order, show_intercept = show_intercept, model_name = model_name, model_order = model_order, style = style, by_2sd = FALSE, vline = vline, dot_args = dot_args, whisker_args = whisker_args, dist_args = dist_args, line_args = line_args, list(...) ) return(p) } dw_tidy <- function(x, ci, by_2sd, margins,...) { estimate <- model <- std.error <- conf.high <- conf.low <- NULL AME <- SE <- lower <- p <- upper <- z <- NULL get_dat <- function(x) { tryCatch( as.data.frame(model.matrix(x)), error = function(e) model.frame(x) ) } mk_model <- function(x) { if (all(!is.na(suppressWarnings(as.numeric(x))))) { paste("Model", x) } else x } if (!is.data.frame(x)) { if (!inherits(x, "list")) { if(margins){ df <- margins::margins(x) %>% summary(level = ci) %>% rename(term = factor, estimate = AME, std.error = SE, conf.low = lower, conf.high = upper, statistic = z, p.value = p) }else{ df <- standardize_names(parameters(x, ci, conf.int = TRUE, ...), style = "broom") } if (by_2sd) { df <- df %>% by_2sd(get_dat(x)) } } else { if (by_2sd) { df <- purrr::map_dfr(x, .id = "model", function(x) { if(margins){ df <- margins::margins(x) %>% summary(level = ci) %>% rename(term = factor, estimate = AME, std.error = SE, conf.low = lower, conf.high = upper, statistic = z, p.value = p) }else{ df <- standardize_names(parameters(x, ci, conf.int = TRUE, ...), style = "broom") } dotwhisker::by_2sd(df, dataset = get_dat(x)) }) %>% mutate(model = mk_model(model)) } else { df <- purrr::map_dfr(x, .id = "model", function(x) { if(margins){ df <- margins::margins(x) %>% summary(level = ci) %>% rename(term = factor, estimate = AME, std.error = SE, conf.low = lower, conf.high = upper, statistic = z, p.value = p) }else{ df <- standardize_names(parameters(x, ci, conf.int = TRUE, ...), style = "broom") } }) %>% mutate(model = if_else( !is.na(suppressWarnings(as.numeric( model ))), paste("Model", model), model )) } } } else { df <- x if ((!"conf.low" %in% names(df)) || (!"conf.high" %in% names(df))) { if ("std.error" %in% names(df)) { df <- transform( df, conf.low = estimate - stats::qnorm(1 - (1 - ci) / 2) * std.error, conf.high = estimate + stats::qnorm(1 - (1 - ci) / 2) * std.error ) } else { df <- transform(df, conf.low = NA, conf.high = NA) } } } return(df) } add_NAs <- function(df = df, n_models = n_models, mod_names = mod_names, model_name = "model") { term <- model <- NULL if (!is.factor(df$term)) { df$term <- factor(df$term, levels = unique(df$term)) } if (!is.factor(dfmod <- df[[model_name]])) { df[[model_name]] <- factor(dfmod, levels = unique(dfmod)) } for (i in seq(n_models)) { m <- df %>% filter(model == factor(mod_names[[i]], levels = mod_names)) not_in <- setdiff(unique(df$term), m$term) for (j in seq(not_in)) { t <- data.frame( term = factor(not_in[j], levels = levels(df$term)), model = factor(mod_names[[i]], levels = mod_names) ) if ("submodel" %in% names(m)) { t$submodel <- m$submodel[1] } if ("submodel" %in% names(m)) { m <- full_join(m, t, by = c("term", "model", "submodel")) } else { m <- full_join(m, t, by = c("term", "model")) } } if (i == 1) { dft <- m %>% arrange(term) } else { dft <- bind_rows(dft, m %>% arrange(term)) } } df <- dft df$estimate <- as.numeric(df$estimate) if ("std.error" %in% names(df)) { df$std.error <- as.numeric(df$std.error) } if ("conf.high" %in% names(df)) { df$conf.high <- as.numeric(df$conf.high) } if ("conf.low" %in% names(df)) { df$conf.low <- as.numeric(df$conf.low) } return(df) } geom_dwdist <- function(data = NULL, df1, line_args, dist_args) { loc <- dens <- model <- term <- y_ind <- conf.high <- conf.low <- NULL l1 <- layer( data = df1, mapping = aes( x = loc, y = dens, group = interaction(model, term), color = model, fill = model ), stat = "identity", position = "identity", geom = GeomPolygon, params = dist_args ) l2 <- layer( data = data, mapping = aes( y = y_ind, xmin = conf.low, xmax = conf.high, color = model ), stat = "identity", position = "identity", geom = ggstance::GeomLinerangeh, show.legend = FALSE, params = line_args ) return(list(l1, l2)) } geom_dw <- function(df, point_args, segment_args, dodge_size) { loc <- dens <- model <- term <- y_ind <- conf.high <- conf.low <- estimate <- NULL point_arguments <- tryCatch({ added_point_aes <- point_args[names(point_args) == ""][[1]] point_mapping <- modifyList( aes( y = stats::reorder(term, y_ind), x = estimate, group = interaction(model, term), color = model ), added_point_aes ) point_arguments <- point_args[names(point_args) != ""] list(point_mapping, point_arguments) }, error = function(e) { point_mapping <- aes( y = stats::reorder(term, y_ind), x = estimate, group = interaction(model, term), color = model ) return(list(point_mapping, point_args)) }) segment_arguments <- tryCatch({ added_segment_aes <- segment_args[names(segment_args) == ""][[1]] segment_mapping <- modifyList( aes( y = stats::reorder(term, y_ind), xmin = conf.low, xmax = conf.high, group = interaction(model, term), color = model ), added_segment_aes ) segment_arguments <- segment_args[names(segment_args) != ""] list(segment_mapping, segment_arguments) }, error = function(e) { segment_mapping <- aes( y = stats::reorder(term, y_ind), xmin = conf.low, xmax = conf.high, group = interaction(model, term), color = model ) return(list(segment_mapping, segment_args)) }) l1 <- layer( data = df, mapping = point_arguments[[1]], stat = "identity", position = ggstance::position_dodgev(height = dodge_size), geom = "point", params = point_arguments[[2]] ) l2 <- layer( data = df, mapping = segment_arguments[[1]], stat = "identity", position = ggstance::position_dodgev(height = dodge_size), geom = ggstance::GeomLinerangeh, show.legend = FALSE, params = segment_arguments[[2]] ) return(list(l2, l1)) } dw_plot <- dwplot
demRegression <- function(path=getwd(), filename='demRegression', png=FALSE, gif=FALSE) { noiseLevel = 0.2 noiseVar = noiseLevel^2 options = gpOptions(); options$kern$comp = list('rbf','white') l=9; x = as.matrix(seq(-1, 1, length=l)) trueKern = kernCreate(x, 'rbf') K = kernCompute(trueKern, x) + diag(dim(x)[1])*noiseVar yTrue = gaussSamp(Sigma=K, numSamps=1) steps = 2^c(round(log2(l-1)):0); s=0 indTrain=list(); length(indTrain)=length(steps) indTrain = lapply(indTrain, function(x) x=(seq(1,l,by=steps[(s<<-s+1)]))) graphics.off() figNo = 1 for (i in 1:length(indTrain)) { if (i > 0) { yTrain = as.matrix(yTrue[indTrain[[i]]]) xTrain = as.matrix(x[indTrain[[i]]]) kern = kernCreate(x, 'rbf') kern$inverseWidth = 5 xTest = as.matrix(seq(-2, 2, length=200)) Kx = kernCompute(kern, xTest, xTrain) Ktrain = kernCompute(kern, xTrain) invKtrain = .jitCholInv(Ktrain + diag(dim(Ktrain)[1])*noiseVar, silent=TRUE)$invM yPred = Kx %*% invKtrain %*% yTrain yVar = kernDiagCompute(kern, xTest) - rowSums(Kx %*% invKtrain * Kx) model = gpCreate(dim(xTrain)[2], dim(yTrain)[2], xTrain, yTrain, options) dev.new(); plot.new() gpPlot(model, xTest, yPred, yVar, ylim=c(-3,3), col='black') zeroAxes() pathfilename = paste(path,'/',filename,'_', figNo, '.eps', sep='') if (png) { dev.copy2eps(file = pathfilename) system(paste('eps2png ', pathfilename, sep='')) } figNo = figNo + 1 } else { xTest = as.matrix(seq(-2, 2, length=200)) kern = kernCreate(xTest, 'rbf') kern$inverseWidth = 5 yPred = array(0,dim(xTest)) yVar = kernDiagCompute(kern, xTest) plot(xTest, yPred, col='blue', lwd=.5) zeroAxes() pathfilename = paste(path,'/',filename,'_', figNo, '.eps', sep='') if (png) { dev.copy2eps(file = pathfilename) system(paste('eps2png ', pathfilename, sep='')) } figNo = figNo + 1 } if (i < length(indTrain)) { dev.new(); plot.new() gpPlot(model, xTest, yPred, yVar, ylim=c(-3,3), col='black') if (i < 1) diffs = indTrain[[i+1]] else diffs = setdiff(indTrain[[i+1]], indTrain[[i]]) newx = x[diffs]; newy = yTrue[diffs] points(newx, newy, pch = 4, cex = 1.5, lwd=3, col='blue') pathfilename = paste(path,'/',filename,'_', figNo, '.eps', sep='') if (png) { dev.copy2eps(file = pathfilename) system(paste('eps2png ', pathfilename, sep='')) } figNo = figNo + 1 } } if (gif) system(paste('convert -delay 80 ',path,'/',filename,'*.png ', path,'/',filename,'.gif', sep='')) }
shinyML_regression <- function(data = data,y,framework = "h2o", share_app = FALSE,port = NULL){ set.seed(123) if(!(framework %in% c("h2o","spark"))){stop("framework must be selected between h2o or spark")} data <- data.table(data) colnames(data) <- gsub("\\.","_",colnames(data)) y <- gsub("\\.","_",y) if (!(y %in% colnames(data))){ stop("y must match one data input variable") } if (!(eval(parse(text = paste0("class(data$",y,")"))) == "numeric")){ stop("y column class must be numeric") } x <- setdiff(colnames(data),y) if (nrow(data) > 1000000) { stop("Input dataset must not exceed one million rows") } options(dplyr.summarise.inform=F) model <- reactiveValues() train_1 <- reactiveValues() test_1 <- reactiveValues() test_2 <- reactiveValues() v_neural <- reactiveValues(type_model = NA) v_grad <- reactiveValues(type_model = NA) v_glm <- reactiveValues(type_model = NA) v_decision_tree <- reactiveValues(type_model = NA) v_random <- reactiveValues(type_model = NA) v_auto_ml <- reactiveValues(type_model = NA) parameter <- reactiveValues() time_gbm <- data.table() time_random_forest <- data.table() time_glm <- data.table() time_decision_tree <- data.table() time_neural_network <- data.table() time_auto_ml <- data.table() importance_gbm <- data.table() importance_decision_tree <- data.table() importance_random_forest <- data.table() importance_neural_network <- data.table() scaled_importance <- NULL variable <- NULL Predicted_value <- NULL Model <- NULL `.` <- NULL `MAPE(%)` <- NULL Counter <- NULL feature <- NULL importance <- NULL fit <- NULL prediction <- NULL `..density..` <- NULL argonNav <- argonDashNavbar( argonDropNav( title = HTML(paste0("shiny<font color='orange'>ML</font>")), src = "https://www.zupimages.net/up/20/39/ql8k.jpg", orientation = "left" ) ) argonFooter <- argonDashFooter( copyrights = "@shinyML, 2020", src = "https://jeanbertinr.github.io/shinyMLpackage/", argonFooterMenu( argonFooterItem("GitHub", src = "https://github.com/JeanBertinR/shinyML"), argonFooterItem("CRAN", src = "https://cran.r-project.org/web/packages/shinyML/index.html") ) ) dashheader_framework <- argonDashHeader( gradient = TRUE, color = "danger", separator = FALSE, argonRow( argonColumn(width = "20%", argonInfoCard(value = "Regression",gradient = TRUE,width = 12, title = "Machine learning task", icon = icon("chart-bar"), icon_background = "red", background_color = "lightblue" ) ), argonColumn(width = "20%",uiOutput("framework_used")), argonColumn(width = "20%",uiOutput("framework_memory")), argonColumn(width = "20%",uiOutput("framework_cpu")), argonColumn(width = "20%",uiOutput("dataset_infoCard")) ) ) dashheader_explore_input <- argonDashHeader( gradient = FALSE, color = "info", separator = FALSE, div(align = "center", argonButton( name = HTML("<font size='+1'>&nbsp; Explore input data </font>"), status = "info", icon = icon("chart-area"), size = "lg", toggle_modal = TRUE, modal_id = "modal_exlore_input_data" ), argonModal( id = "modal_exlore_input_data", title = HTML("<b>EXPLORE INPUT DATA</b>"), status = "info", gradient = TRUE, br(), HTML("<b>Before running machine learning models, it can be useful to inspect each variable distribution and have an insight of dependencies between explicative variables.</b>"), br(),br(), icon("tools"),icon("tools"),icon("tools"), br(),br(), HTML("This section allows to plot variation of each variable as a function of another, to check classes of explicative variables, to plot histograms of each distribution and show correlation matrix between all variables.<br><br> Please note that this section can be used to determine if some variable are strongly correlated to another and eventually removed from the training phase.") ) ), br(), argonRow( argonColumn(width = 9, argonCard(width = 12, hover_lift = TRUE, shadow = TRUE, argonTabSet(width = 12, id = "tab_input_data", card_wrapper = TRUE, horizontal = TRUE, circle = FALSE, size = "sm", iconList = list(argonIcon("cloud-upload-96"), argonIcon("bell-55"), argonIcon("calendar-grid-58"),argonIcon("calendar-grid-58")), argonTab(tabName = "Explore dataset", active = TRUE, argonRow( argonColumn(width = 6,div(align = "center",uiOutput("X_axis_explore_dataset"))), argonColumn(width = 6,div(align = "center",selectInput(inputId = "y_variable_input_curve",label = "Y-axis variable",choices = colnames(data),selected = y))) ), br(), br(), br(), withSpinner(plotlyOutput("explore_dataset_chart",width = "100%",height = "120%")) ), argonTab(tabName = "Variables Summary", active = FALSE, fluidRow( argonColumn(width = 4, br(), br(), withSpinner(DTOutput("variables_class_input", height = "100%", width = "100%")) ), argonColumn(width = 8, div(align = "center", radioButtons(inputId = "input_var_graph_type",label = "",choices = c("Histogram","Boxplot","Autocorrelation"),selected = "Histogram",inline = T) ), div(align = "center",uiOutput("message_autocorrelation")), withSpinner(plotlyOutput("variable_boxplot", height = "100%", width = "100%"))) ) ), argonTab(tabName = "Correlation matrix", active = FALSE, withSpinner(plotlyOutput("correlation_matrix", height = "100%", width = "100%")) ) ) ) ), argonColumn(width = 3, argonCard(width = 12,src = NULL,hover_lift = T,shadow = TRUE, div(align = "center", argonColumn(width = 6,uiOutput("Time_series_checkbox")), argonColumn(width = 6,uiOutput("time_series_column")), uiOutput("Variables_input_selection"), uiOutput("slider_time_series_train"), uiOutput("slider_time_series_test"), uiOutput("slider_percentage"), uiOutput("message_nrow_train_dataset") ) ) ) ) ) dashheader_explore_results <- argonDashHeader(gradient = TRUE, color = "primary", separator = FALSE, div(align = "center", argonButton( name = HTML("<font size='+1'>&nbsp; Explore results</font>"), status = "primary", icon = icon("list-ol"), size = "lg", toggle_modal = TRUE, modal_id = "modal_explore_results" ), argonModal( id = "modal_explore_results", title = HTML("<b>EXPLORE RESULTS</b>"), status = "primary", gradient = TRUE, br(), HTML("<b>Once machine learning models have been lauched, this section can be used to compare their performances on the testing dataset</b>"), br(),br(), icon("tools"),icon("tools"),icon("tools"), br(),br(), HTML("You can check confusion matrices to get classification results for each model or have an overview of error metric in 'Compare models performances' tab.<br><br> Please note that feature importances of each model are available in the corresponding tab.") ) ), br(), argonRow( argonCard(width = 12, title = "Predictions on test period", src = NULL, hover_lift = TRUE, shadow = TRUE, icon = icon("cogs"), status = "danger", argonTabSet( width = 12, id = "results_models", card_wrapper = TRUE, horizontal = TRUE, circle = FALSE, size = "sm", iconList = list(argonIcon("cloud-upload-96"), argonIcon("bell-55"), argonIcon("calendar-grid-58"),argonIcon("calendar-grid-58")), argonTab( tabName = "Result charts on test period", active = TRUE, withSpinner(dygraphOutput("output_curve", width = "100%")), br(), div(align = "center", switchInput(label = "Bar chart mode",inputId = "bar_chart_mode",value = TRUE) ) ), argonTab( tabName = "Compare models performances", active = FALSE, div(align = "center", br(), br(), uiOutput("message_compare_models_performances") ), withSpinner(DTOutput("score_table")) ), argonTab(tabName = "Feature importance", active = FALSE, div(align = "center", br(), br(), uiOutput("message_feature_importance"), uiOutput("feature_importance_glm_message")), withSpinner(plotlyOutput("feature_importance",height = "100%")) ), argonTab(tabName = "Table of results", active = FALSE, withSpinner(DTOutput("table_of_results")) ) ), br(), br() ) ) ) if(framework == "h2o"){ Sys.setenv(http_proxy="") Sys.setenv(http_proxy_user="") Sys.setenv(https_proxy_user="") h2o.init() h2o::h2o.no_progress() cluster_status <- h2o.clusterStatus() dashheader_select_parameters <- argonDashHeader(gradient = TRUE, color = "default", separator = FALSE, div(align = "center", argonButton( name = HTML("<font size='+1'>&nbsp; Configure parameters and run models</font>"), status = "default", icon = icon("tools"), size = "lg", toggle_modal = TRUE, modal_id = "modal_configure_parameters" ), argonModal( id = "modal_configure_parameters", title = HTML("<b>CONFIGURE PARAMETERS</b>"), status = "default", gradient = TRUE, br(), HTML("<b>Compare different machine learning techniques with your own hyper-parameters configuration.</b>"), br(),br(), icon("tools"),icon("tools"),icon("tools"), br(),br(), HTML("You are free to select hyper-parameters configuration for each machine learning model using different cursors.<br><br> Each model can be lauched separately by cliking to the corresponding button; you can also launch all models simultaneously using 'Run all models!'button<br><br> Please note that autoML algorithm will automatically find the best algorithm to suit your regression task: the user will be informed of the machine learning technique used and know which hyper-parameters should be configured. ") ) ), br(), argonRow( argonColumn(width = 6,div(align = "center",uiOutput("h2o_cluster_mem"))), argonColumn(width = 6,div(align = "center",uiOutput("h2o_cpu"))) ), argonRow( argonCard(width = 3, icon = icon("sliders"), status = "success", title = "Generalized linear regression", div(align = "center", argonRow( argonColumn(width = 6, radioButtons(label = "Family",inputId = "glm_family",choices = c("gaussian","poisson", "gamma","tweedie"),selected = "gaussian") ), argonColumn(width = 6, radioButtons(label = "Link",inputId = "glm_link",choices = c("identity","log"),selected = "identity"), switchInput(label = "Intercept term",inputId = "intercept_term_glm",value = TRUE,width = "auto") ) ), sliderInput(label = "Lambda",inputId = "reg_param_glm",min = 0,max = 10,value = 0), sliderInput(label = "Alpha (0:Ridge <-> 1:Lasso)",inputId = "alpha_param_glm",min = 0,max = 1,value = 0.5), sliderInput(label = "Maximum iteraions",inputId = "max_iter_glm",min = 50,max = 300,value = 100), actionButton("run_glm","Run glm",style = 'color:white; background-color:green; padding:4px; font-size:120%',icon = icon("cogs",lib = "font-awesome")) ) ), argonCard(width = 3, icon = icon("sliders"), status = "danger", title = "Random Forest", div(align = "center", sliderInput(label = "Number of trees",min = 1,max = 100, inputId = "num_tree_random_forest",value = 50), sliderInput(label = "Subsampling rate",min = 0.1,max = 1, inputId = "subsampling_rate_random_forest",value = 0.6), sliderInput(label = "Max depth",min = 1,max = 50, inputId = "max_depth_random_forest",value = 20), sliderInput(label = "Number of bins",min = 2,max = 100, inputId = "n_bins_random_forest",value = 20), actionButton("run_random_forest","Run random forest",style = 'color:white; background-color:red; padding:4px; font-size:120%',icon = icon("cogs",lib = "font-awesome")) ) ), argonCard(width = 3, icon = icon("sliders"), status = "primary", title = "Neural network", div(align = "center", argonRow( argonColumn(width = 6, radioButtons(label = "Activation function",inputId = "activation_neural_net",choices = c( "Rectifier", "Maxout","Tanh", "RectifierWithDropout", "MaxoutWithDropout","TanhWithDropout"),selected = "Rectifier") ), argonColumn(width = 6, radioButtons(label = "Loss function",inputId = "loss_neural_net",choices = c("Automatic", "Quadratic", "Huber", "Absolute", "Quantile"),selected = "Automatic") ) ), textInput(label = "Hidden layers",inputId = "hidden_neural_net",value = "c(200,200)"), sliderInput(label = "Epochs",min = 10,max = 100, inputId = "epochs_neural_net",value = 10), sliderInput(label = "Learning rate",min = 0.001,max = 0.1, inputId = "rate_neural_net",value = 0.005), actionButton("run_neural_network","Run neural network",style = 'color:white; background-color:darkblue; padding:4px; font-size:120%',icon = icon("cogs",lib = "font-awesome")) ) ), argonCard(width = 3, icon = icon("sliders"), status = "warning", title = "Gradient boosting", div(align = "center", sliderInput(label = "Max depth",min = 1,max = 20, inputId = "max_depth_gbm",value = 5), sliderInput(label = "Number of trees",min = 1,max = 100, inputId = "n_trees_gbm",value = 50), sliderInput(label = "Sample rate",min = 0.1,max = 1, inputId = "sample_rate_gbm",value = 1), sliderInput(label = "Learn rate",min = 0.1,max = 1, inputId = "learn_rate_gbm",value = 0.1), actionButton("run_gradient_boosting","Run gradient boosting",style = 'color:white; background-color:orange; padding:4px; font-size:120%',icon = icon("cogs",lib = "font-awesome")) ) ) ), argonRow( argonColumn(width = 6, argonCard(width = 12, icon = icon("cogs"), status = "warning", title = "Compare all models", div(align = "center", argonH1("Click this button to run all model simultaneously",display = 4), argonH1(HTML("<small><i> The four models will be runed with the parameters selected above</i></small>"),display = 4), br(), br(), actionBttn(label = "Run all models !",inputId = "train_all",color = "primary", icon = icon("cogs",lib = "font-awesome")), br() ) ) ), argonColumn(width = 6, argonCard(width = 12,icon = icon("cogs"),status = "warning", title = "Auto Machine Learning", div(align = "center", prettyCheckboxGroup( inputId = "auto_ml_autorized_models", label = HTML("<b>Authorized searching</b>"), choices = c("DRF", "GLM", "XGBoost", "GBM", "DeepLearning"), selected = c("DRF", "GLM", "XGBoost", "GBM", "DeepLearning"), icon = icon("check-square-o"), status = "primary", inline = TRUE, outline = TRUE, animation = "jelly" ), br(), knobInput(inputId = "run_time_auto_ml",label = HTML("<b>Max running time (in seconds)</b>"),value = 15,min = 10,max = 60, displayPrevious = TRUE, lineCap = "round",fgColor = " ), actionButton("run_auto_ml","Run auto ML",style = 'color:white; background-color:red; padding:4px; font-size:120%',icon = icon("cogs",lib = "font-awesome")) ) ) ) ) ) } else if(framework == "spark"){ if (nrow(spark_installed_versions()) == 0){spark_install()} sc <- spark_connect(master = "local") config_spark<- spark_session_config(sc) dashheader_select_parameters <- argonDashHeader(gradient = TRUE, color = "default", separator = FALSE, div(align = "center", argonButton( name = HTML("<font size='+1'>&nbsp; Configure parameters and run models</font>"), status = "default", icon = icon("tools"), size = "lg", toggle_modal = TRUE, modal_id = "modal_configure_parameters" ), argonModal( id = "modal_configure_parameters", title = HTML("<b>CONFIGURE PARAMETERS</b>"), status = "default", gradient = TRUE, br(), HTML("<b>Compare different machine learning techniques with your own hyper-parameters configuration.</b>"), br(),br(), icon("tools"),icon("tools"),icon("tools"), br(),br(), HTML("You are free to select hyper-parameters configuration for each machine learning model using different cursors.<br><br> Each model can be lauched separately by cliking to the corresponding button; you can also launch all models simultaneously using 'Run all models!'button<br><br> Please note that autoML algorithm will automatically find the best algorithm to suit your regression task: the user will be informed of the machine learning technique used and know which hyper-parameters should be configured. ") ) ), br(), argonRow( argonColumn(width = 6,div(align = "center",uiOutput("spark_cluster_mem"))), argonColumn(width = 6,div(align = "center",uiOutput("spark_cpu"))) ), argonRow( argonCard(width = 3, icon = icon("sliders"), status = "success", title = "Generalized linear regression", div(align = "center", argonRow( argonColumn(width = 6, radioButtons(label = "Family",inputId = "glm_family",choices = c("gaussian","Gamma","poisson"),selected = "gaussian") ), argonColumn(width = 6, radioButtons(label = "Link",inputId = "glm_link",choices = c("identity","log"),selected = "identity"), switchInput(label = "Intercept term",inputId = "intercept_term_glm",value = TRUE,width = "auto") ) ), sliderInput(label = "Lambda",inputId = "reg_param_glm",min = 0,max = 10,value = 0), sliderInput(label = "Alpha (0:Ridge <-> 1:Lasso)",inputId = "alpha_param_glm",min = 0,max = 1,value = 0.5), sliderInput(label = "Maximum iteraions",inputId = "max_iter_glm",min = 50,max = 300,value = 100), actionButton("run_glm","Run glm",style = 'color:white; background-color:green; padding:4px; font-size:120%',icon = icon("cogs",lib = "font-awesome")) ) ), argonCard(width = 3, icon = icon("sliders"), status = "danger", title = "Random Forest", div(align = "center", sliderInput(label = "Number of trees",min = 1,max = 100, inputId = "num_tree_random_forest",value = 50), sliderInput(label = "Subsampling rate",min = 0.1,max = 1, inputId = "subsampling_rate_random_forest",value = 1), sliderInput(label = "Max depth",min = 1,max = 50, inputId = "max_depth_random_forest",value = 20), sliderInput(label = "Number of bins",min = 2,max = 100, inputId = "n_bins_random_forest",value = 20), actionButton("run_random_forest","Run random forest",style = 'color:white; background-color:red; padding:4px; font-size:120%',icon = icon("cogs",lib = "font-awesome")) ) ), argonCard(width = 3, icon = icon("sliders"), status = "primary", title = "Decision tree", div(align = "center", argonRow( argonColumn( sliderInput(label = "Max depth",inputId = "max_depth_decision_tree",min = 1,max = 30,value = 20), sliderInput(label = "Max bins",inputId = "max_bins_decision_tree",min = 2,max = 60,value = 32), sliderInput(label = "Min instance per node",inputId = "min_instance_decision_tree",min = 1,max = 10,value = 1), actionButton("run_decision_tree","Run decision tree regression",style = 'color:white; background-color:darkblue; padding:4px; font-size:120%',icon = icon("cogs",lib = "font-awesome")) ) ) ) ), argonCard(width = 3, icon = icon("sliders"), status = "warning", title = "Gradient boosting", div(align = "center", sliderInput(label = "Step size",min = 0,max = 1, inputId = "step_size_gbm",value = 0.1), sliderInput(label = "Subsampling rate",min = 0.1,max = 1, inputId = "subsampling_rate_gbm",value = 1), sliderInput(label = "Max depth",min = 1,max = 30, inputId = "max_depth_gbm",value = 20), actionButton("run_gradient_boosting","Run gradient boosting",style = 'color:white; background-color:orange; padding:4px; font-size:120%',icon = icon("cogs",lib = "font-awesome")) ) ) ), argonRow( argonColumn(width = 12, center = T, argonCard(width = 12, icon = icon("cogs"), status = "warning", title = "Compare all models", div(align = "center", argonH1("Click this button to run all model simultaneously",display = 4), argonH1(HTML("<small><i> The four models will be runed with the parameters selected above</i></small>"),display = 4), br(), br(), actionBttn(label = "Run all models !",inputId = "train_all",color = "primary", icon = icon("cogs",lib = "font-awesome")), br() ) ) ) ) ) } argonHeader <- argonColumn(width = "100%", dashheader_framework, dashheader_explore_input , dashheader_select_parameters, dashheader_explore_results ) server = function(session,input, output) { dates_variable_list <- reactive({ dates_columns_list <- c() for (i in colnames(data)){ if (is.Date(eval(parse(text = paste0("data$",i)))) | is.POSIXct(eval(parse(text = paste0("data$",i))))){ dates_columns_list <- c(dates_columns_list,i) } } dates_columns_list }) output$Time_series_checkbox <- renderUI({ if (length(dates_variable_list()) >= 1){value = TRUE} else {value = FALSE} awesomeCheckbox("checkbox_time_series", "Time series",status = "primary",value = value) }) observe({ if (length(dates_variable_list()) == 0){ shinyjs::hideElement("Time_series_checkbox") } }) observe({ req(!is.null(input$checkbox_time_series)) if (input$checkbox_time_series == TRUE){ req(!is.null(input$time_serie_select_column)) test_1$date <- eval(parse(text = paste0("mean(as.Date(data$",input$time_serie_select_column,"))"))) test_2$date <- eval(parse(text = paste0("max(as.Date(data$",input$time_serie_select_column,"))"))) } }) output$framework_used <- renderUI({ if (framework == "h2o"){selected_framework <- "H2O"} else if (framework == "spark"){selected_framework <- "Spark"} argonInfoCard( value = selected_framework,gradient = TRUE,width = 12, title = "Selected framework", icon = icon("atom"), icon_background = "orange", background_color = "lightblue" ) }) output$framework_memory <- renderUI({ if (framework == "h2o"){ used_memory <- paste(round(as.numeric(cluster_status$free_mem)/1024**3,2), "GB", sep = "") title <- "H2O Cluster Total Memory" } else if (framework == "spark"){ used_memory <- paste(gsub("g","GB",config_spark$spark.driver.memory), sep = "") title <-"Spark Cluster Total Memory" } argonInfoCard( value = used_memory , title = title, gradient = TRUE,width = 12, icon = icon("server"), icon_background = "yellow", background_color = "lightblue" ) }) output$framework_cpu <- renderUI({ if (framework == "h2o"){cpu_number <- cluster_status$num_cpus} else if (framework == "spark"){cpu_number <- config_spark$spark.sql.shuffle.partitions} argonInfoCard( value = cpu_number,gradient = TRUE,width = 12, title = "Number of CPUs in Use", icon = icon("microchip"), icon_background = "green", background_color = "lightblue" ) }) output$dataset_infoCard <- renderUI({ argonInfoCard( value = paste0(nrow(data)," rows x ",ncol(data)," columns"), gradient = TRUE,width = 12, title = "Your dataset", icon = icon("image"), icon_background = "blue", background_color = "lightblue" ) }) output$message_nrow_train_dataset <- renderUI({ req(!is.null(input$checkbox_time_series)) req(!is.null(table_forecast()[["data_train"]])) if (input$checkbox_time_series == TRUE){ number_rows_datatest <- nrow(eval(parse(text = paste0("data[",input$time_serie_select_column," >= input$train_selector[1],][",input$time_serie_select_column," <= input$train_selector[2],]")))) } else if (input$checkbox_time_series == FALSE){ number_rows_datatest <- nrow(table_forecast()[["data_train"]]) } argonBadge(text = HTML(paste0("<big><big>Training dataset contains <b>",number_rows_datatest,"</b> rows</big></big>")),status = "success") }) output$message_autocorrelation <- renderUI({ points_serie <-eval(parse(text = paste0("data[,",colnames(data)[input$variables_class_input_rows_selected],"]"))) if (input$input_var_graph_type %in% c("Histogram","Autocorrelation") & !is.numeric(points_serie)){ argonH1("Only available for numerical variables",display = 4) } }) observeEvent(input$run_glm,{ train_1$date <- input$train_selector[1] test_1$date <- input$test_selector[1] test_2$date <- input$test_selector[2] model$train_variables <- input$input_variables v_grad$type_model <- NA v_neural$type_model <- NA v_random$type_model <- NA v_decision_tree$type_model <- NA v_auto_ml$type_model <- NA v_glm$type_model <- "ml_generalized_linear_regression" parameter$family_glm <- input$glm_family parameter$glm_link <- input$glm_link parameter$intercept_term_glm <- input$intercept_term_glm parameter$reg_param_glm <- input$reg_param_glm parameter$alpha_param_glm <- input$alpha_param_glm parameter$max_iter_glm <- input$max_iter_glm }) observeEvent(input$run_random_forest,{ train_1$date <- input$train_selector[1] test_1$date <- input$test_selector[1] test_2$date <- input$test_selector[2] model$train_variables <- input$input_variables v_grad$type_model <- NA v_neural$type_model <- NA v_glm$type_model <- NA v_auto_ml$type_model <- NA v_decision_tree$type_model <- NA v_random$type_model <- "ml_random_forest" parameter$num_tree_random_forest <- input$num_tree_random_forest parameter$subsampling_rate_random_forest <- input$subsampling_rate_random_forest parameter$max_depth_random_forest <- input$max_depth_random_forest parameter$n_bins_random_forest <- input$n_bins_random_forest }) observeEvent(input$run_gradient_boosting,{ train_1$date <- input$train_selector[1] test_1$date <- input$test_selector[1] test_2$date <- input$test_selector[2] model$train_variables <- input$input_variables v_grad$type_model <- "ml_gradient_boosted_trees" v_neural$type_model <- NA v_glm$type_model <- NA v_random$type_model <- NA v_auto_ml$type_model <- NA v_decision_tree$type_model <- NA parameter$sample_rate_gbm <- input$sample_rate_gbm parameter$n_trees_gbm <- input$n_trees_gbm parameter$max_depth_gbm <- input$max_depth_gbm parameter$learn_rate_gbm <- input$learn_rate_gbm parameter$step_size_gbm <- input$step_size_gbm parameter$subsampling_rate_gbm <- input$subsampling_rate_gbm }) output$slider_time_series_train <- renderUI({ req(!is.null(input$checkbox_time_series)) req(!is.null(input$time_serie_select_column)) if (input$checkbox_time_series == TRUE){ sliderInput("train_selector", "Choose train period:", min = eval(parse(text = paste0("min(data$",input$time_serie_select_column,")"))), max = eval(parse(text = paste0("max(data$",input$time_serie_select_column,")"))), value = eval(parse(text = paste0("c(min(data$",input$time_serie_select_column,"),mean(data$",input$time_serie_select_column,"))")))) } }) output$slider_time_series_test <- renderUI({ req(!is.null(input$checkbox_time_series)) req(!is.null(input$time_serie_select_column)) if (input$checkbox_time_series == TRUE){ sliderInput("test_selector", "Choose test period:", min = eval(parse(text = paste0("min(data$",input$time_serie_select_column,")"))), max = eval(parse(text = paste0("max(data$",input$time_serie_select_column,")"))), value = eval(parse(text = paste0("c(mean(data$",input$time_serie_select_column,"),max(data$",input$time_serie_select_column,"))")))) } }) output$slider_percentage <- renderUI({ req(!is.null(input$checkbox_time_series)) if (input$checkbox_time_series == FALSE){ selectInput(label = "Train/ Test splitting",inputId = "percentage_selector",choices = paste0(c(50:99),"%"),selected = 70,multiple = FALSE) } }) output$time_series_column <- renderUI({ req(!is.null(input$checkbox_time_series)) if (input$checkbox_time_series == TRUE){ selectInput(inputId = "time_serie_select_column",label = "Date column",choices = dates_variable_list(),multiple = FALSE) } }) output$Variables_input_selection<- renderUI({ req(!is.null(input$checkbox_time_series)) variable_input_list <- x[!(x %in% dates_variable_list())] selectInput( inputId = "input_variables",label = "Input variables: ",choices = x,multiple = TRUE,selected = variable_input_list) }) output$X_axis_explore_dataset <- renderUI({ req(!is.null(input$checkbox_time_series)) if (input$checkbox_time_series == TRUE){ req(!is.null(input$time_serie_select_column)) selected_column <- input$time_serie_select_column } else {selected_column <- colnames(data)[1]} selectInput(inputId = "x_variable_input_curve",label = "X-axis variable",choices = colnames(data),selected = selected_column) }) output$variables_class_input <- renderDT({ table_classes <- data.table() for (i in 1:ncol(data)){ table_classes <- rbind(table_classes, data.frame(Variable = colnames(data)[i], Class = class(eval(parse(text = paste0("data$",colnames(data)[i])))) ) ) } datatable(table_classes,options = list(pageLength =10,searching = FALSE,lengthChange = FALSE),selection = list(mode = "single",selected = c(1)) ) }) output$variable_boxplot <- renderPlotly({ par("mar") par(mar=c(1,1,1,1)) column_name <- colnames(data)[input$variables_class_input_rows_selected] points_serie <-eval(parse(text = paste0("data[,",column_name,"]"))) if (input$input_var_graph_type == "Histogram"){ req(is.numeric(points_serie)) ggplotly( ggplot(data = data,aes(x = eval(parse(text = column_name)),fill = column_name))+ xlab(column_name)+ geom_histogram(aes(y=..density..), colour="black", fill=" geom_density(alpha = 0.4,size = 1.3) + scale_fill_manual(values=" theme_bw(),tooltip = "density" ) %>% hide_legend() } else if (input$input_var_graph_type == "Boxplot"){ plot_ly(x = points_serie,type = "box",name = column_name) } else if (input$input_var_graph_type == "Autocorrelation"){ req(is.numeric(points_serie)) acf_object <- acf(points_serie,lag.max = 100) data_acf <- cbind(acf_object$lag,acf_object$acf) %>% as.data.table() %>% setnames(c("Lag","ACF")) plot_ly(x = data_acf$Lag, y = data_acf$ACF, type = "bar") } }) output$explore_dataset_chart <- renderPlotly({ req(!is.null(input$checkbox_time_series)) req(!is.null(input$x_variable_input_curve)) req(!is.null(input$y_variable_input_curve)) if (input$checkbox_time_series == TRUE){ data_train_chart <- eval(parse(text = paste0("data[",input$time_serie_select_column," >= input$train_selector[1],][",input$time_serie_select_column," <= input$train_selector[2],]"))) data_test_chart <- eval(parse(text = paste0("data[",input$time_serie_select_column," > input$test_selector[1],][",input$time_serie_select_column," <= input$test_selector[2],]"))) } else if (input$checkbox_time_series == FALSE){ req(!is.null(table_forecast()[["data_train"]])) data_train_chart <- table_forecast()[["data_train"]] data_test_chart <- table_forecast()[["data_test"]] } plot_ly(data = data_train_chart, x = eval(parse(text = paste0("data_train_chart$",input$x_variable_input_curve))), y = eval(parse(text = paste0("data_train_chart$",input$y_variable_input_curve))), type = "scatter",mode = "markers", name = "Training dataset") %>% add_trace(x = eval(parse(text = paste0("data_test_chart$",input$x_variable_input_curve))), y = eval(parse(text = paste0("data_test_chart$",input$y_variable_input_curve))), type = "scatter",mode = "markers", name = "Testing dataset") %>% layout(xaxis = list(title = input$x_variable_input_curve), yaxis = list(title = input$y_variable_input_curve),legend = list(orientation = "h",xanchor = "center",x = 0.5,y= 1.2)) }) output$correlation_matrix <- renderPlotly({ data_correlation <- as.matrix(select_if(data, is.numeric)) plot_ly(x = colnames(data_correlation) , y = colnames(data_correlation), z =cor(data_correlation) ,type = "heatmap", source = "heatplot") }) output$output_curve <- renderDygraph({ req(!is.null(input$checkbox_time_series)) if (input$checkbox_time_series == TRUE){ req(!is.null(input$time_serie_select_column)) data_output_curve <- table_forecast()[['results']] %>% select(-input$input_variables) } else if (input$checkbox_time_series == FALSE){ data_output_curve <- table_forecast()[['results']] %>% select(-c(setdiff(colnames(data),y))) %>% mutate(Counter = row_number()) %>% select(Counter,everything()) } output_dygraph <- dygraph(data = data_output_curve ,main = "Prediction results on test period",width = "100%",height = "150%") %>% dyAxis("x",valueRange = c(0,nrow(data))) %>% dyAxis("y",valueRange = c(0,1.5 * max(eval(parse(text =paste0("table_forecast()[['results']]$",y)))))) %>% dyOptions(animatedZooms = TRUE,fillGraph = T,drawPoints = TRUE, pointSize = 2) if (input$bar_chart_mode == TRUE){ output_dygraph <- output_dygraph %>% dyBarChart() } output_dygraph %>% dyLegend(width = 800) }) output$score_table <- renderDT({ req(ncol(table_forecast()[['results']]) > ncol(data)) req(!is.null(input$checkbox_time_series)) if (input$checkbox_time_series == TRUE){ req(!is.null(input$time_serie_select_column)) performance_table <- eval(parse(text = paste0("table_forecast()[['results']] %>% gather(key = Model,value = Predicted_value,-",input$time_serie_select_column,",-y) %>% as.data.table()"))) } else if (input$checkbox_time_series == FALSE){ performance_table <- table_forecast()[['results']] %>% select(-c(setdiff(colnames(data),y))) %>% gather(key = Model,value = Predicted_value,-y) %>% as.data.table() } performance_table <- performance_table %>% group_by(Model) %>% summarise(`MAPE(%)` = round(100 * mean(abs((Predicted_value - eval(parse(text = y)))/eval(parse(text = y))),na.rm = TRUE),1), RMSE = round(sqrt(mean((Predicted_value - eval(parse(text = y)))**2)),2)) if (nrow(table_forecast()[['traning_time']]) != 0){ performance_table <- performance_table %>% merge(.,table_forecast()[['traning_time']],by = "Model") } datatable( performance_table %>% arrange(`MAPE(%)`) %>% as.data.table() , extensions = 'Buttons', options = list(dom = 'Bfrtip',buttons = c('csv', 'excel', 'pdf', 'print')) ) }) output$feature_importance <- renderPlotly({ if (nrow(table_forecast()[['table_importance']]) != 0){ if (framework == 'h2o'){ ggplotly( ggplot(data = table_forecast()[['table_importance']])+ geom_bar(aes(x = reorder(`variable`,scaled_importance),y = scaled_importance,fill = `model`),stat = "identity",width = 0.3)+ facet_wrap( model ~ .)+ coord_flip()+ xlab("")+ ylab("")+ theme(legend.position="none") ) } else if (framework == 'spark'){ ggplotly( ggplot(data = table_forecast()[['table_importance']])+ geom_bar(aes(x = reorder(`feature`,importance),y = importance,fill = `model`),stat = "identity",width = 0.3)+ facet_wrap( model ~ .)+ coord_flip()+ xlab("")+ ylab("")+ theme(legend.position="none") ) } } }) output$table_of_results <- renderDT({ datatable( table_forecast()[['results']], extensions = 'Buttons', options = list(dom = 'Bfrtip',buttons = c('csv', 'excel', 'pdf', 'print')) ) },server = FALSE) observeEvent(input$train_selector,{ updateSliderInput(session,'test_selector', value= c(input$train_selector[2],input$test_selector[2]) ) }) observeEvent(input$test_selector,{ updateSliderInput(session,'train_selector', value= c(input$train_selector[1],input$test_selector[1]) ) }) output$feature_importance_glm_message <- renderUI({ if (!is.na(v_glm$type_model) & is.na(v_random$type_model) & is.na(v_neural$type_model) & is.na(v_decision_tree$type_model) & is.na(v_grad$type_model) & is.na(v_auto_ml$type_model)){ sendSweetAlert( session = session, title = "Sorry ...", text = "Feature importance not available for generalized regression method !", type = "error" ) argonH1("Feature importance not available for generalized regression method",display = 4) } }) output$message_compare_models_performances <- renderUI({ if (ncol(table_forecast()[['results']]) <= ncol(data)){ sendSweetAlert( session = session, title = "", text = "Please run at least one algorithm to check model performances !", type = "error" ) argonH1("Please run at least one algorithm to check model performances !",display = 4) } }) output$message_feature_importance <- renderUI({ if (ncol(table_forecast()[['results']]) <= ncol(data)){ sendSweetAlert( session = session, title = "", text = "Please run at least one algorithm to check features importances !", type = "error" ) argonH1("Please run at least one algorithm to check features importances !",display = 4) } }) observe({ if (ncol(table_forecast()[['results']]) == ncol(data) + 4){ sendSweetAlert( session = session, title = "The four machine learning models have been trained !", text = "Click ok to see results", type = "success" ) } }) if(framework == "h2o"){ observeEvent(input$train_all,{ train_1$date <- input$train_selector[1] test_1$date <- input$test_selector[1] test_2$date <- input$test_selector[2] model$train_variables <- input$input_variables v_neural$type_model <- "ml_neural_network" v_grad$type_model <- "ml_gradient_boosted_trees" v_glm$type_model <- "ml_generalized_linear_regression" v_random$type_model <- "ml_random_forest" v_auto_ml$type_model <- NA parameter$family_glm <- input$glm_family parameter$glm_link <- input$glm_link parameter$intercept_term_glm <- input$intercept_term_glm parameter$reg_param_glm <- input$reg_param_glm parameter$alpha_param_glm <- input$alpha_param_glm parameter$max_iter_glm <- input$max_iter_glm parameter$num_tree_random_forest <- input$num_tree_random_forest parameter$subsampling_rate_random_forest <- input$subsampling_rate_random_forest parameter$max_depth_random_forest <- input$max_depth_random_forest parameter$n_bins_random_forest <- input$n_bins_random_forest parameter$sample_rate_gbm <- input$sample_rate_gbm parameter$n_trees_gbm <- input$n_trees_gbm parameter$max_depth_gbm <- input$max_depth_gbm parameter$learn_rate_gbm <- input$learn_rate_gbm parameter$hidden_neural_net <- input$hidden_neural_net parameter$epochs_neural_net <- input$epochs_neural_net parameter$activation_neural_net <- input$activation_neural_net parameter$loss_neural_net <- input$loss_neural_net parameter$rate_neural_net <- input$rate_neural_net }) observeEvent(input$run_neural_network,{ train_1$date <- input$train_selector[1] test_1$date <- input$test_selector[1] test_2$date <- input$test_selector[2] model$train_variables <- input$input_variables v_neural$type_model <- "ml_neural_network" v_grad$type_model <- NA v_glm$type_model <- NA v_random$type_model <- NA v_auto_ml$type_model <- NA parameter$hidden_neural_net <- input$hidden_neural_net parameter$epochs_neural_net <- input$epochs_neural_net parameter$activation_neural_net <- input$activation_neural_net parameter$loss_neural_net <- input$loss_neural_net parameter$rate_neural_net <- input$rate_neural_net }) observeEvent(input$run_auto_ml,{ train_1$date <- input$train_selector[1] test_1$date <- input$test_selector[1] test_2$date <- input$test_selector[2] model$train_variables <- input$input_variables v_grad$type_model <- NA v_neural$type_model <- NA v_glm$type_model <- NA v_random$type_model <- NA v_auto_ml$type_model <- "ml_auto" parameter$run_time_auto_ml <- input$run_time_auto_ml parameter$auto_ml_autorized_models <- input$auto_ml_autorized_models }) data_train_not_time_serie <- reactive({ data %>% sample_frac(as.numeric(as.character(gsub("%","",input$percentage_selector)))*0.01) }) table_forecast <- reactive({ req(!is.null(input$checkbox_time_series)) if (input$checkbox_time_series == TRUE){ req(!is.null(test_1$date)) data_train <- data.table() data_test <- data.table() data_results <- eval(parse(text = paste0("data[",input$time_serie_select_column,">'",test_1$date,"',][",input$time_serie_select_column,"< '",test_2$date,"',]"))) } else if (input$checkbox_time_series == FALSE){ req(!is.null(input$percentage_selector)) data_train <- data_train_not_time_serie() data_test <- data %>% anti_join(data_train,by = colnames(data)) data_results <- data_test } table_results <- data_results dl_auto_ml <- NA var_input_list <- c() for (i in 1:length(model$train_variables)){ var_input_list <- c(var_input_list,model$train_variables[i]) } if (length(var_input_list) != 0){ if (input$checkbox_time_series == TRUE){ data_h2o_train <- as.h2o(eval(parse(text = paste0("data[",input$time_serie_select_column,"<='",test_1$date,"',][",input$time_serie_select_column,">='",train_1$date,"',][, !'",input$time_serie_select_column,"']")))) data_h2o_test <- as.h2o(eval(parse(text = paste0("data[",input$time_serie_select_column,">'",test_1$date,"',][",input$time_serie_select_column,"< '",test_2$date,"',][, !'",input$time_serie_select_column,"']")))) } else if (input$checkbox_time_series == FALSE){ if (length(dates_variable_list()) >= 1){ data_train <- eval(parse(text = paste0("data_train[, !'",dates_variable_list()[1] ,"']"))) data_test <- eval(parse(text = paste0("data_test[, !'",dates_variable_list()[1],"']"))) } data_h2o_train <- as.h2o(data_train) data_h2o_test <- as.h2o(data_test) } if (!is.na(v_glm$type_model) & v_glm$type_model == "ml_generalized_linear_regression"){ t1 <- Sys.time() fit <- h2o.glm(x = as.character(var_input_list), y = y, training_frame = data_h2o_train, family = parameter$family_glm, link = parameter$glm_link, intercept = parameter$intercept_term_glm, lambda = parameter$reg_param_glm, alpha = parameter$alpha_param_glm, max_iterations = parameter$max_iter_glm, seed = 123 ) t2 <- Sys.time() time_glm <- data.frame(`Training time` = paste0(round(t2 - t1,1)," seconds"), Model = "Generalized linear regression") table_glm <- h2o.predict(fit,data_h2o_test) %>% as.data.table() %>% mutate(predict = round(predict,3)) %>% rename(`Generalized linear regression` = predict) table_results <- cbind(data_results,table_glm)%>% as.data.table() } if (!is.na(v_random$type_model) & v_random$type_model == "ml_random_forest"){ t1 <- Sys.time() fit <- h2o.randomForest(x = as.character(var_input_list), y = y, training_frame = data_h2o_train, ntrees = parameter$num_tree_random_forest, sample_rate = parameter$subsampling_rate_random_forest, max_depth = parameter$max_depth_random_forest, nbins = parameter$n_bins_random_forest, seed = 123 ) t2 <- Sys.time() time_random_forest <- data.frame(`Training time` = paste0(round(t2 - t1,1)," seconds"), Model = "Random forest") importance_random_forest <- h2o.varimp(fit) %>% as.data.table() %>% select(`variable`,scaled_importance) %>% mutate(model = "Random forest") table_random_forest<- h2o.predict(fit,data_h2o_test) %>% as.data.table() %>% mutate(predict = round(predict,3)) %>% rename(`Random forest` = predict) table_results <- cbind(data_results,table_random_forest)%>% as.data.table() } if (!is.na(v_neural$type_model) & v_neural$type_model == "ml_neural_network"){ t1 <- Sys.time() fit <- h2o.deeplearning(x = as.character(var_input_list), y = y, training_frame = data_h2o_train, activation = parameter$activation_neural_net, loss = parameter$loss_neural_net, hidden = eval(parse(text = parameter$hidden_neural_net)) , epochs = parameter$epochs_neural_net, rate = parameter$rate_neural_net, reproducible = T, seed = 123 ) t2 <- Sys.time() time_neural_network <- data.frame(`Training time` = paste0(round(t2 - t1,1)," seconds"), Model = "Neural network") importance_neural_network <- h2o.varimp(fit) %>% as.data.table() %>% select(`variable`,scaled_importance) %>% mutate(model = "Neural network") table_neural_network <- h2o.predict(fit,data_h2o_test) %>% as.data.table() %>% mutate(predict = round(predict,3)) %>% rename(`Neural network` = predict) table_results <- cbind(data_results,table_neural_network)%>% as.data.table() } if (!is.na(v_grad$type_model) & v_grad$type_model == "ml_gradient_boosted_trees"){ t1 <- Sys.time() fit <- h2o.gbm(x = as.character(var_input_list), y = y, training_frame = data_h2o_train, sample_rate = parameter$sample_rate_gbm, ntrees = parameter$n_trees_gbm, max_depth = parameter$max_depth_gbm, learn_rate = parameter$learn_rate_gbm, min_rows = 2, seed = 123 ) t2 <- Sys.time() time_gbm <- data.frame(`Training time` = paste0(round(t2 - t1,1)," seconds"), Model = "Gradient boosted trees") importance_gbm <- h2o.varimp(fit) %>% as.data.table() %>% select(`variable`,scaled_importance) %>% mutate(model = "Gradient boosted trees") table_gradient_boosting <- h2o.predict(fit,data_h2o_test) %>% as.data.table() %>% mutate(predict = round(predict,3)) %>% rename(`Gradient boosted trees` = predict) table_results <- cbind(data_results,table_gradient_boosting)%>% as.data.table() } if (!is.na(v_auto_ml$type_model) & v_auto_ml$type_model == "ml_auto"){ req(!is.null(parameter$auto_ml_autorized_models)) dl_auto_ml <- h2o.automl(x = as.character(var_input_list), include_algos = parameter$auto_ml_autorized_models, y = y, training_frame = data_h2o_train, max_runtime_secs = parameter$run_time_auto_ml, seed = 123 ) time_auto_ml <- data.frame(`Training time` = paste0(parameter$run_time_auto_ml," seconds"), Model = "Auto ML") table_auto_ml<- h2o.predict(dl_auto_ml,data_h2o_test) %>% as.data.table() %>% mutate(predict = round(predict,3)) %>% rename(`Auto ML` = predict) table_results <- cbind(data_results,table_auto_ml)%>% as.data.table() } if (!is.na(v_neural$type_model) & !is.na(v_grad$type_model) & !is.na(v_glm$type_model) & !is.na(v_random$type_model)){ table_results <- cbind(data_results,table_glm,table_random_forest,table_neural_network,table_gradient_boosting)%>% as.data.table() } } table_training_time <- rbind(time_gbm,time_random_forest,time_glm,time_neural_network,time_auto_ml) table_importance <- rbind(importance_gbm,importance_random_forest,importance_neural_network) %>% as.data.table() list(data_train = data_train, data_test = data_test, traning_time = table_training_time, table_importance = table_importance, results = table_results,auto_ml_model = dl_auto_ml) }) observeEvent(input$run_auto_ml,{ if (is.null(parameter$auto_ml_autorized_models)){ sendSweetAlert(session = session, title = "Warning !", text = "Please authorize at least one model family to perform auto ML", type = "warning" ) } }) observe({ if("Auto ML" %in% colnames(table_forecast()[['results']])){ list <- c(HTML(paste0("<b>Selected model:</b> ",table_forecast()[['auto_ml_model']]@leader@algorithm))) for (i in 1:ncol(table_forecast()[['auto_ml_model']]@leader@model$model_summary)){ list <- rbind(list,HTML(paste0("<b>",colnames(table_forecast()[['auto_ml_model']]@leader@model$model_summary[i]),":</b> ", table_forecast()[['auto_ml_model']]@leader@model$model_summary[i]))) } sendSweetAlert( session = session, title = "Auto ML algorithm succeed!", text = HTML(paste0( "<br>", list)), type = "success", html = TRUE ) } }) } else if(framework == "spark"){ observeEvent(input$train_all,{ test_1$date <- input$test_selector[1] test_2$date <- input$test_selector[2] model$train_variables <- input$input_variables v_decision_tree$type_model <- "ml_decision_tree" v_glm$type_model <- "ml_generalized_linear_regression" v_grad$type_model <- "ml_gradient_boosted_trees" v_random$type_model <- "ml_random_forest" parameter$step_size_gbm <- input$step_size_gbm parameter$subsampling_rate_gbm <- input$subsampling_rate_gbm parameter$max_depth_gbm <- input$max_depth_gbm parameter$num_tree_random_forest <- input$num_tree_random_forest parameter$subsampling_rate_random_forest <- input$subsampling_rate_random_forest parameter$max_depth_random_forest <- input$max_depth_random_forest parameter$family_glm <- input$glm_family parameter$link_glm <- input$glm_link parameter$intercept_term_glm <- input$intercept_term_glm parameter$reg_param_glm <- input$reg_param_glm parameter$max_iter_glm <- input$max_iter_glm parameter$max_depth_decision_tree <- input$max_depth_decision_tree parameter$max_bins_decision_tree <- input$max_bins_decision_tree parameter$min_instance_decision_tree <- input$min_instance_decision_tree }) observeEvent(input$run_decision_tree,{ test_1$date <- input$test_selector[1] test_2$date <- input$test_selector[2] model$train_variables <- input$input_variables parameter$max_depth_decision_tree <- input$max_depth_decision_tree parameter$max_bins_decision_tree <- input$max_bins_decision_tree parameter$min_instance_decision_tree <- input$min_instance_decision_tree v_decision_tree$type_model <- "ml_decision_tree" v_glm$type_model <- NA v_grad$type_model <- NA v_random$type_model <- NA }) data_train_not_time_serie <- reactive({ data %>% sample_frac(as.numeric(as.character(gsub("%","",input$percentage_selector)))*0.01) }) table_forecast <- reactive({ req(!is.null(input$checkbox_time_series)) if (input$checkbox_time_series == TRUE){ req(!is.null(test_1$date)) req(!is.null(test_2$date)) data_train <- data.table() data_test <- data.table() data_results <- eval(parse(text = paste0("data[",input$time_serie_select_column,">'",test_1$date,"',][",input$time_serie_select_column,"< '",test_2$date,"',]"))) } else if (input$checkbox_time_series == FALSE){ req(!is.null(input$percentage_selector)) data_train <- data_train_not_time_serie() data_test <- data %>% anti_join(data_train, by = colnames(data)) data_results <- data_test } table_results <- data_results var_input_list <- "" for (i in 1:length(model$train_variables)){var_input_list <- paste0(var_input_list,"+",model$train_variables[i])} var_input_list <- ifelse(startsWith(var_input_list,"+"),substr(var_input_list,2,nchar(var_input_list)),var_input_list) if (var_input_list != "+"){ if (input$checkbox_time_series == TRUE){ data_spark_train <- eval(parse(text = paste0("data[",input$time_serie_select_column,"<='",test_1$date,"',]"))) data_spark_test <- eval(parse(text = paste0("data[",input$time_serie_select_column,">'",test_1$date,"',][",input$time_serie_select_column,"< '",test_2$date,"',]"))) } else if (input$checkbox_time_series == FALSE){ data_spark_train <- data_train data_spark_test <- data_test } data_spark_train <- copy_to(sc, data_spark_train, "data_spark_train", overwrite = TRUE) data_spark_test <- copy_to(sc, data_spark_test, "data_spark_test", overwrite = TRUE) if (!is.na(v_glm$type_model) & v_glm$type_model == "ml_generalized_linear_regression"){ t1 <- Sys.time() eval(parse(text = paste0("fit <- data_spark_train %>% ml_generalized_linear_regression(", y ," ~ " ,var_input_list , ",family = ", parameter$family_glm, ",link =",parameter$link_glm, ",fit_intercept =",parameter$intercept_term_glm, ",reg_param =",parameter$reg_param_glm, ",max_iter =",parameter$max_iter_glm, ")"))) t2 <- Sys.time() time_glm <- data.frame(`Training time` = paste0(round(t2 - t1,1)," seconds"), Model = "Generalized linear regression") table_ml_glm <- ml_predict(fit,data_spark_test) %>% select(prediction)%>% mutate(prediction = round(prediction,3)) %>% rename(`Generalized linear regression` = prediction) %>% as.data.table() table_results <- cbind(data_results,table_ml_glm) %>% as.data.table() } if (!is.na(v_grad$type_model) & v_grad$type_model == "ml_gradient_boosted_trees"){ t1 <- Sys.time() eval(parse(text = paste0("fit <- data_spark_train %>% ml_gradient_boosted_trees(", y ," ~ " ,var_input_list , ",step_size =",parameter$step_size_gbm, ",subsampling_rate =",parameter$subsampling_rate_gbm, ",max_depth =",parameter$max_depth_gbm, " )"))) t2 <- Sys.time() time_gbm <- data.frame(`Training time` = paste0(round(t2 - t1,1)," seconds"), Model = "Gradient boosted trees") importance_gbm <- ml_feature_importances(fit) %>% mutate(model = "Gradient boosted trees") table_ml_gradient_boosted <- ml_predict(fit,data_spark_test) %>% select(prediction) %>% mutate(prediction = round(prediction,3)) %>% rename(`Gradient boosted trees` = prediction) %>% as.data.table() table_results <- cbind(data_results,table_ml_gradient_boosted) %>% as.data.table() } if (!is.na(v_random$type_model) & v_random$type_model == "ml_random_forest"){ t1 <- Sys.time() eval(parse(text = paste0("fit <- data_spark_train %>% ml_random_forest(", y ," ~ " ,var_input_list , ",num_trees =",parameter$num_tree_random_forest, ",subsampling_rate =",parameter$subsampling_rate_random_forest, ",max_depth =",parameter$max_depth_random_forest, ")"))) t2 <- Sys.time() time_random_forest <- data.frame(`Training time` = paste0(round(t2 - t1,1)," seconds"), Model = "Random forest") importance_random_forest <- ml_feature_importances(fit) %>% mutate(model = "Random forest") table_ml_random_forest <- ml_predict(fit,data_spark_test) %>% select(prediction)%>% mutate(prediction = round(prediction,3)) %>% rename(`Random forest` = prediction) %>% as.data.table() table_results <- cbind(data_results,table_ml_random_forest) %>% as.data.table() } if (!is.na(v_decision_tree$type_model) & v_decision_tree$type_model == "ml_decision_tree"){ t1 <- Sys.time() eval(parse(text = paste0("fit <- data_spark_train %>% ml_decision_tree(", y ," ~ " ,var_input_list , ",max_depth =",parameter$max_depth_decision_tree, ",max_bins =",parameter$max_bins_decision_tree, ",min_instances_per_node =",parameter$min_instance_decision_tree, ")"))) t2 <- Sys.time() time_decision_tree <- data.frame(`Training time` = paste0(round(t2 - t1,1)," seconds"), Model = "Decision tree") importance_decision_tree <- ml_feature_importances(fit) %>% mutate(model = "Decision tree") table_ml_decision_tree <- ml_predict(fit,data_spark_test) %>% select(prediction)%>% mutate(prediction = round(prediction,3)) %>% rename(`Decision tree` = prediction) %>% as.data.table() table_results <- cbind(data_results,table_ml_decision_tree) %>% as.data.table() } if (!is.na(v_decision_tree$type_model) & !is.na(v_grad$type_model) & !is.na(v_glm$type_model) & !is.na(v_random$type_model)) table_results <- cbind(data_results,table_ml_gradient_boosted,table_ml_random_forest,table_ml_glm,table_ml_decision_tree) %>% as.data.table() } table_training_time <- rbind(time_gbm,time_random_forest,time_glm,time_decision_tree) table_importance <- rbind(importance_gbm,importance_random_forest,importance_decision_tree) %>% as.data.table() list(data_train = data_train, data_test = data_test, traning_time = table_training_time, table_importance = table_importance, results = table_results) }) } } app <- shiny::shinyApp( ui = argonDashPage( useShinyjs(), title = "shinyML_regression", author = "Jean", description = "Use of shinyML_regression function", navbar = argonNav, header = argonHeader, footer = argonFooter ), server = server ) if (share_app == TRUE){ if(is.null(port)){stop("Please choose a port to share dashboard")} else if (nchar(port) != 4) {stop("Incorrect format of port")} else if (nchar(port) == 4){ ip_adress <- gsub(".*? ([[:digit:]])", "\\1", system("ipconfig", intern=TRUE)[grep("IPv4", system("ipconfig", intern=TRUE))])[2] message("Forecast dashboard shared on LAN at ",ip_adress,":",port) runApp(app,host = "0.0.0.0",port = port,quiet = TRUE,launch.browser = TRUE) } } else {runApp(app,quiet = TRUE,launch.browser = TRUE)} }
`dimnames.mefa` <- function (x) { out <- list(samp = rownames(x$xtab), taxa = colnames(x$xtab), segm = names(x$segm)) if (is.null(out$segm)) out$segm <- "undefined" return(out) }
MARSSresiduals.tt1 <- function(object, method = c("SS"), normalize = FALSE, silent = FALSE, fun.kf = c("MARSSkfas", "MARSSkfss")) { MLEobj <- object if (missing(fun.kf)) { fun.kf <- MLEobj$fun.kf } else { MLEobj$fun.kf <- fun.kf } method <- match.arg(method) model.dims <- attr(MLEobj$marss, "model.dims") TT <- model.dims[["x"]][2] m <- model.dims[["x"]][1] n <- model.dims[["y"]][1] y <- MLEobj$marss$data et <- st.et <- mar.st.et <- bchol.st.et <- matrix(NA, n + m, TT) model.et <- matrix(NA, n, TT) model.var.et <- array(0, dim = c(n, n, TT)) var.et <- array(0, dim = c(n + m, n + m, TT)) msg <- NULL time.varying <- is.timevarying(MLEobj) kf <- MARSSkf(MLEobj) Kt.ok <- TRUE if (MLEobj$fun.kf == "MARSSkfas") { Kt <- try(MARSSkfss(MLEobj), silent = TRUE) if (inherits(Kt, "try-error") || !Kt$ok) { Kt <- array(0, dim = c(m, n, TT)) Kt.ok <- FALSE } else { Kt <- Kt$Kt } kf$Kt <- Kt } Ey <- MARSShatyt(MLEobj, only.kem = FALSE) Rt <- parmat(MLEobj, "R", t = 1)$R Ht <- parmat(MLEobj, "H", t = 1)$H Rt <- Ht %*% tcrossprod(Rt, Ht) Zt <- parmat(MLEobj, "Z", t = 1)$Z Qtp <- parmat(MLEobj, "Q", t = 2)$Q if (method == "SS") { model.et <- Ey$ytt - fitted(MLEobj, type = "ytt1", output = "matrix") et[1:n, ] <- model.et cov.et <- matrix(0, n, m) for (t in 1:TT) { if (time.varying$R) Rt <- parmat(MLEobj, "R", t = t)$R if (time.varying$H) Ht <- parmat(MLEobj, "H", t = t)$H if (time.varying$R || time.varying$H) Rt <- Ht %*% tcrossprod(Rt, Ht) if (time.varying$Z) Zt <- parmat(MLEobj, "Z", t = t)$Z model.var.et[, , t] <- Rt + tcrossprod(Zt %*% kf$Vtt1[, , t], Zt) } for (t in 1:TT) { if (t < TT) { Ktp <- sub3D(kf$Kt, t = t + 1) et[(n + 1):(n + m), t] <- Ktp %*% model.et[, t + 1] tmpvar.state.et <- tcrossprod(Ktp %*% model.var.et[, , t + 1], Ktp) } else { tmpvar.state.et <- matrix(0, m, m) } var.et[1:n, , t] <- cbind(model.var.et[, , t], cov.et) var.et[(n + 1):(n + m), , t] <- cbind(t(cov.et), tmpvar.state.et) if (normalize) { Qpinv <- matrix(0, m, n + m) Rinv <- matrix(0, n, n + m) if (t < TT) { if (time.varying$Q) Qtp <- parmat(MLEobj, "Q", t = t + 1)$Q Qpinv[, (n + 1):(n + m)] <- psolve(t(pchol(Qtp))) } Rinv[, 1:n] <- psolve(t(pchol(Rt))) RQinv <- rbind(Rinv, Qpinv) et[, t] <- RQinv %*% et[, t] var.et[, , t] <- tcrossprod(RQinv %*% var.et[, , t], RQinv) } } } for (t in 1:TT) { tmpvar <- sub3D(var.et, t = t) resids <- et[, t, drop = FALSE] is.miss <- c(is.na(y[, t]), rep(FALSE, m)) resids[is.miss] <- 0 tmpvar[abs(tmpvar) < sqrt(.Machine$double.eps)] <- 0 tmpvarinv <- try(psolve(makediag(takediag(tmpvar))), silent = TRUE) if (inherits(tmpvarinv, "try-error")) { mar.st.et[, t] <- NA msg <- c(msg, paste('MARSSresiduals.tt1 warning: the diagonal matrix of the variance of the residuals at t =", t, "is not invertible. NAs returned for mar.residuals at t =", t, "\n')) } else { mar.st.et[, t] <- sqrt(tmpvarinv) %*% resids mar.st.et[is.miss, t] <- NA } tmpchol <- try(pchol(tmpvar[(n + 1):(n + m), (n + 1):(n + m), drop = FALSE]), silent = TRUE) if (inherits(tmpchol, "try-error")) { bchol.st.et[(n + 1):(n + m), t] <- NA msg <- c(msg, paste("MARSSresiduals.tT warning: the variance of the state residuals at t =", t, "is not invertible. NAs returned for bchol.std.residuals at t =", t, ". See MARSSinfo(\"residvarinv\")\n")) } else { tmpcholinv <- try(psolve(t(tmpchol)), silent = TRUE) if (inherits(tmpcholinv, "try-error")) { bchol.st.et[(n + 1):(n + m), t] <- NA msg <- c(msg, paste("MARSSresiduals.tT warning: the variance of the state residuals at t =", t, "is not invertible. NAs returned for bchol.std.residuals at t =", t, ". See MARSSinfo('residvarinv')\n")) } else { bchol.st.et[(n + 1):(n + m), t] <- tmpcholinv %*% resids[(n + 1):(n + m), 1, drop = FALSE] } } tmpchol <- try(pchol(tmpvar), silent = TRUE) if (inherits(tmpchol, "try-error")) { st.et[, t] <- NA msg <- c(msg, paste("MARSSresiduals.tt1 warning: the variance of the residuals at t =", t, "is not invertible. NAs returned for std.residuals at t =", t, ". See MARSSinfo(\"residvarinv\")\n")) next } tmpcholinv <- try(psolve(t(tmpchol)), silent = TRUE) if (inherits(tmpcholinv, "try-error")) { st.et[, t] <- NA msg <- c(msg, paste("MARSSresiduals.tt1 warning: the variance of the residuals at t =", t, "is not invertible. NAs returned for std.residuals at t =", t, ". See MARSSinfo('residvarinv')\n")) next } st.et[, t] <- tmpcholinv %*% resids st.et[is.miss, t] <- NA } bchol.st.et[1:n, ] <- st.et[1:n, ] et[(n + 1):(n + m), TT] <- NA var.et[, (n + 1):(n + m), TT] <- NA var.et[(n + 1):(n + m), , TT] <- NA st.et[, TT] <- NA mar.st.et[(n + 1):(n + m), TT] <- NA E.obs.v <- et[1:n, , drop = FALSE] var.obs.v <- array(0, dim = c(n, n, TT)) for (t in 1:TT) var.obs.v[, , t] <- Ey$Ott1[, , t] - tcrossprod(Ey$ytt1[, t]) model.et <- et[1:n, , drop = FALSE] model.et[is.na(y)] <- NA et[1:n, ] <- model.et Y.names <- attr(MLEobj$model, "Y.names") X.names <- attr(MLEobj$model, "X.names") rownames(et) <- rownames(st.et) <- rownames(mar.st.et) <- rownames(bchol.st.et) <- rownames(var.et) <- colnames(var.et) <- c(Y.names, X.names) rownames(E.obs.v) <- Y.names rownames(var.obs.v) <- colnames(var.obs.v) <- Y.names if (!is.null(msg) && object[["control"]][["trace"]] >= 0 & !silent) cat("MARSSresiduals.tt1 reported warnings. See msg element of returned residuals object.\n") if (!Kt.ok) { et[(n + 1):(n + m), ] <- NA var.et[(n + 1):(n + m), (n + 1):(n + m), ] <- NA st.et[(n + 1):(n + m), ] <- NA mar.st.et[(n + 1):(n + m), ] <- NA bchol.st.et[(n + 1):(n + m), ] <- NA } ret <- list( model.residuals = et[1:n, , drop = FALSE], state.residuals = et[(n + 1):(n + m), , drop = FALSE], residuals = et, var.residuals = var.et, std.residuals = st.et, mar.residuals = mar.st.et, bchol.residuals = bchol.st.et, E.obs.residuals = E.obs.v, var.obs.residuals = var.obs.v, msg = msg ) return(ret) }
pslide_index <- function(.l, .i, .f, ..., .before = 0L, .after = 0L, .complete = FALSE) { pslide_index_impl( .l, .i, .f, ..., .before = .before, .after = .after, .complete = .complete, .ptype = list(), .constrain = FALSE, .atomic = FALSE ) } pslide_index_vec <- function(.l, .i, .f, ..., .before = 0L, .after = 0L, .complete = FALSE, .ptype = NULL) { out <- pslide_index_impl( .l, .i, .f, ..., .before = .before, .after = .after, .complete = .complete, .ptype = list(), .constrain = FALSE, .atomic = TRUE ) vec_simplify(out, .ptype) } pslide_index_vec_direct <- function(.l, .i, .f, ..., .before, .after, .complete, .ptype) { pslide_index_impl( .l, .i, .f, ..., .before = .before, .after = .after, .complete = .complete, .ptype = .ptype, .constrain = TRUE, .atomic = TRUE ) } pslide_index_dbl <- function(.l, .i, .f, ..., .before = 0L, .after = 0L, .complete = FALSE) { pslide_index_vec_direct( .l, .i, .f, ..., .before = .before, .after = .after, .complete = .complete, .ptype = double() ) } pslide_index_int <- function(.l, .i, .f, ..., .before = 0L, .after = 0L, .complete = FALSE) { pslide_index_vec_direct( .l, .i, .f, ..., .before = .before, .after = .after, .complete = .complete, .ptype = integer() ) } pslide_index_lgl <- function(.l, .i, .f, ..., .before = 0L, .after = 0L, .complete = FALSE) { pslide_index_vec_direct( .l, .i, .f, ..., .before = .before, .after = .after, .complete = .complete, .ptype = logical() ) } pslide_index_chr <- function(.l, .i, .f, ..., .before = 0L, .after = 0L, .complete = FALSE) { pslide_index_vec_direct( .l, .i, .f, ..., .before = .before, .after = .after, .complete = .complete, .ptype = character() ) } pslide_index_dfr <- function(.l, .i, .f, ..., .before = 0L, .after = 0L, .complete = FALSE, .names_to = rlang::zap(), .name_repair = c("unique", "universal", "check_unique")) { out <- pslide_index( .l, .i, .f, ..., .before = .before, .after = .after, .complete = .complete ) vec_rbind(!!!out, .names_to = .names_to, .name_repair = .name_repair) } pslide_index_dfc <- function(.l, .i, .f, ..., .before = 0L, .after = 0L, .complete = FALSE, .size = NULL, .name_repair = c("unique", "universal", "check_unique", "minimal")) { out <- pslide_index( .l, .i, .f, ..., .before = .before, .after = .after, .complete = .complete ) vec_cbind(!!!out, .size = .size, .name_repair = .name_repair) } pslide_index_impl <- function(.l, .i, .f, ..., .before, .after, .complete, .ptype, .constrain, .atomic) { check_is_list(.l) lapply(.l, vec_assert) .f <- as_function(.f) .l <- vec_recycle_common(!!!.l) type <- vec_size(.l) slicers <- lapply( seq_len(type), function(x) { expr(.l[[!!x]]) } ) names(slicers) <- names(.l) f_call <- expr(.f(!!! slicers, ...)) slide_index_common( x = .l, i = .i, f_call = f_call, before = .before, after = .after, complete = .complete, ptype = .ptype, constrain = .constrain, atomic = .atomic, env = environment(), type = type ) }
test_that("tbl and src classes include connection class", { mf <- memdb_frame(x = 1, y = 2) expect_true(inherits(mf, "tbl_SQLiteConnection")) expect_true(inherits(mf$src, "src_SQLiteConnection")) })
context("mlllogis") set.seed(313) small_data <- actuar::rllogis(100, 2, 3) tiny_data <- actuar::rllogis(10, 1, 1) expect_error(mlllogis(c(tiny_data, NA))) expect_error(mlllogis(c(tiny_data, 0))) expect_error(mlllogis(c(tiny_data, -1))) obj_1 <- mllogis(log(tiny_data)) obj_2 <- mlllogis(tiny_data) expect_equal( unname(obj_1[1]), unname(-log(obj_2)[2]) ) expect_equal( unname(obj_1[2]), unname(1 / obj_2[1]) ) expect_equal( coef(mlllogis(small_data)), coef(mlllogis(c(small_data, NA), na.rm = TRUE)) ) est <- mlllogis(small_data, na.rm = TRUE) expect_equal( sum(actuar::dllogis(small_data, est[1], est[2], log = TRUE)), attr(est, "logLik") ) expect_equal(attr(est, "model"), "Loglogistic") expect_equal(class(est), "univariateML") expect_equal(names(est), c("shape", "rate"))
med2way <- function(formula, data, ...){ if (missing(data)) { mf <- model.frame(formula) } else { mf <- model.frame(formula, data) } cl <- match.call() J <- nlevels(mf[,2]) K <- nlevels(mf[,3]) p <- J*K grp <- c(1:p) alpha <- .05 x <- as.matrix(mf) lev.col <- 2:3 var.col <- 1 temp <- selby2(x,lev.col,var.col) x <- temp$x x <- lapply(x, as.numeric) if(p!=length(x)){ print("Warning: The number of groups in your data is not equal to JK") } xbar<-0 h<-0 d<-0 R<-0 W<-0 d<-0 r<-0 w<-0 nuhat<-0 omegahat<-0 DROW<-0 DCOL<-0 xtil<-matrix(0,J,K) aval<-matrix(0,J,K) for (j in 1:p){ xbar[j]<-median(x[[grp[j]]]) h[j]<-length(x[[grp[j]]]) d[j]<-msmedse(x[[grp[j]]], sewarn=FALSE)^2 } d<-matrix(d,J,K,byrow=T) xbar<-matrix(xbar,J,K,byrow=T) h<-matrix(h,J,K,byrow=T) for(j in 1:J){ R[j]<-sum(xbar[j,]) nuhat[j]<-(sum(d[j,]))^2/sum(d[j,]^2/(h[j,]-1)) r[j]<-1/sum(d[j,]) DROW[j]<-sum(1/d[j,]) } for(k in 1:K){ W[k]<-sum(xbar[,k]) omegahat[k]<-(sum(d[,k]))^2/sum(d[,k]^2/(h[,k]-1)) w[k]<-1/sum(d[,k]) DCOL[k]<-sum(1/d[,k]) } D<-1/d for(j in 1:J){ for(k in 1:K){ xtil[j,k]<-sum(D[,k]*xbar[,k]/DCOL[k])+sum(D[j,]*xbar[j,]/DROW[j])- sum(D*xbar/sum(D)) aval[j,k]<-(1-D[j,k]*(1/sum(D[j,])+1/sum(D[,k])-1/sum(D)))^2/(h[j,k]-3) } } Rhat<-sum(r*R)/sum(r) What<-sum(w*W)/sum(w) Ba<-sum((1-r/sum(r))^2/nuhat) Bb<-sum((1-w/sum(w))^2/omegahat) Va<-sum(r*(R-Rhat)^2)/((J-1)*(1+2*(J-2)*Ba/(J^2-1))) Vb<-sum(w*(W-What)^2)/((K-1)*(1+2*(K-2)*Bb/(K^2-1))) sig.A<-1-pf(Va,J-1,9999999) sig.B<-1-pf(Vb,K-1,9999999) Vab<-sum(D*(xbar-xtil)^2) dfinter<-(J-1)*(K-1) sig.AB<-1-pchisq(Vab,dfinter) result <- list(Qa=Va, A.p.value=sig.A, Qb=Vb, B.p.value=sig.B, Qab=Vab, AB.p.value=sig.AB, call = cl, varnames = colnames(mf), dim = c(J,K)) class(result) <- c("t2way") result }
NULL `%agele%` <- function(e1, e2) { stopifnot(identical(length(e2), 2L)) stopifnot(!anyNA(e2)) all(e1 >= min(e2) & e1 <= max(e2)) } `%agel%` <- function(e1, e2) { stopifnot(identical(length(e2), 2L)) stopifnot(!anyNA(e2)) all(e1 >= min(e2) & e1 < max(e2)) } `%agle%` <- function(e1, e2) { stopifnot(identical(length(e2), 2L)) stopifnot(!anyNA(e2)) all(e1 > min(e2) & e1 <= max(e2)) } `%agl%` <- function(e1, e2) { stopifnot(identical(length(e2), 2L)) stopifnot(!anyNA(e2)) all(e1 > min(e2) & e1 < max(e2)) } `%age%` <- function(e1, e2) {all(e1 >= e2)} `%ag%` <- function(e1, e2) {all(e1 > e2)} `%ale%` <- function(e1, e2) {all(e1 <= e2)} `%al%` <- function(e1, e2) {all(e1 < e2)} `%ain%` <- function(e1, e2) {all(e1 %in% e2)} `%a!in%` <- function(e1, e2) {all(e1 %!in% e2)} `%anin%` <- `%a!in%` `%a==%` <- function(e1, e2) {all(e1 == e2)} `%a!=%` <- function(e1, e2) {all(e1 != e2)} `%ac%` <- function(e1, e2) { all(e1 %c% e2) } `%ae%` <- function(e1, e2) { all(e1 %e% e2) }
insideAreaGridCell <- function(sfobject, rdx.u, xc, yc, dx, dy) { cell.df <- data.frame() for (i in 1:length(xc)) { temp <- rbind( c(xc[i] - dx, yc[i] - dy), c(xc[i], yc[i] - dy), c(xc[i], yc[i]), c(xc[i] - dx, yc[i]), c(xc[i] - dx, yc[i] - dy) ) sfcell <- st_sf(st_sfc(st_polygon(list(temp)), crs = st_crs(sfobject))) tempsf <- st_intersection(sfobject, sfcell) cell.df <- rbind(cell.df, cbind( cellID = rdx.u[i], featureArea = as.numeric(st_area(tempsf)), featureID = tempsf$id )) } return(cell.df) }
setGeneric("fitKinetics", function(obj) standardGeneric("fitKinetics")) setMethod("fitKinetics", "Bli", function(obj) { t <- obj@traces[, 1] traces <- obj@traces[, 2:ncol(obj@traces)] tExp <- obj@tExp tAss <- tExp[2] - tExp[1] lig <- obj@lig kOn0 <- obj@kOn0 kOff0 <- obj@kOff0 if ((length(kOn0) * length(kOff0)) == 0) stop("no intial kOn0 and kOff0: input or estimate!") if (length(lig) != ncol(traces)) stop("the trace number mis-match ligand concentrations") totRange <- which(t >= tExp[1]) tTot <- t[totRange] dTot <- traces[totRange, ] t <- tTot - tExp[1] rMax0 <- min(dTot) x = rep(lig, each = length(tTot)) t = rep(t, length(lig)) y = unlist(dTot) temp = rep(0, length(lig)) dLig = matrix(0, nrow = length(y), ncol = length(lig)) iNum <- 1:length(lig) for (i in iNum) { temp1 = temp temp1[i] = 1 dLig[, i] = rep(temp1, each = length(tTot)) } mA = mD = rep(0, length(t)) mA[which(t < tAss)] = 1 mD[which(t > tAss)] = 1 dfTot = data.frame(y, t, x, dLig, mA, mD) colnames(dfTot)[4:(3 + length(lig))] = paste("dLig", iNum, sep = "") startLst = c(rMax0, kOn0, kOff0, rep(0, 4 * length(lig))) names(startLst) <- c("rMax", "kOn", "kOff", paste("sa", iNum, sep = ""), paste("sd", iNum, sep = ""), paste("ja", iNum, sep = ""), paste("jd", iNum, sep = "")) fmla <- "y ~ mA*(rMax/(1+(kOff/kOn/x))*(1-1/exp((kOn*x+kOff)*t))+" fmla <- paste(fmla, paste(paste(paste("dLig", iNum, sep = ""), paste(paste("ja", iNum, sep = ""), paste(paste("sa", iNum, sep = ""), "t", sep = "*"), sep = "+"), sep = "*("), collapse = ")+"), collapse = "") fmla <- paste(fmla, ")) + mD*( rMax/(1+(kOff/kOn/x))*(1-1/exp((kOn*x+kOff)*tAss))/exp(kOff*(t-tAss))+", collapse = "") fmla <- paste(fmla, paste(paste(paste("dLig", iNum, sep = ""), paste(paste("jd", iNum, sep = ""), paste(paste("sd", iNum, sep = ""), "(t-tAss)", sep = "*"), sep = "+"), sep = "*("), collapse = ")+"), "))", collapse = "") fmla <- as.formula(fmla) modTot <- nls(fmla, data = dfTot, start = startLst, trace = TRUE) obj@kinetics <- modTot obj@status[5] <- TRUE return(obj) })
read_pubmed_jats <- function(jats_file, topic = NULL) { mirna_file <- xml2::read_xml(jats_file) node_articles <- xml2::xml_find_all(mirna_file, "//PubmedArticle") df <- data.frame("PMID" = integer(), "Year" = integer(), "Title" = character(), "Abstract" = character(), "Language" = character(), "Type" = character(), stringsAsFactors = FALSE) df <- dplyr::as_tibble(df) for (i in sequence(length(node_articles))) { node_abstr <- node_articles[i] pmid <- xml2::xml_find_all(node_abstr, ".//PMID") %>% xml2::xml_text() %>% as.numeric() year <- xml2::xml_find_first(node_abstr, ".//Year") %>% xml2::xml_text() %>% as.numeric() title <- xml2::xml_find_all(node_abstr, ".//ArticleTitle") %>% xml2::xml_text() abstr <- xml2::xml_find_all(node_abstr, ".//Abstract") %>% xml2::xml_text() lang <- xml2::xml_find_all(node_abstr, ".//Language") %>% xml2::xml_text() type <- xml2::xml_find_all(node_abstr, ".//PublicationType") %>% xml2::xml_text() df[i, "PMID"] <- pmid[1] df[i, "Year"] <- year[1] df[i, "Title"] <- title[1] df[i, "Abstract"] <- abstr[1] df[i, "Language"][[1]] <- list(lang) df[i, "Type"][[1]] <- list(type) } df$Topic <- topic return(df) } read_pubmed <- function(pubmed_file, topic = NULL) { . = NULL df <- suppressMessages(readr::read_fwf(pubmed_file)) df <- df %>% dplyr::rename("Term" = 1, "Content" = 2) %>% mutate(Term = stringr::str_replace_all(Term, "-", ""), Term = stringr::str_trim(Term), Term = ifelse(Term == "", NA, Term), Term = zoo::na.locf(Term)) terms_interest <- c("PMID", "DP", "TI", "AB", "LA", "PT") df <- dplyr::filter(df, Term %in% terms_interest) indices_pubmed <- which(df$Term == "PMID") abstract_names <- stringr::str_c("Abstract_", seq_along(indices_pubmed)) df[indices_pubmed, "Abstract_no"] <- abstract_names df <- df %>% mutate(Abstract_no = zoo::na.locf(Abstract_no)) %>% {suppressWarnings(tidyr::pivot_wider(., names_from = Term, values_from = Content))} %>% mutate(AB = purrr::map(AB, ~ stringr::str_c(.x, collapse = " "))) %>% mutate(TI = purrr::map(TI, ~ stringr::str_c(.x, collapse = " "))) %>% mutate(LA = purrr::map(LA, ~ stringr::str_c(.x, collapse = ""))) %>% {suppressWarnings(tidyr::unnest(., PMID, DP, AB, TI, LA, keep_empty = TRUE))} %>% mutate(Year = substr(DP, 1, 4)) %>% dplyr::select(PMID, Year, TI, AB, LA, PT) %>% mutate(PT = purrr::map(PT,~ stringr::str_c(.x))) %>% dplyr::rename(Title = TI, Abstract = AB, Language = LA, Type = PT) %>% {suppressWarnings(mutate(.,PMID = as.double(PMID), Year = as.double(Year)))} df$Topic <- topic return(df) } save_excel <- function(..., excel_file = "miRetrieve_data.xlsx") { openxlsx::write.xlsx(x = list(...), file = excel_file) } save_plot <- function(plot_file, width = NULL, height = NULL, units = "in", dpi = 300, device = NULL) { if(is.null(width)) { width <- par("din")[1] } if(is.null(height)) { height <- par("din")[2] } ggsave(filename = plot_file, width = width, height = height, units = units, dpi = dpi, device = device) }
setClass("A", representation("numeric")) a <- new("A") setMethod("Logic", c("A", "A"), function(e1, e2) FALSE) res0 <- a & a setMethod("Logic", c("A", "A"), function(e1, e2) TRUE) stopifnot(a & a) removeMethod("Logic", c("A", "A")) stopifnot(logical() == a & a) removeClass("A") if(require(Matrix)) { sm <- selectMethod("-", c("dgCMatrix", "numeric")) s2 <- selectMethod("-", c("dtCMatrix", "numeric")) stopifnot(sm@generic == "Arith", s2@generic == "Arith") } setGeneric("f1", signature=c("a"), function(..., a) standardGeneric("f1")) setMethod("f1", c(a="ANY"), function(..., a) list(a=a, ...)) setMethod("f1", c(a="missing"), function(..., a) callGeneric(a=1, ...)) f2 <- function(b,c,d, a) { if (missing(a)) f1(b=b, c=c, d=d) else f1(a=a, b=b, c=c, d=d) } stopifnot(identical(c(1,2,3,4), as.vector(unlist(f1(2,3,4))))) stopifnot(identical(c(1,2,3,4), as.vector(unlist(f2(2,3,4))))) Hide <- setClass("Hide", slots = c(data = "vector"), contains = "vector") unhide <- function(obj) obj@data setGeneric("%p%", function(e1, e2) e1 + e2, group = "Ops2") setGeneric("%gt%", function(e1, e2) e1 > e2, group = "Ops2") setGroupGeneric("Ops2", function(e1,e2)NULL, knownMembers = c("%p%","%gt%")) setMethod("Ops2", c("Hide", "Hide"), function(e1, e2) { e1 <- unhide(e1) e2 <- unhide(e2) callGeneric() }) setMethod("Ops2", c("Hide", "vector"), function(e1, e2) { e1 <- unhide(e1) callGeneric() }) setMethod("Ops2", c("vector", "Hide"), function(e1, e2) { e2 <- unhide(e2) callGeneric() }) h1 <- Hide(data = 1:10) h2 <- Hide(data = (1:10)*.5+ 0.5) stopifnot(all.equal(h1%p%h2, h1@data + h2@data)) stopifnot(all.equal(h1 %gt% h2, h1@data > h2@data)) removeClass("Hide") for(g in c("f1", "%p%", "%gt%", "Ops2")) removeGeneric(g)
data("jags_logit") test_that("Simple model runs with mcmcTab", { object <- mcmcTab(jags_logit, ci = c(0.025, 0.975), pars = NULL, Pr = FALSE, ROPE = NULL) value <- object[2, 2] check_against <- c(0.527) expect_equal(round(as.numeric(value), 2), round(check_against, 2)) }) test_that("mcmcTab works with different input types", { expect_equal(mcmcTab(jags_logit)[1,3], 0.09) expect_equal(mcmcTab(coda::as.mcmc(jags_logit))[2,3], 0.166) }) test_that("pars subsetting works", { data("jags_logit") object <- mcmcTab(jags_logit, ci = c(0.025, 0.975), pars = "b", Pr = FALSE, ROPE = NULL, regex = TRUE) expect_equal( object$Variable, factor(c(sprintf("b[%s]", 1:3))) ) object <- mcmcTab(jags_logit, ci = c(0.025, 0.975), pars = c("b\\[1\\]", "b\\[2\\]"), Pr = FALSE, ROPE = NULL, regex = TRUE) expect_equal( object$Variable, factor(c(sprintf("b[%s]", 1:2))) ) object <- mcmcTab(jags_logit, ci = c(0.025, 0.975), pars = c("b[1]", "b[3]"), Pr = FALSE, ROPE = NULL) expect_equal( object$Variable, factor(c(sprintf("b[%s]", c(1, 3)))) ) }) test_that("ROPE argument works", { expect_message( object <- mcmcTab(jags_logit, pars = "b", ROPE = c(0, 1), regex = TRUE), "This table contains an estimate for parameter" ) expect_equal( object$PrOutROPE, c(0, 0.002, 0.011) ) expect_error( object <- mcmcTab(jags_logit, ROPE = 0), "Invalid ROPE argument" ) }) pkgs_win <- c("rjags", "R2WinBUGS") if (!all(sapply(pkgs_win, require, quietly = TRUE, character.only = TRUE))) { data(LINE, package = "rjags") LINE$recompile() bugs_model <- rjags::coda.samples(LINE, c("alpha", "beta", "sigma"), n.iter = 1000) bugs_model <- R2WinBUGS::as.bugs.array(sims.array = as.array(bugs_model)) test_that("mcmcTab works with bugs", { expect_equal(mcmcTab(bugs_model)[1,2], 1.031) }) }
NULL check <- function( pkg = "." ) { devtools::check( pkg = pkg, manual = FALSE, run_dont_test = FALSE ) } check_fast <- function( pkg = "." ) { devtools::check( pkg = pkg, manual = FALSE, run_dont_test = FALSE, build_args = c("--no-build-vignettes"), args = c("--ignore-vignettes") ) } check_faster <- function( pkg = "." ) { devtools::check( pkg = pkg, manual = FALSE, run_dont_test = FALSE, build_args = c("--no-build-vignettes"), args = c("--ignore-vignettes", "--no-examples") ) } check_fastest <- function( pkg = "." ) { devtools::check( pkg = pkg, manual = FALSE, run_dont_test = FALSE, build_args = c("--no-build-vignettes"), args = c("--ignore-vignettes", "--no-tests", "--no-examples") ) } check_slow <- function( pkg = "." ) { devtools::check( pkg = pkg, manual = TRUE, run_dont_test = TRUE, ) } check_slower <- function( pkg = "." ) { devtools::check( pkg = pkg, manual = TRUE, run_dont_test = TRUE, args = c("--run-dontrun") ) } check_slowest <- function( pkg = "." ) { devtools::check( pkg = pkg, manual = TRUE, run_dont_test = TRUE, args = c("--run-dontrun", "--use-gct") ) }
NULL fhplot<- function(Ce, theta){ .Deprecated("fhanalysis") x <- log10(1-theta) y <- log10(theta/Ce) fit22 <- lm(y~x) plot(y~x, xlab="ce", ylab="theta", main="Flory Huggins Analysis") abline(fit22, col="black") }
library(hamcrest) expected <- structure(list(x = c(-2.17792306908218, -2.1347958795954, -2.09166869010863, -2.04854150062185, -2.00541431113508, -1.9622871216483, -1.91915993216152, -1.87603274267475, -1.83290555318797, -1.7897783637012, -1.74665117421442, -1.70352398472764, -1.66039679524087, -1.61726960575409, -1.57414241626732, -1.53101522678054, -1.48788803729376, -1.44476084780699, -1.40163365832021, -1.35850646883344, -1.31537927934666, -1.27225208985989, -1.22912490037311, -1.18599771088633, -1.14287052139956, -1.09974333191278, -1.05661614242601, -1.01348895293923, -0.970361763452454, -0.927234573965678, -0.884107384478902, -0.840980194992126, -0.79785300550535, -0.754725816018574, -0.711598626531798, -0.668471437045022, -0.625344247558246, -0.58221705807147, -0.539089868584694, -0.495962679097918, -0.452835489611142, -0.409708300124366, -0.36658111063759, -0.323453921150814, -0.280326731664038, -0.237199542177262, -0.194072352690486, -0.150945163203711, -0.107817973716934, -0.0646907842301587, -0.0215635947433825, 0.0215635947433932, 0.0646907842301694, 0.107817973716945, 0.150945163203721, 0.194072352690497, 0.237199542177273, 0.280326731664049, 0.323453921150825, 0.366581110637601, 0.409708300124377, 0.452835489611153, 0.495962679097929, 0.539089868584705, 0.58221705807148, 0.625344247558256, 0.668471437045032, 0.711598626531808, 0.754725816018584, 0.79785300550536, 0.840980194992136, 0.884107384478912, 0.927234573965688, 0.970361763452464, 1.01348895293924, 1.05661614242602, 1.09974333191279, 1.14287052139957, 1.18599771088634, 1.22912490037312, 1.2722520898599, 1.31537927934667, 1.35850646883345, 1.40163365832022, 1.444760847807, 1.48788803729378, 1.53101522678055, 1.57414241626733, 1.6172696057541, 1.66039679524088, 1.70352398472766, 1.74665117421443, 1.78977836370121, 1.83290555318798, 1.87603274267476, 1.91915993216154, 1.96228712164831, 2.00541431113509, 2.04854150062186, 2.09166869010864, 2.13479587959541, 2.17792306908219), y = c(0.0837786659629955, 0.0991726432001737, 0.113575653162038, 0.127006994127686, 0.139485964376218, 0.151031862186732, 0.161663985838327, 0.171401633610103, 0.180264103781157, 0.18827069463059, 0.195440704437499, 0.201793431480984, 0.207348174040144, 0.212124230394078, 0.216140898821884, 0.219417477602661, 0.221973265015509, 0.223827559339526, 0.224999658853812, 0.225508861837464, 0.225374466569582, 0.224615771329266, 0.223252074395612, 0.221302674047722, 0.218786868564693, 0.215723956225626, 0.212133235309618, 0.208034004095768, 0.203445560863176, 0.198387203890939, 0.192878231458158, 0.18693794184393, 0.180585633327356, 0.173840604187533, 0.166722152703562, 0.15924957715454, 0.151442175819567, 0.143319246977741, 0.134900088908162, 0.126203999889927, 0.117250278202137, 0.108058222123891, 0.0986471299342862, 0.0890362999124227, 0.079245030337399, 0.069292619488314, 0.0591983656442669, 0.0489815670843564, 0.0386615220876814, 0.0282575289333409, 0.0177888859004337, 0.00727489126805892, -0.00326515668468487, -0.0138119596786984, -0.0243462194348828, -0.0348486376741394, -0.0452999161173691, -0.0556807564854732, -0.0659718604993526, -0.0761539298799083, -0.0862076663480414, -0.0961137716246534, -0.105852947430645, -0.115405895486918, -0.124753317514372, -0.133875915233909, -0.142754390366429, -0.151369444632836, -0.159701779754029, -0.167732097450909, -0.175441099444377, -0.182809487455334, -0.189817963204683, -0.196447228413322, -0.202677984802155, -0.208490934092081, -0.213866778004002, -0.21878621825882, -0.223229956577434, -0.227178694680747, -0.230613134289658, -0.233513977125071, -0.235861924907885, -0.237637679359001, -0.238821942199321, -0.239395415149745, -0.239338799931176, -0.238632798264513, -0.237258111870658, -0.235195442470512, -0.232425491784977, -0.228928961534952, -0.22468655344134, -0.219678969225042, -0.213886910606958, -0.207291079307989, -0.199872177049038, -0.191610905551004, -0.182487966534789, -0.172484061721294, -0.16157989283142, -0.149756161586068 )), .Names = c("x", "y")) assertThat(stats:::spline(x=c(-0.873569134615088, 0.110812912299157, -0.260967400401453, 0.770208081875476, -1.44999890874045, -1.7047809048894, 0.499187842050876, 0.338091656804207, -0.417284139389022, 1.7047809048894, -0.499187842050876, 0.417284139389022, 0.987230991990176, -0.584589857059473, 1.26496924488415, 2.17792306908219, 0.0368705326620802, -0.987230991990176, 0.584589857059473, 0.674489750196082, -0.185367017289597, 1.11533735773379, -2.17792306908218, 1.44999890874045, -0.338091656804207, -0.110812912299157, 0.260967400401453, -1.11533735773379, -0.0368705326620803, -1.26496924488415, 0.873569134615088, -0.770208081875476, -0.674489750196082, 0.185367017289597),y=structure(c(0.191465786179708, -0.0145441318070686, 0.0747962795196774, -0.162620345655999, 0.223639125476708, 0.201619667641865, -0.106574023381159, -0.0694409308783482, 0.109689330027232, -0.232333960154808, 0.126863467960568, -0.0879590361669838, -0.198932911276963, 0.143774036552627, -0.230070082035199, -0.149756161586068, 0.00353594454344365, 0.20529735446124, -0.125261251276442, -0.143972859126161, 0.0571453269671675, -0.215699249400361, 0.0837786659629955, -0.238924565906323, 0.0923194916468324, 0.0393811253742007, -0.0510308559179646, 0.216893381672356, 0.0215106633993303, 0.224427414221871, -0.181041490059821, 0.176305978996573, 0.160312902241177, -0.0327321939651579), .Names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34"))) , identicalTo( expected, tol = 1e-6 ) )
summary.Mtabs <- function(object,...,range=NULL) { o.Mt<- object test<- is.null(range) if(test == TRUE) range<- c(1,ncol(o.Mt$centroids)) print(t(o.Mt$centroids[,range[1]:range[2]]),quote=FALSE) }
suppressPackageStartupMessages(library(dplyr)) data("usz_13c") data = usz_13c %>% dplyr::filter( patient_id %in% c("norm_001", "norm_002", "norm_004", "norm_007", "pat_004", "pat_012", "pat_023")) %>% cleanup_data() fit = nls_fit(data) cm = comment(fit$data) test_that("Result with default parameters is tbl_df with required columns",{ cf = coef_by_group(fit) expect_is(cf, "tbl_df") expect_is(cf, "coef_by_group") expect_identical(ncol(cf), 7L) expect_equal(names(cf), c("parameter", "method", "group", "estimate", "conf.low", "conf.high", "diff_group")) expect_identical(nrow(cf), 36L) expect_identical(unique(cf$diff_group), c("a", "c", "b", "bc", "ab")) expect_equal(unique(cf$group), c("liquid_normal", "liquid_patient", "solid_normal", "solid_patient")) expect_equal(comment(cf), cm) }) digs = function(x){ nchar(stringr::str_replace_all(paste(abs(x)), "[0\\.]","")) } test_that("Options digits is served",{ options(digits = 4) cf = coef_by_group(fit) expect_is(cf, "tbl_df") expect_lte(digs(cf[[1,"estimate"]]) ,4L) }) test_that("Fit must be of class breathtestfit",{ expect_error(coef_by_group(NULL)) }) test_that("nlme_fit can be used to compute coefficients for multiple records in one group",{ data = cleanup_data(simulate_breathtest_data(4)) fit = nlme_fit(data) cf = coef_by_group(fit) expect_is(cf, "tbl_df") expect_identical(ncol(cf), 7L) expect_equal(unique(cf$group), "A") expect_equal(unique(cf$diff_group), "a") expect_equal(names(cf), c("parameter", "method", "group", "estimate", "conf.low", "conf.high", "diff_group")) }) test_that("nlme_fit can be used to compute coefficients for multiple groups",{ skip_on_cran() fit = nlme_fit(data) cf = coef_by_group(fit) expect_is(cf, "tbl_df") expect_identical(ncol(cf), 7L) expect_equal(names(cf), c("parameter", "method", "group", "estimate", "conf.low", "conf.high", "diff_group")) }) test_that("Fit of a single curve returns valid data", { data = usz_13c %>% dplyr::filter( patient_id == "pat_001") %>% cleanup_data() comment(data) = "comment" options(digits = 4) fit = nls_fit(data) cf = coef_by_group(fit) expect_identical(ncol(cf), 7L) expect_identical(nrow(cf), 9L) expect_equal(cf$conf.low, rep(NA, 9L)) expect_equal(cf$conf.high, rep(NA, 9L)) expect_equal(comment(cf), "comment") expect_lte(digs(cf[[1,"estimate"]]) ,4L) })
computeTrend <- function(jk2, tv, repFunOut, fun) { jk2_all <- do.call("rbind", jk2) jk2_bind<- jk2_all jk2_bind<- check1(jk2=jk2, jk2_bind=jk2_bind, jk2_all=jk2_all, tv=tv) if(identical(fun, "mean")) { jk2_bind<- jk2_bind[jk2_bind[["parameter"]] %in% c("mean", "sd"), ] } if ( fun == "glm" ) { jk2_bind<- jk2_bind[which(!jk2_bind[,"parameter"] %in% c("Nvalid", "Ncases", "R2", "R2nagel")),] } jk2_bind<- jk2_bind[jk2_bind[["coefficient"]] %in% c("est", "se"), ] jk2_wide<- reshape2::dcast ( jk2_bind, as.formula ( paste ( " ... ~ coefficient + ", tv ,sep="") ) ) lev <- unique(jk2_bind[[tv]]) le <- check2(repFunOut=repFunOut, jk2=jk2_bind, fun=fun) vgl <- combinat::combn(names(jk2),2, simplify=FALSE) adds<- lapply( 1:length(vgl), FUN = function ( comp) { jk2_wide[,paste0("est_trend_",vgl[[comp]][1],".vs.",vgl[[comp]][2])] <- jk2_wide[,paste("est_",vgl[[comp]][2],sep="")] - jk2_wide[,paste("est_",vgl[[comp]][1],sep="")] years.c <- unlist(apply(le, MARGIN = 1, FUN = function (zeile) {paste(c(zeile[["trendLevel1"]], zeile[["trendLevel2"]]), collapse="_")})) le.years<- le[which(years.c == paste(sort(vgl[[comp]]), collapse="_")),] jk2_wide<- merge(jk2_wide, le.years[,-na.omit(match(c("trendLevel1", "trendLevel2", "domain"), colnames(le.years)))], by = c("parameter", "depVar"), all = TRUE) miss <- which(is.na(jk2_wide[,"le"])) if ( length(miss)>0){ warning(paste0("Found ",length(miss)," missing linking errors for dependent variable '",unique(jk2_wide[,"depVar"]),"' and parameter(s) '",paste(unique(jk2_wide[which(is.na(jk2_wide[,"le"])),"parameter"])),"'. Assume linking error of 0 for these cases.")) jk2_wide[which(is.na(jk2_wide[,"le"])),"le"] <- 0 } jk2_wide[,paste0("se_trend_", vgl[[comp]][1],".vs.",vgl[[comp]][2])] <- sqrt(jk2_wide[, paste("se_",vgl[[comp]][2],sep="")]^2 + jk2_wide[, paste("se_",vgl[[comp]][2],sep="")]^2 + jk2_wide[, "le"]^2) jk2_wide[,paste0("sig_trend_", vgl[[comp]][1],".vs.",vgl[[comp]][2])]<- 2*pnorm(abs(jk2_wide[, paste0("est_trend_",vgl[[comp]][1],".vs.",vgl[[comp]][2])]/jk2_wide[, paste0("se_trend_", vgl[[comp]][1],".vs.",vgl[[comp]][2])]), lower.tail=FALSE) existSD <- "sd" %in% jk2_bind[,"parameter"] es <- character(0) if(fun == "mean" && !existSD && comp == 1) {message("Cannot find standard deviations in output. Skip computation of effect sizes.")} if ( fun == "mean" && existSD) { jk2_wide[, paste0("es_trend_", vgl[[comp]][1],".vs.",vgl[[comp]][2])] <- NA jk2_wideS<- jk2_wide[!jk2_wide[, "comparison"] %in% c("crossDiff_of_groupDiff", "groupDiff") | is.na(jk2_wide[, "comparison"]), ] tabs <- table(jk2_wideS[,c("parameter", "group")]) if ( !all ( tabs == 1) ) { message("Cannot find standard deviations of following groups: \n",print_and_capture(tabs, 5),"\nSkip computation of effect sizes.") } else { jk2_wideS<- jk2_wideS[with(jk2_wideS, order(parameter, group)),] pooledSD <- sqrt(0.5 * (jk2_wideS[jk2_wideS[, "parameter"] == "sd", paste("est_",vgl[[comp]][1], sep="")]^2 + jk2_wideS[jk2_wideS[, "parameter"] == "sd", paste("est_",vgl[[comp]][2], sep="")]^2)) jk2_wideS[jk2_wideS[, "parameter"] == "mean", paste0("es_trend_", vgl[[comp]][1],".vs.",vgl[[comp]][2])] <- jk2_wideS[jk2_wideS[, "parameter"] == "mean", paste0("est_trend_", vgl[[comp]][1],".vs.",vgl[[comp]][2])] / pooledSD es <- c(es, paste0("es_trend_", vgl[[comp]][1],".vs.",vgl[[comp]][2])) jk2_wide <- unique(rbind(jk2_wide, jk2_wideS)) } } jk2_add <- reshape2::melt ( jk2_wide, measure.vars = c(paste("est", unique(unlist(vgl)), sep="_"), paste("se", unique(unlist(vgl)), sep="_"), paste0("est_trend_",vgl[[comp]][1],".vs.",vgl[[comp]][2]), paste0("se_trend_",vgl[[comp]][1],".vs.",vgl[[comp]][2]), paste0("sig_trend_",vgl[[comp]][1],".vs.",vgl[[comp]][2]), es), na.rm = FALSE) jk2_add <- jk2_add[!is.na(jk2_add[, "value"]), ] zusatz <- data.frame ( eatTools::halveString (string = as.character(jk2_add[,"variable"]), pattern = "_", first = TRUE ), stringsAsFactors = FALSE) colnames(zusatz) <- c("coefficient", tv) jk2_add <- data.frame ( jk2_add[,-match("variable", colnames(jk2_add))], zusatz, stringsAsFactors = FALSE) return(jk2_add[, names(jk2_all)])}) jk2 <- unique(rbind(jk2_all, do.call("rbind", adds))) return(jk2) } check1 <- function(jk2, jk2_bind, jk2_all, tv) { vgl <- combinat::combn(1:length(jk2),2, simplify=FALSE) chks<- sapply(vgl, FUN = function ( x ) { length(unique(jk2[[x[1]]]$group)) != length(unique(jk2[[x[2]]]$group)) || suppressWarnings(!all(sort(unique(jk2[[x[1]]]$group)) == sort(unique(jk2[[x[1]]]$group))))}) if(sum(chks)>0) { weg <- unique(unlist(lapply(vgl, FUN = function ( v ) { uneven1 <- setdiff(unique(jk2[[v[1]]]$group), unique(jk2[[v[2]]]$group)) uneven2 <- setdiff(unique(jk2[[v[2]]]$group), unique(jk2[[v[1]]]$group)) if(length(uneven1) > 0) {cat("Categories", uneven1, "are missing in year", jk2[[2]][1, tv] ,". \n")} if(length(uneven2) > 0) {cat("Categories", uneven2, "are missing in year", jk2[[1]][1, tv] ,". \n")} weg1 <- which( jk2_all$group %in% c(uneven1, uneven2)) return(weg1)}))) if ( length(weg)>0) { jk2_bind <- jk2_all[-weg,] } } return(jk2_bind)} check2 <- function(repFunOut, jk2, fun){ wdf <- attr(repFunOut[["le"]], "linkingErrorFrame") if(is.null(wdf)) { return(repFunOut[["le"]]) } else { allV <- list(trendLevel1 = "trendLevel1", trendLevel2 = "trendLevel2", parameter = "parameter", linkingError="linkingError", depVar = "depVar") allN <- lapply(allV, FUN=function(ii) {eatTools::existsBackgroundVariables(dat = repFunOut[["le"]], variable=ii, warnIfMissing = TRUE)}) le <- repFunOut[["le"]] dv <- unique(jk2[,"depVar"]) stopifnot(length(dv)==1) if(!dv %in% le[,"depVar"]) {stop(paste0("Cannot found dependent variable '",dv,"' in 'depVar' column of linking error data.frame 'linkErr'."))} le <- le[which(le[,"depVar"] == dv),] le1 <- le[,c("parameter", "trendLevel1", "trendLevel2")] if(nrow(le1) != nrow(unique(le1))) {stop("Linking error data.frame 'linkErr' is not unique in 'parameter', 'trendLevel1', 'trendLevel2'. Probable cause: 'linkErr' contains linking errors of multiple competence domains?")} add <- setdiff(unique(jk2[,"parameter"]), unique(le[,"parameter"])) if ( length(add)>0) { warning(paste0("No linking errors for parameters '",paste(add, collapse="', '"),"'. Linking errors for these parameters will be defaulted to 0."))} years <- sort(unique (jk2[,repFunOut[["allNam"]][["trend"]]])) combs <- combinat::combn(x=years, m=2, simplify=FALSE) exist <- unique(plyr::alply(le, .margins = 1, .fun = function (zeile) {sort(c(zeile[["trendLevel1"]], zeile[["trendLevel2"]]))})) drin <- combs %in% exist if(!all(drin)) {stop(paste0("Data contains combination of years '",paste(combs[!drin], collapse="', '"), "' which are not included in linking error data.frame 'linkErr'."))} colnames(le) <- car::recode(colnames(le), "'linkingError'='le'") return(le) }}
rstpoint <- function(n, f, W = NULL, correction = 1.5, maxpass = 50) { if(!inherits(f,"stim")&&!inherits(f,"stden")) stop("'f' must be of class 'stim' or 'stden'") if(inherits(f,"stden")){ g <- list(v=f$z,tlay=f$tgrid,a=abind(lapply(f$z,as.matrix),along=3)) f <- g } if(is.null(W)) W <- as.polygonal(Window(f$v[[1]])) if(!is.owin(W)) stop("'W' must be of spatstat class 'owin'") if(is.null(intersect.owin(Window(f$v[[1]]),W,fatal=FALSE))) stop("'W' must overlap the spatial domain of 'f'") nacc <- 0 dummyim <- f$v[[1]] dummyim[] <- 1 xacc <- yacc <- tacc <- c() ngen <- ceiling(n*correction) tlay <- f$tlay tstep <- tlay[2]-tlay[1] tgrid <- seq(min(tlay)-0.5*tstep,max(tlay)+0.5*tstep,length=length(tlay)+1) pass <- 0 while(nacc<n&&pass<maxpass) { cand <- rimpoly(ngen,dummyim,W) cand.t.raw <- runif(ngen,min(tgrid),max(tgrid)) cand.t.int <- findInterval(cand.t.raw,tgrid,all.inside=TRUE) cand.dens <- rep(NA,ngen) ut <- unique(cand.t.int) for(i in 1:length(ut)){ cand.ti <- which(cand.t.int==ut[i]) cand.dens[cand.ti] <- safelookup(f$v[[ut[i]]],cand[cand.ti]) } cand.probs <- cand.dens/max(f$a,na.rm=TRUE) cand.acc <- which(runif(ngen)<cand.probs) xacc <- c(xacc,cand$x[cand.acc]) yacc <- c(yacc,cand$y[cand.acc]) tacc <- c(tacc,cand.t.raw[cand.acc]) nacc <- nacc + length(cand.acc) pass <- pass + 1 } if(nacc<n) warning(paste("'maxpass' reached with only",nacc,"points accepted")) result <- ppp(c(),c(),window=W) if(nacc>0){ accs <- 1:min(n,nacc) result <- ppp(x=xacc[accs],yacc[accs],marks=tacc[accs],window=W) } return(result) }
IBCF <- function(object, dec = 4) { if (!inherits(object, 'CrossValidation')) stop("This function only works for objects of class 'CrossValidation'") time.init <- proc.time()[3] nIL <- ncol(object$DataSet) - 1 Y_avr <- matrix(0, ncol = nIL, nrow = nrow(object$DataSet)) Ind_all <- Y_avr NPartitions <- length(object$CrossValidation_list) predicted <- vector('list', NPartitions) names(predicted) <- paste0('Partition', 1:NPartitions) results <- data.frame() for (j in seq_len(NPartitions)) { Part <- object$CrossValidation_list[[j]] pos.NA <- which(Part == 2, arr.ind = TRUE) pos.NA[, 2] <- c(pos.NA[, 2]) + 1 pos.No_NA <- which(Part == 1, arr.ind = TRUE) if (length(pos.NA) == 0) { stop('An error ocurred with the CrossValidation data') } Data.trn <- object$DataSet Data.trn[pos.NA] <- NA rows.Na <- which(apply(Data.trn, 1, function(x) any(is.na(x))) == TRUE) Means_trn <- apply(Data.trn[, -c(1)], 2, mean, na.rm = TRUE) SDs_trn <- apply(Data.trn[, -c(1)], 2, sd, na.rm = TRUE) Scaled_Col <- scale(Data.trn[, -c(1)]) Means_trn_Row <- apply(Scaled_Col, 1, mean, na.rm = TRUE) SDs_trn_Row <- apply(Scaled_Col, 1, sd, na.rm = TRUE) if (any(is.na(SDs_trn_Row))) { Data.trn_scaled <- data.frame(ID = as.character(Data.trn[, c(1)]), Scaled_Col) } else { Scaled_Row <- t(scale(t(Scaled_Col))) Data.trn_scaled <- data.frame(ID = as.character(Data.trn[, c(1)]), Scaled_Row) } Hybrids.New <- Data.trn_scaled Hybrids.New[, 2:ncol(Data.trn_scaled)] <- NA ratings <- Data.trn_scaled x <- ratings[, 2:(ncol(ratings))] x[is.na(x)] <- 0 item_sim <- lsa::cosine(as.matrix((x))) for (i in seq_len(length(rows.Na))) { pos <- rows.Na[i] ratings[pos, 2:ncol(ratings)] <- rec_itm_for_geno(pos, item_sim, ratings[,2:ncol(ratings)]) } All.Pred <- data.matrix(ratings[,-1]) if (any(is.na(SDs_trn_Row))) { All.Pred_O <- sapply(seq_len(ncol(All.Pred)), function(i) (All.Pred[,i]*SDs_trn[i] + Means_trn[i])) } else { All.Pred_O_Row <- t(sapply(seq_len(nrow(All.Pred)), function(i) (All.Pred[i,]*SDs_trn_Row[i] + Means_trn_Row[i])) ) All.Pred_O <- sapply(seq_len(ncol(All.Pred_O_Row)), function(i) (All.Pred_O_Row[,i]*SDs_trn[i] + Means_trn[i])) } colnames(All.Pred_O) <- colnames(Data.trn_scaled[,-c(1)]) All.Pred_O[pos.No_NA] <- NA All.Pred_O_tst <- All.Pred_O[rows.Na, ] predicted[[paste0('Partition', j)]] <- c(All.Pred_O) pos.No_NA[,2] <- pos.No_NA[,2] + 1 DataSet_tst <- object$DataSet DataSet_tst[pos.No_NA] <- NA DataSet_tst <- DataSet_tst[rows.Na, ] Data.Obs_tst <- getTidyForm(DataSet_tst) posTST <- which(complete.cases(Data.Obs_tst) == TRUE) YYY <- All.Pred_O Ind <- is.na(YYY) YYY[Ind] <- 0 Y_avr <- Y_avr + YYY Ind <- !(Ind) Ind_all <- Ind_all + Ind results <- rbind(results, data.frame(Position = posTST, Partition = j, Environment = Data.Obs_tst$Env[posTST], Trait = Data.Obs_tst$Trait[posTST], Observed = round(Data.Obs_tst$Response[posTST],dec), Predicted = round(c(All.Pred_O_tst[which(!is.na(All.Pred_O_tst))]), dec))) } Y_avr <- Y_avr/Ind_all Yhat_Obs_pred <- data.frame(object$DataSet, Y_avr) colnames(Yhat_Obs_pred) <- c(colnames(object$DataSet), paste0(colnames(Y_avr),'.predicted')) out <- list(NPartitions = NPartitions, predictions_Summary = results, observed = getTidyForm(object$DataSet)$Response, yHat = Y_avr, predicted_Partition = predicted, Data.Obs_Pred = Yhat_Obs_pred, executionTime = proc.time()[3] - time.init) class(out) <- 'IBCF' return(out) }
get_jmodel <- function(x, workspace, userdefined = NULL, progress_bar = TRUE){ UseMethod("get_jmodel", x) } get_jmodel.workspace <- function(x, workspace, userdefined = NULL, progress_bar = TRUE){ multiprocessings <- get_all_objects(x) nb_mp <- length(multiprocessings) result <- lapply(1:nb_mp, function(i){ if (progress_bar) cat(sprintf("Multiprocessing %i on %i:\n", i, nb_mp)) get_jmodel(multiprocessings[[i]], workspace = x, userdefined = userdefined, progress_bar = progress_bar) }) names(result) <- names(multiprocessings) result } get_jmodel.multiprocessing <- function(x, workspace, userdefined = NULL, progress_bar = TRUE){ all_sa_objects <- get_all_objects(x) nb_sa_objs <- length(all_sa_objects) if (progress_bar) pb <- txtProgressBar(min = 0, max = nb_sa_objs, style = 3) result <- lapply(1:nb_sa_objs, function(i){ res <- get_jmodel(all_sa_objects[[i]], workspace = workspace, userdefined = userdefined) if (progress_bar) setTxtProgressBar(pb, i) res }) names(result) <- names(all_sa_objects) if (progress_bar) close(pb) result } get_jmodel.sa_item <- function(x, workspace, userdefined = NULL, progress_bar = TRUE){ jspec <- get_jspec(x) jresult <- sa_results(x) if(is.null(jresult)) return(NULL) if (.jinstanceof(jspec, "jdr/spec/x13/X13Spec")) { jresult <- new(Class = "X13_java", internal = jresult) }else{ jresult <- new(Class = "TramoSeats_java", internal = jresult) } dictionary <- .jcall(workspace, "Ljdr/spec/ts/Utility$Dictionary;", "dictionary") jSA(result = jresult, spec = jspec, dictionary = dictionary) }
"beta0" <- 0 "beta" <- 0 "q" <- 0.5 "phi" <- structure(c(0.5, 0.5, 0.5, 0.5), .Dim = as.integer(c(2, 2)))
kendallSeasonalTrendTest.formula <- function (y, data = NULL, subset, na.action = na.pass, ...) { if (missing(y) || (length(y) != 3L)) stop("formula missing or incorrect") m <- match.call(expand.dots = FALSE) if (is.matrix(eval(m$data, parent.frame()))) m$data <- as.data.frame(data) m$... <- NULL m$formula <- m$y m$y <- NULL m$na.action <- na.action requireNamespace("stats", quietly = TRUE) m[[1L]] <- as.name("model.frame") mf <- eval(m, parent.frame()) ncol.mf <- ncol(mf) if (ncol.mf != 3) stop("Incorrect formula; it must be of the form y ~ season + year") response <- attr(attr(mf, "terms"), "response") season <- (1:ncol.mf)[-response][1] year <- (1:ncol.mf)[-c(response, season)] arg.list <- list(y = mf[, response], season = mf[, season], year = mf[, year]) names.mf <- names(mf) names.list <- list(data.name = names.mf[response], season.name = names.mf[season], year.name = names.mf[year]) dot.list <- list(...) match.vec <- pmatch(names(dot.list), c("data.name", "season.name", "year.name"), nomatch = 0) if (length(match.vec) == 0 || all(match.vec == 0)) arg.list <- c(arg.list, names.list, dot.list) else arg.list <- c(arg.list, names.list[-match.vec], dot.list) if (!missing(data)) arg.list$parent.of.data <- deparse(substitute(data)) if (!missing(subset)) arg.list$subset.expression <- deparse(substitute(subset)) do.call(kendallSeasonalTrendTest.default, arg.list) }
context("joinRtData") testthat::test_that("Test that joinRtData runs without error in dry run mode when used with summaryWidget", { testthat::skip_on_cran() subnational <- national <- list("Cases" = readInEpiNow2( path = "https://raw.githubusercontent.com/epiforecasts/covid-rt-estimates/master/subnational/italy/cases/summary", region_var = "region")) national <- list("Cases" = readInEpiNow2( path = "https://raw.githubusercontent.com/epiforecasts/covid-rt-estimates/master/national/cases/summary", region_var = "country"), regions = "Italy") out <- list() out$Cases <- joinRtData(subnational$Cases, national$Cases) testthat::expect_true(summaryWidget(rtData = out, dryRun = TRUE)) })
const.b1<-2 const.b2<-2 const.b3<-2 const.b.vec<-c(const.b1, const.b2, const.b3) "paraEst.v" <- function(X, paraIni, memSubjects, maxFlag=TRUE, thrshPostProb=0.50, geneNames=NULL, ITMAX=100, eps=1.0e-03, quiet=TRUE) { checkPara.v(paraIni, eps) sumb<-sum(const.b.vec, na.rm=TRUE) const.b1.b2<-c(const.b1, const.b2) n<-ncol(X) nc<-sum(memSubjects==1, na.rm=TRUE) nn<-sum(memSubjects==0, na.rm=TRUE) if(nc>=n){ stop("Number of cases >= Total number of patients!\n") } if(nn>=n){ stop("Number of controls >= Total number of patients!\n") } Psi.m<-paraIni nGenes<-nrow(X) xcMat<-X[,memSubjects==1,drop=FALSE] xnMat<-X[,memSubjects==0,drop=FALSE] xcTxc<-apply(xcMat, 1, function(x) {sum(x^2, na.rm=TRUE)}) xcT1<-apply(xcMat, 1, function(x) {sum(x, na.rm=TRUE)}) xnTxn<-apply(xnMat, 1, function(x) {sum(x^2, na.rm=TRUE)}) xnT1<-apply(xnMat, 1, function(x) {sum(x, na.rm=TRUE)}) loop<-0 while(1) { if(!quiet) { cat("************\n") cat("loop=", loop, "\n") } wiMat<-t(apply(X, 1, wiFun.v, Psi.m=Psi.m, memSubjects=memSubjects, eps=eps)) w1<-as.numeric(wiMat[,1]) w2<-as.numeric(wiMat[,2]) w3<-as.numeric(wiMat[,3]) sumw1<-sum(w1, na.rm=TRUE) sumw2<-sum(w2, na.rm=TRUE) sumw3<-sum(w3, na.rm=TRUE) if(!quiet) { cat("sumw1=", sumw1, " sumw2=", sumw2, " sumw3=", sumw3, "\n") } sumw1xcTxc<-sum(w1*xcTxc, na.rm=TRUE) sumw1xcT1<-sum(w1*xcT1, na.rm=TRUE) sumw1xcT1.sq<-sum(w1*xcT1^2, na.rm=TRUE) sumw1xnTxn<-sum(w1*xnTxn, na.rm=TRUE) sumw1xnT1<-sum(w1*xnT1, na.rm=TRUE) sumw1xnT1.sq<-sum(w1*xnT1^2, na.rm=TRUE) sumw2xcTxc<-sum(w2*xcTxc, na.rm=TRUE) sumw2xcT1<-sum(w2*xcT1, na.rm=TRUE) sumw2xcT1.sq<-sum(w2*xcT1^2, na.rm=TRUE) sumw2xnTxn<-sum(w2*xnTxn, na.rm=TRUE) sumw2xnT1<-sum(w2*xnT1, na.rm=TRUE) sumw2xnT1.sq<-sum(w2*xnT1^2, na.rm=TRUE) sumw3xcTxc<-sum(w3*xcTxc, na.rm=TRUE) sumw3xcT1<-sum(w3*xcT1, na.rm=TRUE) sumw3xcT1.sq<-sum(w3*xcT1^2, na.rm=TRUE) sumw3xnTxn<-sum(w3*xnTxn, na.rm=TRUE) sumw3xnT1<-sum(w3*xnT1, na.rm=TRUE) sumw3xnT1.sq<-sum(w3*xnT1^2, na.rm=TRUE) piVec.new<-(c(sumw1, sumw2)+const.b1.b2-1)/(nGenes+sumb-3) names(piVec.new)<-c("pi.1", "pi.2") thetaIni<-Psi.m[-c(1:2)] nTheta<-length(thetaIni) lower<-rep(-Inf, nTheta) upper<-rep(Inf, nTheta) res<-optim(par=thetaIni, fn=negQFunc.v, nc=nc, nn=nn, n=n, xcMat=xcMat, xnMat=xnMat, xcTxc=xcTxc, xnTxn=xnTxn, sumw1=sumw1, sumw2=sumw2, sumw3=sumw3, sumw1xcTxc=sumw1xcTxc, sumw1xcT1=sumw1xcT1, sumw1xcT1.sq=sumw1xcT1.sq, sumw1xnTxn=sumw1xnTxn, sumw1xnT1=sumw1xnT1, sumw1xnT1.sq=sumw1xnT1.sq, sumw2xcTxc=sumw2xcTxc, sumw2xcT1=sumw2xcT1, sumw2xcT1.sq=sumw2xcT1.sq, sumw2xnTxn=sumw2xnTxn, sumw2xnT1=sumw2xnT1, sumw2xnT1.sq=sumw2xnT1.sq, sumw3xcTxc=sumw3xcTxc, sumw3xcT1=sumw3xcT1, sumw3xcT1.sq=sumw3xcT1.sq, sumw3xnTxn=sumw3xnTxn, sumw3xnT1=sumw3xnT1, sumw3xnT1.sq=sumw3xnT1.sq, method = "L-BFGS-B", lower = lower, upper = upper) if(res$convergence) { cat("convergence=", res$convergence, "\n") cat("message=", res$message, "\n") cat("number of calls to fn and gr>>\n"); print(res$counts); cat("\n"); cat("thetaIni>>\n"); print(thetaIni); cat("\n"); } negQ<-res$value theta<-res$par Psi.m.new<-c(piVec.new, theta) names(Psi.m.new)<-paraNamesRP if(!quiet) { cat("-negQ = ", -negQ, "\n") cat("Psi.m.new>>\n"); print(round(Psi.m.new,3)); cat("\n") } err.len<-sum(abs(Psi.m.new-Psi.m)<eps, na.rm=TRUE) if(err.len==length(Psi.m)) { Psi.m<-Psi.m.new break } Psi.m<-Psi.m.new loop<-loop+1 if(loop>ITMAX) { cat("*********************\n") cat("Warning! Number of looping (= ", loop, ") exceeds ITMAX (=", ITMAX, ")!\n") cat("EM algorithm did not converge!\n") cat("*********************\n") break } } if(!quiet) { cat("Total iterations for EM algorithm=", loop, "\n") } memMat<-t(apply(X, 1, wiFun.v, Psi.m=Psi.m, memSubjects=memSubjects, eps=eps)) colnames(memMat)<-c("cluster1", "cluster2", "cluster3") rownames(memMat)<-geneNames memGenes<-apply(memMat, 1, maxPosFun.v, maxFlag=maxFlag, thrshPostProb=thrshPostProb) sumw1<-mean(memMat[,1], na.rm=TRUE) sumw2<-mean(memMat[,2], na.rm=TRUE) sumw3<-mean(memMat[,3], na.rm=TRUE) sumw1xcTxc<-sum(w1*xcTxc, na.rm=TRUE) sumw1xcT1<-sum(w1*xcT1, na.rm=TRUE) sumw1xcT1.sq<-sum(w1*xcT1^2, na.rm=TRUE) sumw1xnTxn<-sum(w1*xnTxn, na.rm=TRUE) sumw1xnT1<-sum(w1*xnT1, na.rm=TRUE) sumw1xnT1.sq<-sum(w1*xnT1^2, na.rm=TRUE) sumw2xcTxc<-sum(w2*xcTxc, na.rm=TRUE) sumw2xcT1<-sum(w2*xcT1, na.rm=TRUE) sumw2xcT1.sq<-sum(w2*xcT1^2, na.rm=TRUE) sumw2xnTxn<-sum(w2*xnTxn, na.rm=TRUE) sumw2xnT1<-sum(w2*xnT1, na.rm=TRUE) sumw2xnT1.sq<-sum(w2*xnT1^2, na.rm=TRUE) sumw3xcTxc<-sum(w3*xcTxc, na.rm=TRUE) sumw3xcT1<-sum(w3*xcT1, na.rm=TRUE) sumw3xcT1.sq<-sum(w3*xcT1^2, na.rm=TRUE) sumw3xnTxn<-sum(w3*xnTxn, na.rm=TRUE) sumw3xnT1<-sum(w3*xnT1, na.rm=TRUE) sumw3xnT1.sq<-sum(w3*xnT1^2, na.rm=TRUE) llkh<- -negQFunc.v(Psi.m[-c(1:2)], X, nc, nn, n, xcMat, xnMat, xcTxc, xnTxn, sumw1, sumw2, sumw3, sumw1xcTxc, sumw1xcT1, sumw1xcT1.sq, sumw1xnTxn, sumw1xnT1, sumw1xnT1.sq, sumw2xcTxc, sumw2xcT1, sumw2xcT1.sq, sumw2xnTxn, sumw2xnT1, sumw2xnT1.sq, sumw3xcTxc, sumw3xcT1, sumw3xcT1.sq, sumw3xnTxn, sumw3xnT1, sumw3xnT1.sq) memGenes2<-rep(1, nGenes) memGenes2[memGenes==2]<-0 if(sum(is.null(geneNames), na.rm=TRUE)) { geneNames<-paste("gene", 1:nGenes, sep="") } names(Psi.m)<-paraNamesRP names(memGenes)<-geneNames names(memGenes2)<-geneNames invisible(list(para=Psi.m, llkh=llkh, memGenes=memGenes, memGenes2=memGenes2, memMat=memMat, loop=loop)) } maxPosFun.v<-function(x, maxFlag=TRUE, thrshPostProb=0.50) { if(maxFlag) { pos<-which(x==max(x, na.rm=TRUE)) pos<-pos[1] return(pos) } pos<-which(x>thrshPostProb) len<-length(pos) if(len==0) { return(2) } pos<-which(x==max(x, na.rm=TRUE)) return(pos) }
test_that("test ceteris_paribus_cutoff with plot", { cpc <- ceteris_paribus_cutoff(fobject, subgroup = "African_American") expect_equal(cpc$subgroup, "African_American") expect_equal(cpc$cumulated, FALSE) metrics_used <- (unique(as.character(cpc$cutoff_data$metric))) expect_equal(sort(metrics_used), sort(fairness_check_metrics())) cpc <- ceteris_paribus_cutoff(fobject, subgroup = "African_American", cumulated = TRUE) expect_equal(cpc$cumulated, TRUE) cpc <- ceteris_paribus_cutoff(fobject, subgroup = "African_American", cumulated = TRUE) plt <- plot(cpc) expect_equal(plt$labels$subtitle, "Based on African_American and cumulated") expect_s3_class(plt, "ggplot") cpc <- ceteris_paribus_cutoff(fobject, subgroup = "African_American") plt <- plot(cpc) expect_s3_class(plt, "ggplot") })
yadirAuth <- function(Login = getOption("ryandexdirect.user"), NewUser = FALSE, TokenPath = yadirTokenPath()) { if (!dir.exists(TokenPath)) { dir.create(TokenPath) } if ( is.null(Login) && ! is.null(getOption("ryandexdirect.user") ) ) { Login <- getOption("ryandexdirect.user") } TokenPath <- gsub(pattern = '\\\\', replacement = '/', x = TokenPath) if (NewUser == FALSE && file.exists(paste0(paste0(TokenPath, "/", Login, ".yadirAuth.RData")))) { message("Load token from ", paste0(paste0(TokenPath, "/", Login, ".yadirAuth.RData"))) load(paste0(TokenPath, "/", Login, ".yadirAuth.RData")) if (as.numeric(token$expire_at - Sys.time(), units = "days") < 30) { message("Auto refresh token") token_raw <- httr::POST("https://oauth.yandex.ru/token", body = list(grant_type="refresh_token", refresh_token = token$refresh_token, client_id = "365a2d0a675c462d90ac145d4f5948cc", client_secret = "f2074f4c312449fab9681942edaa5360"), encode = "form") if (!is.null(token$error_description)) { stop(paste0(token$error, ": ", token$error_description)) } token <- content(token_raw) token$expire_at <- Sys.time() + as.numeric(token$expires_in, units = "secs") class(token) <- "yadir_token" save(token, file = paste0(TokenPath, "/", Login, ".yadirAuth.RData")) message("Token saved in file ", paste0(TokenPath, "/", Login, ".yadirAuth.RData")) return(token) } else { message("Token expire in ", round(as.numeric(token$expire_at - Sys.time(), units = "days"), 0), " days") return(token) } } if ( ! interactive() ) { stop(paste0("Function yadirAuth does not find the ", Login, ".yadirAuth.RData file in ",TokenPath,". You must run this script in interactive mode in RStudio or RGui and go through the authorization process for create ", Login,".yadirAuth.RData file, and using him between R session in batch mode. For more details see realise https://github.com/selesnow/ryandexdirect/releases/tag/3.0.0. For more details about R modes see https://www.r-bloggers.com/batch-processing-vs-interactive-sessions/") ) } else { browseURL(paste0("https://oauth.yandex.ru/authorize?response_type=code&client_id=365a2d0a675c462d90ac145d4f5948cc&redirect_uri=https://selesnow.github.io/ryandexdirect/getToken/get_code.html&force_confirm=", as.integer(NewUser), ifelse(is.null(Login), "", paste0("&login_hint=", Login)))) temp_code <- readline(prompt = "Enter authorize code:") while(nchar(temp_code) != 7) { message("The verification code entered by you is not 7-digit, try to enter the code again.") temp_code <- readline(prompt = "Enter authorize code:") } } token_raw <- httr::POST("https://oauth.yandex.ru/token", body = list(grant_type="authorization_code", code = temp_code, client_id = "365a2d0a675c462d90ac145d4f5948cc", client_secret = "f2074f4c312449fab9681942edaa5360"), encode = "form") token <- content(token_raw) token$expire_at <- Sys.time() + as.numeric(token$expires_in, units = "secs") class(token) <- "yadir_token" if (!is.null(token$error_description)) { stop(paste0(token$error, ": ", token$error_description)) } message("Do you want save API credential in local file (",paste0(TokenPath, "/", Login, ".yadirAuth.RData"),"), for use it between R sessions?") ans <- readline("y / n (recomedation - y): ") if ( tolower(ans) %in% c("y", "yes", "ok", "save") ) { save(token, file = paste0(TokenPath, "/", Login, ".yadirAuth.RData")) message("Token saved in file ", paste0(TokenPath, "/", Login, ".yadirAuth.RData")) } return(token) }
Vlocate<-function(Ldat,EQ,vel, distwt = 10, lambdareg =100, REG = TRUE, WTS = TRUE, STOPPING = TRUE, tolx = 0.1, toly = 0.1, tolz = 0.5, RESMAX = c(.4,.5), maxITER = c(7, 5, 7, 4), PLOT=FALSE) { BADSOLUTION = FALSE Ksolutions = vector(mode="list") MLAT = median(Ldat$lat) MLON = median(Ldat$lon) proj = GEOmap::setPROJ(type=2, LAT0=MLAT, LON0=MLON) XY = GEOmap::GLOB.XY(Ldat$lat, Ldat$lon, proj) Ldat$x = XY$x Ldat$y = XY$y if(is.na(EQ$lat)) { cat("Guess at first arrival station", sep="\n" ) wstart = which.min(Ldat$sec) EQ = list(lat=Ldat$lat[wstart], lon=Ldat$lon[wstart], z=6, t=Ldat$sec[wstart]-1) EQ$x = XY$x[wstart] EQ$y = XY$y[wstart] }else{ eqxy = GEOmap::GLOB.XY(EQ$lat, EQ$lon, proj) EQ$x = eqxy$x EQ$y = eqxy$y } if( !checkLOCATEinput(Ldat, EQ) ) { cat(' Vlocate has bad/missing data.\n') ; return(NULL) } AQ = XYlocate(Ldat,EQ,vel, maxITER = maxITER[1], distwt = distwt, lambdareg =lambdareg , FIXZ =TRUE, REG = REG, WTS = WTS, STOPPING = STOPPING, RESMAX = c(0,0), tolx = tolx, toly = toly , tolz = tolz, PLOT=PLOT) Ksolutions[[1]] = AQ$guesses if(is.null(AQ$EQ)) { return(list(EQ=NULL )) } eqLL = GEOmap::XY.GLOB(AQ$EQ$x, AQ$EQ$y, proj) AQ$EQ$lat = eqLL$lat AQ$EQ$lon = eqLL$lon EQ = AQ$EQ AQ = XYlocate(Ldat,EQ,vel, maxITER = maxITER[2], distwt = distwt, lambdareg =lambdareg , FIXZ =FALSE, REG = REG, WTS = WTS, STOPPING = STOPPING, RESMAX =RESMAX , tolx = tolx, toly = toly , tolz = tolz, PLOT=PLOT) Ksolutions[[2]] = AQ$guesses if(is.null(AQ$EQ)) { return(list(EQ=NULL )) } eqLL = GEOmap::XY.GLOB(AQ$EQ$x, AQ$EQ$y, proj) AQ$EQ$lat = eqLL$lat AQ$EQ$lon = eqLL$lon EQ = AQ$EQ AQ = XYlocate(Ldat,EQ,vel, maxITER = maxITER[3], distwt = distwt, lambdareg =lambdareg , FIXZ = FALSE, REG = REG, WTS = WTS, STOPPING = STOPPING, RESMAX = c(0,0), tolx = tolx, toly = toly , tolz = tolz, PLOT=PLOT) Ksolutions[[3]] = AQ$guesses if(is.null(AQ$EQ)) { return(list(EQ=NULL )) } eqLL = GEOmap::XY.GLOB(AQ$EQ$x, AQ$EQ$y, proj) AQ$EQ$lat = eqLL$lat AQ$EQ$lon = eqLL$lon EQ = AQ$EQ KITS = AQ$its if(BADSOLUTION) { AQ = XYlocate(Ldat,EQ,vel, maxITER = maxITER[4], distwt = distwt, lambdareg =2*lambdareg , FIXZ=FALSE, REG = REG, WTS = WTS, STOPPING = STOPPING, tolx = tolx, toly = toly , tolz = tolz, PLOT=PLOT) eqLL = GEOmap::XY.GLOB(AQ$EQ$x, AQ$EQ$y, proj) AQ$EQ$lat = eqLL$lat AQ$EQ$lon = eqLL$lon EQ = AQ$EQ Ksolutions[[4]] = AQ$guesses } wup = eqwrapup(Ldat, EQ, vel, distwt=distwt, verbose=FALSE) return(list(EQ=EQ, ERR=wup, its=AQ$its , proj=proj, Ksolutions=Ksolutions )) }
add_colored_str <- function(text = "", color = c(51, 122, 183), alpha = 255, bgcolor = NULL, bgalpha = 51, fontsize = 1, bold = FALSE, it = FALSE ) { fontsize = suppressWarnings(as.numeric(fontsize)) if (is.null(text) | (!is.character(text))) { text <- "" warning("text should be a string") } colorrgb = mtb_color2rgb( color, alpha, outalpha=TRUE ) colorrgb[4] = colorrgb[4]/255 colorstr <- paste( "color: rgba(", paste(colorrgb, collapse = ","),"); ",sep="") if( !is.null(bgcolor) ){ bgcolorrgb = mtb_color2rgb( bgcolor, bgalpha, outalpha=TRUE ) bgcolorrgb[4] = bgcolorrgb[4]/255 bgcolorstr <- paste( "background-color: rgba(", paste(bgcolorrgb, collapse = ","),"); ",sep="") }else{bgcolorstr=""} if( !(length(fontsize)==1) | is.na(fontsize) ){ fontsize <- 1 } else { fontsize <- min(max(fontsize, 0.5), 5) } fontwtstr = ifelse(bold==TRUE, "font-weight: bold;", "") fontwtstr = paste(fontwtstr, ifelse(it==TRUE, "font-style: italic;", ""), sep="") text <- mtb_cleanupstr(text) htmltools::tags$span( htmltools::HTML(text), style = paste( bgcolorstr, colorstr, fontwtstr, "margin: 3px auto 3px auto; font-size:", paste(floor(100 * fontsize), "%", sep=""),sep="" ) ) } add_colored_box = function( type = 'blue-default', label = '', info = 'place details here using info option', bgcolor = NULL, width = 0.5, halign = 'c', top = FALSE ){ if( is.null(type) ){type="blue-default"}else{type=as.character(type)} if( !is.character(type)|length(type)!=1){ type="blue-default"; warning('Type should be a string.')} if( is.null(label) ){label=""}else{label=as.character(label)} if( !is.character(label)|length(label)!=1){ label=""; warning('Label should be a string.')} if( is.null(info) ){info = ""}else{info=as.character(info)} if( !is.character(info)|length(info)!=1 ){ info = ""; warning('Info should be a string.')} info = mtb_cleanupstr(info) width = as.numeric(width) if( length(width)!=1 ){ width = 0.5 } if( width > 0.95 ){ width = 0.95 } if( width < 0.25 ){ width = 0.25 } if( is.null(halign) ){ halign=''; warning('halign should be either c or r')} if( !is.character(halign) | !(halign=='c'|halign=='r') ){ halign=''; warning('halign should be either c or r')} if( halign == 'r' ){ width = min(width, 0.35); alignstr = 'position: absolute; right:0;'}else{alignstr=''} if( !is.logical(top) ){ top = FALSE; warning('top should be either TRUE or FALSE') } if( top ){ alignstr = paste(alignstr, 'top:0;')} lsttype = c('blue-default', 'blue-info','gray-info','green-reminder', 'yellow-warning','red-stop') typestr = c('& if(length(typestr)==0){typestr=''} if(label==""){ label = c('Note', 'Note', 'Note', 'Reminder', 'Warning', 'Stop')[lsttype==type]; if(length(label)==0) label="" } if( is.null(bgcolor) ){ bgcolor = rbind( c(51, 122, 183), c(60,110,230), rep(110,3), c(110,230,60), c(230,200,60), c(230,110,60))[lsttype==type, ] if(length(bgcolor)==0){bgcolor=rep(120,3)} } if( !is.null(bgcolor) ){ bgcolorrgb = mtb_color2rgb( bgcolor )[1:3] }else{bgcolorrgb=rep(120,3)} htmltools::tags$div(htmltools::HTML(paste("<b> &nbsp; <span style='font-size:110%;'>", typestr, "</span><i>", label, "</i></b>", htmltools::tags$div(htmltools::HTML(info), style='background-color: rgba(255,255,255,0.75); padding: 10px 20px 10px 20px; border-radius: 0px 0px 5px 0px;'))), style=paste( alignstr, "background-color: rgba(", paste(bgcolorrgb, collapse=','), ", 0.2); margin: 3px auto 3px auto; width:", paste(floor(100*width),"%", sep=""), "; border-width: 0px 0px 0px 3px; border-color: rgba(", paste(bgcolorrgb, collapse=','), ",1); border-style: solid; padding: 1px 1px 1px 0px; border-radius: 0px 0px 5px 0px;")) }
expected <- eval(parse(text="c(1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3)")); test(id=0, code={ argv <- eval(parse(text="list(list(c(TRUE, TRUE), c(TRUE, TRUE), c(TRUE, TRUE), c(TRUE, TRUE), c(1, 2, 3)), TRUE, TRUE)")); .Internal(unlist(argv[[1]], argv[[2]], argv[[3]])); }, o=expected);
test_that("X_valid_user functions work as expected", { expect_true(is.character(check_valid_user(21))) expect_true(is.character(check_valid_user(21))) expect_true(is.character(check_valid_user(NA_character_))) expect_true(is.character(check_valid_user(""))) expect_true(is.character(check_valid_user(NULL))) expect_true(is.character(check_valid_user("notauser"))) expect_true(check_valid_user("uQiRzpo4DXghDmr9QzzfQu27cmVRsG")) expect_false(test_valid_user(21)) expect_false(test_valid_user(NA_character_)) expect_false(test_valid_user("")) expect_false(test_valid_user(NULL)) expect_false(test_valid_user("notauser")) expect_true(test_valid_user("uQiRzpo4DXghDmr9QzzfQu27cmVRsG")) expect_false( test_valid_user( c("uQiRzpo4DXghDmr9QzzfQu27cmVRsG", "uQiRzpo4DXghDmr9QzzfQu27cmVRsG") ) ) expect_error(assert_valid_user(21)) expect_error(assert_valid_user(NA_character_)) expect_error(assert_valid_user("")) expect_error(assert_valid_user(NULL)) expect_error(assert_valid_user("notauser")) expect_error( assert_valid_user( c("uQiRzpo4DXghDmr9QzzfQu27cmVRsG", "uQiRzpo4DXghDmr9QzzfQu27cmVRsG") ) ) }) test_that("X_valid_group functions work as expected", { expect_true(is.character(check_valid_group(21))) expect_true(is.character(check_valid_group(21))) expect_true(is.character(check_valid_group(NA_character_))) expect_true(is.character(check_valid_group(""))) expect_true(is.character(check_valid_group(NULL))) expect_true(is.character(check_valid_group("notagroup"))) expect_true(check_valid_group("gznej3rKEVAvPUxu9vvNnqpmZpokzF")) expect_false(test_valid_group(21)) expect_false(test_valid_group(NA_character_)) expect_false(test_valid_group("")) expect_false(test_valid_group(NULL)) expect_false(test_valid_group("notagroup")) expect_true(test_valid_group("gznej3rKEVAvPUxu9vvNnqpmZpokzF")) expect_false( test_valid_group( c("gznej3rKEVAvPUxu9vvNnqpmZpokzF", "gznej3rKEVAvPUxu9vvNnqpmZpokzF") ) ) expect_error(assert_valid_group(21)) expect_error(assert_valid_group(NA_character_)) expect_error(assert_valid_group("")) expect_error(assert_valid_group(NULL)) expect_error(assert_valid_group("notagroup")) expect_error( assert_valid_group( c("gznej3rKEVAvPUxu9vvNnqpmZpokzF", "gznej3rKEVAvPUxu9vvNnqpmZpokzF") ) ) })
suppressMessages(library("circular")) angles <- circular(c(70, 80, 80, 85, 85, 90, 95, 95, 5, 5, 15, 55, 55, 65, 105, 120, 340), units="degrees", template="geographics") group <- factor(c(rep("control", 8), rep("experimental", 9))) homeDir <- 40 xn <- angles wallraff.test(xn, group) wallraff.test(xn, group, ref=homeDir) wallraff.test(xn, as.factor(group), ref=homeDir) xl <- split(xn, group) wallraff.test(xl, ref=homeDir) wallraff.test(xl) xl <- split(xn, group) names(xl) <- NULL wallraff.test(xl) xd <- data.frame(group=group, angles=angles) wallraff.test(angles ~ group, xd)
vif.rma <- function(x, btt, intercept=FALSE, table=FALSE, digits, ...) { mstyle <- .get.mstyle("crayon" %in% .packages()) .chkclass(class(x), must="rma", notav=c("robust.rma", "rma.uni.selmodel")) vif.loc <- TRUE vif.scale <- TRUE if (inherits(x, "rma.ls")) { if (x$int.only) vif.loc <- FALSE if (x$Z.int.only) vif.scale <- FALSE if (!vif.loc && !vif.scale) stop(mstyle$stop("VIF not applicable for intercept-only models.")) } else { if (x$int.only) stop(mstyle$stop("VIF not applicable for intercept-only models.")) } if (missing(digits)) { digits <- .get.digits(xdigits=x$digits, dmiss=TRUE) } else { digits <- .get.digits(digits=digits, xdigits=x$digits, dmiss=FALSE) } ddd <- list(...) .chkdots(ddd, c("att")) if (vif.loc) { vcov <- vcov(x) if (inherits(x, "rma.ls")) vcov <- vcov$beta if (missing(btt) || is.null(btt)) { if (x$intercept && !intercept) vcov <- vcov[-1,-1,drop=FALSE] rb <- cov2cor(vcov) vif <- try(diag(chol2inv(chol(rb))), silent=TRUE) if (inherits(vif, "try-error")) stop(mstyle$stop("Cannot invert var-cov matrix to compute VIFs.")) if (x$intercept && !intercept && table) vif <- c(NA, vif) if (table) { tab <- coef(summary(x)) if (inherits(x, "rma.ls")) tab <- tab$beta vif <- cbind(tab, vif=vif, sif=sqrt(vif)) } else { names(vif) <- rownames(vcov) } res <- list(vif=vif, digits=digits, table=table, test=x$test) } else { btt <- .set.btt(btt, x$p, x$int.incl, colnames(x$X)) if (x$intercept && !intercept) { vcov <- vcov[-1,-1,drop=FALSE] btt <- btt - 1 if (any(btt < 1)) warning(mstyle$warning("Intercept term not included in GVIF computation."), call.=FALSE) btt <- btt[btt > 0] } m <- length(btt) rb <- cov2cor(vcov) detrv <- det(rb) gvif <- det(as.matrix(rb[btt,btt])) * det(as.matrix(rb[-btt,-btt])) / detrv gsif <- gvif^(1/(2*m)) if (x$intercept && !intercept) btt <- btt + 1 res <- list(gvif=gvif, gsif=gsif, btt=btt, m=m, digits=digits) } class(res) <- "vif.rma" } else { res <- NULL } if (inherits(x, "rma.ls") && vif.scale) { res.loc <- res vcov <- vcov(x)$alpha if (is.null(ddd$att)) { if (x$Z.intercept && !intercept) vcov <- vcov[-1,-1,drop=FALSE] rb <- cov2cor(vcov) vif <- try(diag(chol2inv(chol(rb))), silent=TRUE) if (inherits(vif, "try-error")) stop(mstyle$stop("Cannot invert var-cov matrix to compute VIFs for the scale model.")) if (x$Z.intercept && !intercept && table) vif <- c(NA, vif) if (table) { tab <- coef(summary(x))$alpha vif <- cbind(tab, vif=vif, sif=sqrt(vif)) } else { names(vif) <- rownames(vcov) } res.scale <- list(vif=vif, digits=digits, table=table, test=x$test) } else { att <- .set.btt(ddd$att, x$q, x$Z.int.incl, colnames(x$Z)) if (x$Z.intercept && !intercept) { vcov <- vcov[-1,-1,drop=FALSE] att <- att - 1 if (any(att < 1)) warning(mstyle$warning("Intercept term not included in GVIF computation."), call.=FALSE) att <- att[att > 0] } m <- length(att) rb <- cov2cor(vcov) detrv <- det(rb) gvif <- det(as.matrix(rb[att,att])) * det(as.matrix(rb[-att,-att])) / detrv gsif <- gvif^(1/(2*m)) if (x$Z.intercept && !intercept) att <- att + 1 res.scale <- list(gvif=gvif, gsif=gsif, btt=att, m=m, digits=digits) } class(res.scale) <- "vif.rma" if (vif.loc) { if (vif.scale) { res <- list(beta=res.loc, alpha=res.scale) } else { res <- res.loc } } else { res <- res.scale } } return(res) }
IRT.RISE <- function( mod_p, mod_np, use_probs=TRUE ) { p1 <- IRT.irfprob(mod_p) probs <- aperm( p1, perm=c(3,1,2) ) pi.k <- attr(p1, "prob.theta") n.ik <- IRT.expectedCounts(mod_np) n.ik <- aperm(n.ik, perm=c(3,1,2,4)) p2 <- aperm( IRT.irfprob(mod_np), perm=c(3,1,2) ) if (use_probs){ n.ik[,,,1] <- p2 } fmod <- CDM::IRT_RMSD_calc_rmsd( n.ik=n.ik, pi.k=pi.k, probs=probs ) res <- fmod$RMSD return(res) }
tidy_add_reference_rows <- function( x, no_reference_row = NULL, model = tidy_get_model(x), quiet = FALSE ) { if (is.null(model)) { stop("'model' is not provided. You need to pass it or to use 'tidy_and_attach()'.") } if (inherits(model, "aov")) { return(x %>% dplyr::mutate(reference_row = NA)) } if ("header_row" %in% names(x)) { stop("`tidy_add_reference_rows()` cannot be applied after `tidy_add_header_rows().`") } if ("reference_row" %in% names(x)) { if (!quiet) cli_alert_danger("{.code tidy_add_reference_rows()} has already been applied. x has been returned unchanged.") return(x) } .attributes <- .save_attributes(x) if ("label" %in% names(x)) { if (!quiet) cli_alert_info(paste0( "tidy_add_reference_rows() has been applied after tidy_add_term_labels().\n", "You should consider applying tidy_add_reference_rows() first." )) } if ("n_obs" %in% names(x)) { if (!quiet) cli_alert_info(paste0( "{.code tidy_add_reference_rows()} has been applied after {.code tidy_add_n()}.\n", "You should consider applying {.code tidy_add_reference_rows()} first." )) } if (!"contrasts" %in% names(x)) { x <- x %>% tidy_add_contrasts(model = model) } no_reference_row <- .select_to_varnames({{ no_reference_row }}, var_info = x, arg_name = "no_reference_row") terms_levels <- model_list_terms_levels(model) if (!is.null(terms_levels)) terms_levels <- terms_levels %>% dplyr::filter( .data$variable %in% unique(stats::na.omit(x$variable)) & !.data$variable %in% no_reference_row ) if (is.null(terms_levels) || nrow(terms_levels) == 0) return( x %>% dplyr::mutate(reference_row = NA) %>% tidy_attach_model(model) ) terms_levels <- terms_levels %>% dplyr::group_by(.data$variable) %>% dplyr::mutate(rank = 1:dplyr::n()) has_var_label <- "var_label" %in% names(x) if (!has_var_label) { x$var_label <- NA_character_ } x <- x %>% dplyr::mutate( reference_row = dplyr::if_else( .data$variable %in% unique(terms_levels$variable), FALSE, NA ), rank = 1:dplyr::n() ) group <- NULL if ("component" %in% names(x)) group <- "component" if ("y.level" %in% names(x) & inherits(model, "multinom")) group <- "y.level" if (!is.null(group)) x$.group_by_var <- x[[group]] else x$.group_by_var <- "" ref_rows <- terms_levels %>% dplyr::filter(.data$reference) %>% dplyr::mutate(reference_row = TRUE) %>% dplyr::select(.data$term, .data$variable, .data$label, .data$reference_row, .data$rank) if (!"label" %in% names(x)) ref_rows <- ref_rows %>% dplyr::select(-.data$label) tmp <- x if (!"effect" %in% names(x)) tmp$effect <- NA_character_ var_summary <- tmp %>% dplyr::group_by(.data$.group_by_var, .data$variable) %>% dplyr::summarise( var_class = dplyr::first(.data$var_class), var_type = dplyr::first(.data$var_type), var_label = dplyr::first(.data$var_label), var_nlevels = dplyr::first(.data$var_nlevels), effect = dplyr::first(.data$effect), contrasts = dplyr::first(.data$contrasts), contrasts_type = dplyr::first(.data$contrasts_type), var_min_rank = min(.data$rank), var_max_rank = min(.data$rank), .groups = "drop_last" ) ref_rows <- ref_rows %>% dplyr::left_join( var_summary, by = "variable" ) %>% dplyr::mutate( rank = .data$var_min_rank -1.25 + .data$rank, rank = dplyr::if_else( .data$rank > .data$var_max_rank, .data$rank - .5, .data$rank ) ) %>% dplyr::select(-.data$var_min_rank, -.data$var_max_rank) if (!"effect" %in% names(x)) ref_rows <- ref_rows %>% dplyr::select(-.data$effect) x <- x %>% dplyr::bind_rows(ref_rows) if (!is.null(group)) x[[group]] <- x$.group_by_var x <- x %>% dplyr::select(-.data$.group_by_var) if (!has_var_label) { x <- x %>% dplyr::select(-.data$var_label) } x %>% dplyr::arrange(.data$rank) %>% dplyr::select(-.data$rank) %>% tidy_attach_model(model = model, .attributes = .attributes) }
context("Building Query Parameters") test_that("Query parameter types can be assigned appropriately", { params <- list(foo="hi", bar=1L, baz=FALSE, quux=1.1, dt=as.Date('2019-01-01')) types <- AzureKusto:::build_param_list(params) expect_equal( types, "(foo:string, bar:int, baz:bool, quux:real, dt:datetime)") }) test_that("build_request_body without params gives expected result", { body <- AzureKusto:::build_request_body("Samples", "StormEvents | take 5") expect_null(body$properties$Parameters) expect_equal(body$db, "Samples") expect_equal(body$csl, "StormEvents | take 5") }) test_that("build_request_body with params gives expected result", { params <- list( foo="hi", bar=1L, baz=FALSE, quux=1.1 ) body <- AzureKusto:::build_request_body("Samples", "MyFunction(foo, bar, baz, quux)", query_parameters=params) expect_equal(body$properties$Parameters$foo, "hi") expect_equal(body$db, "Samples") expect_equal(body$csl, "declare query_parameters (foo:string, bar:int, baz:bool, quux:real) ; MyFunction(foo, bar, baz, quux)") })
library(wkb) library(sp) context("Conversion from WKB LineString representations") l1 <- data.frame(x = c(1, 2), y = c(3, 2)) l2 <- data.frame(x = c(1,2), y = c(1, 1.5)) Sl1 <- Line(l1) Sl2 <- Line(l2) S1 <- Lines(list(Sl1), ID = "1") S2 <- Lines(list(Sl2), ID = "2") refobj <- SpatialLines(list(S1, S2)) refwkb <- I(list( as.raw(c(0x01, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40)), as.raw(c(0x01, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x3f)) )) refwkbbe <- I(list( as.raw(c(0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)), as.raw(c(0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)) )) test_that("little-endian WKB LineString representation converts to SpatialLines object", { obj <- readWKB(refwkb) expect_equal(obj, refobj) }) test_that("big-endian WKB LineString representation converts to SpatialLines object", { obj <- readWKB(refwkbbe) expect_equal(obj, refobj) })
ce.simnormal.Init.MeanVar.BIC <- function(N, init.locs, data, h, L0, L, M, Melite, eps, a, b, var.init){ new_para <- rbind(init.locs, rep(var.init, N)) k<-0 repeat { k<-k+1 ch<-array(0,dim=c(M,N+2)) ch[,1]<-c(1) ch[,N+2]<-c(L+1) ch[,(2:(N+1))]<-apply(new_para,2,normrand,L0,L,M) ch<-t(apply(ch,1,sort)) LL.full <- apply(ch, 1, llhood.MeanVarNormal, data, h) BIC.val <- apply(as.data.frame(LL.full), 1, BIC.MeanVarNormal, N, L) ch <- cbind(ch, LL.full, BIC.val) ch <- ch[order(ch[, (N + 4)], decreasing = FALSE), ] melitesmpl<-ch[1:Melite,] new_par_n<-array(0,dim=c(2,N)) new_par_n[1,]<-apply(as.matrix(melitesmpl[,(2:(N+1))]),2,mean) new_par_n[2,]<-apply(as.matrix(melitesmpl[,(2:(N+1))]),2,sd) new_para[1,] <- a*new_par_n[1,] + (1-a)*new_para[1,] new_para[2,] <- b*new_par_n[2,] + (1-b)*new_para[2,] mad<-apply(as.matrix(melitesmpl[,(2:(N+1))]),2,mad) if(max(mad)<=eps){break} } return(list(loci=ch[1,(1:(N+2))], BIC.Val = melitesmpl[1, (N + 4)][[1]], LogLike = melitesmpl[1, (N + 3)][[1]])) }
read_bib2tib = function(file){ if (!is.character(file)) { stop("Invalid file path: Non-character supplied.", call. = FALSE) } if (grepl("http://|https://|www.", file)) { tryCatch( { GET(file) }, error = function(e) { stop("Invalid URL: File is not readable.", call. = FALSE) } ) } else { if (as.numeric(file.access(file, mode = 4)) != 0) { stop("Invalid file path: File is not readable.", call. = FALSE) } } bib = readLines(file,encoding = "UTF-8") bib <- str_replace_all(bib, "[^[:graph:]]", " ") temp = grep("^( {0,})@Comment{jabref-meta: databaseType:bibtex;}( {0,})$",bib,perl =T) if(!rlang::is_empty(temp)){ warning('This file is exported from "JabRef" and we will automatically remove the "JabRef" tag. tag: @Comment{jabref-meta: databaseType:bibtex;}') bib[temp] = "" } rm(temp) from <- which(str_extract(bib, "[:graph:]") == "@") to <- c(from[-1] - 1, length(bib)) if (!length(from)) { return(NULL) } itemslist <- mapply( function(x, y) return(bib[x:y]), x = from, y = to - 1, SIMPLIFY = FALSE ) item_tib = tibble::enframe(itemslist,name = "sitenum", value = "value") item_tib$rawchar = NA item_tib$rawchar = map(item_tib$value, function(x){ str_trim(x,side = 'both') }) item_tib$rawchar = map(item_tib$rawchar, function(x){ gsub('[ \t]{2,}',' ',x) }) len = map(item_tib$rawchar, function(x){ max(grep('\\}',x)) }) dupl = sum(sapply(len, is.infinite)) if (dupl > 0) { message("Some BibTeX entries may have been dropped. The results may not be correct. Check the. Bib file to make sure that each entry starts with '@' and ends with '}'") } item_tib$rawchar = map2(item_tib$rawchar, len, function(x,y){ x[1:y] }) item_tib$rawchar = map(item_tib$rawchar, function(x){ gsub('(^,?)(.*?)(,?$)','\\2',x) }) item_tib$rawchar = map(item_tib$rawchar, function(x){ x[which(x !='')] }) len = map(item_tib$rawchar, function(x){ max(grep('\\}',x)) }) item_tib$rawchar = map2(item_tib$rawchar, len, function(x,y){ x[y]=gsub('\\}$','',x[y]);x }) item_tib$rawchar = map(item_tib$rawchar, function(x){ x[which(x !='')] }) item_tib$keybib = NA item_tib$keybib = purrr::map_chr(item_tib$rawchar, function(x) { temp = str_extract(x[1], "(?<=\\{)[^,]+") str_trim(temp, side = "both") } ) temp = NULL temp = unlist(map(item_tib$keybib, function(x)!is.na(x))) temp = item_tib$keybib[temp] if(any(duplicated(temp))){ s = paste0(temp[duplicated(temp)],collapse = '\n') s = paste0('Duplicate key in uploaded Bib file\n',s) warning(s) } rm(temp) item_tib$typebib = NA item_tib$typebib = purrr::map_chr(item_tib$rawchar, function(x) { temp = str_extract(x[1], "(?<=@)[^\\{]+") str_trim(temp, side = "both") }) item_tib$typebib = purrr::map_chr(item_tib$typebib , toupper) items = map(item_tib$rawchar,function(x){ str_split(x[-1],'[ ]*=[ ]*', n = 2, simplify = T) }) items = map(items,function(x){ x[,1] = toupper(x[,1]);x }) items = map(items,function(x){ for(i in seq_len(1)){ x[,2] = gsub('^(\\")(.*?)(\\")$',"\\2",x[,2]) } x }) items = map(items,function(x){ for(i in seq_len(5)){ x[,2] = gsub('^(\\{)(.*?)(\\})$',"\\2",x[,2]) } x }) categories_field = unlist(map(items,function(x)x[,1])) for (ii in categories_field) { item_tib[[ii]] = NA item_tib[[ii]] = map_chr(items,function(x){ temp = which(x[,1] == ii) ifelse(!is_empty(temp),x[temp[1],2], NA) }) } item_tib$AUTHOR = gsub('([\u4e00-\u9fa5])(\\}){1,}([ ]{1,})(and)([ ]{1,})(\\{){1,}([\u4e00-\u9fa5])','\\1 and \\7', item_tib$AUTHOR) return(item_tib) }
context("PredictionClust") test_that("Construction", { task = tsk("usarrests") p = PredictionClust$new(row_ids = task$row_ids, partition = rep.int(1L, nrow(task$data()))) expect_prediction(p) expect_prediction_clust(p) expect_prediction(c(p, p)) }) test_that("Internally constructed Prediction", { task = tsk("usarrests") lrn = mlr_learners$get("clust.featureless") lrn$param_set$values = list(num_clusters = 1L) p = lrn$train(task)$predict(task) expect_prediction(p) expect_prediction_clust(p) })
score.univregs <- function(target, dataset, test) { univariateModels <- list(); dm <- dim(dataset) rows <- dm[1] cols <- dm[2] if ( identical(test, testIndBeta) ) { mod <- Rfast::score.betaregs(target, dataset, logged = TRUE ) univariateModels$stat <- mod[, 1] univariateModels$pvalue <- mod[, 2] } else if ( identical(test, testIndNB) ) { mod <- Rfast::score.negbinregs(target, dataset, logged = TRUE ) univariateModels$stat <- mod[, 1] univariateModels$pvalue <- mod[, 2] } else if ( identical(test, testIndPois) ) { mod <- Rfast::score.glms(target, dataset, oiko = "poisson", logged = TRUE ) univariateModels$stat <- mod[, 1] univariateModels$pvalue <- mod[, 2] } else if ( identical(test, testIndLogistic) ) { mod <- Rfast::score.glms(target, dataset, oiko = "binomial", logged = TRUE) univariateModels$stat <- mod[, 1] univariateModels$pvalue <- mod[, 2] } else if ( identical(test, testIndMultinom) ) { mod <- Rfast::score.multinomregs(target, dataset, logged = TRUE) univariateModels$stat <- mod[, 1] univariateModels$pvalue <- mod[, 2] } else if ( identical(test, testIndGamma) ) { mod <- Rfast::score.gammaregs(target, dataset, logged = TRUE) univariateModels$stat <- mod[, 1] univariateModels$pvalue <- mod[, 2] } else if ( identical(test, censIndWR) ) { mod <- Rfast::score.weibregs(target, dataset, logged = TRUE ) univariateModels$stat <- mod[, 1] univariateModels$pvalue <- mod[, 2] } else univariateModels <- NULL if ( !is.null(univariateModels) ) { id <- which( is.na(univariateModels$stat) ) univariateModels$stat[id] <- 0 univariateModels$pvalue[id] <- 1 } univariateModels }