code
stringlengths
1
13.8M
try(dev.off(),silent=TRUE) par(mfrow = c(1, 3), mar = c(4, 4, 2, 1), oma = c(0, 0, 2, 0)) plot(airquality$Wind, airquality$Ozone, main = "Ozone and Wind") plot(airquality$Solar.R, airquality$Ozone, main = "Ozone and Solar Radiation") plot(airquality$Temp, airquality$Ozone, main = "Ozone and Temperature")
.load_fotmob_leagues <- function() { read.csv("https://raw.githubusercontent.com/JaseZiv/worldfootballR_data/3c6ff713a08a0ef5f9355b8eba791a899fe68189/raw-data/fotmob-leagues/all_leagues.csv", stringsAsFactors = F) } .fotmob_get_league_ids <- function(league_id = NULL, country = NULL, league_name = NULL) { leagues <- .load_fotmob_leagues() has_country <- !is.null(country) has_league_name <- !is.null(league_name) has_league_id <- !is.null(league_id) if(!has_league_id & !(has_country & has_league_name)) { stop( 'Must provide `league_id` or both of `country` and `league_name`.' ) } has_country_and_league_name <- has_country & has_league_name league_urls <- if(has_country_and_league_name) { n_country <- length(country) n_league_name <- length(league_name) if(n_country != n_league_name) { stop( sprintf( 'If providing `country` and `league_name`, length of each must be the same (%s != %s).', n_country, n_league_name ) ) } pairs <- list( country = country, league_name = league_name ) %>% purrr::transpose() purrr::map_dfr( pairs, ~dplyr::filter( leagues, .data$ccode == .x$country, .data$name == .x$league_name ) ) } else { leagues %>% dplyr::filter(.data$id %in% league_id) } n_league_urls <- nrow(league_urls) if(n_league_urls == 0) { stop( 'Could not find any leagues matching specified parameters.' ) } n_params <- ifelse( has_country_and_league_name, n_country, length(league_id) ) if(n_league_urls < n_params) { warning( sprintf( 'Found less leagues than specified (%s < %s).', n_league_urls, n_params ) ) } else if (n_league_urls > n_params) { warning( sprintf( 'Found more leagues than specified (%s > %s).', n_league_urls, n_params ) ) } league_urls$id } .fotmob_get_league_resp <- function(league_id) { main_url <- "https://www.fotmob.com/leagues?id=" url <- sprintf("%s%s", main_url, league_id) jsonlite::fromJSON(url) } fotmob_get_league_matches <- function(country, league_name, league_id) { ids <- .fotmob_get_league_ids( country = rlang::maybe_missing(country, NULL), league_name = rlang::maybe_missing(league_name, NULL), league_id = rlang::maybe_missing(league_id, NULL) ) fp <- purrr::possibly( .fotmob_get_league_matches, quiet = FALSE, otherwise = tibble::tibble() ) purrr::map_dfr( ids, .fotmob_get_league_matches ) } .fotmob_get_league_matches <- function(...) { resp <- .fotmob_get_league_resp(...) resp$fixtures %>% janitor::clean_names() %>% tibble::as_tibble() } fotmob_get_league_tables <- function(country, league_name, league_id) { ids <- .fotmob_get_league_ids( country = rlang::maybe_missing(country, NULL), league_name = rlang::maybe_missing(league_name, NULL), league_id = rlang::maybe_missing(league_id, NULL) ) fp <- purrr::possibly( .fotmob_get_league_tables, quiet = FALSE, otherwise = tibble::tibble() ) purrr::map_dfr( ids, fp ) } .fotmob_get_league_tables <- function(...) { resp <- .fotmob_get_league_resp(...) table <- resp$tableData$table %>% janitor::clean_names() %>% tibble::as_tibble() table %>% tidyr::pivot_longer( colnames(.), names_to = "table_type", values_to = "table" ) %>% tidyr::unnest_longer( .data$table ) %>% tidyr::unnest( .data$table ) }
list_packages <- function() { all_pkg <- installed.packages() %>% as.data.frame() %>% pull(Package) base_pkg <- installed.packages() %>% as.data.frame() %>% filter(Priority == "base") %>% pull(Package) all_pkg[!all_pkg %in% base_pkg] } restore_packages <- function(status = latest_r_version()) { versions <- c(status$latest, attr(status, "current")) versions_split <- strsplit(versions, ".", fixed = TRUE) names(versions_split) <- c("latest", "current") if (versions_split$latest[3] != versions_split$current[3]) { update_type <- "patch" } if (versions_split$latest[2] != versions_split$current[2]) { update_type <- "minor" } if (versions_split$latest[1] != versions_split$current[1]) { update_type <- "major" } prompt_msg <- paste( c("This is a %s update.", "Choose one of the following options to restore your packages:", "%s\n"), collapse = "\n" ) prompt_options <- switch(update_type, "major" = "1. Reinstall all the packages\n", "minor" = paste( c("1. Reinstall all the packages", "2. Copy all packages"), collapse = "\n"), "patch" = paste( c("Restoring packages is NOT necessary.", "Press [Enter] to continue (this is the only option in the list)"), collapse = "\n")) prompt_msg <- sprintf(prompt_msg, update_type, prompt_options) choice <- as.numeric(readline(prompt_msg)) while(!choice %in% c(1, 2, "", NA)) { message("!Invalid option. Please try again\n") choice <- as.numeric(readline(prompt_msg)) } if(choice %in% 1) { message("list of packages loaded") cat(sprintf("%s,", list_packages())) install.packages(list_packages()) } else if (update_type == "minor" & choice %in% 2) { old_version_path <- paste0(versions_split$current[1:2], collapse = ".") new_version_path <- paste0(versions_split$latest[1:2], collapse = ".") for (l in .libPaths()) { old_lib_path <- l new_lib_path <- str_replace(l, old_version_path, new_version_path) message(sprintf( "Copying from old LibPath\n%s/\nto new LibPath\n%s/\n...", old_lib_path, new_lib_path )) system(sprintf("mkdir -p %s", new_lib_path)) system(sprintf("cp -R %s/ %s/", old_lib_path, new_lib_path)) replace_libpath_profile(old_lib_path, new_lib_path) } message("Complete.") } else if(update_type == "patch") { message("\n") } }
`scores.rda` <- function (x, choices = c(1, 2), display = c("sp", "wa", "cn"), scaling = "species", const, correlation = FALSE, ...) { if (!is.null(x$na.action) && inherits(x$na.action, "exclude")) x <- ordiNApredict(x$na.action, x) tabula <- c("species", "sites", "constraints", "biplot", "regression", "centroids") names(tabula) <- c("sp", "wa", "lc", "bp", "reg", "cn") if (is.null(x$CCA)) tabula <- tabula[1:2] display <- match.arg(display, c("sites", "species", "wa", "lc", "bp", "cn", "reg"), several.ok = TRUE) if("sites" %in% display) display[display == "sites"] <- "wa" if("species" %in% display) display[display == "species"] <- "sp" take <- tabula[display] sumev <- x$tot.chi eigval <- eigenvals(x) if (inherits(x, "dbrda") && any(eigval < 0)) eigval <- eigval[eigval > 0] slam <- sqrt(eigval[choices]/sumev) nr <- if (is.null(x$CCA)) nrow(x$CA$u) else nrow(x$CCA$u) if (missing(const)) const <- sqrt(sqrt((nr-1) * sumev)) if (length(const) == 1) { const <- c(const, const) } if (inherits(x, "dbrda")) rnk <- x$CCA$poseig else rnk <- x$CCA$rank sol <- list() scaling <- scalingType(scaling = scaling, correlation = correlation) if ("species" %in% take) { v <- cbind(x$CCA$v, x$CA$v)[, choices, drop=FALSE] if (scaling) { scal <- list(1, slam, sqrt(slam))[[abs(scaling)]] v <- sweep(v, 2, scal, "*") if (scaling < 0) { v <- sweep(v, 1, x$colsum, "/") v <- v * sqrt(sumev / (nr - 1)) } v <- const[1] * v } if (nrow(v) > 0) sol$species <- v else sol$species <- NULL } if ("sites" %in% take) { wa <- cbind(x$CCA$wa, x$CA$u)[, choices, drop=FALSE] if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] wa <- sweep(wa, 2, scal, "*") wa <- const[2] * wa } sol$sites <- wa } if ("constraints" %in% take) { u <- cbind(x$CCA$u, x$CA$u)[, choices, drop=FALSE] if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] u <- sweep(u, 2, scal, "*") u <- const[2] * u } sol$constraints <- u } if ("biplot" %in% take && !is.null(x$CCA$biplot)) { b <- matrix(0, nrow(x$CCA$biplot), length(choices)) b[, choices <= rnk] <- x$CCA$biplot[, choices[choices <= rnk]] colnames(b) <- c(colnames(x$CCA$u), colnames(x$CA$u))[choices] rownames(b) <- rownames(x$CCA$biplot) if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] b <- sweep(b, 2, scal, "*") } sol$biplot <- b } if ("regression" %in% take) { b <- coef(x, norm = TRUE) reg <- matrix(0, nrow(b), length(choices)) reg[, choices <= rnk] <- b[, choices[choices <= rnk]] dimnames(reg) <- list(rownames(b), c(colnames(x$CCA$u), colnames(x$CA$u))[choices]) if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] reg <- sweep(reg, 2, scal, "*") } sol$regression <- reg } if ("centroids" %in% take) { if (is.null(x$CCA$centroids)) sol$centroids <- NA else { cn <- matrix(0, nrow(x$CCA$centroids), length(choices)) cn[, choices <= rnk] <- x$CCA$centroids[, choices[choices <= rnk]] colnames(cn) <- c(colnames(x$CCA$u), colnames(x$CA$u))[choices] rownames(cn) <- rownames(x$CCA$centroids) if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] cn <- sweep(cn, 2, scal, "*") cn <- const[2] * cn } sol$centroids <- cn } } if (length(sol)) { for (i in seq_along(sol)) { if (is.matrix(sol[[i]])) rownames(sol[[i]]) <- rownames(sol[[i]], do.NULL = FALSE, prefix = substr(names(sol)[i], 1, 3)) } } if (length(sol) == 1) sol <- sol[[1]] if (identical(const[1], const[2])) const <- const[1] attr(sol, "const") <- const sol }
propCI_exact <- function(x, n, l){ if (x == 0){ lw <- 0 up <- 1 - l[3] ^ (1/n) } else if (x == n){ lw <- l[3] ^ (1/n) up <- 1 } else{ lw <- qbeta(l[1], x, n - x + 1, lower.tail = T) up <- qbeta(l[2], x + 1, n - x, lower.tail = T) } return(c(lw, up)) }
predict.pipelearner <- function(pl) { if (is.null(pl$fits)) stop ("Models haven't learned yet. See ?learn") to_pred <- pl %>% recover_fits() to_pred %>% dplyr::select(fit, target, train, test, .id) %>% purrr::pmap_df(make_predictions) %>% tidyr::gather(key, val, -fits.id) %>% tidyr::separate(key, into = c("origin", "data")) %>% tidyr::spread(origin, val) %>% tidyr::unnest(predicted, true) %>% dplyr::mutate( fits_info = purrr::map(fits.id, ~ dplyr::filter(to_pred, .id == .) %>% dplyr::select(model, target, params, train_p)) ) %>% tidyr::unnest(fits_info) %>% dplyr::select(model, target, params, train_p, data, true, predicted, fits.id, dplyr::everything()) } make_predictions <- function(fit, target, train, test, .id) { tibble::tibble( true_train = list(as.data.frame(train)[[target]]), true_test = list(as.data.frame(test)[[target]]), predicted_train = list(predict(fit)), predicted_test = list(predict(fit, newdata = test)), fits.id = .id ) }
streamParserFromFileName <- function(fileName,encoding = getOption("encoding")) { if( Sys.info()["sysname"] == "Windows" ) { fromString <- TRUE } else { conn <- file(fileName,"r",encoding =encoding) if ( ! isOpen(conn) ) stop(paste("Error: file cannot be opened",fileName)) fromString <- tryCatch({ seek(conn) ; FALSE}, error =function(e) TRUE, finally= close(conn) ) } if ( fromString ) return( streamParserFromString( readLines( fileName, encoding=encoding)) ) else return( list( streamParserNextChar = function(stream) { if ( stream$pos != seek(stream$conn) ) seek(stream$conn,stream$pos) char <- readChar(stream$conn,nchars=1,useBytes = FALSE) if (length(char) == 0) list(status="eof",char="" ,stream=stream) else { stream$pos <- seek(stream$conn) if ( char == "\n" ) { stream$line <- stream$line + 1 stream$linePos <- 0 } else { stream$linePos <- stream$linePos + 1 } list(status="ok" ,char=char,stream=stream) } }, streamParserNextCharSeq = function(stream) { char <- readChar(stream$conn,nchars=1,useBytes = FALSE) if (length(char) == 0) list(status="eof",char="" ,stream=stream) else { stream$pos <- seek(stream$conn) if ( char == "\n" ) { stream$line <- stream$line + 1 stream$linePos <- 0 } else { stream$linePos <- stream$linePos + 1 } list(status="ok" ,char=char,stream=stream) } }, streamParserClose = function(stream) { close(stream$conn) ; stream$conn <- -1 ; invisible(NULL) }, streamParserPosition = function(stream) { list(fileName=stream$fileName, line=stream$line, linePos=stream$linePos+1, streamPos=stream$pos+1) }, conn = local({ conn <- file(fileName,"r",encoding =encoding) if ( ! isOpen(conn) ) stop(paste("Error: file cannot be opened.",fileName)) tryCatch( seek(conn) , error =function(e) stop(paste("Error: 'seek' not enabled for this connection", fileName))) conn }), pos = 0, line = 1, linePos = 0, fileName = fileName ) ) }
shift <- function(x,n){ length <- length(x) c(rep(NA,n),x)[1:length] } tsData <- function(data, vars =NULL, beepvar = NULL, dayvar = NULL, idvar = NULL, groupvar = NULL, lags = 1, scale = FALSE, center = FALSE, centerWithin = FALSE ){ if (!is.null(groupvar)){ groups <- unique(data[[groupvar]]) res <- lapply(seq_along(groups),function(g){ dat <- data[data[[groupvar]] == groups[g],names(data)!=groupvar] dat <- tsData(dat, vars, beepvar, dayvar, idvar) dat[[groupvar]] <- groups[g] dat }) return(do.call(rbind,res)) } . <- NULL deleteMissings = FALSE data <- as.data.frame(data) if (is.null(idvar)){ idvar <- "ID" data[[idvar]] <- 1 } if (is.null(dayvar)){ dayvar <- "DAY" data[[dayvar]] <- 1 } if (is.null(beepvar)){ beepvar <- "BEEP" data <- data %>% dplyr::group_by(.data[[dayvar]],.data[[idvar]]) %>% dplyr::mutate(BEEP = seq_len(n())) } if (is.null(vars)){ vars <- names(data[!names(data)%in%c(idvar,dayvar,beepvar)]) } data <- data[,c(vars,idvar,dayvar,beepvar)] for (v in vars){ data[,v] <- as.numeric(scale(data[,v], center, scale)) } MeansData <- data %>% dplyr::group_by(.data[[idvar]]) %>% dplyr::summarise_at(funs(mean(.,na.rm=TRUE)),.vars = vars) if (centerWithin){ if (length(unique(data[[idvar]])) > 1){ data <- data %>% dplyr::group_by(.data[[idvar]]) %>% dplyr::mutate_at(funs(scale(.,center=TRUE,scale=FALSE)),.vars = vars) } } augData <- data beepsummary <- data %>% group_by(.data[[idvar]],.data[[dayvar]],.data[[beepvar]]) %>% tally if (any(beepsummary$n!=1)){ print_and_capture <- function(x) { paste(capture.output(print(x)), collapse = "\n") } warning(paste0("Some beeps are recorded more than once! Results are likely unreliable.\n\n",print_and_capture( beepsummary %>% filter(.data[["n"]]!=1) %>% select(.data[[idvar]],.data[[dayvar]],.data[[beepvar]]) %>% as.data.frame ))) } beepsPerDay <- dplyr::summarize(data %>% group_by(.data[[idvar]],.data[[dayvar]]), first = min(.data[[beepvar]],na.rm=TRUE), last = max(.data[[beepvar]],na.rm=TRUE)) allBeeps <- expand.grid(unique(data[[idvar]]),unique(data[[dayvar]]),seq(min(data[[beepvar]],na.rm=TRUE),max(data[[beepvar]],na.rm=TRUE))) names(allBeeps) <- c(idvar,dayvar,beepvar) allBeeps <- allBeeps %>% dplyr::left_join(beepsPerDay, by = c(idvar,dayvar)) %>% dplyr::group_by(.data[[idvar]],.data[[dayvar]]) %>% dplyr::filter(.data[[beepvar]] >= .data$first, .data[[beepvar]] <= .data$last)%>% dplyr::arrange(.data[[idvar]],.data[[dayvar]],.data[[beepvar]]) augData <- augData %>% dplyr::right_join(allBeeps, by = c(idvar,dayvar,beepvar)) %>% arrange(.data[[idvar]],.data[[dayvar]],.data[[beepvar]]) data_c <- augData %>% ungroup %>% dplyr::select(all_of(vars)) data_l <- do.call(cbind,lapply(lags, function(l){ data_lagged <- augData %>% dplyr::group_by(.data[[idvar]],.data[[dayvar]]) %>% dplyr::mutate_at(funs(shift),.vars = vars) %>% ungroup %>% dplyr::select(all_of(vars)) names(data_lagged) <- paste0(vars,"_lag",l) data_lagged })) isNA <- rowSums(is.na(data_c)) == ncol(data_c) data_c <- data_c[!isNA,] data_l <- data_l[!isNA,] fulldata <- as.data.frame(cbind(data_l,data_c)) return(fulldata) }
library(testthat) library(OpenMx) data(demoOneFactor) factorModel <- mxModel( "One Factor", mxMatrix("Full", 5, 1, values=0.2, free=TRUE, name="A"), mxMatrix("Symm", 1, 1, values=1, free=FALSE, name="L"), mxMatrix("Diag", 5, 5, values=1, free=TRUE, name="U"), mxAlgebra(A %*% L %*% t(A) + U, name="R"), mxExpectationNormal("R", dimnames = names(demoOneFactor)), mxFitFunctionML(), mxData(cov(demoOneFactor), type="cov", numObs=500), mxComputeSequence(list( mxComputeNumericDeriv(), mxComputeReportDeriv())) ) fitModel <- mxRun(factorModel) fullH <- fitModel$output$hessian omxCheckEquals(fitModel$compute$steps[[1]]$output$probeCount, 4 * (10^2+10)) kh <- fullH[3:10,3:10] kh[1,2] <- kh[1,2] + 5 kh[2,1] <- kh[2,1] - 5 kh[3,3] <- NA limModel <- mxModel(factorModel, mxComputeSequence(list( mxComputeNumericDeriv(verbose=0, knownHessian=kh), mxComputeReportDeriv()))) limModel <- expect_warning(mxRun(limModel), "knownHessian[1,2] is not symmetric", fixed=TRUE) omxCheckCloseEnough(limModel$output$hessian[,1:2], fullH[,1:2], 1e-3) omxCheckEquals(limModel$compute$steps[[1]]$output$probeCount, 160)
predict.nft = function( object, x.test=object$x.train, tc=1, XPtr=TRUE, K=0, events=object$events, FPD=FALSE, probs=c(0.025, 0.975), take.logs=TRUE, na.rm=FALSE, fmu=object$fmu, soffset=object$soffset, drawMuTau=object$drawMuTau, ...) { ptm <- proc.time() nd=object$ndpost m=object$ntree[1] if(length(object$ntree)==2) mh=object$ntree[2] else mh=object$ntreeh xi=object$xicuts n = nrow(object$x.train) p = ncol(object$x.train) np = nrow(x.test) xp = t(x.test) if(is.null(object)) stop("No fitted model specified!\n") if(length(K)==0) { K=0 take.logs=FALSE } if(length(drawMuTau)==0) drawMuTau=0 q.lower=min(probs) q.upper=max(probs) if(XPtr) { res=.Call("cpsambrt_predict", xp, m, mh, nd, xi, tc, object, PACKAGE="nftbart" ) res$f.test.=res$f.test.+fmu res$f.test.mean.=apply(res$f.test.,2,mean) res$f.test.lower.= apply(res$f.test.,2,quantile,probs=q.lower,na.rm=na.rm) res$f.test.upper.= apply(res$f.test.,2,quantile,probs=q.upper,na.rm=na.rm) res$s.test.mean.=apply(res$s.test.,2,mean) res$s.test.lower.= apply(res$s.test.,2,quantile,probs=q.lower,na.rm=na.rm) res$s.test.upper.= apply(res$s.test.,2,quantile,probs=q.upper,na.rm=na.rm) } else { res=list() } if(np>0) { res.=.Call("cprnft", object, xp, tc, PACKAGE="nftbart" ) res$f.test=res.$f.test+fmu res$fmu=fmu m=length(soffset) if(m==0) soffset=0 else if(m>1) soffset=sqrt(mean(soffset^2, na.rm=TRUE)) res$s.test=exp(res.$s.test-soffset) res$s.test.mean =apply(res$s.test, 2, mean) res$s.test.lower=apply(res$s.test, 2, quantile, probs=q.lower, na.rm=na.rm) res$s.test.upper=apply(res$s.test, 2, quantile, probs=q.upper, na.rm=na.rm) res$soffset=soffset res$f.test.mean =apply(res$f.test, 2, mean) res$f.test.lower=apply(res$f.test, 2, quantile,probs=q.lower,na.rm=na.rm) res$f.test.upper=apply(res$f.test, 2, quantile,probs=q.upper,na.rm=na.rm) if(K>0) { if(length(events)==0) { events <- unique(quantile(object$z.train.mean, probs=(1:K)/(K+1))) attr(events, 'names') <- NULL } else if(take.logs) events=log(events) events.matrix=(class(events)[1]=='matrix') if(events.matrix) K=ncol(events) else K <- length(events) if(FPD) { H=np/n if(drawMuTau>0) { for(h in 1:H) { if(h==1) { mu. = object$dpmu sd. = object$dpsd } else { mu. = cbind(mu., object$dpmu) sd. = cbind(sd., object$dpsd) } } mu. = mu.*res$s.test sd. = sd.*res$s.test mu. = mu.+res$f.test } else { mu. = res$f.test sd. = res$s.test } if(K>1) { res$f.test = NULL if(length(res$f.test.)>0) res$f.test. = NULL res$s.test = NULL if(length(res$s.test.)>0) res$s.test. = NULL } surv.fpd=list() pdf.fpd =list() surv.test=list() pdf.test =list() for(i in 1:H) { h=(i-1)*n+1:n for(j in 1:K) { if(j==1) { surv.fpd[[i]]=list() pdf.fpd[[i]] =list() surv.test[[i]]=list() pdf.test[[i]] =list() } surv.fpd[[i]][[j]]= apply(matrix(pnorm(events[j], mu.[ , h], sd.[ , h], lower.tail=FALSE), nrow=nd, ncol=n), 1, mean) pdf.fpd[[i]][[j]]= apply(matrix(dnorm(events[j], mu.[ , h], sd.[ , h]), nrow=nd, ncol=n), 1, mean) if(i==1 && j==1) { res$surv.fpd=cbind(surv.fpd[[1]][[1]]) res$pdf.fpd =cbind(pdf.fpd[[1]][[1]]) } else { res$surv.fpd=cbind(res$surv.fpd, surv.fpd[[i]][[j]]) res$pdf.fpd =cbind(res$pdf.fpd, pdf.fpd[[i]][[j]]) } if(K==1) { surv.test[[i]][[j]]=matrix(pnorm(events[j], mu.[ , h], sd.[ , h], lower.tail=FALSE), nrow=nd, ncol=n) pdf.test[[i]][[j]] =matrix(dnorm(events[j], mu.[ , h], sd.[ , h]), nrow=nd, ncol=n) if(i==1 && j==1) { res$surv.test=cbind(surv.test[[1]][[1]]) res$pdf.test =cbind(pdf.test[[1]][[1]]) } else { res$surv.test=cbind(res$surv.test, surv.test[[i]][[j]]) res$pdf.test =cbind(res$pdf.test, pdf.test[[i]][[j]]) } } } } res$surv.fpd.mean=apply(cbind(res$surv.fpd), 2, mean) res$surv.fpd.lower= apply(cbind(res$surv.fpd), 2, quantile, probs=q.lower) res$surv.fpd.upper= apply(cbind(res$surv.fpd), 2, quantile, probs=q.upper) res$pdf.fpd.mean =apply(cbind(res$pdf.fpd), 2, mean) if(K==1) { res$surv.test.mean=apply(res$surv.test, 2, mean) res$pdf.test.mean =apply(res$pdf.test, 2, mean) } } else if(drawMuTau>0) { res$surv.test=matrix(0, nrow=nd, ncol=np*K) H=max(c(object$dpn.)) events.=events for(i in 1:np) { if(events.matrix) events.=events[i, ] mu.=res$f.test[ , i] sd.=res$s.test[ , i] for(j in 1:K) { k=(i-1)*K+j for(h in 1:H) { res$surv.test[ , k]=res$surv.test[ , k]+ object$dpwt.[ , h]* pnorm(events.[j], mu.+sd.*object$dpmu.[ , h], sd.*object$dpsd.[ , h], FALSE) } } } res$surv.test.mean=apply(res$surv.test, 2, mean) } if(take.logs) res$events=exp(events) else res$events=events } res$K=K } else { res$f.test=res$f.test. res$s.test=res$s.test. } res$probs=probs res$elapsed <- (proc.time()-ptm)['elapsed'] attr(res$elapsed, 'names')=NULL return(res) }
jNoComb <- function(n,k,alpha){ C <- 1 for (i in 1:k){ C <- C * (n-i+1)/i*alpha*(1-alpha) } C <- C * (1-alpha)^(n-k-k) return(C) }
context("pd0 and d.prime0 arguments to discrim") test_that("Expect error if more than one of pd0/d.prime0 has been specified", { expect_error( discrim(26, 75, method = "triangle", d.prime0 = 2, pd0=.2, test = "similarity"), "Only specify one of") expect_error( discrim(26, 75, method = "triangle", test = "similarity") , "Either 'pd0' or 'd.prime0' has to be specified for a similarity test") }) test_that("Specification of different scales give the same results:", { T1 <- discrim(26, 75, method = "triangle", pd0 = .2, test = "similarity") T2 <- discrim(26, 75, method = "triangle", test = "similarity", d.prime0 = psyinv(pd2pc(.2, 1/3), "triangle")) expect_equal(T1$p.value, T2$p.value, tolerance=1e-3) }) test_that("Test boundary values for d.prime0 (-1, 0, 1, Inf):", { expect_that( discrim(26, 75, method = "triangle", d.prime0 = -1, test = "similarity") , throws_error("d.prime0 >= 0")) expect_that( discrim(26, 75, method = "triangle", d.prime0 = 0, test = "similarity") , gives_warning("'d.prime0' should be positive for a similarity test")) expect_output( print(discrim(26, 75, method = "triangle", d.prime0 = 1, test = "similarity")) , "p-value = 0.1274") expect_output( print(discrim(26, 75, method = "triangle", d.prime0 = Inf, stat="like", test="similarity")) , "d-prime is less than Inf") }) test_that("Test boundary values for pd0 (-1, 0, .2. 1. 2):", { expect_that( discrim(26, 75, method = "triangle", pd0 = -1, test = "similarity") , throws_error("pd0 >= 0 is not TRUE")) expect_that( discrim(26, 75, method = "triangle", pd0 = 0, test = "similarity") , gives_warning("'pd0' should be positive for a similarity test")) expect_output( print(discrim(26, 75, method = "triangle", pd0 = .2, test = "similarity")) , "'exact' binomial test: p-value = 0.02377") expect_output( print(discrim(26, 75, method = "triangle", pd0 = 1, test = "similarity")) , "'exact' binomial test: p-value = < 2.2e-16") expect_error( discrim(26, 75, method = "triangle", pd0 = 2, test = "similarity") , "pd0 <= 1 is not TRUE") }) test_that("Test that all statistics works in the limit of pd0 and d.prime0", { Stat <- eval(formals(discrim)$statistic) pvals <- sapply(Stat, function(stat) { discrim(26, 75, method = "triangle", d.prime0 = Inf, stat=stat, test="similarity")$p.value }) expect_equivalent(pvals, rep(0, length(Stat))) pvals <- sapply(Stat, function(stat) { discrim(26, 75, method = "triangle", d.prime0 = Inf, stat=stat, test="diff")$p.value }) expect_equivalent(pvals, rep(1, length(Stat))) pvals <- sapply(Stat, function(stat) { discrim(26, 75, method = "triangle", pd0=1, stat=stat, test="simi")$p.value }) expect_equivalent(pvals, rep(0, length(Stat))) pvals <- sapply(Stat, function(stat) { discrim(26, 75, method = "triangle", pd0=1, stat=stat, test="diff")$p.value }) expect_equivalent(pvals, rep(1, length(Stat))) }) test_that("Test error at invalid args for pd0 and d.prime0", { expect_error( discrim(26, 75, pd0=1:2) ) expect_error( discrim(26, 75, pd0="2") ) expect_error( discrim(26, 75, d.prime0=1:2) ) expect_error( discrim(26, 75, d.prime="2") ) expect_error( discrim(26, 75, pd0=list(1)) ) }) test_that("Printing alternative hypothesis in terms of d-prime (default):", { expect_output( print(discrim(26, 75, method = "triangle")) , "Alternative hypothesis: d-prime is greater than 0 ") expect_equal( discrim(26, 75, method = "triangle")$pd0 , 0) expect_equal( discrim(26, 75, method = "triangle")$alt.scale , "d-prime") expect_equal( discrim(26, 75, method = "triangle", test="simil", pd0=.2)$alt.scale , "pd") expect_equal( discrim(26, 75, method = "triangle", test="simil", d.prime0=2)$alt.scale , "d-prime") }) test_that("Test that alternative hypothesis uses d.prime/pd", { expect_output( print(discrim(26, 75, d.prime=0, method = "triangle")) , "Alternative hypothesis: d-prime is greater than 0 ") expect_output( print(discrim(26, 75, pd0=0, method = "triangle")) , "Alternative hypothesis: pd is greater than 0 ") })
position_finder <- function(vec) { if(length(which(vec == 1)) != 0) { return(min(which(vec == 1))) } else { return(999999) } }
"level.setCOP" <- function(cop=NULL, para=NULL, getlevel=NULL, delu=0.001, lines=FALSE, ...) { zz <- level.curvesCOP(cop=cop, para=para, getlevel=getlevel, delt=NULL, ploton=FALSE, plotMW=FALSE, lines=lines, delu=delu, ramp=FALSE, ...) return(zz) }
"ex_node"
knitr::opts_chunk$set( collapse = TRUE, comment = " warning = F, fig.align = "center" ) devtools::load_all() library(tidyverse) lubridate_download_history <- tidyverse_cran_downloads %>% filter(package == "lubridate") %>% ungroup() lubridate_download_history %>% head(10) %>% knitr::kable() p1 <- lubridate_download_history %>% time_decompose(count, method = "stl", frequency = "1 week", trend = "3 months") %>% anomalize(remainder) %>% plot_anomaly_decomposition() + ggtitle("STL Decomposition") p2 <- lubridate_download_history %>% time_decompose(count, method = "twitter", frequency = "1 week", trend = "3 months") %>% anomalize(remainder) %>% plot_anomaly_decomposition() + ggtitle("Twitter Decomposition") p1 p2 set.seed(100) x <- rnorm(100) idx_outliers <- sample(100, size = 5) x[idx_outliers] <- x[idx_outliers] + 10 qplot(1:length(x), x, main = "Simulated Anomalies", xlab = "Index") iqr_outliers <- iqr(x, alpha = 0.05, max_anoms = 0.2, verbose = TRUE)$outlier_report gesd_outliers <- gesd(x, alpha = 0.05, max_anoms = 0.2, verbose = TRUE)$outlier_report ggsetup <- function(data) { data %>% ggplot(aes(rank, value, color = outlier)) + geom_point() + geom_line(aes(y = limit_upper), color = "red", linetype = 2) + geom_line(aes(y = limit_lower), color = "red", linetype = 2) + geom_text(aes(label = index), vjust = -1.25) + theme_bw() + scale_color_manual(values = c("No" = " expand_limits(y = 13) + theme(legend.position = "bottom") } p3 <- iqr_outliers %>% ggsetup() + ggtitle("IQR: Top outliers sorted by rank") p4 <- gesd_outliers %>% ggsetup() + ggtitle("GESD: Top outliers sorted by rank") p3 p4
"HeartRate"
aic.dof <- function (RSS, n, DoF, sigmahat) { aic_temp <- RSS/n + 2 * (DoF/n) * sigmahat^2 return(aic_temp) }
cor <- function(x, y = NULL, use = "everything", method = c("pearson", "kendall", "spearman")) { na.method <- pmatch(use, c("all.obs", "complete.obs", "pairwise.complete.obs", "everything", "na.or.complete")) if(is.na(na.method)) stop("invalid 'use' argument") method <- match.arg(method) if(is.data.frame(y)) y <- as.matrix(y) if(is.data.frame(x)) x <- as.matrix(x) if(!is.matrix(x) && is.null(y)) stop("supply both 'x' and 'y' or a matrix-like 'x'") if(!(is.numeric(x) || is.logical(x))) stop("'x' must be numeric") stopifnot(is.atomic(x)) if(!is.null(y)) { if(!(is.numeric(y) || is.logical(y))) stop("'y' must be numeric") stopifnot(is.atomic(y)) } Rank <- function(u) { if(length(u) == 0L) u else if(is.matrix(u)) { if(nrow(u) > 1L) apply(u, 2L, rank, na.last="keep") else row(u) } else rank(u, na.last="keep") } if(method == "pearson") .Call(C_cor, x, y, na.method, FALSE) else if (na.method %in% c(2L, 5L)) { if (is.null(y)) { .Call(C_cor, Rank(na.omit(x)), NULL, na.method, method == "kendall") } else { nas <- attr(na.omit(cbind(x,y)), "na.action") dropNA <- function(x, nas) { if(length(nas)) { if (is.matrix(x)) x[-nas, , drop = FALSE] else x[-nas] } else x } .Call(C_cor, Rank(dropNA(x, nas)), Rank(dropNA(y, nas)), na.method, method == "kendall") } } else if (na.method != 3L) { x <- Rank(x) if(!is.null(y)) y <- Rank(y) .Call(C_cor, x, y, na.method, method == "kendall") } else { if (is.null(y)) { ncy <- ncx <- ncol(x) if(ncx == 0) stop("'x' is empty") r <- matrix(0, nrow = ncx, ncol = ncy) for (i in seq_len(ncx)) { for (j in seq_len(i)) { x2 <- x[,i] y2 <- x[,j] ok <- complete.cases(x2, y2) x2 <- rank(x2[ok]) y2 <- rank(y2[ok]) r[i, j] <- if(any(ok)) .Call(C_cor, x2, y2, 1L, method == "kendall") else NA } } r <- r + t(r) - diag(diag(r)) rownames(r) <- colnames(x) colnames(r) <- colnames(x) r } else { if(length(x) == 0L || length(y) == 0L) stop("both 'x' and 'y' must be non-empty") matrix_result <- is.matrix(x) || is.matrix(y) if (!is.matrix(x)) x <- matrix(x, ncol=1L) if (!is.matrix(y)) y <- matrix(y, ncol=1L) ncx <- ncol(x) ncy <- ncol(y) r <- matrix(0, nrow = ncx, ncol = ncy) for (i in seq_len(ncx)) { for (j in seq_len(ncy)) { x2 <- x[,i] y2 <- y[,j] ok <- complete.cases(x2, y2) x2 <- rank(x2[ok]) y2 <- rank(y2[ok]) r[i, j] <- if(any(ok)) .Call(C_cor, x2, y2, 1L, method == "kendall") else NA } } rownames(r) <- colnames(x) colnames(r) <- colnames(y) if(matrix_result) r else drop(r) } } } cov <- function(x, y = NULL, use = "everything", method = c("pearson", "kendall", "spearman")) { na.method <- pmatch(use, c("all.obs", "complete.obs", "pairwise.complete.obs", "everything", "na.or.complete")) if(is.na(na.method)) stop("invalid 'use' argument") method <- match.arg(method) if(is.data.frame(y)) y <- as.matrix(y) if(is.data.frame(x)) x <- as.matrix(x) if(!is.matrix(x) && is.null(y)) stop("supply both 'x' and 'y' or a matrix-like 'x'") stopifnot(is.numeric(x) || is.logical(x), is.atomic(x)) if(!is.null(y)) stopifnot(is.numeric(y) || is.logical(y), is.atomic(y)) Rank <- function(u) { if(length(u) == 0L) u else if(is.matrix(u)) { if(nrow(u) > 1L) apply(u, 2L, rank, na.last="keep") else row(u) } else rank(u, na.last="keep") } if(method == "pearson") .Call(C_cov, x, y, na.method, method == "kendall") else if (na.method %in% c(2L, 5L)) { if (is.null(y)) { .Call(C_cov, Rank(na.omit(x)), NULL, na.method, method == "kendall") } else { nas <- attr(na.omit(cbind(x,y)), "na.action") dropNA <- function(x, nas) { if(length(nas)) { if (is.matrix(x)) x[-nas, , drop = FALSE] else x[-nas] } else x } .Call(C_cov, Rank(dropNA(x, nas)), Rank(dropNA(y, nas)), na.method, method == "kendall") } } else if (na.method != 3L) { x <- Rank(x) if(!is.null(y)) y <- Rank(y) .Call(C_cov, x, y, na.method, method == "kendall") } else stop("cannot handle 'pairwise.complete.obs'") } var <- function(x, y = NULL, na.rm = FALSE, use) { if(missing(use)) use <- if(na.rm) "na.or.complete" else "everything" na.method <- pmatch(use, c("all.obs", "complete.obs", "pairwise.complete.obs", "everything", "na.or.complete")) if(is.na(na.method)) stop("invalid 'use' argument") if (is.data.frame(x)) x <- as.matrix(x) else stopifnot(is.atomic(x)) if (is.data.frame(y)) y <- as.matrix(y) else stopifnot(is.atomic(y)) .Call(C_cov, x, y, na.method, FALSE) } cov2cor <- function(V) { p <- (d <- dim(V))[1L] if(!is.numeric(V) || length(d) != 2L || p != d[2L]) stop("'V' is not a square numeric matrix") Is <- sqrt(1/diag(V)) if(any(!is.finite(Is))) warning("diag(.) had 0 or NA entries; non-finite result is doubtful") r <- V r[] <- Is * V * rep(Is, each = p) r[cbind(1L:p,1L:p)] <- 1 r }
"mls"
"errormatrix" <- function(true, predicted, relative=FALSE) { stopifnot(length(true)==length(predicted)) tnames <- if(is.factor(true)) levels(true) else unique(true) pnames <- if(is.factor(predicted)) levels(predicted) else unique(predicted) allnames <- sort(union(tnames, pnames)) n <- length(allnames) true <- factor(true, levels = allnames) predicted <- factor(predicted, levels = allnames) tab <- table(true, predicted) mt <- tab * (matrix(1, ncol = n, nrow = n) - diag( , n, n)) rowsum <- rowSums(mt) colsum <- colSums(mt) result <- rbind(cbind(tab, rowsum), c(colsum, sum(colsum))) dimnames(result) <- list("true" = c(allnames, "-SUM-"), "predicted" = c(allnames, "-SUM-")) if(relative){ total <- sum(result[1:n, 1:n]) n1 <- n + 1 result[n1, 1:n] <- if(result[n1, n1] != 0) result[n1, 1:n] / result[n1, n1] else 0 rownorm <- function(Row,Length) { return( if(any(Row[1:Length]>0)) Row/sum(Row[1:Length]) else rep(0,Length+1) ) } result[1:n,] <- t(apply(result[1:n,], 1, rownorm, Length=n)) result[n1, n1] <- result[n1, n1] / total } return(result) }
bbox_from_file <- function(file_path, crs_out) { if (!file.exists(file_path)) { stop("Specified file path does not exist. Aborting!") } if(suppressWarnings(is.character(crs_out) && !is.na(as.numeric(crs_out)))) { crs_out <- as.numeric(crs_out) } else { if (crs_out == "MODIS Sinusoidal") { crs_out <- sf::st_crs("+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs") } } if (!inherits(crs_out, "crs")) { crs_out <- try(sf::st_crs(crs_out)) if (!inherits(crs_out, "crs")) { stop("`crs_out` is not an object of (or cohercible to) class `crs`.", " Aborting!") } } if (!inherits(try(vectin <- sf::st_read(file_path, quiet = TRUE), silent = TRUE), "try-error")) { crs_in <- st_crs(vectin) bbox_in <- matrix(as.numeric(sf::st_bbox(vectin)), ncol = 2, dimnames = list(c("x", "y"), c("min", "max"))) } else if (!inherits(try(suppressWarnings(rastin <- raster::raster(file_path)), silent = TRUE), "try-error")) { crs_in <- sf::st_crs(rastin) bbox_in <- matrix(as.numeric(sf::st_bbox(rastin)), ncol = 2, dimnames = list(c("x", "y"), c("min", "max"))) } else { stop(file_path, "does not appear to be a valid spatial", "file. Please check your inputs. Aborting!") } bbox_out <- reproj_bbox(bbox_in, crs_in, crs_out, enlarge = TRUE) return(bbox_out) }
richJackA1 <- function(cntVec) { cntVec <- round(cntVec) if(is.matrix(cntVec) || is.data.frame(cntVec)) cntVec <- rowSums(cntVec) Sobs <- sum(cntVec > 0) f1 <- sum(cntVec == 1) return(Sobs + f1) } richJackA2 <- function(cntVec) { cntVec <- round(cntVec) if(is.matrix(cntVec) || is.data.frame(cntVec)) cntVec <- rowSums(cntVec) Sobs <- sum(cntVec > 0) f1 <- sum(cntVec == 1) f2 <- sum(cntVec == 2) return(Sobs + 2 * f1 - f2) } richRenLau <- function(cntVec) { cntVec <- round(cntVec) if(is.matrix(cntVec) || is.data.frame(cntVec)) cntVec <- rowSums(cntVec) fk <- table(cntVec[cntVec > 0]) k <- as.numeric(names(fk)) n <- sum(cntVec) C <- if(is.na(fk["1"])) 1 - fk["1"] / n else 1 pik <- 1 - (1 - (C * k / n))^n nuk <- 1 / pik - 1 shadows <- round(fk * nuk) return(sum(fk, shadows)) }
"genepos"
cancelOrder = function(token = '', live = FALSE, orderId = '') { headers = add_headers("accept" = "application/json","Authorization" = paste("Bearer",token)) url = paste0('https://api-invest.tinkoff.ru/openapi/',ifelse(live == FALSE,'sandbox/',''),'orders/cancel?orderId=',orderId) raw_data = POST(url, headers) return(content(raw_data, as = "parsed")) }
sparkmat <- function(x, locs = NULL, w = NULL, h = NULL, lcol = NULL, yscales = NULL, tile.shading = NULL, tile.margin = unit(c(0,0,0,0), 'points'), tile.pars = NULL, just = c('right', 'top'), new = TRUE, ...) { if (new) grid.newpage() if (!is.null(x[[1]]) && is.null(yscales)) { yscales <- vector(mode="list", length=length(x[[1]])) for (i in 1:length(x)) { for (j in 1:length(x[[1]])) { yscales[[j]] <- c(min(yscales[[j]][1], min(x[[i]][,j], na.rm=TRUE)), max(yscales[[j]][2], max(x[[i]][,j], na.rm=TRUE))) } } } vectorize <- function(x,y){ x.v <- rep(x, length(y)) y.v <- as.numeric(matrix(y, nrow = length(x), ncol = length(y), byrow = TRUE)) return(data.frame(x = x.v, y = y.v)) } if (is.null(locs)) { mats.down <- floor(sqrt(length(x))) mats.across <- ceiling(length(x) / mats.down) locs <- vectorize(x = (1:mats.across) / mats.across, y = (mats.down:1) / mats.down) locs$x <- unit(locs$x, 'npc') locs$y <- unit(locs$y, 'npc') if (is.null(w)) w <- unit(1/mats.across, 'npc') if (is.null(h)) h <- unit(1/mats.down, 'npc') } else { if (new) { pushViewport(viewport(x=0.15, y=0.1, width=0.75, height=0.75, just=c("left", "bottom"), xscale=range(pretty(locs[,1])), yscale=range(pretty(locs[,2])))) grid.xaxis() grid.yaxis() } } if (!is.unit(w)) w <- unit(w, "native") if (!is.unit(h)) h <- unit(h, "native") for (i in 1:length(x)) { if (is.unit(locs[i,1])) xloc <- locs[i,1] else xloc <- unit(locs[i,1], "native") if (is.unit(locs[i,2])) yloc <- locs[i,2] else yloc <- unit(locs[i,2], "native") sparklines.viewport <- viewport(x=xloc, y=yloc, just=just, width=w, height=h) pushViewport(sparklines.viewport) if (!is.null(tile.pars)) grid.rect(gp=tile.pars) sparklines(x[[i]], new=FALSE, lcol=lcol, yscale=yscales, outer.margin=tile.margin, outer.margin.pars = gpar(fill = tile.shading[i], col=tile.shading[i]), xaxis = FALSE, yaxis = FALSE) popViewport(1) } }
plot_local.multiple.cross.regression <- function(Lst, lmax, nsig=2, xaxt="s"){ if (xaxt[1]!="s"){ at <- xaxt[[1]] label <- xaxt[[2]] xaxt <- "n" } val <- Lst$cor$vals reg.vals <- Lst$reg$rval[,,-1] reg.stdv <- Lst$reg$rstd[,,-1] reg.lows <- Lst$reg$rlow[,,-1] reg.upps <- Lst$reg$rupp[,,-1] reg.pval <- Lst$reg$rpva[,,-1] reg.order <- Lst$reg$rord[,,-1]-1 reg.order[reg.order==0] <- reg.vals[reg.order==0] <- reg.stdv[reg.order==0] <- reg.lows[reg.order==0] <- reg.upps[reg.order==0] <- reg.pval[reg.order==0] <- NA lag.max <- trunc((ncol(val)-1)/2) lag0 <- lag.max+1 YmaxR <- Lst$YmaxR N <- length(YmaxR) xxnames <- names(Lst$data) lag.labs <- c(paste("lead",lag.max:1),paste("lag",0:lag.max)) reg.vars <- t(matrix(xxnames,length(Lst$data),N)) reg.sel <- reg.order<=nsig & reg.pval<=0.05 reg.vals.sig <- reg.vals*reg.sel reg.lows.sig <- reg.lows*reg.sel reg.upps.sig <- reg.upps*reg.sel reg.order.sig <- reg.order*reg.sel reg.vals.sig[reg.vals.sig==0] <- reg.lows.sig[reg.lows.sig==0] <- reg.upps.sig[reg.upps.sig==0] <- reg.order.sig[reg.order.sig==0] <- NA mycolors <- RColorBrewer::brewer.pal(n=8, name="Dark2") par(mfcol=c(lmax+1,2), las=1, pty="m", mar=c(2,3,1,0)+.1, oma=c(1.2,1.2,0,0)) ymin <- min(reg.vals,na.rm=TRUE) ymax <- max(reg.vals,na.rm=TRUE) mark <- paste0("\u00A9jfm-wavemulcor3.1.0_",Sys.time()," ") for(i in c(-lmax:0,lmax:1)+lag0) { matplot(1:N,reg.vals[,i,], ylim=c(ymin-0.1,ymax+0.1), type="n", xaxt=xaxt, lty=3, col=8, xlab="", ylab="", main=lag.labs[i]) for (j in dim(reg.stdv)[3]:1){ shade <- 1.96*reg.stdv[,i,j] polygon(c(1:N,rev(1:N)),c(-shade,rev(shade)), col=gray(0.8,alpha=0.2), border=NA) } matlines(1:N,reg.vals[,i,], lty=1, col=8) if(abs(ymax-ymin)<3) lo<-2 else lo<-4 abline(h=seq(floor(ymin),ceiling(ymax),length.out=lo),col=8) matlines(1:N, reg.vals.sig[,i,], lty=1, lwd=2, col=mycolors) matlines(1:N, reg.lows.sig[,i,], lty=2, col=mycolors) matlines(1:N, reg.upps.sig[,i,], lty=2, col=mycolors) mtext(mark, side=1, line=-1, adj=1, col=rgb(0,0,0,.1),cex=.2) col <- (reg.order[,i,]<=3)*1 +(reg.order[,i,]>3)*8 xvar <- t(t(which(abs(diff(sign(diff(reg.vals[,i,]))))==2,arr.ind=TRUE))+c(1,0)) text(xvar, reg.vals[xvar,i,], labels=reg.vars[xvar,], col=col,cex=.3) text(xvar, reg.vals[xvar,i,], labels=reg.order[xvar,i,],pos=1, col=col,cex=.3) if (length(unique(YmaxR))==1) { mtext(xxnames[YmaxR][1], at=1, side=3, line=-1, cex=.5) } else { xvaru <- t(t(which(diff(sign(diff(as.matrix(val[,i]))))==-2))+1) xvarl <- t(t(which(diff(sign(diff(as.matrix(val[,i]))))==2))+1) mtext(xxnames[YmaxR][xvaru], at=xvaru, side=3, line=-.5, cex=.3) mtext(xxnames[YmaxR][xvarl], at=xvarl, side=3, line=-1, cex=.3) } if (xaxt!="s") axis(side=1, at=at, labels=label) } par(las=0) mtext('time', side=1, outer=TRUE, adj=0.5) mtext('Local Multiple Cross-Regression', side=2, outer=TRUE, adj=0.5) return() }
context("REST API") test_that("testing REST API Functionality", { n <- 2 object <- "Contact" prefix <- paste0("REST-", as.integer(runif(1,1,100000)), "-") new_contacts <- tibble(FirstName = rep("Test", n), LastName = paste0("REST-Contact-Create-", 1:n), My_External_Id__c = paste0(prefix, letters[1:n])) created_records <- sf_create(new_contacts, object_name = object, api_type="REST") expect_is(created_records, "tbl_df") expect_equal(names(created_records), c("id", "success")) expect_equal(nrow(created_records), n) expect_is(created_records$success, "logical") new_campaign_members <- tibble(CampaignId = "", ContactId = "0036A000002C6MbQAK") create_error_records <- sf_create(new_campaign_members, object_name = "CampaignMember", api_type = "REST") expect_is(create_error_records, "tbl_df") expect_equal(names(create_error_records), c("success", "errors")) expect_equal(nrow(create_error_records), 1) expect_is(create_error_records$errors, "list") expect_equal(length(create_error_records$errors[1][[1]]), 2) expect_equal(names(create_error_records$errors[1][[1]][[1]]), c("statusCode", "message", "fields")) new_campaign_members <- tibble(CampaignId = "7013s000000j6n1AAA", ContactId = "0036A000002C6MbQAK") create_error_records <- sf_create(new_campaign_members, object_name = "CampaignMember", api_type = "REST") expect_is(create_error_records, "tbl_df") expect_equal(names(create_error_records), c("success", "errors")) expect_equal(nrow(create_error_records), 1) expect_is(create_error_records$errors, "list") expect_equal(length(create_error_records$errors[1][[1]]), 1) expect_equal(sort(names(create_error_records$errors[1][[1]][[1]])), c("fields", "message", "statusCode")) dupe_n <- 3 prefix <- paste0("KEEP-", as.integer(runif(1,1,100000)), "-") new_contacts <- tibble(FirstName = rep("KEEP", dupe_n), LastName = paste0("Test-Contact-Dupe", 1:dupe_n), Email = rep("[email protected]", dupe_n), Phone = rep("(123) 456-7890", dupe_n), test_number__c = rep(999.9, dupe_n), My_External_Id__c = paste0(prefix, 1:dupe_n, "ZZZ")) dupe_records <- sf_create(new_contacts, object_name = "Contact", api_type = "REST", control = list(allowSave = FALSE, includeRecordDetails = TRUE, runAsCurrentUser = TRUE)) expect_is(dupe_records, "tbl_df") expect_equal(names(dupe_records), c("success", "errors")) expect_equal(nrow(dupe_records), dupe_n) expect_is(dupe_records$errors, "list") expect_equal(length(dupe_records$errors[1][[1]]), 1) expect_equal(sort(names(dupe_records$errors[1][[1]][[1]])), c("fields", "message", "statusCode")) retrieved_records <- sf_retrieve(ids = created_records$id, fields = c("FirstName", "LastName"), object_name = object, api_type = "REST") expect_is(retrieved_records, "tbl_df") expect_equal(names(retrieved_records), c("sObject", "Id", "FirstName", "LastName")) expect_equal(nrow(retrieved_records), n) my_sosl <- paste("FIND {(336)} in phone fields returning", "contact(id, firstname, lastname, my_external_id__c),", "lead(id, firstname, lastname)") searched_records <- sf_search(my_sosl, is_sosl=TRUE, api_type="REST") expect_is(searched_records, "tbl_df") expect_named(searched_records, c("sObject", "Id", "FirstName", "LastName")) expect_equal(nrow(searched_records), 3) my_soql <- sprintf("SELECT Id, FirstName, LastName, My_External_Id__c FROM Contact WHERE Id in ('%s')", paste0(created_records$id , collapse="','")) queried_records <- sf_query(my_soql, object_name = object , api_type="REST") expect_is(queried_records, "tbl_df") expect_equal(names(queried_records), c("Id", "FirstName", "LastName", "My_External_Id__c")) expect_equal(nrow(queried_records), n) queried_records <- queried_records %>% mutate(FirstName = "TestTest") updated_records <- sf_update(queried_records, object_name = object, api_type="REST") expect_is(updated_records, "tbl_df") expect_equal(names(updated_records), c("id", "success")) expect_equal(nrow(updated_records), n) expect_is(updated_records$success, "logical") new_record <- tibble(FirstName = "Test", LastName = paste0("REST-Contact-Upsert-", n+1), My_External_Id__c=paste0(prefix, letters[n+1])) upserted_contacts <- bind_rows(queried_records %>% select(-Id), new_record) upserted_records <- sf_upsert(input_data = upserted_contacts, object_name = object, external_id_fieldname = "My_External_Id__c", api_type = "REST") expect_is(upserted_records, "tbl_df") expect_equal(names(upserted_records), c("id", "success", "created")) expect_equal(nrow(upserted_records), nrow(upserted_records)) expect_equal(upserted_records$success, c(TRUE, TRUE, TRUE)) expect_equal(upserted_records$created, c(FALSE, FALSE, TRUE)) attachment_details <- tibble(Name = c("salesforcer Logo"), Body = system.file("extdata", "logo.png", package = "salesforcer"), ContentType = c("image/png"), ParentId = upserted_records$id[1]) attachment_records <- sf_create_attachment(attachment_details, api_type="REST") expect_is(attachment_records, "tbl_df") expect_equal(names(attachment_records), c("id", "success", "errors")) expect_equal(nrow(attachment_records), 1) expect_true(attachment_records$success) temp_f <- tempfile(fileext = ".zip") zipr(temp_f, system.file("extdata", "logo.png", package = "salesforcer")) attachment_details2 <- tibble(Id = attachment_records$id[1], Name = "logo.png.zip", Body = temp_f) attachment_records_update <- sf_update_attachment(attachment_details2, api_type="REST") expect_is(attachment_records_update, "tbl_df") expect_equal(names(attachment_records_update), c("id", "success", "errors")) expect_equal(nrow(attachment_records_update), 1) expect_true(attachment_records_update$success) deleted_attachments <- sf_delete_attachment(attachment_records$id, api_type = "REST") expect_is(deleted_attachments, "tbl_df") expect_equal(names(deleted_attachments), c("id", "success")) expect_equal(nrow(deleted_attachments), 1) expect_true(deleted_attachments$success) ids_to_delete <- unique(c(upserted_records$id[!is.na(upserted_records$id)], queried_records$Id)) deleted_records <- sf_delete(ids_to_delete, object_name = object, api_type = "REST") expect_is(deleted_records, "tbl_df") expect_equal(names(deleted_records), c("id", "success")) expect_equal(nrow(deleted_records), length(ids_to_delete)) expect_is(deleted_records$success, "logical") expect_true(all(deleted_records$success)) })
wassersteinpar <- function(mean1,var1,mean2,var2,check=FALSE) { p <- length(mean1) d <- mean1-mean2 vars <- var1+var2 if (p == 1) { if(check) {if(abs(var1) < .Machine$double.eps | abs(var2) < .Machine$double.eps) {stop("At least one variance is zero") } } return(sqrt( d^2 + var1 + var2 - 2*sqrt(var1*var2) )) } else { if(check) { if(abs(det(var1)) < .Machine$double.eps | abs(det(var2)) < .Machine$double.eps) { stop("One of the sample variances is degenerate") } } sqrtvar2 <- sqrtmatrix(var2) sqrtvars <- sqrtmatrix(sqrtvar2%*%var1%*%sqrtvar2) tracevar <- sum(diag(vars - 2*sqrtvars)) return( sqrt( sum(d^2) + tracevar ) ) } }
substrev <- function(x, start, stop = 0) { substr(x, nchar(x) - start, nchar(x) - stop) }
test_that("fetch_rstudio_prefs works", { expect_error( fetch_rstudio_prefs(), NA ) })
bfa.boot2fast.ls <- function(z, p, burn = 5, B){ boot1 <- bfa.boot1.ls(z, p, burn = burn, B, boot.est=TRUE, boot.data=TRUE) boot2 <- apply(boot1$boot.data, 1, bfa.boot1.ls, p, burn = burn, B=1, boot.est=TRUE) return(list(boot1$boot.est, boot2)) }
context("nhl_url_conferences") testthat::test_that( "nhl_url_teams generates all conference url", testthat::expect_equal( nhl_url_conferences(), paste0(baseurl, "conferences") ) ) testthat::test_that( "nhl_url_teams generates single conference url", testthat::expect_equal( nhl_url_conferences(1), paste0(baseurl, "conferences/1") ) ) testthat::test_that( "nhl_url_teams generates multiple conference url", testthat::expect_equal( nhl_url_conferences(c(1, 2)), paste0(baseurl, c("conferences/1", "conferences/2")) ) )
rfalling_object <- function(n = 14, d_0 = 55.86, v_0 = 0, g = -9.8, scale = 1, time = seq(0, 3.25, length.out = n), error_distribution = c("rnorm", "rt"), df = 3){ error_distribution <- match.arg(error_distribution) error_func = get(error_distribution) if(length(time)!=n) stop("length(time) must be equal to n") d <- d_0 + v_0 * time + 0.5*g*time^2 if(error_distribution == "rnorm"){ y <- d + rnorm(n)*scale } else{ y <- d + rt(n, df = df) * scale } dat <- data.frame(time = time, distance = pmax(d,0), observed_distance = pmax(y,0)) attr(dat, "params") <- c(d_0 = d_0, v_0 = v_0, g = g, scale = scale) attr(dat, "error_distribution") <- error_distribution dat }
GeomHollowPolygon <- ggproto("GeomHollowPolygon", Geom, required_aes = c("x", "y"), default_aes = aes( colour = NA, fill = "grey20", size = 0.5, linetype = 1, alpha = 1, cover = TRUE), draw_key = draw_key_polygon, draw_group = function(data, panel_params, coord) { n <- nrow(data) if (n <= 2) return(grid::nullGrob()) coords <- coord$transform(data, panel_params) coords <- coords[order(coords$piece), ] first_row <- coords[1, , drop = FALSE] if (first_row$cover) { cfill <- scales::alpha(first_row$fill, first_row$alpha) } else { cfill <- NA } grid::pathGrob( coords$x, coords$y, default.units = "native", rule = "evenodd", id = coords$piece, gp = grid::gpar( col = scales::alpha(first_row$fill, first_row$alpha), fill = cfill, lwd = first_row$size * .pt, lty = first_row$linetype ) ) } ) geom_hollow_polygon <- function(mapping = NULL, data = NULL, stat = "hollow_contour", position = "identity", show.legend = NA, inherit.aes = TRUE, ...) { layer( geom = GeomHollowPolygon, mapping = mapping, data = data, stat = stat, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(...) ) }
"hist_SA"
cap_beta <- function(Y,X,gamma=NULL,beta=NULL,method=c("asmp","LLR"),boot=FALSE,sims=1000,boot.ci.type=c("bca","perc"),conf.level=0.95,verbose=TRUE) { n<-length(Y) p<-ncol(Y[[1]]) Tvec<-rep(NA,n) q<-ncol(X) if(is.null(colnames(X))) { colnames(X)<-c("Intercept",paste0("X",1:(q-1))) } for(i in 1:n) { Tvec[i]<-nrow(Y[[i]]) } if(boot) { if(is.null(gamma)) { stop("Error! Need gamma value.") }else { beta.boot<-matrix(NA,q,sims) for(b in 1:sims) { idx.tmp<-sample(1:n,n,replace=TRUE) Ytmp<-Y[idx.tmp] Xtmp<-matrix(X[idx.tmp,],ncol=q) beta.boot[,b]<-MatReg_QC_beta(Ytmp,Xtmp,gamma=gamma)$beta if(verbose) { print(paste0("Bootstrap sample ",b)) } } beta.est<-apply(beta.boot,1,mean,na.rm=TRUE) beta.se<-apply(beta.boot,1,sd,na.rm=TRUE) beta.stat<-beta.est/beta.se pv<-(1-pnorm(abs(beta.stat)))*2 if(boot.ci.type[1]=="bca") { beta.ci<-t(apply(beta.boot,1,BC.CI,sims=sims,conf.level=conf.level)) } if(boot.ci.type[1]=="perc") { beta.ci<-t(apply(beta.boot,1,quantile,probs=c((1-conf.level)/2,1-(1-conf.level)/2))) } re<-data.frame(Estiamte=beta.est,SE=beta.se,statistic=beta.stat,pvalue=pv,LB=beta.ci[,1],UB=beta.ci[,2]) rownames(re)<-colnames(X) return(list(Inference=re,beta.boot=beta.boot)) } }else { if(is.null(beta)&is.null(gamma)==FALSE) { beta<-MatReg_QC_beta(Y,X,gamma=gamma)$beta }else if(is.null(gamma)) { stop("Error! Need gamma value.") } if(method[1]=="asmp") { beta.var<-2*solve(t(X)%*%X)/min(Tvec) beta.se<-sqrt(diag(beta.var)) beta.stat<-beta/beta.se pv<-(1-pnorm(abs(beta.stat)))*2 LB<-beta-beta.se*qnorm((1-conf.level)/2,lower.tail=FALSE) UB<-beta+beta.se*qnorm((1-conf.level)/2,lower.tail=FALSE) re<-data.frame(Estimate=beta,SE=beta.se,statistic=beta.stat,pvalue=pv,LB=LB,UB=UB) rownames(re)<-colnames(X) }else if(method[1]=="LLR") { stat=pv<-rep(NA,q) for(j in 1:q) { Xtmp<-matrix(X[,-j],nrow=n) beta0<-MatReg_QC_beta(Y,Xtmp,gamma=gamma)$beta stat[j]<-2*((-objfunc(Y,X,gamma,beta))-(-objfunc(Y,Xtmp,gamma,beta0))) pv[j]<-1-pchisq(stat[j],df=1) } re<-data.frame(Estimate=beta,statistic=stat,pvalue=pv) rownames(re)<-colnames(X) } return(re) } }
knn2nb <- function(knn, row.names=NULL, sym=FALSE) { if (class(knn) != "knn") stop("Not a knn object") res <- vector(mode="list", length=knn$np) if (!is.null(row.names)) { if(length(row.names) != knn$np) stop("row.names wrong length") if (length(unique(row.names)) != length(row.names)) stop("non-unique row.names given") } if (knn$np < 1) stop("non-positive number of spatial units") if (is.null(row.names)) row.names <- as.character(1:knn$np) if(sym){ to<-as.vector(knn$nn) from<-rep(1:knn$np,knn$k) for (i in 1:knn$np)res[[i]] <- sort(unique(c(to[from==i], from[to==i]))) } else { for (i in 1:knn$np) res[[i]] <- sort(knn$nn[i,]) } attr(res, "region.id") <- row.names attr(res, "call") <- attr(knn, "call") attr(res, "sym") <- sym attr(res, "type") <- "knn" attr(res, "knn-k") <- knn$k class(res) <- "nb" res }
"NO2_2011"
epi.ssninfc <- function(treat, control, sd, delta, n, r = 1, power, nfractional = FALSE, alpha){ if (delta < 0){ stop("For a non-inferiority trial delta must be greater than or equal to zero.") } z.alpha <- qnorm(1 - alpha, mean = 0, sd = 1) if (!is.na(treat) & !is.na(control) & !is.na(delta) & !is.na(power) & is.na(n)) { ndelta <- -delta beta <- (1 - power) z.beta <- qnorm(1 - beta, mean = 0, sd = 1) if (sign(z.alpha + z.beta) != sign(treat - control - ndelta)){ stop("Target power is not reachable. Check the exact specification of the hypotheses.") } n.control <- (1 + 1 / r) * (sd * (z.alpha + z.beta) / (treat - control - ndelta))^2 n.treat <- n.control * r if(nfractional == TRUE){ n.control <- n.control n.treat <- n.treat n.total <- n.treat + n.control } if(nfractional == FALSE){ n.control <- ceiling(n.control) n.treat <- ceiling(n.treat) n.total <- n.treat + n.control } rval <- list(n.total = n.total, n.treat = n.treat, n.control = n.control, delta = delta, power = power) } if (!is.na(treat) & !is.na(control) & !is.na(delta) & !is.na(n) & is.na(power) & !is.na(r) & !is.na(alpha)) { ndelta <- -delta if(nfractional == TRUE){ n.control <- 1 / (r + 1) * n n.treat <- n - n.control n.total <- n.treat + n.control } if(nfractional == FALSE){ n.control <- ceiling(1 / (r + 1) * n) n.treat <- n - n.control n.total <- n.treat + n.control } z <- (treat - control - ndelta) / (sd * sqrt((1 + 1 / r) / n.control)) power <- pnorm(z - z.alpha, mean = 0, sd = 1) rval <- list(n.total = n.total, n.treat = n.treat, n.control = n.control, delta = delta, power = power) } rval }
summarise <- function(.data, ..., .groups = NULL) { UseMethod("summarise") } summarise.data.frame <- function(.data, ..., .groups = NULL) { fns <- dotdotdot(...) context$setup(.data) on.exit(context$clean(), add = TRUE) groups_exist <- context$is_grouped() if (groups_exist) { group <- unique(context$get_columns(group_vars(context$.data))) } if (is_empty_list(fns)) { if (groups_exist) return(group) else return(data.frame()) } res <- vector(mode = "list", length = length(fns)) eval_env <- c(as.list(context$.data), vector(mode = "list", length = length(fns))) new_pos <- seq(length(context$.data) + 1L, length(eval_env), 1L) for (i in seq_along(fns)) { eval_env[[new_pos[i]]] <- do.call(with, list(eval_env, fns[[i]])) nms <- if (!is_named(eval_env[[new_pos[i]]])) { if (!is.null(names(fns)[[i]])) names(fns)[[i]] else deparse(fns[[i]]) } else { NULL } if (!is.null(nms)) names(eval_env)[[new_pos[i]]] <- nms res[[i]] <- build_data_frame(eval_env[[new_pos[i]]], nms = nms) } res <- do.call(cbind, res) if (groups_exist) res <- cbind(group, res, row.names = NULL) res } summarise.grouped_df <- function(.data, ..., .groups = NULL) { if (!is.null(.groups)) { .groups <- match.arg(arg = .groups, choices = c("drop", "drop_last", "keep"), several.ok = FALSE) } groups <- group_vars(.data) res <- apply_grouped_function("summarise", .data, drop = TRUE, ...) res <- res[arrange_rows(res, as_symbols(groups)), , drop = FALSE] verbose <- summarise_verbose(.groups) if (is.null(.groups)) { all_one <- as.data.frame(table(res[, groups])) all_one <- all_one[all_one$Freq != 0, ] .groups <- if (all(all_one$Freq == 1)) "drop_last" else "keep" } if (.groups == "drop_last") { n <- length(groups) if (n > 1) { if (verbose) summarise_inform(groups[-n]) res <- groups_set(res, groups[-n], group_by_drop_default(.data)) } } else if (.groups == "keep") { if (verbose) summarise_inform(groups) res <- groups_set(res, groups, group_by_drop_default(.data)) } else if (.groups == "drop") { attr(res, "groups") <- NULL } rownames(res) <- NULL res } summarize <- summarise summarize.data.frame <- summarise.data.frame summarize.grouped_df <- summarise.grouped_df summarise_inform <- function(new_groups) { message(sprintf( "`summarise()` has grouped output by %s. You can override using the `.groups` argument.", paste0("'", new_groups, "'", collapse = ", ") )) } summarise_verbose <- function(.groups) { is.null(.groups) && !identical(getOption("poorman.summarise.inform"), FALSE) }
test_that("funder searching works", { skip_on_cran() search1 <- tsg_search_funders(search = c("bbc", "caBinet")) expect_true("BBC Children in Need grants" %in% search1$title) search2 <- tsg_search_funders( search = c("citybridgetrust", "esmEE"), search_in = "publisher_website" ) expect_true(any(grepl("City Bridge", search2$publisher_name))) search2 <- tsg_specific_df(search1) expect_true(tibble::is_tibble(search2[[1]])) expect_equal(length(search2), nrow(search1)) expect_error(tsg_specific_df("search1")) })
predict <- function(object, views = "all", groups = "all", factors = "all", add_intercept = TRUE) { if (!is(object, "MOFA")) stop("'object' has to be an instance of MOFA") views <- .check_and_get_views(object, views, non_gaussian=FALSE) groups <- .check_and_get_groups(object, groups) if (any(views %in% names(which(object@model_options$likelihoods!="gaussian")))) stop("predict does not work for non-gaussian modalities") if (paste0(factors, collapse="") == "all") { factors <- factors_names(object) } else if (is.numeric(factors)) { factors <- factors_names(object)[factors] } else { stopifnot(all(factors %in% factors_names(object))) } W <- get_weights(object, views = views, factors = factors) Z <- get_factors(object, groups = groups, factors = factors) Z[is.na(Z)] <- 0 predicted_data <- lapply(views, function(m) { lapply(groups, function(g) { pred <- t(Z[[g]] %*% t(W[[m]])) tryCatch( { if (add_intercept & length(object@intercepts[[1]])>0) { intercepts <- object@intercepts[[m]][[g]] intercepts[is.na(intercepts)] <- 0 pred <- pred + object@intercepts[[m]][[g]] } }, error = function(e) { NULL }) return(pred) }) }) predicted_data <- .name_views_and_groups(predicted_data, views, groups) return(predicted_data) }
"KitchenhamEtAl.CorrelationsAmongParticipants.Madeyski10" "KitchenhamEtAl.CorrelationsAmongParticipants.Scanniello15EMSE" "KitchenhamEtAl.CorrelationsAmongParticipants.Scanniello14TOSEM" "KitchenhamEtAl.CorrelationsAmongParticipants.Torchiano17JVLC" "KitchenhamEtAl.CorrelationsAmongParticipants.Abrahao13TSE" "KitchenhamEtAl.CorrelationsAmongParticipants.Scanniello14EASE" "KitchenhamEtAl.CorrelationsAmongParticipants.Ricca14TOSEM" "KitchenhamEtAl.CorrelationsAmongParticipants.Gravino15JVLC" "KitchenhamEtAl.CorrelationsAmongParticipants.Scanniello14JVLC" "KitchenhamEtAl.CorrelationsAmongParticipants.Romano18ESEM" "KitchenhamEtAl.CorrelationsAmongParticipants.Ricca10TSE" "KitchenhamEtAl.CorrelationsAmongParticipants.Reggio15SSM" "KitchenhamEtAl.CorrelationsAmongParticipants.Scanniello17TOSEM"
.tyler.step<-function(V.old,datas,p,n) { sqrt.V.old<-mat.sqrt(V.old) r<-sqrt(rowSums((datas %*% sqrt.V.old)^2)) M.V.old<-p/n*(t(((1/r)*datas%*%sqrt.V.old))%*%((1/r)*datas%*%sqrt.V.old)) M.V.old.inv <- solve(M.V.old) V.new<-sum(diag(V.old %*% M.V.old.inv))^(-1)*(sqrt.V.old %*% M.V.old.inv %*% sqrt.V.old) return(V.new) }
cen_ecdf <- function(y.var, cen.var, group=NULL, xlim = c(0, max(y.var)), Ylab=varname) { varname <- deparse(substitute(y.var)) if ( is.null(group) ) { if (sum(cen.var) != 0 ) { ecdfPlotCensored(y.var, cen.var, main = "ECDF for Censored Data", xlab = Ylab, ecdf.lwd = 1, type = "s")} else {ecdfPlot(y.var, main = paste("ECDF for", varname), xlab = Ylab, ecdf.lwd = 1, type = "s")} } else { Factor <- as.factor(group) factorname <- deparse(substitute(group)) ngp <- length(levels(Factor)) clrs <- c (1:ngp) groupnames <- as.character(levels(Factor)) if (sum(cen.var[Factor == groupnames[1]]) != 0 ) { ecdfPlotCensored(y.var[Factor==groupnames[1]], cen.var[Factor==groupnames[1]], main = "ECDF for Censored Data", xlab = Ylab, ecdf.lwd = 2, type = "s", xlim = xlim) } else {ecdfPlot(y.var[Factor==groupnames[1]], main = "ECDF for Censored Data", xlab = Ylab, ecdf.lwd = 2, type = "s", xlim = xlim) } for (i in 2:ngp) { if (sum(cen.var[Factor == groupnames[i]]) != 0) { ecdfPlotCensored(y.var[Factor==groupnames[i]], cen.var[Factor==groupnames[i]], add = TRUE, ecdf.col = clrs[i], ecdf.lwd = 2, ecdf.lty = clrs[i], type = "s") } else {ecdfPlot(y.var[Factor==groupnames[i]], add = TRUE, ecdf.col = clrs[i], ecdf.lwd = 2, ecdf.lty = clrs[i], type = "s") } } legend("bottomright",levels(Factor), lty=1:ngp, lwd=2, text.col=clrs, col = clrs, title = factorname) } }
library(ODataQuery) service <- ODataQuery$new("testurl.org/") expect_equal(service$url, "testurl.org/") service <- ODataQuery$new("testurl.org") expect_equal(service$url, "testurl.org/") item_resource <- service$path("Items") expect_equal(item_resource$url, "testurl.org/Items") item_singleton <- service$path("Items")$get("it0001") expect_equal(item_singleton$url, "testurl.org/Items('it0001')") item_singleton <- service$path("Items")$get(ItemId = "it0001") expect_equal(item_singleton$url, "testurl.org/Items(ItemId='it0001')") expect_equal(item_resource$select("First", "Second", "Third")$url, "testurl.org/Items?$select=First,Second,Third") expect_equal(item_resource$skip(10)$top(5)$url, "testurl.org/Items?$skip=10&$top=5") expect_equal(item_resource$expand("Prices")$url, "testurl.org/Items?$expand=Prices") expect_equal(item_resource$filter("Quantity > 0", Value.gt = 100)$url, "testurl.org/Items?$filter=(Quantity%20%3E%200%20and%20Value%20gt%20100)") expect_equal(item_resource$orderby("Price", "Quality")$url, "testurl.org/Items?$orderby=Price,Quality")
NULL alias_get <- function(conn, index=NULL, alias=NULL, ignore_unavailable=FALSE, ...) { is_conn(conn) alias_GET(conn, index, alias, ignore_unavailable, ...) } aliases_get <- function(conn, index=NULL, alias=NULL, ignore_unavailable=FALSE, ...) { is_conn(conn) alias_GET(conn, index, alias, ignore_unavailable, ...) } alias_exists <- function(conn, index=NULL, alias=NULL, ...) { is_conn(conn) res <- conn$make_conn(alias_url(conn, index, alias), ...)$head() if (conn$warn) catch_warnings(res) if (res$status_code == 200) TRUE else FALSE } alias_create <- function(conn, index, alias, filter=NULL, routing=NULL, search_routing=NULL, index_routing=NULL, ...) { is_conn(conn) assert(index, "character") assert(alias, "character") assert(routing, "character") assert(search_routing, "character") assert(index_routing, "character") body <- list(actions = unname(Map(function(a, b) { list(add = ec(list(index = esc(a), alias = esc(b), filter = filter, routing = routing, search_routing = search_routing, index_routing = index_routing))) }, index, alias)) ) body <- jsonlite::toJSON(body, auto_unbox = TRUE) out <- conn$make_conn(aliases_url(conn), json_type(), ...)$post(body = body) if (conn$warn) catch_warnings(out) geterror(conn, out) jsonlite::fromJSON(out$parse('UTF-8'), FALSE) } alias_rename <- function(conn, index, alias, alias_new, ...) { is_conn(conn) body <- list(actions = list( list(remove = list(index = index, alias = alias)), list(add = list(index = index, alias = alias_new)) )) body <- jsonlite::toJSON(body, auto_unbox = TRUE) out <- conn$make_conn(aliases_url(conn), json_type(), ...)$post(body = body) if (conn$warn) catch_warnings(out) geterror(conn, out) jsonlite::fromJSON(out$parse('UTF-8'), FALSE) } alias_delete <- function(conn, index=NULL, alias, ...) { is_conn(conn) out <- conn$make_conn(alias_url(conn, index, alias), ...)$delete() if (conn$warn) catch_warnings(out) geterror(conn, out) jsonlite::fromJSON(out$parse('UTF-8'), FALSE) } alias_GET <- function(conn, index, alias, ignore, ...) { cli <- conn$make_conn(alias_url(conn, index, alias), ...) tt <- cli$get(query = ec(list(ignore_unavailable = as_log(ignore)))) if (conn$warn) catch_warnings(tt) geterror(conn, tt) jsonlite::fromJSON(tt$parse("UTF-8"), FALSE) } alias_url <- function(conn, index, alias) { url <- conn$make_url() if (!is.null(index)) { if (!is.null(alias)) sprintf("%s/%s/_alias/%s", url, cl(index), alias) else sprintf("%s/%s/_alias", url, cl(index)) } else { if (!is.null(alias)) sprintf("%s/_alias/%s", url, alias) else sprintf("%s/_alias", url) } } aliases_url <- function(conn) file.path(conn$make_url(), "_aliases")
DUPbank<-function(Qbank) { lens = unlist(lapply(Qbank, "length")) thelens = as.numeric(lens) thefiles = names(lens) allqs = vector() allind = vector() internalind = vector() ifile = vector() nfile = vector() for(i in 1:length(Qbank)) { uq = unlist(Qbank[[i]]) w = which(names(uq)=="Q") nu = seq(from=1, to=length(w)) allqs =c(allqs, as.vector(uq[w]) ) internalind = c(internalind, nu) allind = c(allind, w) ifile = c( ifile, rep( thefiles[i], times=length(w) )) nfile = c( nfile, rep( i, times=length(w) )) } wdup = which( duplicated(allqs) ) if(length(wdup)<1) { return(NULL) } return(list(A=allqs[wdup], F=ifile[wdup], I=internalind[wdup], N=nfile[wdup] ) ) }
setMethod( f = "addsegment", signature = "ADEg", definition = function(object, x0 = NULL, y0 = NULL, x1, y1, plot = TRUE, ...) { xlim <- [email protected]$xlim ylim <- [email protected]$ylim aspect <- [email protected]$paxes$aspectratio sortparameters <- sortparamADEg(...)$adepar params <- adegpar() sortparameters <- modifyList(params, sortparameters, keep.null = TRUE) params <- sortparameters$plines segmentadded <- xyplot(0 ~ 0, xlim = xlim, ylim = ylim, main = NULL, xlab = NULL, ylab = NULL, aspect = aspect, myx0 = x0, myy0 = y0, myx1 = x1, myy1 = y1, panel = function(x, y, ...) panel.segments(x0 = x0, y0 = y0, x1 = x1, y1 = y1, lwd = params$lwd, lty = params$lty, col = params$col), plot = FALSE) segmentadded$call <- call("xyplot", 0 ~ 0, xlim = substitute(xlim), ylim = substitute(ylim), xlab = NULL, ylab = NULL, aspect = substitute(aspect), lwd = params$lwd, lty = params$lty, col = params$col, x0 = substitute(x0), y0 = substitute(y0), x1 = substitute(x1), y1 = substitute(y1), panel = function(x, y, ...) panel.segments(x0 = x0, y0 = y0, x1 = x1, y1 = y1)) obj <- superpose(object, segmentadded, plot = FALSE) nn <- all.names(substitute(object)) names(obj) <- c(ifelse(is.na(nn[2]), nn[1], nn[2]), "segmentadded") if(plot) print(obj) invisible(obj) }) setMethod( f = "addsegment", signature = "ADEgS", definition = function(object, x0 = NULL, y0 = NULL, x1, y1, plot = TRUE, which = 1:length(object), ...) { ngraph <- length(object) if(max(which) > ngraph) stop("Values in 'which' should be lower than the length of object") if(length(which) == 1) { object[[which]] <- addsegment(object[[which]], x0 = x0, y0 = y0, x1 = x1, y1 = y1, ..., plot = FALSE) } else { if(sum(object@add) != 0) stop("The 'addsegment' function is not available for superposed objects.", call. = FALSE) sortparameters <- sortparamADEg(...)$adepar params <- adegpar() sortparameters <- modifyList(params, sortparameters, keep.null = TRUE) params <- sortparameters$plines params <- rapply(params, function(X) rep(X, length.out = length(which)), how = "list") if(!is.null(x0)) x0 <- rep_len(x0, length.out = length(which)) if(!is.null(y0)) y0 <- rep_len(y0, length.out = length(which)) x1 <- rep_len(x1, length.out = length(which)) y1 <- rep_len(y1, length.out = length(which)) for (i in which) object[[i]] <- addsegment(object[[i]], x0 = x0[i], y0 = y0[i], x1 = x1[i], y1 = y1[i], which = 1, plot = FALSE, plines = lapply(params, function(X) X[i])) } obj <- object if(plot) print(obj) invisible(obj) })
fileStatus <- function(repo, testPath) { testStatus <- NULL repoPath <- ifelse(isS4(repo), try(repo@path, silent = TRUE), try(repo$path, silent = TRUE)) if(class(repoPath) == "try-error") { return(infoNotFound()) } repoRoot <- sub("/\\.git/*", "", repoPath, fixed = FALSE) statusVals <- unlist(git2r::status(repo)) hasStatus <- normalizePath(testPath, mustWork = FALSE) == normalizePath(paste(repoRoot, statusVals, sep = "/"), mustWork = FALSE) if(any(hasStatus)) { testStatus <- paste(names(statusVals[hasStatus]), collapse = ", ") } else { testStatus <- "committed" } return(testStatus) }
"EUNITE.Loads.cont"
if (requireNamespace("spelling", quietly = TRUE)) { spelling::spell_check_test( vignettes = TRUE, error = FALSE, skip_on_cran = TRUE ) }
mxMI <- function(model, matrices=NA, full=TRUE){ warnModelCreatedByOldVersion(model) if(single.na(matrices)){ matrices <- names(model$matrices) if (is(model$expectation, "MxExpectationRAM")) { matrices <- setdiff(matrices, model$expectation$F) } } if(imxHasWLS(model)){stop("modification indices not implemented for WLS fitfunction")} param <- omxGetParameters(model) param.names <- names(param) gmodel <- omxSetParameters(model, free=FALSE, labels=param.names) mi.r <- NULL mi.f <- NULL a.names <- NULL new.models <- list() for(amat in matrices){ matObj <- model[[amat]] freemat <- matObj$free sym.sel <- upper.tri(freemat, diag=TRUE) notSymDiag <- !(is(gmodel[[amat]])[1] %in% c("DiagMatrix", "SymmMatrix")) for(i in 1:length(freemat)){ if(freemat[i]==FALSE && ( notSymDiag || sym.sel[i]==TRUE )){ tmpLab <- gmodel[[amat]]$labels[i] plusOneParamModel <- model if(length(tmpLab) > 0 && !is.na(tmpLab)){ gmodel <- omxSetParameters(gmodel, labels=tmpLab, free=TRUE) plusOneParamModel <- omxSetParameters(plusOneParamModel, labels=tmpLab, free=TRUE) } else{ gmodel[[amat]]$free[i] <- TRUE plusOneParamModel[[amat]]$free[i] <- TRUE } if(is(gmodel[[amat]])[1] %in% c("ZeroMatrix")){ cop <- gmodel[[amat]] newSingleParamMat <- mxMatrix("Full", nrow=nrow(cop), ncol=ncol(cop), values=cop$values, free=cop$free, labels=cop$labels, name=cop$name, lbound=cop$lbound, ubound=cop$ubound, dimnames=dimnames(cop)) bop <- plusOneParamModel[[amat]] newPlusOneParamMat <- mxMatrix("Full", nrow=nrow(bop), ncol=ncol(bop), values=bop$values, free=bop$free, labels=bop$labels, name=bop$name, lbound=bop$lbound, ubound=bop$ubound, dimnames=dimnames(bop)) } else if(is(gmodel[[amat]])[1] %in% c("DiagMatrix", "SymmMatrix")){ cop <- gmodel[[amat]] newSingleParamMat <- mxMatrix("Symm", nrow=nrow(cop), ncol=ncol(cop), values=cop$values, free=(cop$free | t(cop$free)), labels=cop$labels, name=cop$name, lbound=cop$lbound, ubound=cop$ubound, dimnames=dimnames(cop)) bop <- plusOneParamModel[[amat]] newPlusOneParamMat <- mxMatrix("Symm", nrow=nrow(bop), ncol=ncol(bop), values=bop$values, free=(bop$free | t(bop$free)), labels=bop$labels, name=bop$name, lbound=bop$lbound, ubound=bop$ubound, dimnames=dimnames(bop)) } else { newSingleParamMat <- gmodel[[amat]] newPlusOneParamMat <- plusOneParamModel[[amat]] } gmodel[[amat]] <- newSingleParamMat plusOneParamModel[[amat]] <- newPlusOneParamMat custom.compute <- mxComputeSequence(list(mxComputeNumericDeriv(checkGradient=FALSE), mxComputeReportDeriv())) gmodel <- mxModel(gmodel, custom.compute) grun <- try(mxRun(gmodel, silent = FALSE, suppressWarnings = FALSE, unsafe=TRUE)) nings =TRUE if (is(grun, "try-error")) { gmodel <- omxSetParameters(gmodel, labels=names(omxGetParameters(gmodel)), free=FALSE) next } grad <- grun$output$gradient hess <- grun$output$hessian modind <- 0.5*grad^2/hess if(full==TRUE){ custom.compute.smart <- mxComputeSequence(list( mxComputeNumericDeriv(knownHessian=model$output$hessian, checkGradient=FALSE), mxComputeReportDeriv())) plusOneParamRun <- mxRun(mxModel(plusOneParamModel, custom.compute.smart), silent = FALSE, suppressWarnings = FALSE, unsafe=TRUE) grad.full <- plusOneParamRun$output$gradient grad.full[is.na(grad.full)] <- 0 hess.full <- plusOneParamRun$output$hessian modind.full <- 0.5*t(matrix(grad.full)) %*% solve(hess.full) %*% matrix(grad.full) } else { modind.full <- NULL } n.names <- names(omxGetParameters(grun)) if(length(modind) > 0){ a.names <- c(a.names, n.names) mi.r <- c(mi.r, modind) mi.f <- c(mi.f, modind.full) new.models <- c(new.models, plusOneParamModel) } gmodel <- omxSetParameters(gmodel, labels=names(omxGetParameters(gmodel)), free=FALSE) } } names(mi.r) <- a.names if(full==TRUE) {names(mi.f) <- a.names} names(new.models) <- a.names } if(length(model$submodels) > 0){ for(asubmodel in names(model$submodels)){ ret <- c(ret, mxMI(asubmodel)) } } return(list(MI=mi.r, MI.Full=mi.f, plusOneParamModels=new.models)) }
expected <- eval(parse(text="c(\"trace\", \"fnscale\", \"parscale\", \"ndeps\", \"maxit\", \"abstol\", \"reltol\", \"alpha\", \"beta\", \"gamma\", \"REPORT\", \"type\", \"lmm\", \"factr\", \"pgtol\", \"tmax\", \"temp\")")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(trace = 0, fnscale = 1, parscale = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), ndeps = c(0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001), maxit = 100L, abstol = -Inf, reltol = 1.49011611938477e-08, alpha = 1, beta = 0.5, gamma = 2, REPORT = 10, type = 1, lmm = 5, factr = 1e+07, pgtol = 0, tmax = 10, temp = 10), .Names = c(\"trace\", \"fnscale\", \"parscale\", \"ndeps\", \"maxit\", \"abstol\", \"reltol\", \"alpha\", \"beta\", \"gamma\", \"REPORT\", \"type\", \"lmm\", \"factr\", \"pgtol\", \"tmax\", \"temp\")))")); do.call(`names`, argv); }, o=expected);
ratioEstimatort <- function(data, tau_x, indices){ d <- data[indices,] y <- d[,1] pis <- d[,2] xsample <- d[, 3] tyHT <- horvitzThompson(y=y,pi=pis)$pop_total txHT <- horvitzThompson(y=xsample,pi=pis)$pop_total return(as.vector(tau_x/txHT*tyHT)) }
get_graphab_linkset_cost <- function(proj_name, linkset, proj_path = NULL){ if(!is.null(proj_path)){ chg <- 1 wd1 <- getwd() setwd(dir = proj_path) } else { chg <- 0 proj_path <- getwd() } if(!inherits(proj_name, "character")){ if(chg == 1){setwd(dir = wd1)} stop("'proj_name' must be a character string") } else if (!(paste0(proj_name, ".xml") %in% list.files(path = paste0("./", proj_name)))){ if(chg == 1){setwd(dir = wd1)} stop("The project you refer to does not exist. Please use graphab_project() before.") } proj_end_path <- paste0(proj_name, "/", proj_name, ".xml") if(!inherits(linkset, "character")){ if(chg == 1){setwd(dir = wd1)} stop("'linkset' must be a character string") } else if (!(paste0(linkset, "-links.csv") %in% list.files(path = paste0("./", proj_name)))){ if(chg == 1){setwd(dir = wd1)} stop("The linkset you refer to does not exist. Please use graphab_link() before.") } xml <- tempfile(pattern = ".txt") file.copy(from = proj_end_path, to = xml) file_data <- utils::read.table(xml) lines_linkset_names <- which(file_data[, 1] == "<Linkset>") + 1 names_linkset <- stringr::str_sub(file_data[lines_linkset_names, 1], 7, -8) line_linkset <- lines_linkset_names[which(names_linkset == linkset)] type_dist <- stringr::str_sub(file_data[line_linkset + 2, 1], 13, -14) if(type_dist == "1"){ message(paste0("Linkset ", linkset, " is a Euclidean linkset without ", "associated cost values")) if(chg == 1){ setwd(dir = wd1) } } else if(type_dist == "2"){ codes <- graph4lg::get_graphab_raster_codes(proj_name = proj_name, mode = "all") lines_costs <- which(file_data[, 1] == "<costs>") lines_end_costs <- which(file_data[, 1] == "</costs>") first_cost_line <- min(lines_costs[lines_costs > line_linkset]) + 2 last_cost_line <- min(lines_end_costs[lines_end_costs > first_cost_line]) - 1 cost_values <- file_data[first_cost_line:last_cost_line, 1] cost_values <- unlist(lapply(cost_values, FUN = function(x){stringr::str_sub(x, 9, -10)})) cost_values <- as.numeric(cost_values) if(length(codes) != length(cost_values)){ cost_values <- cost_values[-which(cost_values == 0)] message("The number of cost values does not strictly correspond ", "to the number of code values. Cost values were probably ", "given for absent code values. Cost values are ", "returned without sure correspondence with codes.") } if(chg == 1){ setwd(dir = wd1) } df_cost <- data.frame(code = codes, cost = cost_values) return(df_cost) } }
use_gomo <- function(){ htmltools::HTML(glue::glue( " <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css' /> </head> " ) ) }
bootstrap_E <- function(te, tb, tset_low, tset_up, index, n){ E_bootstrapped <- list() for(i in 1:n){ te_sample <- sample(te, size = length(te), replace=T) de <- dplyr::case_when( te_sample > tset_low & te_sample < tset_up ~ 0, te_sample < tset_low ~ tset_low - te_sample, te_sample > tset_up ~ te_sample - tset_up) mean_de <- mean(de) tb_sample <- sample(tb, size = length(tb), replace=T) db <- dplyr::case_when( tb_sample > tset_low & tb_sample < tset_up ~ 0, tb_sample < tset_low ~ tset_low - tb_sample, tb_sample > tset_up ~ tb_sample - tset_up) mean_db <- mean(db) if(index=='hertz'){ E <- 1 - (mean_db/mean_de) } else { if(index=='blouin'){ E <- (mean_de - mean_db) } } E_bootstrapped[i] <- E } E_bootstrapped2 <- unlist(E_bootstrapped) sd <- sd(E_bootstrapped2) n <- length(E_bootstrapped2) mean <- mean(E_bootstrapped2) error <- stats::qnorm(0.975) * sd / sqrt(n) E_CI <- as.list(c("mean" = mean, "lower" = mean - error, "upper" = mean + error)) E_list <- as.list(c(E_bootstrapped)) returnlist = list("Confidence Interval" = E_CI, "E values"= E_list) }
set_info_cols <- function(family, info_cols_list = NULL) { assert_collection <- checkmate::makeAssertCollection() checkmate::assert_choice( x = family, choices = c("gaussian", "binomial", "multinomial"), add = assert_collection ) checkmate::assert_list( x = info_cols_list, types = c("logical"), names = "named", any.missing = FALSE, null.ok = TRUE, add = assert_collection ) checkmate::reportAssertions(assert_collection) if (family == "gaussian") { default_cols <- list( "Predictions" = TRUE, "Results" = TRUE, "Coefficients" = TRUE, "Preprocess" = TRUE, "Folds" = TRUE, "Fold Columns" = TRUE, "Convergence Warnings" = TRUE, "Singular Fit Messages" = FALSE, "Other Warnings" = TRUE, "Warnings and Messages" = TRUE, "Process" = TRUE, "Family" = FALSE, "HParams" = TRUE, "Model" = FALSE, "Dependent" = TRUE, "Fixed" = TRUE, "Random" = TRUE ) } else if (family == "binomial") { default_cols <- list( "Predictions" = TRUE, "ROC" = TRUE, "Confusion Matrix" = TRUE, "Results" = TRUE, "Coefficients" = TRUE, "Preprocess" = TRUE, "Folds" = TRUE, "Fold Columns" = TRUE, "Convergence Warnings" = TRUE, "Singular Fit Messages" = FALSE, "Other Warnings" = TRUE, "Warnings and Messages" = TRUE, "Process" = TRUE, "Positive Class" = FALSE, "Family" = FALSE, "HParams" = TRUE, "Model" = FALSE, "Dependent" = TRUE, "Fixed" = TRUE, "Random" = TRUE ) } else if (family == "multinomial") { default_cols <- list( "Predictions" = TRUE, "ROC" = TRUE, "Confusion Matrix" = TRUE, "Results" = TRUE, "Class Level Results" = TRUE, "Coefficients" = TRUE, "Preprocess" = TRUE, "Folds" = TRUE, "Fold Columns" = TRUE, "Convergence Warnings" = TRUE, "Other Warnings" = TRUE, "Warnings and Messages" = TRUE, "Process" = TRUE, "Family" = FALSE, "HParams" = TRUE, "Model" = FALSE, "Dependent" = TRUE, "Fixed" = TRUE, "Random" = TRUE ) } info_cols <- default_cols if (!is.null(info_cols_list)) { if (!is.list(info_cols_list) && info_cols_list == "all") { for (info_col in seq_along(info_cols)) { info_cols[[info_col]] <- TRUE } } else if (length(info_cols_list) > 0) { unknown_colnames <- setdiff(names(info_cols_list), names(info_cols)) if (length(unknown_colnames) > 0) { stop(paste0( "'info_cols_list' contained unknown column names: ", paste0(unknown_colnames, collapse = ", "), "." )) } if (any(unlist(lapply(info_cols_list, function(x) { !(is.logical(x) && !is.na(x)) })))) { stop("The values in 'info_cols_list' must be either TRUE or FALSE.") } for (info_col in seq_along(info_cols_list)) { if (is.null(info_cols_list[[info_col]])) { stop("info_cols in 'info_cols_list' should be logical (TRUE/FALSE) not NULL.") } info_cols[[names(info_cols_list)[[info_col]]]] <- info_cols_list[[info_col]] } } } names( which( sapply(info_cols, function(y) isTRUE(y)) ) ) }
overlap.indicator <- function(vstart,vend,wstart,wend){ lw<-length(wstart) lv<-length(vstart) z<-cbind(c(wstart,vend),c(rep(0,lw),1:lv),c(1:lw,rep(0,lv))) z<-z[order(z[,1]),] endbefore<-cummax(z[,2])[order(z[,3])][sort(z[,3])!=0] z<-cbind(c(vstart,wend),c(1:lv,rep((lv+1),lw)),c(rep(0,lv),1:lw)) z<-z[order(z[,1]),] startafter<-rev(cummin(rev(z[,2])))[order(z[,3])][sort(z[,3])!=0] return(cbind(endbefore+1,startafter-1)) }
context("apg* functions") test_that("apgOrders works", { skip_on_cran() vcr::use_cassette("apgOrders", { orders <- apgOrders() }) expect_is(orders, "data.frame") expect_is(orders$order, "character") expect_is(orders$accepted, "logical") expect_equal(NCOL(orders), 4) }) test_that("apgFamilies works", { skip_on_cran() vcr::use_cassette("apgFamilies", { families <- apgFamilies() }) expect_is(families, "data.frame") expect_is(families$family, "character") expect_is(families$accepted, "logical") expect_equal(NCOL(families), 5) })
context("cv2") test_that("test error catching",{ X<-matrix(runif(10*20)+1,20,20) expect_error(cv2(X,"test"),"Error in cv2: type must be com, comip, or pop") }) test_that("test cases where it actually provides results",{ set.seed(401) X<-matrix(runif(10*20)+1,10,20) h<-cv2(X, "com") Xtot<-colSums(X) expect_equal(h,(sd(Xtot)/mean(Xtot))^2) h<-cv2(X, "comip") vars<-apply(FUN=var,X=X,MARGIN=1) expect_equal(sum(vars)/((mean(Xtot))^2),h) h<-cv2(X, "pop") expect_equal(h,(sum(sqrt(vars)))^2/(mean(Xtot)^2)) })
species_diversity <- function(df, species, plot=NA, NI_label = "", index="all"){ if( missing(df) ){ stop("df not set", call. = F) }else if(!is.data.frame(df)){ stop("df must be a dataframe", call.=F) }else if(length(df)<=1 | nrow(df)<=1){ stop("Length and number of rows of 'df' must be greater than 1", call.=F) } if( missing(species) ){ stop("species not set", call. = F) }else if( !is.character(species) ){ stop("'species' must be a character containing a variable name", call.=F) }else if(length(species)!=1){ stop("Length of 'species' must be 1", call.=F) }else if(forestmangr::check_names(df, species)==F){ stop(forestmangr::check_names(df, species, boolean=F), call.=F) } if(!is.character( NI_label )){ stop( "'NI_label' must be character", call.=F) }else if(length(NI_label)!=1){ stop("Length of 'NI_label' must be 1", call.=F) } if(!is.character( index )){ stop( "'index' must be character", call.=F) }else if(length(index)!=1){ stop("Length of 'index' must be 1", call.=F) }else if(! index %in% c('all', 'H', 'S', 'Hmax', 'J', 'QM') ){ stop("'index' must be equal to 'all', 'H', 'S', 'Hmax', 'j' or 'QM' ", call. = F) } df <- as.data.frame(df) df <- df[!is.na(df[species]),] if(is.null(NI_label)||NI_label==""){NI_label <- ""} semNI = df[ ! df %in% NI_label ] ESPECIES <- semNI[species] if(missing(plot) || is.null(plot) || is.na(plot) || plot == ""){ PARCELAS <- vector("character", nrow(ESPECIES) ) plot <- NA }else{ PARCELAS <- semNI[plot] } tab_indices <- by(ESPECIES, PARCELAS , function(x){ tableFreq = table(x) tableP = data.frame(tableFreq) names(tableP) = c("especie", "freq") N = sum(tableP$freq) tableP$p = tableP$freq / N tableP$lnp = log(tableP$p) tableP[tableP$lnp == "-Inf", "lnp"] = 0 Sesp = length(tableP[tableP$freq > 0, "especie"]) H = round(- sum(tableP$p * tableP$lnp), 2) S = round(1 - (sum(tableP$freq*(tableP$freq - 1))/(N*(N-1))), 2) Hmax = round(log(length(tableP$freq[tableP$freq>0])), 2) J = round(H / Hmax, 2) QM = round(Sesp / N, 2) tab_final <- data.frame(Shannon = H, Simpson = S, EqMaxima = Hmax, Pielou = J, Jentsch = QM) return(tab_final) } ) tab_indices <- data.frame(do.call(rbind, tab_indices)) if( !is.na(plot) ){ tab_indices <- cbind(aux = row.names(tab_indices), tab_indices) names(tab_indices)[names(tab_indices) == "aux"] <- plot row.names(tab_indices) <- NULL } if (missing(index)|index=="all"){ return(dplyr::as_tibble(tab_indices)) } else if (index == "H"){ return( tab_indices$Shannon ) } else if (index == "S"){ return(tab_indices$Simpson) } else if (index == "Hmax"){ return(tab_indices$EqMaxima) } else if (index == "J"){ return(tab_indices$Pielou) } else if (index == "QM"){ return(tab_indices$Jentsch) } else { return(dplyr::as_tibble(tab_indices)) } }
boundedTransform <- function (x, transform="atox", bounds) { eps <- 2.2204e-16 thre <- 36 y <- array(0, dim(as.array(x))) if ( "atox" == transform ) { for ( ind in seq_along(as.array(x)) ) { if ( x[ind] > thre ) y[ind] <- 1-eps else if ( x[ind] < -thre ) y[ind] <- eps else y[ind] <- 1/(1+exp(-x[ind])) } y <- (bounds[2] - bounds[1])*y + bounds[1] } else if ( "xtoa" == transform ) { x <- (x - bounds[1]) / (bounds[2] - bounds[1]) for ( ind in seq_along(as.array(x)) ) { y[ind] <- .complexLog(x[ind]/(1-x[ind])) } } else if ( "gradfact" == transform ) { y <- (x-bounds[1])*(1-(x-bounds[1])/(bounds[2] - bounds[1])) } return (y) }
library(shinypanels) styles <- " app-container { background-color: } .top-olive { border-top: 2px solid } .text-olive { color: } .icon-close--olive line { stroke: } " ui <- panelsPage( styles = styles, header = p("THIS IS A CUSTOM TITLE"), panel(title = "First Panel", color = "olive", collapsed = FALSE, width = 400, body = div( h2("Body"), selectizeInput("selector", "Select One", choices = c("First", "Second"), selected = "Fist"), img(src="https://placeimg.com/640/480/any") ), footer = h3("This is a footer") ), panel(title = "Visualize", color = "olive", head = h2("Head 2"), body = div( h2(textOutput("selected")), img(src="https://placeimg.com/640/480/nature") ), footer = list( div(class="panel-title", "Tipos de visualización"), h3("This is a footer") ) ) ) server <- function(input, output, session) { output$selected <- renderText({ input$selector }) } shinyApp(ui, server)
getRefPoints<- function(no_d, int.range){ xlat <- (int.range[2]-int.range[1])/(no_d^1.5) ref_points <- double(no_d) for(i in 1:no_d){ ref_points[i] <- (i^1.5) * xlat } ref_points <- ref_points+int.range[1] return(ref_points) } flnl.constr<- function(pars, ddfobj, misc.options,...){ if(is.null(ddfobj$adjustment)){ ineq_constr <- rep(10,2*misc.options$mono.points) }else{ ddfobj <- assign.par(ddfobj,pars) constr <- misc.options$mono strict <- misc.options$mono.strict no_d <- misc.options$mono.points ref_p <- getRefPoints(no_d, misc.options$int.range) if(!is.null(ddfobj$scale)){ ddfobj$scale$dm <- rep(1,no_d) } if(!is.null(ddfobj$shape)){ ddfobj$shape$dm <- rep(1,no_d) } df_v_rp <- as.vector(detfct(ref_p,ddfobj,width=misc.options$width, standardize=TRUE)) ref_p0 <- 0 if(!is.null(ddfobj$scale)){ ddfobj$scale$dm <- 1 } if(!is.null(ddfobj$shape)){ ddfobj$shape$dm <- 1 } df_v_rp0 <- as.vector(detfct(ref_p0,ddfobj,width=misc.options$width, standardize=TRUE)) ic_m <- NULL if(constr){ df_v_rp_p <- df_v_rp0 ic_m <- double(no_d) for(i in 1:no_d){ ic_m[i] <- (df_v_rp_p - df_v_rp[i]) if(strict){ df_v_rp_p <- df_v_rp[i] } } } ic_p <- double(no_d) ic_p <- df_v_rp ineq_constr <- c(ic_m, ic_p) } return(ineq_constr) }
summary.MangroveORs <- function(object,K=NULL,...){ x <- object cat("A Mangrove Odds Ratios object:\nNumber of variants:") cat(length(x[,1])) cat("\nMean absolute het OR: ") cat(round(mean(sapply(x$ORhet,function(i) max(i,1/i))),3)) cat("\nMean absolute hom OR: ") cat(round(mean(sapply(x$ORhom,function(i) max(i,1/i))),3)) RAF <- x$Freq RAF[x$ORhet < 1] <- 1 - RAF[x$ORhet < 1] cat("\nMean risk allele frequency: ") cat(round(mean(RAF),3)) if (is.null(K)){ cat('\nFor a common (10%) disease, these variants explain ') cat(round(getVarExp(x,0.1)*100,2)) cat('% of variance\nFor a rare (0.5%) disease, these variants explain ') cat(round(getVarExp(x,0.005)*100,2)) cat('% of variance\n') } else { cat('\nGiven a prevalence of ') cat(K*100) cat('% these variants explain ') cat(round(getVarExp(x,K)*100,2)) cat('% of variance\n') } }
Nonpara.Two.Sample <- function(alpha, beta,k, p1,p2,p3){ n=(qnorm(1-alpha/2)*sqrt(k*(k+1)/12)+qnorm(1-beta)*sqrt(k^2*(p2-p1^2)+k*(p3-p1^2)))^2/(k^2*(1/2-p1)^2) }
x <- seq(0, 3.5, by = 0.5) y <- x * 0.95 df <- data.frame(x, y) gg <- ggplot(df, aes(x, y)) + geom_point() test_that("second trace be the vline", { p <- gg + geom_vline(xintercept = 1.1, colour = "green", size = 3) L <- expect_doppelganger_built(p, "vline") l <- L$data[[2]] expect_equivalent(length(L$data), 2) expect_equivalent(l$x[1], 1.1) expect_true(l$y[1] <= 0) expect_true(l$y[2] >= 3.325) expect_true(l$mode == "lines") expect_true(l$line$color == "rgba(0,255,0,1)") }) test_that("vector xintercept results in multiple vertical lines", { p <- gg + geom_vline(xintercept = 1:2, colour = "blue", size = 3) L <- expect_doppelganger_built(p, "vline-multiple") expect_equivalent(length(L$data), 2) l <- L$data[[2]] xs <- unique(l$x) ys <- unique(l$y) expect_identical(xs, c(1, NA, 2)) expect_true(min(ys, na.rm = TRUE) <= min(y)) expect_true(max(ys, na.rm = TRUE) >= max(y)) expect_true(l$mode == "lines") expect_true(l$line$color == "rgba(0,0,255,1)") }) test_that("vline works with coord_flip", { gg <- ggplot() + geom_point(aes(5, 6)) + geom_vline(xintercept = 5) + coord_flip() l <- plotly_build(gg)$x expect_equivalent(l$data[[2]]$x, c(5.95, 6.05)) expect_equivalent(l$data[[2]]$y, c(5, 5)) })
data(audit) test_that("xform_map produces correct mapping for a data point", { audit_box <- xform_wrap(audit) t <- list() m <- data.frame( c("Sex", "string", "Male", "Female"), c("Employment", "string", "PSLocal", "PSState"), c("d_sex", "integer", 1, 0) ) t[[1]] <- m audit_box <- xform_map(audit_box, xform_info = t, default_value = c(3), map_missing_to = 2) expect_equal(audit_box$field_data["d_sex", "transform"], "MapValues") expect_equal(audit_box$field_data["d_sex", "default"], 3) expect_equal(audit_box$field_data["d_sex", "missingValue"], 2) expect_true(audit_box$data$d_sex[[1]] == 3) }) test_that("PMML from xform_map contains correct local transformation", { audit_box <- xform_wrap(audit) t <- list() m <- data.frame( c("Sex", "string", "Male", "Female"), c("Employment", "string", "PSLocal", "PSState"), c("d_sex", "integer", 1, 0) ) t[[1]] <- m audit_box <- xform_map(audit_box, xform_info = t, default_value = c(3), map_missing_to = 2) fit <- lm(Adjusted ~ ., data = audit_box$data) fit_pmml <- pmml(fit, transforms = audit_box) expect_equal(toString(fit_pmml[[3]][[3]]), "<LocalTransformations>\n <DerivedField name=\"d_sex\" dataType=\"string\" optype=\"categorical\">\n <MapValues mapMissingTo=\"2\" defaultValue=\"3\" outputColumn=\"output\">\n <FieldColumnPair field=\"Sex\" column=\"input1\"/>\n <FieldColumnPair field=\"Employment\" column=\"input2\"/>\n <InlineTable>\n <row>\n <input1>Male</input1>\n <input2>PSLocal</input2>\n <output>1</output>\n </row>\n <row>\n <input1>Female</input1>\n <input2>PSState</input2>\n <output>0</output>\n </row>\n </InlineTable>\n </MapValues>\n </DerivedField>\n</LocalTransformations>") }) test_that("xform_map uses file with xform_info correctly", { audit_box <- xform_wrap(audit) audit_box <- xform_map(audit_box, xform_info = "[Sex -> d_sex][string->integer]", table = "map_audit.csv", map_missing_to = "0" ) expect_equal(audit_box$data$d_sex[1:5], c(2, 1, 1, 1, 1)) f_map <- cbind(c("Sex", "string", "Male", "Female"), c("d_sex", "numeric", "1", "2")) expect_equal(audit_box$field_data$fieldsMap[[14]], f_map, check.attributes = FALSE) })
library(ggplot2) this_base <- "fig04-22_mountain-height-data-line-graph" my_data <- data.frame( cont = c("Asia", "S.America", "N.America", "Africa", "Antarctica", "Europe", "Austrailia"), height = c(29029, 22838, 20322, 19341, 16050, 16024, 7310), mountain = c("Everest", "Aconcagua", "McKinley", "Kilmanjaro", "Vinson", "Blanc", "Kosciuszko"), stringsAsFactors = FALSE ) p <- ggplot(my_data, aes(x = reorder(cont, -height), y = height, group = factor(1))) + geom_line() + geom_point() + scale_y_continuous(breaks = seq(0, 35000, 5000), limits = c(0, 35000), expand = c(0, 0)) + labs(x = "Continent", y = "Height (feet)") + ggtitle("Fig 4.22 Mountain Height Data: Line Graph") + theme_bw() + theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_line(colour = "grey50"), plot.title = element_text(size = rel(1.2), face = "bold", vjust = 1.5), axis.title = element_text(face = "bold")) p ggsave(paste0(this_base, ".png"), p, width = 6, height = 4)
ced <- function(x, y, ni){ return(aDist(x, y)/ni) }
pcirc <- function(gcol = "black", border = "black", ndiv = 36) { if (missing(gcol)) { gcol = "black" } if (missing(border)) { border = "black" } if (missing(ndiv)) { ndiv = 36 } phi = seq(0, 2 * pi, by = 2 * pi/ndiv) y = cos(phi) x = sin(phi) lines(x, y, col = border) lines(c(-1, 1), c(0, 0), col = gcol) lines(c(0, 0), c(-1, 1), col = gcol) }
IWT3_PO <- function(wc, L, qmf) { c <- cubelength(wc) n <- c$x J <- c$y x <- wc nc <- 2^(L + 1) for (jscal in seq(L, J - 1, 1)) { top <- (nc/2 + 1):nc bot <- 1:(nc/2) all <- 1:nc for (iy in 1:nc) { for (iz in 1:nc) { x[all, iy, iz] <- UpDyadLo(x[bot, iy, iz], qmf) + UpDyadHi(x[top, iy, iz], qmf) } } for (ix in 1:nc) { for (iy in 1:nc) { x[ix, iy, all] <- UpDyadLo(x[ix, iy, bot], qmf) + UpDyadHi(x[ix, iy, top], qmf) } } for (ix in 1:nc) { for (iz in 1:nc) { x[ix, all, iz] <- UpDyadLo(x[ix, bot, iz], qmf) + UpDyadHi(x[ix, top, iz], qmf) } } nc <- 2 * nc } return(x) }
.calc_DoseRate <- function( x, data, DR_conv_factors = NULL, ref = NULL, length_step = 1, max_time = 500, mode_optim = FALSE ){ if(is.null(ref)){ Reference_Data <- NULL data("Reference_Data", envir = environment()) ref <- Reference_Data rm(Reference_Data) } TIMEMAX <- x STEP1 <- length_step[1] if(is.null(DR_conv_factors)){ DR_ID <- 1 }else{ DR_ID <- grep( x = ref[["DR_conv_factors"]][["REFERENCE"]], pattern = DR_conv_factors, fixed = TRUE) } handles.UB <- ref[["DR_conv_factors"]][["UB"]][DR_ID] handles.TB <- ref[["DR_conv_factors"]][["TB"]][DR_ID] handles.KB <- ref[["DR_conv_factors"]][["KB"]][DR_ID] handles.UG <- ref[["DR_conv_factors"]][["UG"]][DR_ID] handles.TG <- ref[["DR_conv_factors"]][["TG"]][DR_ID] handles.KG <- ref[["DR_conv_factors"]][["KG"]][DR_ID] KA <- data[["K"]] UA <- data[["U"]] TA <- data[["T"]] K <- KA * (1 + data[["CC"]] / 100) U <- UA * (1 + data[["CC"]] / 100) T <- TA * (1 + data[["CC"]] / 100) C <- c( rep(1, data[["FINISH"]] / STEP1) * data[["CC"]] / 100, seq(data[["CC"]] / 100, 1e-05, length.out = (data[["ONSET"]] - data[["FINISH"]]) / STEP1 + 1), rep(0, (max_time - data[["ONSET"]]) / STEP1) + 1e-05 ) WC <- c( rep(1, data[["FINISH"]] / STEP1) * data[["WCF"]] / 100, seq(data[["WCF"]] / 100, data[["WCI"]] / 100, length.out = (data[["ONSET"]] - data[["FINISH"]]) / STEP1 + 1), rep(0, (max_time - data[["ONSET"]]) / STEP1) + data[["WCI"]] / 100 ) WF <- C + WC WFA <- data[["WCF"]] / 100 LEN <- length(C) TIME <- matrix(seq(0, max_time, STEP1), nrow = 1) TIME_ <- seq(0,round(TIMEMAX * STEP1)/STEP1) TIME_ <- c(rep(0,max_time - max(TIME_)), TIME_) lam_u235 <- log(2) / 703800000 lam_u238 <- log(2) / 4.4680e+09 Aa <- .rad_pop_LU(data[["U234_U238"]], TIME_) Aa <- apply(Aa, 2, rev) A_u238 <- lam_u238 * 6.022e+023 * 1e-3 / (238 * 31.56e+06) A_u235 <- lam_u235 * 6.022e+23 * 1e-03 / (235 * 31.56e+06) conv_const <- 5.056e-03 CONST_Q_U238 <- 0.9927 CONST_Q_U235 <- 1 - CONST_Q_U238 D_b_u238 <- conv_const * A_u238 * 0.8860 * CONST_Q_U238 D_b_u234 <- conv_const * A_u238 * 0.0120 * CONST_Q_U238 D_b_t230 <- conv_const * A_u238 * 1.3850 * CONST_Q_U238 D_b_u235 <- conv_const * A_u235 * 0.1860 * CONST_Q_U235 D_g_u238 <- conv_const * A_u238 * 0.0290 * CONST_Q_U238 D_g_u234 <- conv_const * A_u238 * 0.0020 * CONST_Q_U238 D_g_t230 <- conv_const * A_u238 * 1.7430 * CONST_Q_U238 U238_b_diseq <- D_b_u238 * Aa[,"N_u238"] * data[["U238"]] U234_b_diseq <- D_b_u234 * Aa[,"N_u234"] * data[["U238"]] T230_b_diseq <- D_b_t230 * Aa[,"N_t230"] * data[["U238"]] U238_g_diseq <- D_g_u238 * Aa[,"N_u238"] * data[["U238"]] U234_g_diseq <- D_g_u234 * Aa[,"N_u234"] * data[["U238"]] T230_g_diseq <- D_g_t230 * Aa[,"N_t230"] * data[["U238"]] MK <- 1 - exp( approx(x = log(ref$mejdahl[[1]]), y = log(ref$mejdahl[[2]]), xout = log(data[["DIAM"]]/1000), rule = 2)$y) MT <- 1 - exp( approx(x = log(ref$mejdahl[[1]]), y = log(ref$mejdahl[[3]]), xout = log(data[["DIAM"]]/1000), rule = 2)$y) MU <- 1 - exp( approx(x = log(ref$mejdahl[[1]]), y = log(ref$mejdahl[[4]]), xout = log(data[["DIAM"]]/1000), rule = 2)$y) MU238 <- MU234 <- MT230 <- MU235 <- MP231 <- 1 x_grid <- as.numeric(colnames(ref$DATAek)) y_grid <- x_grid x_grid <- log(rep(x_grid, length(x_grid))) y_grid <- log(rep(y_grid, each = length(y_grid))) xo <- log(WC) yo <- log(C) XKB <- .griddata(x_grid, y_grid, ref$DATAek, xo, yo) XTB <- .griddata(x_grid, y_grid, ref$DATAet, xo, yo) XUB <- .griddata(x_grid, y_grid, ref$DATAeu, xo, yo) XU238B <- .griddata(x_grid, y_grid, ref$DATAeu238, xo, yo) XU234B <- .griddata(x_grid, y_grid, ref$DATAeu234, xo, yo) XT230B <- .griddata(x_grid, y_grid, ref$DATAet230, xo, yo) XKG <- .griddata(x_grid, y_grid, ref$DATApk, xo, yo) XTG <- .griddata(x_grid, y_grid, ref$DATApt, xo, yo) XUG <- .griddata(x_grid, y_grid, ref$DATApu, xo, yo) XU238G <- .griddata(x_grid, y_grid, ref$DATApu238, xo, yo) XU234G <- .griddata(x_grid, y_grid, ref$DATApu234, xo, yo) XT230G <- .griddata(x_grid, y_grid, ref$DATApt230, xo, yo) DRKB <- MK * K * handles.KB / (1 + XKB * WF) DRTB <- MT * T * handles.TB / (1 + XTB * WF) DRUB <- MU * U * handles.UB / (1 + XUB * WF) DRU238B <- MU238 * U238_b_diseq / (1 + XU238B * WF) DRU234B <- MU238 * U234_b_diseq / (1 + XU234B * WF) DRT230B <- MU238 * T230_b_diseq / (1 + XT230B * WF) DRKG <- MK * K * handles.KG / (1 + XKG * WF) DRTG <- MT * T * handles.TG / (1 + XTG * WF) DRUG <- MU * U * handles.UG / (1 + XUG * WF) DRU238G <- MU238 * U238_g_diseq / (1 + XU238G * WF) DRU234G <- MU238 * U234_g_diseq / (1 + XU234G * WF) DRT230G <- MU238 * T230_g_diseq / (1 + XT230G * WF) DR <- DRKB + DRTB + DRUB + DRKG + DRTG + DRUG + data[["COSMIC"]] + data[["INTERNAL"]] + DRU238B + DRU234B + DRT230B + DRU238G + DRU234G + DRT230G XKBA <- XTBA <- XUBA <- XU238BA <- XU234BA <- XT230BA <- 1.25 XKGA <- XTGA <- XUGA <- XU238GA <- XU234GA <- XT230GA <- 1.14 DRKBA <- MK * KA * handles.KB / (1 + XKBA * WFA) DRTBA <- MT * TA * handles.TB / (1 + XTBA * WFA) DRUBA <- MU * UA * handles.UB / (1 + XUBA * WFA) DRU238BA <- MU238 * U238_b_diseq / (1 + XU238BA * WFA) DRU234BA <- MU238 * U234_b_diseq / (1 + XU234BA * WFA) DRT230BA <- MU238 * T230_b_diseq / (1 + XT230BA * WFA) DRKGA <- MK * KA * handles.KG / (1 + XKGA * WFA) DRTGA <- MT * TA * handles.TG / (1 + XTGA * WFA) DRUGA <- MU * UA * handles.UG / (1 + XUGA * WFA) DRU238GA <- MU238 * U238_g_diseq / (1 + XU238GA * WFA) DRU234GA <- MU238 * U234_g_diseq / (1 + XU234GA * WFA) DRT230GA <- MU238 * T230_g_diseq / (1 + XT230GA * WFA) DRA <- DRKBA + DRTBA + DRUBA + DRKGA + DRTGA + DRUGA + data[["COSMIC"]] + data[["INTERNAL"]] + DRU238BA + DRU234BA + DRT230BA + DRU238GA + DRU234GA + DRT230GA DR[is.na(DR)] <- 0 DRA[is.na(DRA)] <- 0 CUMDR <- cumsum(c(0, (DR[1:(length(DR) - 1)] + DR[2:length(DR)]) * STEP1 / 2)) CUMDRA <- cumsum(c(0, (DRA[1:(length(DRA) - 1)] + DRA[2:length(DRA)]) * STEP1 / 2)) if(data[["DE"]] > max(CUMDR)) warning("[.calc_DoseRate()] Extrem case detected: DE > max cumulative dose rate!", call. = FALSE) AGE <- try( approx(x = CUMDR, y = as.numeric(TIME), xout = data[["DE"]], method = "linear", rule = 2)$y, silent = TRUE) AGEA <- try( approx(x = CUMDRA, y = as.numeric(TIME), xout = data[["DE"]], method = "linear", rule = 2)$y, silent = TRUE) if(class(AGE) == 'try-error' || class(AGEA) == 'try-error') stop("[.calc_DoseRate()] Modelling failed, please check your input data, they may not be meaningful!", call. = FALSE) ABS <- abs(AGE - TIMEMAX) if(mode_optim){ results <- ABS }else{ results <- list( ABS = ABS, AGE = AGE, AGEA = AGEA, LEN = LEN, DR = DR, DRA = DRA, CUMDR = CUMDR, CUMDRA = CUMDRA ) } return(results) }
getDictionaryEntries <- function(labbcat.url, manager.id, dictionary.id, keys) { upload.file = "keys.csv" download.file = "entries.csv" write.table(keys, upload.file, sep=",", row.names=FALSE, col.names=FALSE) parameters <- list(managerId=manager.id, dictionaryId=dictionary.id, uploadfile=httr::upload_file(upload.file)) resp <- http.post.multipart(labbcat.url, "dictionary", parameters, download.file) file.remove(upload.file) if (is.null(resp)) return() resp.content <- httr::content(resp, as="text", encoding="UTF-8") if (httr::status_code(resp) != 200) { print(paste("ERROR: ", httr::http_status(resp)$message)) print(resp.content) return() } ncol <- max(count.fields(download.file, sep=",", quote="\"")) entries <- read.csv( download.file, header=F, col.names = paste0("V", seq_len(ncol)), blank.lines.skip=F) colnames(entries) <- c("key", head(colnames(entries), length(colnames(entries)) - 1)) file.remove(download.file) return(entries) }
Rcppfunction_remove_classes <- function(string, maxlen=70, remove=TRUE) { string <- gsub("\n", "", string ) string <- gsub("\t", "", string ) string <- gsub(" ", "", string ) ind1 <- string_find_first(string=string, symbol="(" ) a1 <- c( substring(string,1, ind1-1), substring(string, ind1+1, nchar(string) ) ) s1 <- a1[2] ind1 <- string_find_last(string=s1, symbol=")" ) s1 <- substring(s1,1, ind1-1) s1 <- strsplit( s1, split=",", fixed=TRUE )[[1]] rcpp_classes <- c("double", "bool", "int", "arma::mat", "arma::colvec", "arma::umat", "Rcpp::NumericVector", "Rcpp::IntegerVector", "Rcpp::LogicalVector", "Rcpp::CharacterVector", "Rcpp::CharacterMatrix", "Rcpp::List", "Rcpp::NumericMatrix", "Rcpp::IntegerMatrix", "Rcpp::LogicalMatrix", "char" ) rcpp_classes1 <- paste0( rcpp_classes, " " ) if (remove){ for (rr in rcpp_classes1 ){ s1 <- gsub( rr, "", s1, fixed=TRUE ) a1[1] <- gsub( rr, "", a1[1], fixed=TRUE ) } a1[1] <- gsub( " ", "", a1[1] ) } NS <- length(s1) s2 <- s1 if (remove){ s2 <- gsub( " ", "", s2 ) } M0 <- nchar(a1[1]) for (ss in 1:NS){ if (remove){ s2[ss] <- gsub( " ", "", s2[ss] ) } nss <- nchar(s2[ss]) M0 <- M0 + nss if (M0 > maxlen ){ s2[ss] <- paste0("\n ", s2[ss] ) M0 <- nss } } s2 <- paste0( a1[1], "( ", paste0( s2, collapse=", " ), " )\n" ) s2 <- gsub( ", ", ", ", s2, fixed=TRUE) s2 <- gsub( "( ", "( ", s2, fixed=TRUE) s2 <- gsub( " )", " )", s2, fixed=TRUE) for (uu in 1:2){ s2 <- gsub("\n ", "\n", s2, fixed=TRUE) } return(s2) }
colorwig<-function(x1, y1, COL=rainbow(100)) { if(missing(COL)) COL=rainbow(100) nlen = length(x1) ncol = length(COL) KR = nlen/(ncol-1) KX = floor(seq(from=1, length=nlen)/(KR))+1 cols=COL[KX] plot(x1, y1, type='n', xlab="time, s", ylab="Pa" ) abline(h=0) segments(x1[1:(nlen-1)] , y1[1:(nlen-1)], x1[2:nlen], y1[2:nlen], col=cols) invisible(cols) }
removeNULL <- function (aList){ Filter(Negate(is.null), aList) }
source('loadTestDataFunc.R') test_that('Test assignNAsToMFGs.R',{ loadTestDataFunc(1) expect_error(assignNAsToMFGs(microbeNames,numPaths,keyRes,resourceNames),NA) Archea['halfSat','CH4']<<-2 expect_error(assignNAsToMFGs(microbeNames,numPaths,keyRes,resourceNames)) }) test_that("Test checkResInfo",{ loadTestDataFunc(1) resNames=c('res1') expect_error(checkResInfo(resNames,resInfo1)) resNames=c('H2') expect_error(checkResInfo(resNames,resInfo1),NA) }) test_that("Test checkStoichiom.R",{ loadTestDataFunc(1) stoiTol=0.1 expect_warning(checkStoichiom(stoichiom, Rtype, microbeNames, numPaths, stoiTol,reBalanceStoichiom = FALSE),NA) stoichiom['Archea','H2','path1']=20 expect_warning(checkStoichiom(stoichiom, Rtype, microbeNames, numPaths, stoiTol,reBalanceStoichiom = FALSE)) }) test_that("Test combineGrowthLimFuncDefault",{ loadTestDataFunc(1) maxGrowthRate=out$parms$Pmats$maxGrowthRate[[microbeNames[1]]][1,] growthLim=c(0.5,0.1,NA,NA) names(growthLim)=resourceNames x = combineGrowthLimFuncDefault(allStrainNames[1], microbeNames[1], 'path1', subst=NULL, ess=resourceNames[1:2], boost=NULL, bio.sub=NULL, maxGrowthRate, growthLim, keyResName='H2', nonBoostFrac=1) expect_equal(x,0.5*0.1*maxGrowthRate['H2'],tolerance=0.001) }) test_that("Test entryRateFuncDefault.R",{ loadTestDataFunc(1) stateVarValues=c(seq(1,length(microbeNames)),seq(1,length(resourceNames))) names(stateVarValues)=c(microbeNames,resourceNames) inflowRate=rep(10,length(stateVarValues)) names(inflowRate)=names(stateVarValues) x=entryRateFuncDefault(varName=resourceNames[1], varValue=0.1, stateVarValues, time=1, inflowRate,parms=out$parms) expect_true(is.numeric(x)) expect_equal(length(x),1) x=entryRateFuncDefault(varName=microbeNames[1], varValue=0.1, stateVarValues, time=1, inflowRate,parms=out$parms) expect_true(is.numeric(x)) expect_equal(length(x),1) }) test_that("Test getAllResources.R",{ loadTestDataFunc(1) x=getAllResources('Archea') expect_true(all(is.character(x))) expect_true(is.vector(x)) expect_equal(length(x),4) expect_equal(x,resourceNames) file=paste(system.file("testdata",package="microPop"),'/MFG1.csv',sep='') M1<<-createDF(file) x=getAllResources('M1') expect_true(is.vector(x)) expect_equal(length(x),2) expect_equal(x,c('S1','P1')) }) test_that("Test getKeyRes.R",{ loadTestDataFunc(1) x=getKeyRes(microbeNames,numPaths) expect_true(is.list(x)) expect_equal(x$Archea[[1]],'H2') }) test_that("Test getNonBoostFrac.R",{ loadTestDataFunc(1) x=getNonBoostFrac(microbeNames,resourceNames,numPaths) expect_true(is.array(x)) expect_equal(x['Archea',1,'path1'],1) }) test_that("Test getNumPaths.R",{ loadTestDataFunc(1) x=getNumPaths(microbeNames) expect_true(is.vector(x)) expect_equal(x,round(x)) expect_equal(names(x),microbeNames) }) test_that('Test getValues.R',{ loadTestDataFunc(1) x=getValues(micInfo1, resInfo1, c(microbeNames, resourceNames), 'startValue',allStrainNames,microbeNames, resourceNames, 1) expect_equal(names(x),c(microbeNames,resourceNames)) expect_equal(length(x),length(microbeNames)+length(resourceNames)) expect_true(x[1]-micInfo1['startValue','Archea']==0) }) test_that("Test growthLimFuncDefault.R",{ loadTestDataFunc(1) resVal=seq(1,length(resourceNames)) names(resVal)=resourceNames allSubType=Rtype[1,,1] strainHalfSat=halfSat[[microbeNames[1]]][1,] stateVarValues=c(1,resVal) names(stateVarValues)=c(microbeNames,resourceNames) x=growthLimFuncDefault(strainName=allStrainNames[1], groupName=microbeNames[1], pathName='path1', varName=resourceNames[1], resourceValues=resVal, allSubType, strainHalfSat, stateVarValues) expect_true(x<=1) expect_true(x>=0) }) test_that('Test makeParamMatrixG.R',{ loadTestDataFunc(1) expect_error(makeParamMatrixG(microbeNames, 'Rtype', numPaths, resInfo1, 113, resourceNames),NA) x=makeParamMatrixG('Archea', 'Rtype', numPaths, resInfo1, 113, resourceNames) expect_true(is.array(x)) expect_equal(dim(x),c(length(microbeNames),length(resourceNames),length(numPaths))) expect_equal(names(x['Archea',,'path1']),resourceNames) expect_error(makeParamMatrixG(microbeNames, 'stoichiom', numPaths, resInfo1, 113, resourceNames),NA) x=makeParamMatrixG('Archea', 'stoichiom', numPaths, resInfo1, 113, resourceNames) expect_true(is.array(x)) expect_equal(dim(x),c(length(microbeNames),length(resourceNames),length(numPaths))) expect_equal(names(x['Archea',,'path1']),resourceNames) MFG1=Archea rownames(MFG1)[1]='rtype' numPaths1=numPaths names(numPaths1)='MFG1' expect_error(makeParamMatrixG('MFG1', 'Rtype', numPaths1, resInfo1, 113, resourceNames)) rownames(MFG1)[5]='Stoichiom' expect_error(makeParamMatrixG('MFG1', 'Rtype', numPaths1, resInfo1, 113, resourceNames)) }) test_that('Test productionFuncDefault.R',{ loadTestDataFunc(1) uptake=c(1,2,NA,NA) names(uptake)=resourceNames growthRate=1 varName='CH4' products=c('CH4','H2O') all.substrates=c('H2','CO2') bio.products=NULL water=NULL stoi=stoichiom[,,'path1'] x=productionFuncDefault('Archea', 'Archea', 'path1',varName, all.substrates, 'H2',stoichiom=stoi, products,bio.products, uptake, growthRate, yield, parms, water) expect_true(x>=0) expect_true(is.finite(x)) expect_equal(length(x),1) }) test_that('Test uptakeFuncDefault.R',{ loadTestDataFunc(1) varName='CO2' growthLim=c(0.4,0.9,NA,NA) names(growthLim)=resourceNames stoi=stoichiom[,,'path1'] x=uptakeFuncDefault('Archea', 'Archea', 'path1',varName,keyResName='H2', subst=NULL, ess=c('H2','CO2'),boost=NULL, maxGrowthRate=maxGrowthRate$Archea[1,], growthLim,yield$Archea[1,],nonBoostFrac=parms$nonBoostFrac[,,'path1'], stoichiom=stoi,parms) expect_true(x>=0) expect_true(is.finite(x)) expect_equal(length(x),1) }) test_that('Test waterUptakeRatio.R',{ loadTestDataFunc(1) x=waterUptakeRatio(microbeNames, stoichiom, Rtype, numPaths) expect_equal(rownames(x),microbeNames) expect_true(x-0==0) Rtype1=Rtype Rtype1['Archea','CO2',]='Sw' x=waterUptakeRatio(microbeNames, stoichiom, Rtype1, numPaths) expect_equal(rownames(x),microbeNames) expect_true(x-44/8==0) }) test_that('Test makeParamMatrixS.R',{ loadTestDataFunc(0) expect_error(makeParamMatrixS(resourceNames,microbeNames, 'halfSat', numPaths, out$parms$numStrains,strainOptions=list(), oneStrainRandomParams=FALSE),NA) expect_error(makeParamMatrixS(resourceNames,microbeNames, 'yield', numPaths, out$parms$numStrains,strainOptions=list(), oneStrainRandomParams=FALSE),NA) expect_error(makeParamMatrixS(resourceNames,microbeNames, 'maxGrowthRate', numPaths, out$parms$numStrains,strainOptions=list(), oneStrainRandomParams=FALSE),NA) expect_error(makeParamMatrixS(resourceNames,microbeNames, 'HalfSat', numPaths, out$parms$numStrains,strainOptions=list(), oneStrainRandomParams=FALSE)) expect_error(makeParamMatrixS(resourceNames,microbeNames, 'Yield', numPaths, out$parms$numStrains,strainOptions=list(), oneStrainRandomParams=FALSE)) expect_error(makeParamMatrixS(resourceNames,microbeNames, 'MaxGrowthRate', numPaths, out$parms$numStrains,strainOptions=list(), oneStrainRandomParams=FALSE)) x=makeParamMatrixS(resourceNames,microbeNames, 'halfSat', numPaths, out$parms$numStrains,strainOptions=list(),oneStrainRandomParams=FALSE) expect_true(is.list(x)) expect_equal(dim(x[[microbeNames[1]]]),c(length(numPaths),length(resourceNames))) expect_equal(names(x[[microbeNames[1]]]['path1',]),resourceNames) })
InventoryGrowthFusionDiagnostics <- function(jags.out, combined=NULL) { out <- as.matrix(jags.out) x.cols <- which(substr(colnames(out), 1, 1) == "x") if(length(x.cols) > 0){ ci <- apply(out[, x.cols], 2, quantile, c(0.025, 0.5, 0.975)) ci.names <- parse.MatrixNames(colnames(ci), numeric = TRUE) if(length(x.cols) > 0){ layout(matrix(1:8, 4, 2, byrow = TRUE)) ci <- apply(out[, x.cols], 2, quantile, c(0.025, 0.5, 0.975)) ci.names <- parse.MatrixNames(colnames(ci), numeric = TRUE) smp <- sample.int(data$ni, min(8, data$ni)) for (i in smp) { sel <- which(ci.names$row == i) rng <- c(range(ci[, sel], na.rm = TRUE), range(data$z[i, ], na.rm = TRUE)) plot(data$time, ci[2, sel], type = "n", ylim = range(rng), ylab = "DBH (cm)", main = i) PEcAn.visualization::ciEnvelope(data$time, ci[1, sel], ci[3, sel], col = "lightBlue") points(data$time, data$z[i, ], pch = "+", cex = 1.5) sel <- which(ci.names$row == i) inc.mcmc <- apply(out[, x.cols[sel]], 1, diff) inc.ci <- apply(inc.mcmc, 1, quantile, c(0.025, 0.5, 0.975)) * 5 plot(data$time[-1], inc.ci[2, ], type = "n", ylim = range(inc.ci, na.rm = TRUE), ylab = "Ring Increment (mm)") PEcAn.visualization::ciEnvelope(data$time[-1], inc.ci[1, ], inc.ci[3, ], col = "lightBlue") points(data$time, data$y[i, ] * 5, pch = "+", cex = 1.5, type = "b", lty = 2) } } } if (FALSE) { plot(out[, which(colnames(out) == "x[3,31]")]) abline(h = z[3, 31], col = 2, lwd = 2) hist(out[, which(colnames(out) == "x[3,31]")]) abline(v = z[3, 31], col = 2, lwd = 2) } vars <- (1:ncol(out))[-c(which(substr(colnames(out), 1, 1) == "x"), grep("tau", colnames(out)), grep("year", colnames(out)), grep("ind", colnames(out)), grep("alpha",colnames(out)), grep("deviance",colnames(out)))] par(mfrow = c(1, 1)) for (i in vars) { hist(out[, i], main = colnames(out)[i]) abline(v=0,lwd=3) } if (length(vars) > 1 && length(vars) < 10) { pairs(out[, vars]) } if("deviance" %in% colnames(out)){ hist(out[,"deviance"]) vars <- c(vars,which(colnames(out)=="deviance")) } var.out <- as.mcmc.list(lapply(jags.out,function(x){ x[,vars]})) gelman.diag(var.out) plot(var.out) if("deviance" %in% colnames(out)){ hist(out[,"deviance"]) vars <- c(vars,which(colnames(out)=="deviance")) } var.out <- as.mcmc.list(lapply(jags.out,function(x){ x[,vars]})) gelman.diag(var.out) plot(var.out) par(mfrow = c(2, 3)) prec <- out[, grep("tau", colnames(out))] for (i in seq_along(colnames(prec))) { hist(1 / sqrt(prec[, i]), main = colnames(prec)[i]) } cor(prec) par(mfrow = c(1, 1)) alpha.cols <- grep("alpha", colnames(out)) if (length(alpha.cols) > 0) { alpha.ord <- 1:length(alpha.cols) ci.alpha <- apply(out[, alpha.cols], 2, quantile, c(0.025, 0.5, 0.975)) plot(alpha.ord, ci.alpha[2, ], type = "n", ylim = range(ci.alpha, na.rm = TRUE), ylab = "Random Effects") PEcAn.visualization::ciEnvelope(alpha.ord, ci.alpha[1, ], ci.alpha[3, ], col = "lightBlue") lines(alpha.ord, ci.alpha[2, ], lty = 1, lwd = 2) abline(h = 0, lty = 2) } par(mfrow = c(1, 1)) alpha.cols <- grep("alpha", colnames(out)) if (length(alpha.cols) > 0) { alpha.ord <- 1:length(alpha.cols) ci.alpha <- apply(out[, alpha.cols], 2, quantile, c(0.025, 0.5, 0.975)) plot(alpha.ord, ci.alpha[2, ], type = "n", ylim = range(ci.alpha, na.rm = TRUE), ylab = "Random Effects") PEcAn.visualization::ciEnvelope(alpha.ord, ci.alpha[1, ], ci.alpha[3, ], col = "lightBlue") lines(alpha.ord, ci.alpha[2, ], lty = 1, lwd = 2) abline(h = 0, lty = 2) } year.cols <- grep("year", colnames(out)) if (length(year.cols > 0)) { ci.yr <- apply(out[, year.cols], 2, quantile, c(0.025, 0.5, 0.975)) plot(data$time, ci.yr[2, ], type = "n", ylim = range(ci.yr, na.rm = TRUE), ylab = "Year Effect") PEcAn.visualization::ciEnvelope(data$time, ci.yr[1, ], ci.yr[3, ], col = "lightBlue") lines(data$time, ci.yr[2, ], lty = 1, lwd = 2) abline(h = 0, lty = 2) } ind.cols <- which(substr(colnames(out), 1, 3) == "ind") if (length(ind.cols) > 0 & !is.null(combined)) { boxplot(out[, ind.cols], horizontal = TRUE, outline = FALSE, col = as.factor(combined$PLOT)) abline(v = 0, lty = 2) tapply(apply(out[, ind.cols], 2, mean), combined$PLOT, mean) table(combined$PLOT) spp <- combined$SPP boxplot(out[, ind.cols], horizontal = TRUE, outline = FALSE, col = spp) abline(v = 0, lty = 2) spp.code <- levels(spp)[table(spp) > 0] legend("bottomright", legend = rev(spp.code), col = rev(which(table(spp) > 0)), lwd = 4) tapply(apply(out[, ind.cols], 2, mean), combined$SPP, mean) } }
NULL PrestoDETest <- function( data.use, cells.1, cells.2, verbose = TRUE, ... ) { data.use <- data.use[, c(cells.1, cells.2), drop = FALSE] group.info <- factor( c(rep(x = "Group1", length = length(x = cells.1)), rep(x = "Group2", length = length(x = cells.2))), levels = c("Group1", "Group2")) names(x = group.info) <- c(cells.1, cells.2) data.use <- data.use[, names(x = group.info), drop = FALSE] res <- presto::wilcoxauc(X = data.use, y = group.info) res <- res[1:(nrow(x = res)/2), c('pval','auc')] colnames(x = res)[1] <- 'p_val' return(as.data.frame(x = res, row.names = rownames(x = data.use))) } RunPresto <- function( object, ident.1 = NULL, ident.2 = NULL, group.by = NULL, subset.ident = NULL, assay = NULL, slot = 'data', reduction = NULL, features = NULL, logfc.threshold = 0.25, test.use = "wilcox", min.pct = 0.1, min.diff.pct = -Inf, verbose = TRUE, only.pos = FALSE, max.cells.per.ident = Inf, random.seed = 1, latent.vars = NULL, min.cells.feature = 3, min.cells.group = 3, pseudocount.use = 1, mean.fxn = NULL, fc.name = NULL, base = 2, ... ) { if (test.use != 'wilcox') { stop("Differential expression test must be `wilcox`") } CheckPackage(package = 'immunogenomics/presto', repository = 'github') orig.fxn <- rlang::duplicate(x = Seurat:::WilcoxDETest) assignInNamespace( x = "WilcoxDETest", value = PrestoDETest, ns = "Seurat") tryCatch( expr = res <- FindMarkers( object, ident.1, ident.2, group.by, subset.ident, assay, slot, reduction, features, logfc.threshold, test.use, min.pct, min.diff.pct, verbose, only.pos, max.cells.per.ident, random.seed, latent.vars, min.cells.feature, min.cells.group, pseudocount.use, mean.fxn, fc.name, base, ... ), finally = assignInNamespace( x = "WilcoxDETest", value = orig.fxn, ns = "Seurat") ) return(res) } RunPrestoAll <- function( object, assay = NULL, features = NULL, logfc.threshold = 0.25, test.use = 'wilcox', slot = 'data', min.pct = 0.1, min.diff.pct = -Inf, node = NULL, verbose = TRUE, only.pos = FALSE, max.cells.per.ident = Inf, random.seed = 1, latent.vars = NULL, min.cells.feature = 3, min.cells.group = 3, pseudocount.use = 1, mean.fxn = NULL, fc.name = NULL, base = 2, return.thresh = 1e-2, ... ) { if (test.use != 'wilcox') { stop("Differential expression test must be `wilcox`") } CheckPackage(package = 'immunogenomics/presto', repository = 'github') orig.fxn <- rlang::duplicate(x = Seurat:::WilcoxDETest) assignInNamespace( x = "WilcoxDETest", value = PrestoDETest, ns = "Seurat") tryCatch( expr = res <- FindAllMarkers( object, assay, features, logfc.threshold, test.use, slot, min.pct, min.diff.pct, node, verbose, only.pos, max.cells.per.ident, random.seed, latent.vars, min.cells.feature, min.cells.group, pseudocount.use, mean.fxn, fc.name, base, return.thresh, ... ), finally = assignInNamespace( x = "WilcoxDETest", value = orig.fxn, ns = "Seurat") ) return(res) }
lento <- function(obj, xlim = NULL, ylim = NULL, main = "Lento plot", sub = NULL, xlab = NULL, ylab = NULL, bipart = TRUE, trivial = FALSE, col = rgb(0, 0, 0, .5), ...) { if (inherits(obj, "phylo")) { if (inherits(obj, "phylo", TRUE) == 1) obj <- as.splits(obj)[obj$edge[, 2]] obj <- as.splits(obj) } if (inherits(obj, "multiPhylo")) obj <- as.splits(obj) labels <- attr(obj, "labels") l <- length(labels) if (!trivial) { triv <- lengths(obj) ind <- logical(length(obj)) ind[(triv > 1) & (triv < (l - 1))] <- TRUE if (length(col) == length(obj)) col <- col[ind] obj <- obj[ind] } CM <- compatible(obj) support <- attr(obj, "weights") if (is.null(support)) support <- rep(1, length(obj)) conflict <- -as.matrix(CM) %*% support n <- length(support) if (is.null(ylim)) { eps <- (max(support) - min(conflict)) * 0.05 ylim <- c(min(conflict) - eps, max(support) + eps) } if (is.null(xlim)) { xlim <- c(0, n + 1) } ord <- order(support, decreasing = TRUE) support <- support[ord] conflict <- conflict[ord] if (length(col) == length(obj)) col <- col[ord] plot.new() plot.window(xlim, ylim) title(main = main, sub = sub, xlab = xlab, ylab = ylab, ...) segments(0:(n - 1), support, y1 = conflict, ...) segments(1:n, support, y1 = conflict, ...) segments(0:(n - 1), support, x1 = 1:n, ...) segments(0:(n - 1), conflict, x1 = 1:n, ...) abline(h = 0) axis(2, ...) aty <- diff(ylim) / (l + 1) at <- min(ylim) + (1:l) * aty if (bipart) { Y <- rep(at, n) X <- rep( (1:n) - .5, each = l) Circles <- matrix(1, l, n) for (i in 1:n) Circles[obj[[ord[i]]], i] <- 19 col <- rep(col, each = l) text(x = n + .1, y = at, labels, pos = 4, ...) points(X, Y, pch = as.numeric(Circles), col = col, ...) } invisible(list(support = cbind(support, conflict), splits = obj[ord])) }
score_coefficient_evaluation <- function (PARAM_SFT) { print("Started evaluating score coefficients optimization!!!") output_path <- PARAM_SFT[which(PARAM_SFT[, 1] == "SFT0010"), 2] output_path_score_function_calculations <- paste0(output_path, "/score_function_calculations") Entire_final_list_unoptimized <- loadRdata(paste0(output_path_score_function_calculations, "/Entire_final_list_unoptimized.Rdata")) GA_score <- loadRdata(paste0(output_path_score_function_calculations, "/GA_score.Rdata")) GA_score <- summary(GA_score) Score_coeff <- GA_score$solution Score_coeff <- Score_coeff[1, ] maxNEME <- as.numeric(PARAM_SFT[which(PARAM_SFT[, 1] == "SFT0014"), 2]) PCS <- as.numeric(Entire_final_list_unoptimized[, 11]) RCS <- as.numeric(Entire_final_list_unoptimized[, 15]) NEME <- as.numeric(Entire_final_list_unoptimized[, 10]) R13C_PL <- as.numeric(Entire_final_list_unoptimized[, 12]) R13C_IP <- as.numeric(Entire_final_list_unoptimized[, 13]) size_IP <- as.numeric(Entire_final_list_unoptimized[, 9]) N_compounds <- max(as.numeric(Entire_final_list_unoptimized$CompoundID)) x_c <- lapply(1:N_compounds, function(i) { which(Entire_final_list_unoptimized$CompoundID == i) }) N_candidate <- as.numeric(sapply(1:N_compounds, function(i) { Entire_final_list_unoptimized$CandidateCount[x_c[[i]][1]] })) IdentificationScore <- identification_score(Score_coeff, size_IP, PCS, RCS, NEME, maxNEME, R13C_PL, R13C_IP) Entire_final_list_unoptimized <- cbind(Entire_final_list_unoptimized, IdentificationScore) progressBARboundaries <- txtProgressBar(min = 1, max = N_compounds, initial = 1, style = 3) Entire_final_list_optimized <- do.call(rbind, lapply(1:N_compounds, function(i) { setTxtProgressBar(progressBARboundaries, i) A <- Entire_final_list_unoptimized[x_c[[i]], ] A <- A[order(A[, 20], decreasing = TRUE), ] A$Rank <- seq(1, N_candidate[i]) A[, -20] })) close(progressBARboundaries) names(Entire_final_list_optimized) <- c("FileName", "PeakID", "ID_IonFormula", "IonFormula", "m/z Isotopic Profile", "m/z peaklist", "RT(min)", "PeakHeight", "size IP", "NEME(mDa)", "PCS", "R13C peakList", "R13C Isotopic Profile", "NDCS", "RCS(%)", "Rank", "CandidateCount", "CompoundID", "MolFMatch") rownames(Entire_final_list_optimized) <- c() save(Entire_final_list_optimized, file = paste0(output_path_score_function_calculations, "/Entire_final_list_optimized.Rdata")) obj_function <- gsub(" ", "", tolower(PARAM_SFT[which(PARAM_SFT[, 1] == "SFT0018"), 2])) if (obj_function == "toprank") { max_rank <- as.numeric(PARAM_SFT[which(PARAM_SFT[, 1] == "SFT0019"), 2]) x <- which(as.numeric(Entire_final_list_unoptimized$MolFMatch) == 1) print(paste0("There detected totally ", length(x), " compounds for score coefficients optimization!!!")) r_unop <- length(which(as.numeric(Entire_final_list_unoptimized$Rank[x]) <= max_rank)) print(paste0("There met ", r_unop, " peaks the <=", max_rank, " ranking with score coefficients of 1!!!")) x <- which(as.numeric(Entire_final_list_optimized$MolFMatch) == 1) r_op <- length(which(as.numeric(Entire_final_list_optimized$Rank[x]) <= max_rank)) print(paste0("There met ", r_op, " peaks the <=", max_rank, " ranking after score coefficients optimization!!!")) R <- round((r_unop - r_op)/(r_unop - length(x)) * 100, 2) } if (obj_function == "overalrank") { x <- which(as.numeric(Entire_final_list_unoptimized$MolFMatch) == 1) NC <- as.numeric(Entire_final_list_optimized$CandidateCount[x]) F_min <- sum(1/NC) print(paste0("The minimum value of objective function is ", round(F_min, 2), " for a perfect score coefficients optimization!!!")) r_unop <- as.numeric(Entire_final_list_unoptimized$Rank[x]) F_unop <- sum(r_unop/NC) print(paste0("The objective function was ", round(F_unop, 2), " with score coefficients of 1!!!")) x <- which(as.numeric(Entire_final_list_optimized$MolFMatch) == 1) r_op <- as.numeric(Entire_final_list_unoptimized$Rank[x]) F_op <- sum(r_op/NC) print(paste0("The objective function became ", round(F_op, 2), " after score coefficients optimization!!!")) R <- round((F_unop - F_op)/(F_unop - F_min) * 100, 2) } print(paste0("The score coefficient optimization was ", R, "% successful with respect to score coefficients of 1 !!!")) }
ipdwInterp <- function(spdf, rstack, paramlist, overlapped = FALSE, yearmon = "default", removefile = TRUE, dist_power = 1, trim_rstack = FALSE){ if(missing(paramlist)){ stop("Must pass a specific column name to the paramlist argument.") } if(any(!(paramlist %in% names(spdf)))){ stop( paste0("Variable(s) '", paste0(paramlist[!(paramlist %in% names(spdf))], collapse = "', '"), "' does not exist in spdf object.")) } range <- slot(rstack, "range") if(trim_rstack){ rstack <- raster::mask(rstack, rgeos::gConvexHull(spdf), inverse = FALSE) } for(k in seq_len(length(paramlist))){ points_layers <- rm_na_pointslayers(param_name = paramlist[k], spdf = spdf, rstack = rstack) spdf <- points_layers$spdf rstack <- points_layers$rstack rstack.sum <- raster::calc(rstack, fun = function(x){ sum(x^dist_power, na.rm = TRUE) }) rstack.sum <- raster::reclassify(rstack.sum, cbind(0, NA)) for(i in 1:dim(rstack)[3]){ ras.weight <- rstack[[i]]^dist_power / rstack.sum param.value <- data.frame(spdf[i, paramlist[k]]) param.value2 <- as.vector(unlist(param.value[1])) ras.mult <- ras.weight * param.value2 rf <- raster::writeRaster(ras.mult, filename = file.path(tempdir(), paste(paramlist[k], "A5ras", i, ".grd", sep = "")), overwrite = TRUE) } raster_data_full <- list.files(path = file.path(tempdir()), pattern = paste(paramlist[k], "A5ras*", sep = ""), full.names = TRUE) raster_data <- raster_data_full[grep(".grd", raster_data_full, fixed = TRUE)] as.numeric(gsub('.*A5ras([0123456789]*)\\.grd$', '\\1', raster_data)) -> fileNum raster_data <- raster_data[order(fileNum)] rstack.mult <- raster::stack(raster_data) finalraster <- raster::calc(rstack.mult, fun = function(x){ sum(x, na.rm = TRUE) }) if(overlapped == TRUE){ finalraster <- raster::reclassify(finalraster, cbind(0, NA)) } r <- raster::rasterize(spdf, rstack[[1]], paramlist[k]) finalraster <- raster::cover(r, finalraster) finalraster <- new("ipdwResult", finalraster, range = range, dist_power = dist_power) file.remove(raster_data_full) return(finalraster) } if(removefile == TRUE){ file.remove(list.files(path = file.path(tempdir()), pattern = paste(yearmon, "A4ras*", sep = ""))) file.remove(list.files(path = file.path(tempdir()), pattern = paste(paramlist[k], "A5ras*", sep = ""), full.names = TRUE)) } } rm_na_pointslayers <- function(param_name, spdf, rstack){ param_index_x <- which(names(spdf) == param_name) param_na_y <- which(is.na(spdf@data[,param_index_x])) if(length(param_na_y) > 0){ spdf <- spdf[-which(is.na(spdf@data[,param_index_x])),] rstack <- raster::dropLayer(rstack, param_na_y) } list(spdf = spdf, rstack = rstack) } ipdwResult <- setClass("ipdwResult", slots = c(range = "numeric", dist_power = "numeric"), contains = "RasterLayer")
CIlppvak <- function(x0, x1, p, conf.level=0.95, alternative=c("two.sided", "less", "greater")) { alternative<-match.arg(alternative) expit<-function(p){exp(p)/(1+exp(p))} switch(alternative, two.sided={ z <- qnorm(p=1-(1-conf.level)/2) seest <- setil(x1=x1, k=z) spest <- sptil(x0=x0, k=z) varestlppv <- varlppv(x0=x0, x1=x1, k=z) estlppv <- logitppv(p=p, se=seest[1], sp=spest[1]) llwr<-estlppv - z*sqrt(varestlppv[1]) lupr<-estlppv + z*sqrt(varestlppv[1]) }, less={ z<-qnorm(p=conf.level) seest <- setil(x1=x1, k=z) spest <- sptil(x0=x0, k=z) varestlppv <- varlppv(x0=x0, x1=x1, k=z) estlppv <- logitppv(p=p, se=seest[1], sp=spest[1]) llwr <- (-Inf) lupr <- estlppv + z*sqrt(varestlppv[1]) }, greater={ z<-qnorm(p=conf.level) seest <- setil(x1=x1, k=z) spest <- sptil(x0=x0, k=z) varestlppv <- varlppv(x0=x0, x1=x1, k=z) estlppv <- logitppv(p=p, se=seest[1], sp=spest[1]) llwr <- estlppv - z*sqrt(varestlppv[1]) lupr <- Inf } ) conf.int <- c(expit(llwr), expit(lupr)) names(conf.int)<-c("lower","upper") estimate <- expit(estlppv) names(estimate)<-NULL return(list(conf.int=conf.int, estimate=estimate)) }
test_that("hotspot_cluster() works", { temp_hotspots <- hotspots temp_hotspots$obsTime <- transform_time_id(temp_hotspots$obsTime, "h", 1) result <- hotspot_cluster(temp_hotspots, lon = "lon", lat = "lat", obsTime = "obsTime", activeTime = 24, adjDist = 3000, minPts = 4, minTime = 3, ignitionCenter = "mean") expect_invisible(print(result)) expect_invisible(summary(result)) expect_invisible(summary(result, cluster = c(1,3))) expect_silent(plot(result)) })
knitr::opts_chunk$set( collapse = TRUE, comment = " ) required <- c("viridis") if (!all(sapply(required, requireNamespace, quietly = TRUE))) { knitr::opts_chunk$set(eval = FALSE) } library("raster") library("samc") library("viridisLite")
norm.1972SF <- function(x){ check_1d(x) DNAME <- deparse(substitute(x)) x = sort(x) n = length(x) n <- length(x) if ((n < 5 || n > 5000)){ stop("* norm.1972SF : we only take care of sample size between (5,5000).") } y = qnorm(ppoints(n, a = 3/8)) W = cor(x, y)^2 u = log(n) v = log(u) mu = -1.2725 + 1.0521 * (v - u) sig = 1.0308 - 0.26758 * (v + 2/u) z = (log(1 - W) - mu)/sig thestat = W hname = "Univariate Test of Normality by Shapiro and Francia (1972)" Ha = paste("Sample ", DNAME, " does not follow normal distribution.",sep="") names(thestat) = "W" pvalue = stats::pnorm(z, lower.tail = FALSE) res = list(statistic=thestat, p.value=pvalue, alternative = Ha, method=hname, data.name = DNAME) class(res) = "htest" return(res) }
jPofTest <- function(n,k,p,test_significant){ statistic <- -2*log(((1-p)^(n-k)*p^k)/((1-k/n)^(n-k)*(k/n)^k)) Quantile <- qchisq(1-test_significant,1) rslt <- statistic <= Quantile return(c(statistic,Quantile,rslt)) }
FeatureSetCalculationComponent = function(id) { ns = shiny::NS(id) shiny::div( shiny::selectInput(ns("FeatureSet_function"), label = "Feature Set", choices = c("all Features", listAvailableFeatureSets()), selected = "cm_angle"), shiny::tableOutput(ns("FeatureTable_function")), shiny::downloadButton(ns('downloadData_function'), 'Download')) } FeatureSetCalculation = function(input, output, session, stringsAsFactors, feat.object) { features = shiny::reactive({ if (input$FeatureSet_function == "all Features") { features = calculateFeatures(feat.object(), control = list(ela_curv.sample_size = min(200L, feat.object()$n.obs))) features = data.frame(t(data.frame(features)), stringsAsFactors = stringsAsFactors) } else { print(feat.object) features = calculateFeatureSet(feat.object(), set = input$FeatureSet_function, control = list(ela_curv.sample_size = min(200L, feat.object()$n.obs))) features = data.frame(t(data.frame(features)), stringsAsFactors = stringsAsFactors) } return(features) }) output$FeatureTable_function = shiny::renderTable({ features() }, rownames = TRUE, colnames = FALSE) output$downloadData_function = shiny::downloadHandler( filename = function() { paste0(input$FeatureSet_function, '.csv') }, content = function(file) { utils::write.csv(features(), file) } ) }
tw_create_cache_folder <- function(ask = TRUE) { if (fs::file_exists(tidywikidatar::tw_get_cache_folder()) == FALSE) { if (ask == FALSE) { fs::dir_create(path = tidywikidatar::tw_get_cache_folder(), recurse = TRUE) } else { usethis::ui_info(glue::glue("The cache folder {{usethis::ui_path(tw_get_cache_folder())}} does not exist. If you prefer to cache files elsewhere, reply negatively and set your preferred cache folder with `tw_set_cache_folder()`")) check <- usethis::ui_yeah(glue::glue("Do you want to create {{usethis::ui_path(tw_get_cache_folder())}} for caching data?")) if (check == TRUE) { fs::dir_create(path = tidywikidatar::tw_get_cache_folder(), recurse = TRUE) } } if (fs::file_exists(tidywikidatar::tw_get_cache_folder()) == FALSE) { usethis::ui_stop("This function requires a valid cache folder.") } } } tw_set_cache_folder <- function(path = NULL) { if (is.null(path)) { path <- Sys.getenv("tw_cache_folder") } else { Sys.setenv(tw_cache_folder = path) } if (path == "") { path <- fs::path("tw_data") } invisible(path) } tw_get_cache_folder <- tw_set_cache_folder tw_set_cache_db <- function(db_settings = NULL, driver = NULL, host = NULL, port, database, user, pwd) { if (is.null(db_settings) == TRUE) { if (is.null(driver) == FALSE) Sys.setenv(tw_db_driver = driver) if (is.null(host) == FALSE) Sys.setenv(tw_db_host = host) if (is.null(port) == FALSE) Sys.setenv(tw_db_port = port) if (is.null(database) == FALSE) Sys.setenv(tw_db_database = database) if (is.null(user) == FALSE) Sys.setenv(tw_db_user = user) if (is.null(pwd) == FALSE) Sys.setenv(tw_db_pwd = pwd) return(invisible( list( driver = driver, host = host, port = port, database = database, user = user, pwd = pwd ) )) } else { Sys.setenv(tw_db_driver = db_settings$driver) Sys.setenv(tw_db_host = db_settings$host) Sys.setenv(tw_db_port = db_settings$port) Sys.setenv(tw_db_database = db_settings$database) Sys.setenv(tw_db_user = db_settings$user) Sys.setenv(tw_db_pwd = db_settings$pwd) return(invisible(db_settings)) } } tw_get_cache_db <- function() { list( driver = Sys.getenv("tw_db_driver"), host = Sys.getenv("tw_db_host"), port = Sys.getenv("tw_db_port"), database = Sys.getenv("tw_db_database"), user = Sys.getenv("tw_db_user"), pwd = Sys.getenv("tw_db_pwd") ) } tw_enable_cache <- function(SQLite = TRUE) { Sys.setenv(tw_cache = TRUE) Sys.setenv(tw_cache_SQLite = SQLite) } tw_disable_cache <- function() { Sys.setenv(tw_cache = FALSE) } tw_check_cache <- function(cache = NULL) { if (is.null(cache) == FALSE) { return(as.logical(cache)) } current_cache <- Sys.getenv("tw_cache") if (current_cache == "") { as.logical(FALSE) } else { as.logical(current_cache) } } tw_check_cache_folder <- function() { if (fs::file_exists(tw_get_cache_folder()) == FALSE) { usethis::ui_stop(paste( "Cache folder does not exist. Set it with", usethis::ui_code("tw_get_cache_folder()"), "and create it with", usethis::ui_code("tw_create_cache_folder()") )) } TRUE } tw_disconnect_from_cache <- function(cache = NULL, cache_connection = NULL, disconnect_db = TRUE, language = tidywikidatar::tw_get_language()) { if (isFALSE(disconnect_db)) { return(invisible(NULL)) } if (isTRUE(tw_check_cache(cache))) { db <- tw_connect_to_cache( connection = cache_connection, language = language, cache = cache ) if (pool::dbIsValid(dbObj = db)) { if ("Pool" %in% class(db)) { pool::poolClose(db) } else { DBI::dbDisconnect(db) } } } }
with_groups <- function(.data, .groups, .f, ...) { cur_groups <- group_vars(.data) .groups <- eval_select_pos(.data = .data, .cols = substitute(.groups)) val <- as_symbols(names(.data)[.groups]) out <- do.call(group_by, c(list(.data = .data), val)) .f <- as_function(.f) out <- .f(out, ...) reconstruct_attrs(out, .data) }
fill <- function(data, ..., .direction = c("down", "up", "downup", "updown")) { check_dots_unnamed() UseMethod("fill") } fill.data.frame <- function(data, ..., .direction = c("down", "up", "downup", "updown")) { vars <- tidyselect::eval_select(expr(c(...)), data) .direction <- arg_match0( arg = .direction, values = c("down", "up", "downup", "updown"), arg_nm = ".direction" ) fn <- function(col) { vec_fill_missing(col, direction = .direction) } dplyr::mutate_at(data, .vars = dplyr::vars(any_of(vars)), .funs = fn) }
context("Split and rephase") test_that("split and rephase the map correctly", { map<-get_submap(solcap.err.map[[1]], 1:20) tpt<-est_pairwise_rf(make_seq_mappoly(map)) map2<-split_and_rephase(map, tpt, gap.threshold = 2) expect_is(map2, "mappoly.map") })
library(checkargs) context("isStrictlyPositiveNumberOrNanScalarOrNull") test_that("isStrictlyPositiveNumberOrNanScalarOrNull works for all arguments", { expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(0, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isStrictlyPositiveNumberOrNanScalarOrNull(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull("", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull("X", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isStrictlyPositiveNumberOrNanScalarOrNull(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) })
toLabelEdge <- function(adjMat, consMatrix) { edge.df <- orderEdge(adjMat) lab <- rep(NA, dim(edge.df)[1]) edge.df <- edge.df[order(edge.df$order), ] Head <- edge.df$head Tail <- edge.df$tail for (i in 1:nrow(consMatrix)) { consTail <- consMatrix[i, 1] consHead <- consMatrix[i, 2] ind <- which(edge.df$tail == consTail & edge.df$head == consHead) lab[ind] <- TRUE lab[which(lab != TRUE)] <- NA } while (any(ina <- is.na(lab))) { x.y <- which(ina)[1] x <- Tail[x.y] y <- Head[x.y] y.is.head <- Head == y e1 <- which(Head == x & lab) for (ee in e1) { w <- Tail[ee] if (any(wt.yh <- w == Tail & y.is.head)) lab[wt.yh] <- TRUE else { lab[y.is.head] <- TRUE break } } cand <- which(y.is.head & Tail != x) if (length(cand) > 0) { valid.cand <- rep(FALSE, length(cand)) for (iz in seq_along(cand)) { z <- Tail[cand[iz]] if (!any(Tail == z & Head == x)) valid.cand[iz] <- TRUE } cand <- cand[valid.cand] } lab[which(y.is.head & is.na(lab))] <- (length(cand) > 0) } edge.df$label <- lab return(edge.df) }
conflicts <- function(where = search(), detail = FALSE) { if(length(where) < 1L) stop("argument 'where' of length 0") z <- vector(length(where), mode="list") names(z) <- where for(i in seq_along(where)) z[[i]] <- objects(pos = where[i]) all <- unlist(z, use.names=FALSE) dups <- duplicated(all) dups <- all[dups] if(detail) { for(i in where) z[[i]] <- z[[i]][match(dups, z[[i]], 0L)] z[vapply(z, function(x) length(x) == 0L, NA)] <- NULL z } else dups }
x=rnorm(10,mean=50,sd=10) y=rnorm(10,mean=50,sd=10) m=length(x) n=length(y) sp=sqrt(((m-1)*sd(x)^2+(n-1)*sd(y)^2)/(m+n-2)) t.stat=(mean(x)-mean(y))/(sp*sqrt(1/m+1/n)) tstatistic=function(x,y) { m=length(x) n=length(y) sp=sqrt(((m-1)*sd(x)^2+(n-1)*sd(y)^2)/(m+n-2)) t.stat=(mean(x)-mean(y))/(sp*sqrt(1/m+1/n)) return(t.stat) } data.x=c(1,4,3,6,5) data.y=c(5,4,7,6,10) tstatistic(data.x, data.y) S=readline(prompt="Type <Return> to continue : ") alpha=.1; m=10; n=10 N=10000 n.reject=0 for (i in 1:N) { x=rnorm(m,mean=0,sd=1) y=rnorm(n,mean=0,sd=1) t.stat=tstatistic(x,y) if (abs(t.stat)>qt(1-alpha/2,n+m-2)) n.reject=n.reject+1 } true.sig.level=n.reject/N s=readline(prompt="Type <Return> to continue : ") m=10; n=10 my.tsimulation=function() tstatistic(rnorm(m,mean=10,sd=2), rexp(n,rate=1/10)) tstat.vector=replicate(10000, my.tsimulation()) plot(density(tstat.vector),xlim=c(-5,8),ylim=c(0,.4),lwd=3) curve(dt(x,df=18),add=TRUE)