code
stringlengths
1
13.8M
fitsoilwater3 <- function (theta, x, xlab = NULL, ylab = NULL, ...) { if (!requireNamespace("rpanel", quietly = TRUE)) stop("package rpanel is required") if (!inherits(c(theta, x), "numeric")) stop("non-numeric arguments!") if (length(theta) != length(x)) stop("incompatible dimensions!") dat <- data.frame(theta, x) if (is.null(xlab)) xlab = "Matric potential" if (is.null(ylab)) ylab = "Soil water content" f.graph <- function() { plot(theta ~ x, data = dat, las = 1, xlab = xlab, ylab = ylab, main = "Soil Water Retention Curve", ...) } f.graph() theta_R <- a1 <- p1 <- a2 <- p2 <- NULL f.panel <- function(pan) { f.graph() with(pan, curve(soilwater3(x, theta_R, a1, p1, a2, p2), add = TRUE, col = "red")) return(pan) } f.fit <- function(pan) { start <- with(pan, pan[c("theta_R", "a1", "p1", "a2", "p2")]) fit <- try(with(pan, nls(theta ~ soilwater3(x, theta_R, a1, p1, a2, p2), data = dat, start = start))) if (inherits(fit, "try-error")) { rpanel::rp.messagebox("No convergence... try other initial values.", title = "Warning!") } else { f.graph() est <- coef(fit) curve(soilwater3(x, est[1], est[2], est[3], est[4], est[5]), add = TRUE, col = "blue") print(summary(fit)) print(Rsq(fit)) } return(pan) } panel <- rpanel::rp.control("Interactive fit") ran.t <- 2 * range(theta) rpanel::rp.slider(panel, variable = theta_R, from = 0, to = max(theta), resolution = 0.01, initval = 0.8 * min(theta), title = "theta_R", action = f.panel) rpanel::rp.doublebutton(panel, variable = theta_R, step = 0.01, title = "", action = f.panel, showvalue = TRUE, foreground = "blue") rpanel::rp.slider(panel, variable = a1, from = -0.5, to = 10, resolution = 0.01, initval = 0.07, title = "a1", action = f.panel) rpanel::rp.doublebutton(panel, variable = a1, step = 0.01, title = "", action = f.panel, showvalue = TRUE, foreground = "blue") rpanel::rp.slider(panel, variable = p1, from = 0, to = 15000, resolution = 5, initval = 3670, title = "p1", action = f.panel) rpanel::rp.doublebutton(panel, variable = p1, step = 1, title = "", action = f.panel, showvalue = TRUE, foreground = "blue") rpanel::rp.slider(panel, variable = a2, from = 0, to = 10, resolution = 0.01, initval = 0.32, title = "a2", action = f.panel) rpanel::rp.doublebutton(panel, variable = a2, step = 0.01, title = "", action = f.panel, showvalue = TRUE, foreground = "blue") rpanel::rp.slider(panel, variable = p2, from = 0, to = 1500, resolution = 5, initval = 70, title = "p2", action = f.panel) rpanel::rp.doublebutton(panel, variable = p2, step = 1, title = "", action = f.panel, showvalue = TRUE, foreground = "blue") rpanel::rp.button(panel, title = "NLS estimates", action = f.fit, foreground = "white", background = "navy") rpanel::rp.button(panel, title = "__________________ Quit __________________", action = function(pan) return(pan), quitbutton = TRUE, foreground = "red") }
summary.marqLevAlg <- function(object,digits=8,loglik=FALSE,...){ x <- object if (!inherits(x, "marqLevAlg")) stop("use only with \"marqLevAlg\" objects") cat(" \n") cat(" Robust marqLevAlg algorithm ", "\n") cat(" \n") cl <- x$cl minimize <- TRUE if(length(cl$minimize)){ if(cl$minimize==FALSE) minimize <- FALSE } dput(cl) cat(" \n") cat("Iteration process:", "\n") cat(" Number of parameters:", length(x$b)," \n") cat(" Number of iterations:", x$ni, "\n") cat(" Optimized objective function:", round(x$fn.value,digits)," \n") if(x$istop==1) cat(" Convergence criteria satisfied","\n") if(x$istop==2) cat(" Maximum number of iteration reached without convergence","\n") if(x$istop==4|x$istop==5) { cat(" The program stopped abnormally. No results can be displayed.\n") } cat(" \n") cat("Convergence criteria: parameters stability=", round(x$ca[1],digits), "\n") cat(" : objective function stability=", round(x$cb,digits), "\n") if (x$ier == -1){ cat(" : Matrix inversion for RDM failed \n") }else{ cat(" : Matrix inversion for RDM successful \n") } if(minimize==TRUE){ cat(" : relative distance to minimum(RDM)=", round(x$rdm,digits), "\n") }else{ cat(" : relative distance to maximum(RDM)=", round(x$rdm,digits), "\n") } if(x$istop!=4&x$istop!=5) { cat(" \n") cat("Final parameter values:", "\n") id <- 1:length(x$b) indice <- rep(id*(id+1)/2) se <-sqrt(x$v[indice]) wald <- (x$b/se)**2 z <- abs(qnorm((1 + .95)/2)) binf <- x$b-1.96*se bsup <- x$b+1.96*se if(loglik==FALSE){ tmp <- data.frame("coef"=format(round(x$b,3))) cat(format(round(x$b,3)),"\n") }else{ tmp <- data.frame("coef"=format(round(x$b,3)),"SE coef"=format(round(se,3)),"Wald"=format(wald,4),"P-value"=round(1 - pchisq(wald, 1),5),"binf"=round(binf,3),"bsup"=round(bsup,3)) print(tmp,row.names=F) } cat(" \n") return(invisible(tmp)) } }
.create_diagonal <- function(params) { diagonal <- data.frame( "Parameter1" = unique(params$Parameter1), "Parameter2" = unique(params$Parameter1) ) if ("Group" %in% names(params)) diagonal$Group <- unique(params$Group)[1] if ("r" %in% names(params)) diagonal$r <- 1 if ("rho" %in% names(params)) diagonal$rho <- 1 if ("tau" %in% names(params)) diagonal$tau <- 1 if ("p" %in% names(params)) diagonal$p <- 0 if ("t" %in% names(params)) diagonal$t <- Inf if ("S" %in% names(params)) diagonal$S <- Inf if ("z" %in% names(params)) diagonal$z <- Inf if ("df" %in% names(params)) diagonal$df <- unique(params$df)[1] if ("df_error" %in% names(params)) diagonal$df_error <- unique(params$df_error)[1] if ("CI" %in% names(params)) diagonal$CI <- unique(params$CI)[1] if ("CI_low" %in% names(params)) diagonal$CI_low <- 1 if ("CI_high" %in% names(params)) diagonal$CI_high <- 1 if ("Method" %in% names(params)) diagonal$Method <- unique(params$Method)[1] if ("n_Obs" %in% names(params)) diagonal$n_Obs <- unique(params$n_Obs)[1] if ("Median" %in% names(params)) diagonal$Median <- 1 if ("Mean" %in% names(params)) diagonal$Mean <- 1 if ("MAP" %in% names(params)) diagonal$MAP <- 1 if ("SD" %in% names(params)) diagonal$SD <- 0 if ("MAD" %in% names(params)) diagonal$MAD <- 0 if ("pd" %in% names(params)) diagonal$pd <- 1 if ("ROPE_Percentage" %in% names(params)) diagonal$ROPE_Percentage <- 0 if ("BF" %in% names(params)) diagonal$BF <- Inf if ("log_BF" %in% names(params)) diagonal$log_BF <- Inf if ("Prior_Distribution" %in% names(params)) diagonal$Prior_Distribution <- unique(params$Prior_Distribution)[1] if ("Prior_Location" %in% names(params)) diagonal$Prior_Location <- unique(params$Prior_Location)[1] if ("Prior_Scale" %in% names(params)) diagonal$Prior_Scale <- unique(params$Prior_Scale)[1] for (var in names(params)[!names(params) %in% names(diagonal)]) { if (length(unique(params[[var]])) > 1) { stop("Something's unexpected happened when creating the diagonal data. Please open an issue at https://github.com/easystats/correlation/issues") } diagonal[[var]] <- unique(params[[var]])[1] } diagonal }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(dplyr) library(purrr) library(tidyr) library(tsibble) library(loadflux) data(djanturb) df <- hydro_events(dataframe = djanturb, q = discharge, datetime = time, window = 21) df %>% event_plot(q = discharge, datetime = time, he = he, ssc = ntu, y2label = "Turbidity") TI_index <- df %>% group_by(he) %>% nest() %>% mutate(TI = map_dbl(data, ~TI(.x, ntu, time))) %>% select(-data) %>% ungroup() TI_index library(tsibble) df_ts <- df %>% as_tsibble(key = he, index = time) df_ts library(feasts) df_ts %>% features(time, feat_event) library(brolgar) library(feasts) df_ts %>% features(ntu, feat_five_num) df_ts %>% features(ntu, c(feat_spectral, feat_acf))
summary.fmem <- function(object, ...){ chains <- object$chains p <- object$p q <- object$q ks <- object$ks nu0 <- object$nu0 homo <- object$homo quant005 <- function(x){quantile(x,prob=0.025)} quant095 <- function(x){quantile(x,prob=0.975)} reem <- function(aa,b){ ag <- aa ag <- sub("(", "", ag,fixed=TRUE) ag <- sub(")", "", ag,fixed=TRUE) ag <- sub(b, "", ag,fixed=TRUE) ag <- strsplit(ag, ",") ag <- ag[[1]][1] ag } if(object$family=="Normal" || object$family=="Laplace" || attr(object$eta,"know")==0){ cat("\n Error distribution:", object$family) }else{ cat("\n Error distribution:", object$family,"(",object$eta,")") } cat("\n Sample size:", length(object$y)) cat("\n Size of posterior sample:", object$post.sam.s, "\n") cat("\n =============== Parametric part =============== ") if(p >0){ cat("\n ======= Covariates measured without error \n") a <- round(apply(as.matrix(chains[,1:p]), 2, mean), digits=4) a2 <- round(apply(as.matrix(chains[,1:p]), 2, median), digits=4) b <- round(apply(as.matrix(chains[,1:p]), 2, sd), digits=4) c <- round(apply(as.matrix(chains[,1:p]), 2, quant005), digits=4) d <- round(apply(as.matrix(chains[,1:p]), 2, quant095), digits=4) e <- cbind(a,a2,b,c,d) colnames(e) <- c("Mean ","Median","SD "," C.I.","95% ") rownames(e) <- colnames(object$X) printCoefmat(e) } cat("\n ======= Covariates measured with error \n") a <- round(apply(as.matrix(chains[,(p+1):(p+q)]), 2, mean), digits=4) a2 <- round(apply(as.matrix(chains[,(p+1):(p+q)]), 2, median), digits=4) b <- round(apply(as.matrix(chains[,(p+1):(p+q)]), 2, sd), digits=4) c <- round(apply(as.matrix(chains[,(p+1):(p+q)]), 2, quant005), digits=4) d <- round(apply(as.matrix(chains[,(p+1):(p+q)]), 2, quant095), digits=4) e <- cbind(a,a2,b,c,d) colnames(e) <- c("Mean ","Median","SD "," C.I.","95% ") rownames(e) <- colnames(object$M) printCoefmat(e) if(sum(ks) >0){ cat("\n =============== Nonparametric part =============== \n") nvar <- matrix(0,length(ks),1) for(i in 1:length(ks)){ nvar[i] <- reem(colnames(object$nps)[i],"bsp")} cat(" Effects internal knots ") b <- (object$ks - 3) rownames(b) <- nvar colnames(b) <- " " printCoefmat(b) cat("\n Graphs of the nonparametric effects are provided by \n") cat(" using the function 'bsp.graph.fmem' \n") } if(object$family!="Normal" && object$family!="Laplace" && attr(object$eta,"know")==0){ cat("\n ======= Eta parameter \n") if(homo==1){ if(sum(ks)==0) length(ks) <- 0 a <- round(apply(as.matrix(chains[,(p+3*q+sum(ks)+1+length(ks)+1):(p+3*q+sum(ks)+1+length(ks)+length(nu0))]), 2, mean), digits=4) a2 <- round(apply(as.matrix(chains[,(p+3*q+sum(ks)+1+length(ks)+1):(p+3*q+sum(ks)+1+length(ks)+length(nu0))]), 2, median), digits=4) b <- round(apply(as.matrix(chains[,(p+3*q+sum(ks)+1+length(ks)+1):(p+3*q+sum(ks)+1+length(ks)+length(nu0))]), 2, sd), digits=4) c <- round(apply(as.matrix(chains[,(p+3*q+sum(ks)+1+length(ks)+1):(p+3*q+sum(ks)+1+length(ks)+length(nu0))]), 2, quant005), digits=4) d <- round(apply(as.matrix(chains[,(p+3*q+sum(ks)+1+length(ks)+1):(p+3*q+sum(ks)+1+length(ks)+length(nu0))]), 2, quant095), digits=4) e <- cbind(a,a2,b,c,d) colnames(e) <- c("Mean ","Median","SD "," C.I.","95% ") rownames(e) <- colnames(object$nu0) printCoefmat(e) }else{ if(sum(ks)==0) length(ks) <- 0 a <- round(apply(as.matrix(chains[,(p+3*q+sum(ks)+length(ks)+1):(p+3*q+sum(ks)+length(ks)+length(nu0))]), 2, mean), digits=4) a2 <- round(apply(as.matrix(chains[,(p+3*q+sum(ks)+length(ks)+1):(p+3*q+sum(ks)+length(ks)+length(nu0))]), 2, median), digits=4) b <- round(apply(as.matrix(chains[,(p+3*q+sum(ks)+length(ks)+1):(p+3*q+sum(ks)+length(ks)+length(nu0))]), 2, sd), digits=4) c <- round(apply(as.matrix(chains[,(p+3*q+sum(ks)+length(ks)+1):(p+3*q+sum(ks)+length(ks)+length(nu0))]), 2, quant005), digits=4) d <- round(apply(as.matrix(chains[,(p+3*q+sum(ks)+length(ks)+1):(p+3*q+sum(ks)+length(ks)+length(nu0))]), 2, quant095), digits=4) e <- cbind(a,a2,b,c,d) colnames(e) <- c("Mean ","Median","SD "," C.I.","95% ") rownames(e) <- colnames(object$nu0) printCoefmat(e) } } if(homo ==1){ cat("\n ======= Dispersion parameter \n") a <- round(apply(as.matrix(chains[,(p+3*q+1)]), 2, mean), digits=4) a2 <- round(apply(as.matrix(chains[,(p+3*q+1)]), 2, median), digits=4) b <- round(apply(as.matrix(chains[,(p+3*q+1)]), 2, sd), digits=4) c <- round(apply(as.matrix(chains[,(p+3*q+1)]), 2, quant005), digits=4) d <- round(apply(as.matrix(chains[,(p+3*q+1)]), 2, quant095), digits=4) e <- cbind(a,a2,b,c,d) colnames(e) <- c("Mean ","Median","SD "," C.I.","95% ") rownames(e) <- "Sigma2_y " printCoefmat(e) cat("\n Ratio of the error variances: " , (object$omeg)) } cat("\n\n ========== Model Selection Criteria ==========") cat("\n DIC=" , object$DIC, " LMPL=" , object$LMPL, "\n") }
epim <- function( rt, inf, obs, data, algorithm = c("sampling", "meanfield", "fullrank"), group_subset = NULL, prior_PD = FALSE, ... ) { call <- match.call(expand.dots = TRUE) op <- options("warn") on.exit(options(op)) options(warn=1) check_rt(rt) check_inf(inf) check_obs(obs) if (inherits(obs, "epiobs")) obs <- list(obs) check_group_subset(group_subset) check_data(data, rt, inf, obs, group_subset) check_logical(prior_PD) check_scalar(prior_PD) algorithm <- match.arg(algorithm) sampling_args <- list(...) data <- parse_data(data, rt, inf, obs, group_subset) rt_orig <- rt obs_orig <- obs rt <- epirt_(rt, data) obs <- lapply(obs_orig, epiobs_, data) args <- nlist(rt, inf, obs, data, prior_PD) sdat <- do.call(standata_all, args) if (algorithm == "sampling") { chains <- sampling_args$chains if (!is.null(chains) && chains == 0) { message("Returning standata as chains = 0") return(do.call(standata_all, args)) } } if (is.null(sampling_args$init_r)) sampling_args$init_r <- 1e-6 args <- c( sampling_args, list( object = stanmodels$epidemia_base, pars = pars(sdat), data = sdat ) ) fit <- if (algorithm == "sampling") { do.call(rstan::sampling, args) } else { args$algorithm <- algorithm do.call(rstan::vb, args) } orig_names <- fit@sim$fnames_oi fit@sim$fnames_oi <- new_names(sdat, rt, obs, fit, data) out <- nlist( rt_orig, obs_orig, call, stanfit = fit, rt, inf, obs, data, algorithm, standata = sdat, orig_names ) return(epimodel(out)) } pars <- function(sdat) { out <- c( if (sdat$has_intercept) "alpha", if (sdat$K > 0) "beta", if (sdat$q > 0) "b", if (length(sdat$ac_nterms)) "ac_noise", if (sdat$num_ointercepts > 0) "ogamma", if (sdat$K_all > 0) "obeta", if (length(sdat$obs_ac_nterms)) "obs_ac_noise", if (sdat$len_theta_L) "theta_L", "seeds", if (sdat$hseeds) "seeds_aux", if (length(sdat$ac_nterms)) "ac_scale", if (length(sdat$obs_ac_nterms)) "obs_ac_scale", if (sdat$num_oaux > 0) "oaux", if (sdat$latent) "infections_raw", if (sdat$latent) "inf_aux", if (!sdat$S0_fixed) "S0", if (!sdat$veps_fixed) "veps" ) return(out) } make_Sigma_nms <- function(rt, sdat, fit) { if (sdat$len_theta_L) { cnms <- rt$group$cnms fit <- transformTheta_L(fit, cnms) Sigma_nms <- lapply(cnms, FUN = function(grp) { nm <- outer(grp, grp, FUN = paste, sep = ",") nm[lower.tri(nm, diag = TRUE)] }) nms <- names(cnms) for (j in seq_along(Sigma_nms)) { Sigma_nms[[j]] <- paste0(nms[j], ":", Sigma_nms[[j]]) } Sigma_nms <- unlist(Sigma_nms) return(Sigma_nms) } } new_names <- function(sdat, rt, obs, fit, data) { out <- c( if (sdat$has_intercept) { "R|(Intercept)" }, if (sdat$K > 0) { paste0("R|", colnames(sdat$X)) }, if (length(rt$group) && length(rt$group$flist)) { c(paste0("R|", colnames(rt$group$Z))) }, if (sdat$ac_nterms > 0) { paste0("R|", grep("NA", colnames(rt$autocor$Z), invert=TRUE, value=TRUE)) }, if (sdat$num_ointercepts > 0) { make_ointercept_nms(obs, sdat) }, if (sdat$K_all > 0) { make_obeta_nms(obs, sdat) }, if (sdat$obs_ac_nterms > 0) { make_obs_ac_nms(obs) }, if (sdat$len_theta_L) { paste0("R|Sigma[", make_Sigma_nms(rt, sdat, fit), "]") }, c(paste0("seeds[", sdat$groups, "]")), if (sdat$hseeds) "seeds_aux", if (sdat$ac_nterms > 0) { make_rw_sigma_nms(rt, data) }, if (sdat$obs_ac_nterms > 0) { do.call("c", as.list(sapply(obs, function(x) make_rw_sigma_nms(x, data)))) }, if (sdat$num_oaux > 0) { make_oaux_nms(obs) }, if (sdat$latent) { make_inf_nms(sdat$begin, sdat$starts, sdat$N0, sdat$NC, sdat$groups) }, if (sdat$latent) { "inf|dispersion" }, if (!sdat$S0_fixed) { paste0("S0[",sdat$groups, "]") }, if (!sdat$veps_fixed) { paste0("rm_noise[", sdat$groups, "]") }, "log-posterior" ) return(out) } transformTheta_L <- function(stanfit, cnms) { thetas <- rstan::extract(stanfit, pars = "theta_L", inc_warmup = TRUE, permuted = FALSE ) nc <- sapply(cnms, FUN = length) nms <- names(cnms) Sigma <- apply(thetas, 1:2, FUN = function(theta) { Sigma <- lme4::mkVarCorr(sc = 1, cnms, nc, theta, nms) unlist(sapply(Sigma, simplify = FALSE, FUN = function(x) x[lower.tri(x, TRUE)] )) }) l <- length(dim(Sigma)) end <- tail(dim(Sigma), 1L) shift <- grep("^theta_L", names(stanfit@sim$samples[[1]]))[1] - 1L if (l == 3) { for (chain in 1:end) { for (param in 1:nrow(Sigma)) { stanfit@sim$samples[[chain]][[shift + param]] <- Sigma[param, , chain] } } } else { for (chain in 1:end) { stanfit@sim$samples[[chain]][[shift + 1]] <- Sigma[, chain] } } return(stanfit) } make_obs_ac_nms <- function(obs) { nms <- c() for (o in obs) { x <- grep("NA", colnames(o$autocor$Z), invert=T, value=T) if (length(x) > 0) { x <- paste0(.get_obs(o$formula), "|", x) nms <- c(nms, x) } } return(nms) } make_rw_nms <- function(formula, data) { trms <- terms_rw(formula) nms <- character() for (trm in trms) { trm <- eval(parse(text = trm)) time <- if (is.null(trm$time)) data$date else data[[trm$time]] group <- if (is.null(trm$gr)) "all" else droplevels(as.factor(data[[trm$gr]])) f <- unique(paste0(trm$label, "[", time, ",", group, "]")) nms <- c(nms, f) } return(c( grep("NA", nms, invert=TRUE, value=TRUE), grep("NA", nms, value=TRUE) )) } make_rw_sigma_nms <- function(obj, data) { trms <- terms_rw(formula(obj)) nme <- ifelse(class(obj) == "epirt_", "R", .get_obs(formula(obj))) nms <- character() for (trm in trms) { trm <- eval(parse(text = trm)) group <- if (is.null(trm$gr)) "all" else droplevels(as.factor(data[[trm$gr]])) nms <- c(nms, unique(paste0(nme, "|sigma:", trm$label, "[", group, "]"))) } return(nms) } make_oaux_nms <- function(obs) { nms <- list() for (o in obs) { if (!is.null(o$prior_aux)) { if (o$family == "neg_binom") { x <- "|reciprocal dispersion" } else if (o$family == "quasi_poisson") { x <- "|dispersion" } else if (o$family == "normal"){ x <- "|standard deviation" } else { x <- "|sigma" } nms <- c(nms, paste0(.get_obs(formula(o)), x)) } } return(unlist(nms)) } make_ointercept_nms <- function(obs, sdat) { nms <- character() for (i in 1:length(obs)) { if (sdat$has_ointercept[i]) { nms <- c(nms, paste0(.get_obs(formula(obs[[i]])), "|(Intercept)")) } } return(nms) } make_obeta_nms <- function(obs, sdat) { if (sdat$K_all == 0) { return(character(0)) } obs_nms <- sapply( obs, function(x) .get_obs(formula(x)) ) repnms <- unlist(Map( rep, obs_nms, utils::head(sdat$oK, length(obs_nms)) )) obs_beta_nms <- unlist(lapply( obs, function(a) colnames(get_x(a)) )) obs_beta_nms <- grep( pattern = "^\\(Intercept\\)|^rw\\(", x = obs_beta_nms, invert = T, value = T ) return(paste0(repnms, "|", obs_beta_nms)) } make_inf_nms <- function(begin, starts, N0, NC, groups) { nms <- c() for (m in 1:length(groups)) nms <- c(nms, paste0("infections_raw[", begin -1 + N0 + starts[m] + seq(0, NC[m]-N0 - 1), ",", groups[m],"]")) return(nms) }
Exhaustive_double_deletion<-function(fba_object,thread_no=0,core_number=1){ message("Generating Reaction Combinations...") reacn_combos<-combn(1:dim(fba_object$mat)[2],2) message("Done!") ko_1x=vector() ko_2x=vector() ko_stat=vector() message("Starting Double Knockout Simulation...") if(core_number==1) { for(i in 1:dim(reacn_combos)[2]) { print(paste(i,dim(reacn_combos)[2],sep=" ")) fba_mutant<-CHANGE_RXN_BOUNDS(reaction_number=reacn_combos[,i],fba_object,lb=0,ub=0) FBA_MUTANT<-FBA_solve(fba_mutant) if(FBA_MUTANT$objective==0) { ko_1x=c(ko_1x,reacn_combos[,i][1]) ko_2x=c(ko_2x,reacn_combos[,i][2]) ko_stat=c(ko_stat,FBA_MUTANT$status) } } message("End of simulation.") flux_pairs<-cbind(ko_1x,ko_2x,ko_stat) message("Writing output to file...") write.table(flux_pairs,file=paste("results",thread_no+1,sep=""),sep="\t",row.names=TRUE, col.names=FALSE,quote=FALSE) message("Complete!") } if(core_number>1) { OP_size<-round(dim(reacn_combos)[2]/core_number) I_1=1+(OP_size*thread_no) I_2=I_1+OP_size-1 if(I_2>dim(reacn_combos)[2]){I_2=dim(reacn_combos)[2]} for(i in I_1:I_2) { print(paste(i,I_2,sep=" ")) fba_mutant<-CHANGE_RXN_BOUNDS(reaction_number=reacn_combos[,i],fba_object,lb=0,ub=0) FBA_MUTANT<-FBA_solve(fba_mutant) if(FBA_MUTANT$objective==0) { ko_1x=c(ko_1x,reacn_combos[,i][1]) ko_2x=c(ko_2x,reacn_combos[,i][2]) ko_stat=c(ko_stat,FBA_MUTANT$status) } } message("End of Simulation") flux_pairs<-cbind(ko_1x,ko_2x,ko_stat) message("Writing output to file...") write.table(flux_pairs,file=paste("results",thread_no+1,sep=""),sep="\t",row.names=FALSE, col.names=FALSE) message("Complete!") } }
test_that("table has 3 rows on grouped iris (species)", { rowcount_tbl <- nrow(make_group_table(dplyr::group_by(iris, Species))) rowcount_dplyr <- dplyr::n_groups(dplyr::group_by(iris, Species)) expect_identical(rowcount_tbl, rowcount_dplyr) })
data <- httr::RETRY( "GET", "https://randomuser.me/api/?seed=123&results=10&format=csv", times = 5) text <- httr::content(data, as = "text") data <- readr::read_csv(I(text)) names(data) <- gsub(".", "_", names(data), fixed = TRUE) final <- data test_that("testing equal results", { testthat::expect_equal(final,get_data(n = 10, seed = "123")) testthat::expect_s3_class(final, "data.frame") testthat::expect_equal(ncol(final), ncol(get_data(n = 10))) })
knitr::opts_chunk$set(collapse = TRUE, comment = " fig.width = 7, fig.height = 7, fig.align = "center", eval = FALSE) suppressPackageStartupMessages(library(pathfindR)) knitr::kable(head(myeloma_input)) enrichment_chart(myeloma_output) knitr::kable(myeloma_output)
predict.fast = function(object, data= NULL, quantiles= c(0.1,0.5,0.9),obs=1,...) { origObs = object$origObs nobs = length(origObs) origNodes = object$origNodes ntree = object$num.trees thres = 5*.Machine$double.eps filterednodes = rep(0, nobs*ntree) z = matrix(nrow=nobs, ncol=ntree) newnodes = matrix(nrow = nobs, ncol = ntree) newindex = matrix(0, nrow = nobs, ncol = ntree) z = apply(origNodes, 2, function(x) order(x, stats::rnorm(length(x)))) newnodes = sapply(seq(ncol(z)), function(x) origNodes[z[, x], x]) if(is.null(data)){ weightvec = rep(0, nobs*nobs) quant = matrix(nrow=nobs,ncol=length(quantiles)) result = Findweightsinbagfast(as.double(as.vector(origNodes)), as.double(as.vector(newnodes)), as.double(filterednodes), as.integer(as.vector(z)), as.integer(as.vector(newindex)), as.integer(as.vector(unlist(t(as.data.frame(object$inbag))))), as.double(weightvec), as.integer(nobs), as.integer(ntree), as.double(thres), as.integer(obs)) } else { nnew = nrow(data) weightvec = rep(0, nobs*nnew) quant = matrix(nrow = nrow(data), ncol = length(quantiles)) nodes = getnodes(object, data) result = Findweightsfast(as.double(as.vector(newnodes)), as.double(as.vector(nodes)), as.double(filterednodes), as.integer(as.vector(z)), as.integer(as.vector(newindex)), as.double(weightvec), as.integer(nobs), as.integer(nnew), as.integer(ntree), as.double(thres), as.integer(obs)) } weights = matrix(result, nrow = nobs) ord = order(origObs) origObs = origObs[ord] weights = weights[ord, , drop = FALSE] cumweights = apply(weights, 2, cumsum) cumweights = sweep(cumweights, 2, as.numeric(cumweights[nobs,]), FUN = "/") for (qc in 1:length(quantiles)){ larg = cumweights<quantiles[qc] wc = apply(larg, 2, sum)+1 ind1 = which(wc<1.1) indn1 = which(wc>1.1) quant[ind1,qc] = rep(origObs[1], length(ind1)) quantmax = origObs[wc[indn1]] quantmin = origObs[wc[indn1]-1] weightmax = cumweights[cbind(wc[indn1], indn1)] weightmin = cumweights[cbind(wc[indn1]-1, indn1)] factor = numeric(length(indn1)) indz = weightmax-weightmin<10^(-10) factor[indz] = 0.5 factor[!indz] = (quantiles[qc]-weightmin[!indz])/(weightmax[!indz]-weightmin[!indz]) quant[indn1,qc] = quantmin + factor* (quantmax-quantmin) } colnames(quant) = paste("quantile=", quantiles) return(quant) }
gen_events <- function(.data, ease, start, end = NULL, range = NULL, enter = NULL, exit = NULL, enter_length = 0, exit_length = 0) { start <- enquo(start) if (quo_is_missing(start)) stop('start must be provided', call. = FALSE) start <- eval_tidy(start, .data) end <- enquo(end) end <- eval_tidy(end, .data) enter_length <- enquo(enter_length) enter_length <- eval_tidy(enter_length, .data) exit_length <- enquo(exit_length) exit_length <- eval_tidy(exit_length, .data) if (is.null(enter_length)) enter_length <- 0 if (is.null(exit_length)) exit_length <- 0 .data$.phase <- NULL if (length(ease) == 1) ease <- rep(ease, ncol(.data)) if (length(ease) == ncol(.data)) { ease <- c(ease, 'linear') } else { stop('Ease must be either a single string or one for each column', call. = FALSE) } .data$.phase <- rep_len(factor("raw", levels = PHASE_LEVELS), nrow(.data)) class(.data) <- c(c("component_generator", "frame_generator"), class(.data)) gen_data <- .complete_events(.data, start, end, enter, exit, enter_length, exit_length) time <- gen_data$.time id <- gen_data$.id gen_data$.time <- NULL gen_data$.id <- NULL d_order <- order(id, time) if (is.null(range)) range <- range(time) if (diff(range) == 0) stop('range cannot be 0', call. = FALSE) generator_settings(.data) <- list( data = gen_data[d_order, ], id = id[d_order], time = time[d_order], range = range, ease_type = ease, col_types = col_classes(.data) ) .data }
test_that("lst handles named and unnamed NULL arguments", { expect_equal(lst(NULL), list("NULL" = NULL)) expect_identical(lst(a = NULL), list(a = NULL)) expect_identical( lst(NULL, b = NULL, 1:3), list("NULL" = NULL, b = NULL, "1:3" = 1:3) ) }) test_that("lst handles internal references", { expect_identical(lst(a = 1, b = a), list(a = 1, b = 1)) expect_identical(lst(a = NULL, b = a), list(a = NULL, b = NULL)) }) test_that("lst supports duplicate names ( expect_identical(lst(a = 1, a = a + 1, b = a), list(a = 1, a = 2, b = 2)) expect_identical(lst(b = 1, a = b, a = b + 1, b = a), list(b = 1, a = 1, a = 2, b = 2)) })
mod_Rectangular_Lattice_ui <- function(id){ ns <- NS(id) tagList( h4("Rectangular Lattice Design"), sidebarLayout( sidebarPanel(width = 4, radioButtons(ns("owndata_rectangular"), label = "Import entries' list?", choices = c("Yes", "No"), selected = "No", inline = TRUE, width = NULL, choiceNames = NULL, choiceValues = NULL), conditionalPanel("input.owndata_rectangular != 'Yes'", ns = ns, numericInput(ns("t.rectangular"), label = "Input value = NULL, min = 2) ), conditionalPanel("input.owndata_rectangular == 'Yes'", ns = ns, fluidRow( column(8, style=list("padding-right: 28px;"), fileInput(inputId = ns("file.rectangular"), label = "Upload a CSV File:", multiple = FALSE)), column(4, style=list("padding-left: 5px;"), radioButtons(inputId = ns("sep.rectangular"), "Separator", choices = c(Comma = ",", Semicolon = ";", Tab = "\t"), selected = ",")) ) ), numericInput(inputId = ns("r.rectangular"), label = "Input selectInput(inputId = ns("k.rectangular"), label = "Input numericInput(inputId = ns("l.rectangular"), label = "Input fluidRow( column(6, style=list("padding-right: 28px;"), textInput(inputId = ns("plot_start.rectangular"), "Starting Plot Number:", value = 101) ), column(6,style=list("padding-left: 5px;"), textInput(inputId = ns("Location.rectangular"), "Input Location:", value = "FARGO") ) ), numericInput(inputId = ns("myseed.rectangular"), label = "Seed Number:", value = 007, min = 1), fluidRow( column(6, actionButton(inputId = ns("RUN.rectangular"), "Run!", icon = icon("cocktail"), width = '100%'), ), column(6, actionButton(inputId = ns("Simulate.rectangular"), "Simulate!", icon = icon("cocktail"), width = '100%') ) ), br(), downloadButton(ns("downloadData.rectangular"), "Save My Experiment", style = "width:100%") ), mainPanel( width = 8, tabsetPanel( tabPanel("Rectangular Lattice Field Book", shinycssloaders::withSpinner(DT::DTOutput(ns("RECTANGULAR.output")), type = 5)) ) ) ) ) } mod_Rectangular_Lattice_server <- function(id) { moduleServer(id, function(input, output, session) { ns <- session$ns getData.rectangular <- reactive({ req(input$file.rectangular) inFile <- input$file.rectangular dataUp.rectangular<- load_file(name = inFile$name, path = inFile$datapat, sep = input$sep.rectangular) return(list(dataUp.rectangular= dataUp.rectangular)) }) get_tRECT <- reactive({ if(is.null(input$file.rectangular)) { req(input$t.rectangular) t.rectangular <- input$t.rectangular }else { req(input$file.rectangular) t.rectangular <- nrow(getData.rectangular()$dataUp.rectangular) } return(list(t.rectangular = t.rectangular)) }) observeEvent(get_tRECT()$t.rectangular, { req(get_tRECT()$t.rectangular) t <- as.numeric(get_tRECT()$t.rectangular) D <- numbers::divisors(t) D <- D[2:(length(D)-1)] pk <- numeric() z <- 1 for (i in D) { s <- t / i if (i == s - 1) { pk[z] <- i z <- z + 1 }else z <- z } if (length(pk) == 0) { k <- "No Options Available" }else { k <- pk } updateSelectInput(session = session, inputId = 'k.rectangular', label = "Input choices = k, selected = k[1]) }) entryListFormat_RECT <- data.frame(ENTRY = 1:9, NAME = c(paste("Genotype", LETTERS[1:9], sep = ""))) entriesInfoModal_RECT <- function() { modalDialog( title = div(tags$h3("Important message", style = "color: red;")), h4("Please, follow the format shown in the following example. Make sure to upload a CSV file!"), renderTable(entryListFormat_RECT, bordered = TRUE, align = 'c', striped = TRUE), h4("Entry numbers can be any set of consecutive positive numbers."), easyClose = FALSE ) } toListen <- reactive({ list(input$owndata_rectangular) }) observeEvent(toListen(), { if (input$owndata_rectangular == "Yes") { showModal( shinyjqui::jqui_draggable( entriesInfoModal_RECT() ) ) } }) RECTANGULAR_reactive <- eventReactive(input$RUN.rectangular,{ req(input$k.rectangular) req(input$owndata_rectangular) req(input$myseed.rectangular) req(input$plot_start.rectangular) req(input$Location.rectangular) req(input$l.rectangular) req(input$r.rectangular) r.rectangular<- as.numeric(input$r.rectangular) k.rectangular<- as.numeric(input$k.rectangular) plot_start.rectangular<- as.vector(unlist(strsplit(input$plot_start.rectangular, ","))) plot_start.rectangular<- as.numeric(plot_start.rectangular) loc <- as.vector(unlist(strsplit(input$Location.rectangular, ","))) seed.rcbd <- as.numeric(input$myseed.rectangular) if (input$owndata_rectangular == "Yes") { t.rectangular <- as.numeric(get_tRECT()$t.rectangular) data.rectangular <- getData.rectangular()$dataUp.rectangular }else { req(input$t.rectangular) t.rectangular <- as.numeric(input$t.rectangular) data.rectangular <- NULL } seed.rectangular <- as.numeric(input$myseed.rectangular) l.rectangular <- as.numeric(input$l.rectangular) rectangular_lattice(t = t.rectangular, k = k.rectangular, r = r.rectangular, l = l.rectangular, plotNumber = plot_start.rectangular, seed = seed.rectangular, locationNames = loc, data = data.rectangular) }) valsRECT <- reactiveValues(maxV.rectangular= NULL, minV.rectangular= NULL, trail.rectangular= NULL) simuModal.rectangular<- function(failed = FALSE) { modalDialog( selectInput(inputId = ns("trailsRECT"), label = "Select One:", choices = c("YIELD", "MOISTURE", "HEIGHT", "Other")), conditionalPanel("input.trailsRECT == 'Other'", ns = ns, textInput(inputId = ns("OtherRECT"), label = "Input Trial Name:", value = NULL) ), fluidRow( column(6, numericInput(inputId = ns("min.rectangular"), "Input the min value", value = NULL) ), column(6, numericInput(inputId = ns("max.rectangular"), "Input the max value", value = NULL) ) ), if (failed) div(tags$b("Invalid input of data max and min", style = "color: red;")), footer = tagList( modalButton("Cancel"), actionButton(inputId = ns("ok.rectangular"), "GO") ) ) } observeEvent(input$Simulate.rectangular, { req(input$k.rectangular) req(input$r.rectangular) req(RECTANGULAR_reactive()$fieldBook) showModal( shinyjqui::jqui_draggable( simuModal.rectangular() ) ) }) observeEvent(input$ok.rectangular, { req(input$max.rectangular, input$min.rectangular) if (input$max.rectangular> input$min.rectangular&& input$min.rectangular!= input$max.rectangular) { valsRECT$maxV.rectangular<- input$max.rectangular valsRECT$minV.rectangular<- input$min.rectangular if(input$trailsRECT == "Other") { req(input$OtherRECT) if(!is.null(input$OtherRECT)) { valsRECT$trail.rectangular<- as.character(input$OtherRECT) }else showModal(simuModal.rectangular(failed = TRUE)) }else { valsRECT$trail.rectangular<- as.character(input$trailsRECT) } removeModal() }else { showModal( shinyjqui::jqui_draggable( simuModal.rectangular(failed = TRUE) ) ) } }) simuDataRECT <- reactive({ req(RECTANGULAR_reactive()$fieldBook) if(!is.null(valsRECT$maxV.rectangular) && !is.null(valsRECT$minV.rectangular) && !is.null(valsRECT$trail.rectangular)) { max <- as.numeric(valsRECT$maxV.rectangular) min <- as.numeric(valsRECT$minV.rectangular) df.rectangular<- RECTANGULAR_reactive()$fieldBook cnamesdf.rectangular<- colnames(df.rectangular) df.rectangular<- norm_trunc(a = min, b = max, data = df.rectangular) colnames(df.rectangular) <- c(cnamesdf.rectangular[1:(ncol(df.rectangular) - 1)], valsRECT$trail.rectangular) a <- ncol(df.rectangular) }else { df.rectangular<- RECTANGULAR_reactive()$fieldBook a <- ncol(df.rectangular) } return(list(df = df.rectangular, a = a)) }) output$RECTANGULAR.output <- DT::renderDataTable({ req(input$k.rectangular) k.rect <- input$k.rectangular if (k.rect == "No Options Available") { validate("A Rectangular Lattice requires t = s*(s-1), where s is the number of iBlock per replicate.") } df <- simuDataRECT()$df a <- as.numeric(simuDataRECT()$a) options(DT.options = list(pageLength = nrow(df), autoWidth = FALSE, scrollX = TRUE, scrollY = "500px")) DT::datatable(df, rownames = FALSE, options = list( columnDefs = list(list(className = 'dt-center', targets = "_all")))) }) output$downloadData.rectangular <- downloadHandler( filename = function() { loc <- paste("Rectangular_Lattice_", sep = "") paste(loc, Sys.Date(), ".csv", sep = "") }, content = function(file) { df <- as.data.frame(simuDataRECT()$df) write.csv(df, file, row.names = FALSE) } ) }) }
"thiesclima_sensors"
getRuleFromIonSymbol <- function(ions="[M+H]+") { checkSymbol <- function(ion) { regexpr("\\[[0-9]{0,2}M.*\\][0-9]{0,2}[\\+\\-]{1,2}", ion) != -1 } shortCuts <- cbind(c("M+H","M+Na","M+K","M+NH4", "M+", "M", "M-H","M+Cl-", "M-"), c("[M+H]+", "[M+Na]+", "[M+K]+", "[M+NH4]+", "[M]+", "[M]+", "[M-H]-","[M+Cl]-", "[M]-")) em <- 0.0005485799 chemical_elements <- NULL utils::data(chemical_elements, envir=environment(), package="InterpretMSSpectrum") on.exit(rm(chemical_elements)) out <- lapply(ions, function(ion) { if(ion %in% shortCuts[,1]) ion <- shortCuts[,2][ which(shortCuts[,1] == ion) ] if(!checkSymbol(ion)) stop("invalid ion") nmol <- sub(".*[^0-9M]([0-9]?M).*", "\\1", ion) nmol <- sub("M", "", nmol) nmol <- as.numeric(ifelse(nmol=="", 1, nmol)) ch <- sub(".*[^0-9]([0-9]{0,2}[\\+\\-])$", "\\1", ion) sgn <- sub("[^\\+\\-]", "", ch) sgn <- ifelse(sgn=="+", 1, -1) ch <- sub("[\\+\\-]", "", ch) ch[ch==""] <- "1" ch <- as.numeric(ch) ch <- ch * sgn x <- ion x <- sub("^.*\\[", "", x) x <- sub("\\].*", "", x) x <- sub("[0-9]?M", "", x) starts <- gregexpr("[\\+\\-]", x)[[1]] ends <- c(starts[-1]-1, nchar(x)) n <- length(starts) spl <- lapply(1:n, function(i) substr(x, starts[i], ends[i])) massdiff <- lapply(spl, function(y) { sgn <- sub("^([\\+\\-]).*", "\\1", y) sgn <- ifelse(sgn=="+", 1, -1) el <- sub("^[\\+\\-]", "", y) if (regexpr("^[0-9]+[A-Za-z]+", el) != -1) el <- gsub("([0-9]+)([A-Za-z]+)", "\\2\\1", el) el <- CountChemicalElements(x=el) masses <- sapply(names(el), function(a) { chemical_elements[,2][ which(chemical_elements[,1] == a)[1] ] }) return(sum(masses * el) * sgn) }) massdiff <- sum(unlist(massdiff), na.rm=TRUE) + ch * -em return(data.frame(name=ion, nmol=nmol, charge=ch, massdiff=massdiff, stringsAsFactors = FALSE)) }) return(do.call("rbind", out)) }
context("head-to-head") cr_data <- data.frame( game = c(1, 1, 1, 2, 2, 3, 3, 4), player = c(1, NA, NA, 1, 2, 2, 1, 2), score = as.numeric(1:8), scoreSP = -(1:8) ) output_long <- tibble::tibble( player1 = rep(c(1, 2, NA), each = 3), player2 = rep(c(1, 2, NA), times = 3), mean_score1 = c(4, 5.5, 1, 5.5, 19 / 3, NA, 2.5, NA, 2.5), sum_score = c(24, 22, 7, 22, 38, NA, 7, NA, 20) ) class(output_long) <- c("h2h_long", class(tibble::tibble())) output_mat <- matrix( c( 4, 5.5, 1, 5.5, 19/3, NA, 2.5, NA, 2.5), nrow = 3, dimnames = list(c("1", "2", NA), c("1", "2", NA)), byrow = TRUE ) matrix_class <- class(matrix(1:2, nrow = 1)) test_that("h2h_long works", { output_1 <- h2h_long( cr_data, mean_score1 = mean(score1), sum_score = sum(score1 + score2) ) expect_is(output_1, "h2h_long") expect_equal(output_1, output_long) output_2 <- h2h_long(cr_data) output_ref_2 <- output_long[, 1:2] expect_is(output_2, "h2h_long") expect_equal(output_2, output_ref_2) }) test_that("h2h_long handles `player` as factor", { input <- cr_data input$player <- factor(input$player, levels = c(1, 2, 3)) output <- h2h_long(input, sum_score = sum(score1 + score2)) output_ref <- tibble::tibble( player1 = factor(rep(c(1, 2, 3), each = 3), levels = c(1, 2, 3)), player2 = factor(rep(c(1, 2, 3), times = 3), levels = c(1, 2, 3)), sum_score = c(24, 22, NA, 22, 38, rep(NA, 4)) ) class(output_ref) <- c("h2h_long", class(tibble::tibble())) expect_is(output, "h2h_long") expect_equal(output, output_ref) }) test_that("h2h_long handles unnamed Head-to-Head functions", { output <- h2h_long(cr_data, sum(score1)) output_ref <- h2h_long(cr_data, sum_score1 = sum(score1)) colnames(output_ref) <- c("player1", "player2", "sum(score1)") expect_equal(output, output_ref) }) test_that("h2h_long handles not NULL `fill`", { output <- h2h_long( cr_data, mean_score1 = mean(score1), sum_score = sum(score1 + score2), fill = list(mean_score1 = 0, sum_score = -1) ) output_ref <- output_long output_ref$mean_score1[c(6, 8)] <- 0 output_ref$sum_score[c(6, 8)] <- -1 expect_equal(output, output_ref) }) test_that("to_h2h_long works", { output_1 <- output_mat %>% to_h2h_long(value = "mean_score1") output_ref_1 <- output_long[, 1:3] output_ref_1$player1 <- as.character(output_ref_1$player1) output_ref_1$player2 <- as.character(output_ref_1$player2) expect_is(output_1, "h2h_long") expect_equal(output_1, output_ref_1) expect_equal( output_mat %>% to_h2h_long(value = "new_val") %>% colnames(), c("player1", "player2", "new_val") ) output_2 <- output_mat %>% to_h2h_long(value = "mean_score1", drop = TRUE) output_ref_2 <- output_ref_1[-c(6, 8), ] expect_equal(output_2, output_ref_2) }) test_that("as_tibble.h2h_long removes `h2h_long` class", { input <- output_long output_ref <- input class(output_ref) <- class(tibble::tibble()) expect_identical(tibble::as_tibble(input), output_ref) }) test_that("h2h_mat works", { expect_equal( cr_data %>% h2h_mat(mean_score1 = mean(score1)), cr_data %>% h2h_mat(mean(score1)) ) output_1 <- cr_data %>% h2h_mat(mean_score1 = mean(score1)) output_ref_1 <- output_mat class(output_ref_1) <- c("h2h_mat", matrix_class) expect_equal(output_1, output_ref_1) output_2 <- cr_data %>% h2h_mat() output_ref_2 <- matrix( rep(NA, 9), nrow = 3, dimnames = list(c("1", "2", NA), c("1", "2", NA)), byrow = TRUE ) class(output_ref_2) <- c("h2h_mat", matrix_class) expect_is(output_2, "h2h_mat") expect_equal(output_2, output_ref_2) }) test_that("h2h_mat handles `player` as factor", { input <- cr_data input$player <- factor(input$player, levels = c(1, 2, 3)) output <- h2h_mat(input, sum(score1 + score2)) output_ref <- matrix( c(24, 22, NA, 22, 38, NA, NA, NA, NA), nrow = 3, dimnames = list(c("1", "2", "3"), c("1", "2", "3")), byrow = TRUE ) class(output_ref) <- c("h2h_mat", matrix_class) expect_equal(output, output_ref) }) test_that("h2h_mat allows multiple Head-to-Head functions", { expect_silent(h2h_mat(cr_data)) expect_message( h2h_mat( cr_data, mean_score1 = mean(score1), sum_score = sum(score1 + score2) ), "mean_score1" ) capt_output <- capture_error( h2h_mat(cr_data, mean_score1 = mean(score1), error = stop()) ) expect_identical(capt_output, NULL) }) test_that("h2h_mat handles not NULL `fill`", { output <- cr_data %>% h2h_mat(mean_score1 = mean(score1), fill = 0) output_ref <- output_mat output_ref[cbind(c(3, 2), c(2, 3))] <- 0 class(output_ref) <- c("h2h_mat", matrix_class) expect_equal(output, output_ref) }) test_that("to_h2h_mat works", { output <- to_h2h_mat(output_long, value = "mean_score1") output_ref <- output_mat class(output_ref) <- c("h2h_mat", matrix_class) expect_is(output, "h2h_mat") expect_equal(output, output_ref) }) test_that("to_h2h_mat gives messages", { expect_message(to_h2h_mat(output_long), "mean_score1") expect_message(to_h2h_mat(output_long[, 1:2]), "dummy") }) test_that("to_h2h_mat handles not NULL `fill`", { output <- output_long[-1, ] %>% to_h2h_mat(fill = 0) output_ref <- output_mat output_ref[1, 1] <- 0 class(output_ref) <- c("h2h_mat", matrix_class) expect_equal(output, output_ref) }) test_that("h2h_funs can be used with !!!", { output <- h2h_long(cr_data, !!!h2h_funs[c("num_wins", "num_wins2")]) expect_true(tibble::is_tibble(output)) expect_equal( colnames(output), c("player1", "player2", "num_wins", "num_wins2") ) }) test_that("num_wins works", { score_1 <- c(1, NA, 2, 1, 0) score_2 <- c(2, 1, 1, 1, 10^(-17)) expect_equal(num_wins(score_1, score_2), 1) expect_equal(num_wins(score_1, score_2, half_for_draw = TRUE), 2) expect_equal(num_wins(score_1, score_2, na.rm = FALSE), NA_real_) })
to_miniature <- function(filename, row = NULL, width = NULL, border_color = " fileout = NULL, use_docx2pdf = FALSE, timeout = 120) { if (!file.exists(filename)) { stop("filename does not exist") } if(grepl("\\.(ppt|pptx)$", filename)){ if(is.null(width)) width <- 750 pptx_to_miniature( filename, row = row, width = width, border_color = border_color, border_geometry = border_geometry, fileout = fileout, timeout = timeout) } else if(grepl("\\.(doc|docx)$", filename)){ if(is.null(width)) width <- 650 docx_to_miniature( filename, row = row, width = width, border_color = border_color, border_geometry = border_geometry, fileout = fileout, use_docx2pdf = use_docx2pdf, timeout = timeout) } else if(grepl("\\.pdf$", filename)){ if(is.null(width)) width <- 650 pdf_to_miniature( filename, row = row, width = width, border_color = border_color, border_geometry = border_geometry, fileout = fileout) } else { stop("function to_miniature do support this type of file:", basename(filename)) } } pdf_to_miniature <- function(filename, row = NULL, width = 650, border_color = " fileout = NULL) { img_list <- pdf_to_images(filename) x <- images_to_miniature( img_list = img_list, row = row, width = width, border_color = border_color, border_geometry = border_geometry ) if(!is.null(fileout)) image_write(x, path = fileout, format = "png") x } docx_to_miniature <- function(filename, row = NULL, width = 650, border_color = " fileout = NULL, use_docx2pdf = FALSE, timeout = 120) { pdf_filename <- tempfile(fileext = ".pdf") if(use_docx2pdf && exec_available("word") && docx2pdf_available()) docx2pdf(input = filename, output = pdf_filename) else to_pdf(input = filename, output = pdf_filename, timeout = timeout) x <- pdf_to_miniature(pdf_filename, row = row, width = width, border_color = border_color, border_geometry = border_geometry ) if(!is.null(fileout)) image_write(x, path = fileout, format = "png") x } pptx_to_miniature <- function(filename, row = NULL, width = 750, border_color = " fileout = NULL, timeout = 120) { pdf_filename <- tempfile(fileext = ".pdf") to_pdf(input = filename, output = pdf_filename, timeout = timeout) x <- pdf_to_miniature(pdf_filename, row = row, width = width, border_color = border_color, border_geometry = border_geometry ) if(!is.null(fileout)) image_write(x, path = fileout, format = "png") x }
df.residual.lme <- function(object, ...){max(object$fixDF$terms)}
is_integer <- function(x) { UseMethod("is_integer", x) } is_integer.default <- function(x) { if (mode(x) != "numeric") FALSE } is_integer.factor <- function(x) { FALSE } is_integer.numeric <- function(x) { (x %% 1) == 0 } is_not_integer <- function(x) { !is_integer(x) } is_positive_integer <- function(x) { (is_positive(x) & is_integer(x)) } is_negative_integer <- function(x) { (is_negative(x) & is_integer(x)) }
SardiniaHotels <- structure(list(municipality = structure(c(55L, 55L, 55L, 55L, 7L, 7L, 7L, 7L, 48L, 48L, 48L, 48L, 48L, 49L, 48L, 48L, 55L, 55L, 55L, 7L, 7L, 48L, 49L, 48L, 48L, 48L, 48L, 48L, 48L, 48L, 48L, 48L, 55L, 7L, 48L, 55L, 55L, 55L, 55L, 55L, 55L, 55L, 55L, 55L, 55L, 7L, 7L, 48L, 48L, 74L, 74L, 47L, 74L, 47L, 74L, 74L, 74L, 74L, 13L, 44L, 74L, 74L, 74L, 74L, 74L, 74L, 74L, 74L, 74L, 74L, 74L, 74L, 74L, 47L, 13L, 57L, 57L, 13L, 13L, 13L, 13L, 74L, 74L, 74L, 13L, 74L, 44L, 74L, 74L, 74L, 74L, 13L, 13L, 26L, 26L, 26L, 26L, 26L, 79L, 26L, 26L, 76L, 79L, 79L, 79L, 79L, 79L, 79L, 79L, 79L, 79L, 79L, 26L, 26L, 26L, 26L, 26L, 26L, 26L, 26L, 26L, 76L, 79L, 79L, 26L, 76L, 79L, 79L, 76L, 76L, 76L, 78L, 76L, 25L, 25L, 25L, 25L, 72L, 22L, 61L, 36L, 61L, 36L, 36L, 36L, 36L, 61L, 61L, 61L, 25L, 25L, 25L, 25L, 25L, 72L, 25L, 21L, 72L, 72L, 72L, 72L, 72L, 72L, 17L, 72L, 72L, 72L, 72L, 71L, 71L, 21L, 21L, 17L, 25L, 25L, 72L, 72L, 72L, 72L, 66L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 70L, 23L, 84L, 3L, 3L, 3L, 3L, 3L, 3L, 41L, 70L, 70L, 9L, 8L, 34L, 82L, 39L, 5L, 77L, 51L, 10L, 54L, 3L, 3L, 3L, 3L, 3L, 16L, 23L, 16L, 3L, 70L, 23L, 45L, 3L, 8L, 3L, 53L, 53L, 53L, 53L, 53L, 16L, 16L, 16L, 50L, 16L, 33L, 16L, 53L, 16L, 16L, 53L, 53L, 53L, 53L, 53L, 53L, 53L, 53L, 53L, 53L, 53L, 53L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 33L, 33L, 53L, 16L, 33L, 53L, 53L, 53L, 16L, 53L, 43L, 60L, 40L, 40L, 35L, 35L, 35L, 35L, 35L, 49L, 48L, 48L, 48L, 48L, 48L, 49L, 48L, 49L, 49L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 35L, 35L, 35L, 35L, 49L, 48L, 48L, 49L, 49L, 49L, 48L, 48L, 48L, 35L, 86L, 86L, 86L, 86L, 86L, 86L, 86L, 86L, 86L, 32L, 86L, 87L, 15L, 28L, 75L, 32L, 15L, 15L, 86L, 86L, 87L, 87L, 87L, 87L, 32L, 32L, 87L, 87L, 87L, 86L, 86L, 86L, 86L, 86L, 62L, 62L, 62L, 62L, 62L, 15L, 15L, 15L, 62L, 86L, 19L, 64L, 62L, 28L, 69L, 56L, 56L, 56L, 56L, 56L, 56L, 56L, 7L, 7L, 59L, 56L, 56L, 56L, 56L, 56L, 56L, 56L, 56L, 56L, 56L, 56L, 56L, 18L, 56L, 56L, 56L, 56L, 7L, 18L, 56L, 56L, 56L, 56L, 56L, 56L, 56L, 7L, 18L, 7L, 7L, 7L, 18L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 80L, 4L, 11L, 14L, 52L, 52L, 52L, 14L, 4L, 65L, 63L, 11L, 12L, 11L, 11L, 11L, 52L, 52L, 52L, 14L, 14L, 11L, 68L, 73L, 73L, 73L, 37L, 37L, 20L, 73L, 73L, 73L, 73L, 67L, 58L, 67L, 73L, 73L, 73L, 29L, 37L, 73L, 6L, 1L, 73L, 1L, 37L, 38L, 83L, 30L, 1L, 27L, 31L, 31L, 31L, 31L, 27L, 27L, 27L, 27L, 27L, 27L, 8L, 8L, 24L, 24L, 8L, 42L, 24L, 24L, 24L, 24L, 24L, 8L, 8L, 46L, 46L, 31L, 31L, 31L, 81L, 81L, 85L, 85L), .Label = c("Aglientu", "Alghero", "Arbatax/Tortol_", "Arborea", "Aritzo", "Badesi", "Baja Sardinia", "Bari Sardo", "Baunei", "Belvi", "Bosa", "Bosa ", "Budoni", "Cabras", "Cagliari", "Cala Gonone", "Calasetta ", "Cannigione", "Capitana", "Capo Testa", "Carbonia", "Carbonia ", "Cardedu", "Cardedu ", "Carloforte", "Castelsardo", "Castiadas", "Chia ", "Conca Verde", "Costa Paradiso", "Costa Rei (Muravera)", "Domus De Maria ", "Dorgali", "Girasole", "Golfo Aranci ", "Iglesias", "Isola Rossa", "Isola Rossa. Trinit_ D'agultu E Vignola", "Jerzu", "La Maddalena", "Lanusei", "Loceri", "Loc Nido D'aquila - Maddalena", "Loiri Porto San Paolo", "Lotzorai", "Muravera", "Murta Maria. Olbia", "Olbia", "Olbia ", "Oliena", "Orgosolo", "Oristano", "Orosei", "Ottana", "Palau", "Porto Cervo", "Porto Ottiolu. Budoni", "Porto Pozzo", "Porto Rotondo", "Porto Rotondo ", "Portoscuso", "Pula", "Putzu Idu", "Quartu", "Riola Sardo", "San Giovanni Suergiu", "San Pasquale", "Santa Caterina", "Santa Margherita Di Pula ", "Santa Maria Navarrese", "Sant'anna Arresi", "Sant'antioco", "Santa Teresa Di Gallura", "San Teodoro", "Sarroch", "Sassari", "Seulo", "Sorso", "Stintino", "Terralba", "Tertenia", "Tortoli", "Trinit_ D'agulta E Vignola", "Villagrande Strisaili", "Villaputzu", "Villasimius", "Villasimius " ), class = "factor"), stars = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 4L, 3L, 2L, 3L, 2L, 2L, 3L, 3L, 3L, 3L, 2L, 3L, 4L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 4L, 4L,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3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 5L, 3L, 3L, 3L, 3L, 5L, 5L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 5L, 5L, 5L, 5L, 5L, 5L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 11L, 11L, 11L, 11L, 11L, 7L, 7L, 11L, 11L), .Label = c("AlgheroSassari", "CagliariVillasimius", "CostaSmeralda", "DorgaliOrosei", "Gallura", "NurraAnglona", "Ogliastra", "Olbia", "OristanoBosa", "PulaChia", "Sarrabus", "Sulcis"), class = "factor"), seaLocation = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,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, 88L, 67L, 27L, 127L, 107L, 23L, 14L, 57L, 1L, 75L, 59L, 55L, 37L, 39L, 19L, 64L, 226L, 78L, 61L, 27L, 186L, 61L, 1L, 6L, 1L, 10L, 13L, 86L, 12L, 69L, 8L, 3L, 82L, 86L, 5L, 73L, 78L, 370L, 11L, 92L, 25L, 22L, 142L, 60L, 194L, 35L, 113L, 2L, 0L, 78L, 52L, 97L, 25L, 2L, 41L, 10L, 127L, 60L, 3L, 8L, 10L, 7L, 111L, 3L, 40L, 7L, 68L, 49L, 45L, 13L, 32L, 49L, 183L, 31L, 17L, 11L, 8L, 18L, 5L, 15L, 16L, 2L, 4L, 33L, 37L, 112L, 18L, 54L, 11L, 51L, 4L, 14L, 23L, 3L, 14L, 63L, 96L, 56L, 33L, 62L, 15L, 20L, 26L, 32L, 1L, 3L, 12L, 11L, 19L, 0L, 4L, 6L, 9L, 13L, 55L, 366L, 0L, 264L, 82L, 10L, 94L, 69L, 53L, 228L, 94L, 87L, 115L, 32L, 22L, 23L, 62L, 94L, 1L, 71L, 109L, 39L, 15L, 9L, 1L, 20L, 14L, 8L, 0L, 317L, 85L, 59L, 71L, 105L, 388L, 120L, 102L, 315L, 123L, 136L, 80L, 15L, 7L, 23L, 55L, 35L, 385L, 55L, 33L, 55L, 34L, 15L, 255L, 97L, 35L, 16L, 203L, 260L, 96L, 286L, 206L, 72L, 69L, 84L, 86L, 16L, 25L, 22L, 22L, 0L, 30L, 7L, 4L, 48L, 32L, 24L, 24L, 31L, 26L, 9L, 12L, 47L, 68L, 1L, 16L, 18L, 7L, 9L, 68L, 33L, 86L, 26L, 100L, 26L, 173L, 118L, 18L, 2L, 130L, 309L, 141L, 438L, 149L, 13L, 108L, 97L, 11L, 27L, 109L, 166L, 39L, 45L, 19L, 18L, 27L, 12L, 8L, 0L, 92L, 10L, 45L, 153L, 82L, 5L, 22L, 7L, 51L, 68L, 11L, 71L, 55L, 1L, 49L, 38L, 24L, 59L, 29L, 7L, 27L, 6L, 48L, 23L, 83L, 43L, 3L, 6L, 6L, 6L, 55L, 6L, 14L, 150L, 92L, 83L, 154L, 287L, 48L, 116L, 20L, 225L, 81L, 304L, 116L, 93L, 61L, 105L, 24L, 124L, 107L, 163L, 135L, 878L, 33L, 195L, 74L, 539L, 155L, 30L, 237L, 157L, 51L, 36L, 85L, 74L, 82L, 118L, 41L, 116L, 171L, 77L, 52L, 25L, 97L, 142L, 76L, 150L, 128L, 3L, 59L, 32L, 75L, 100L, 27L, 158L, 25L, 11L, 14L, 4L, 35L, 34L, 54L, 32L, 0L, 3L, 1L, 3L, 39L, 46L, 66L, 170L, 81L, 71L, 56L, 296L, 367L, 40L, 84L, 213L, 25L, 327L, 163L, 122L, 105L, 302L, 173L, 25L, 216L, 193L, 13L, 15L, 31L, 15L, 20L, 26L, 10L, 91L, 3L, 14L, 0L, 1L, 2L, 10L, 26L, 12L, 19L, 2L, 3L, 25L, 18L, 5L, 22L, 18L, 0L, 16L, 32L, 21L, 87L, 28L, 14L, 23L, 18L, 17L, 17L, 20L, 19L, 28L, 22L, 45L, 82L, 35L, 2L, 21L, 14L, 37L, 65L, 3L, 29L, 41L, 13L, 30L, 34L, 33L, 59L, 25L, 14L, 71L, 4L, 6L, 336L, 49L, 147L, 372L, 9L, 12L, 36L, 62L, 21L, 175L, 301L, 66L, 125L, 220L, 145L, 47L, 98L, 124L, 142L, 49L, 12L, 4L, 26L, 0L, 17L, 3L, 39L, 37L, 35L, 26L, 16L, 2L, 236L, 33L, 40L, 9L, 14L, 8L, 47L, 24L), good = c(49L, 66L, 29L, 19L, 10L, 12L, 33L, 15L, 13L, 13L, 19L, 56L, 31L, 23L, 8L, 33L, 25L, 27L, 149L, 19L, 17L, 17L, 7L, 65L, 32L, 58L, 22L, 33L, 4L, 104L, 19L, 85L, 16L, 20L, 11L, 23L, 6L, 117L, 2L, 12L, 2L, 12L, 5L, 4L, 3L, 21L, 17L, 0L, 3L, 46L, 176L, 165L, 334L, 43L, 21L, 67L, 96L, 121L, 182L, 45L, 161L, 72L, 189L, 47L, 51L, 23L, 97L, 63L, 28L, 65L, 34L, 12L, 11L, 44L, 0L, 27L, 16L, 10L, 47L, 28L, 16L, 28L, 147L, 132L, 19L, 52L, 45L, 88L, 0L, 1L, 0L, 10L, 2L, 70L, 12L, 18L, 16L, 6L, 94L, 70L, 12L, 90L, 69L, 272L, 8L, 113L, 8L, 9L, 61L, 83L, 136L, 48L, 128L, 15L, 1L, 112L, 84L, 33L, 33L, 0L, 48L, 23L, 149L, 114L, 14L, 14L, 15L, 4L, 137L, 45L, 32L, 6L, 232L, 72L, 39L, 9L, 20L, 31L, 78L, 46L, 12L, 5L, 16L, 8L, 7L, 23L, 29L, 3L, 5L, 31L, 32L, 21L, 24L, 23L, 6L, 49L, 5L, 24L, 22L, 1L, 26L, 27L, 63L, 79L, 33L, 17L, 27L, 21L, 46L, 35L, 3L, 1L, 28L, 1L, 2L, 1L, 2L, 0L, 0L, 23L, 68L, 146L, 1L, 93L, 57L, 14L, 26L, 21L, 51L, 65L, 59L, 50L, 81L, 18L, 6L, 29L, 12L, 53L, 2L, 23L, 55L, 39L, 3L, 17L, 9L, 12L, 7L, 1L, 0L, 276L, 97L, 66L, 51L, 71L, 328L, 120L, 175L, 117L, 46L, 103L, 55L, 3L, 7L, 11L, 60L, 49L, 369L, 64L, 48L, 27L, 16L, 7L, 58L, 44L, 38L, 13L, 190L, 101L, 168L, 214L, 193L, 38L, 17L, 56L, 48L, 9L, 15L, 15L, 13L, 11L, 16L, 14L, 9L, 19L, 20L, 23L, 49L, 13L, 23L, 20L, 25L, 21L, 49L, 1L, 6L, 33L, 2L, 8L, 8L, 49L, 22L, 10L, 86L, 46L, 75L, 29L, 11L, 1L, 58L, 265L, 69L, 98L, 55L, 17L, 71L, 44L, 18L, 31L, 90L, 44L, 27L, 39L, 32L, 32L, 26L, 22L, 28L, 1L, 67L, 3L, 19L, 171L, 43L, 32L, 42L, 21L, 40L, 9L, 8L, 30L, 76L, 8L, 70L, 50L, 18L, 79L, 28L, 7L, 18L, 19L, 18L, 30L, 50L, 62L, 6L, 13L, 11L, 12L, 80L, 11L, 15L, 87L, 8L, 42L, 49L, 55L, 3L, 150L, 29L, 49L, 79L, 13L, 95L, 122L, 58L, 88L, 64L, 58L, 87L, 247L, 79L, 495L, 75L, 283L, 11L, 235L, 190L, 58L, 38L, 51L, 33L, 20L, 24L, 44L, 27L, 45L, 9L, 106L, 77L, 20L, 23L, 35L, 91L, 107L, 31L, 67L, 84L, 6L, 59L, 28L, 63L, 39L, 29L, 79L, 24L, 14L, 18L, 10L, 12L, 47L, 40L, 9L, 2L, 5L, 2L, 9L, 14L, 33L, 34L, 74L, 110L, 40L, 44L, 90L, 270L, 114L, 187L, 67L, 43L, 232L, 110L, 198L, 212L, 243L, 149L, 86L, 169L, 217L, 17L, 13L, 32L, 23L, 81L, 41L, 50L, 158L, 15L, 53L, 1L, 5L, 8L, 21L, 37L, 26L, 6L, 1L, 3L, 27L, 21L, 18L, 32L, 13L, 0L, 5L, 18L, 26L, 44L, 26L, 3L, 31L, 7L, 37L, 28L, 10L, 65L, 19L, 20L, 58L, 42L, 22L, 1L, 27L, 42L, 17L, 23L, 5L, 33L, 63L, 11L, 21L, 27L, 37L, 27L, 15L, 15L, 44L, 8L, 10L, 52L, 25L, 63L, 117L, 22L, 9L, 19L, 10L, 16L, 110L, 378L, 73L, 46L, 183L, 121L, 6L, 132L, 136L, 28L, 44L, 8L, 7L, 30L, 7L, 9L, 5L, 13L, 29L, 12L, 30L, 14L, 3L, 119L, 37L, 32L, 2L, 9L, 6L, 12L, 17L), average = c(17L, 31L, 4L, 11L, 2L, 1L, 8L, 7L, 15L, 9L, 0L, 9L, 12L, 6L, 12L, 4L, 7L, 4L, 53L, 7L, 1L, 14L, 8L, 9L, 2L, 11L, 12L, 6L, 0L, 11L, 14L, 21L, 3L, 6L, 10L, 7L, 1L, 48L, 13L, 7L, 3L, 11L, 1L, 5L, 0L, 1L, 4L, 0L, 1L, 23L, 63L, 41L, 158L, 12L, 4L, 13L, 46L, 64L, 44L, 12L, 44L, 33L, 43L, 5L, 14L, 14L, 27L, 20L, 8L, 11L, 4L, 1L, 14L, 5L, 0L, 14L, 7L, 0L, 9L, 6L, 10L, 8L, 49L, 46L, 31L, 13L, 2L, 28L, 0L, 0L, 0L, 0L, 1L, 15L, 1L, 3L, 7L, 0L, 31L, 15L, 16L, 30L, 13L, 82L, 4L, 22L, 2L, 6L, 10L, 20L, 33L, 20L, 34L, 1L, 0L, 59L, 31L, 7L, 19L, 0L, 19L, 41L, 105L, 53L, 6L, 11L, 11L, 0L, 47L, 65L, 22L, 0L, 64L, 29L, 8L, 1L, 9L, 19L, 15L, 15L, 5L, 2L, 9L, 9L, 11L, 10L, 22L, 3L, 5L, 12L, 7L, 2L, 2L, 5L, 10L, 29L, 3L, 17L, 8L, 3L, 10L, 3L, 13L, 26L, 7L, 3L, 12L, 4L, 16L, 22L, 0L, 1L, 7L, 2L, 0L, 0L, 2L, 0L, 0L, 5L, 17L, 38L, 2L, 24L, 13L, 8L, 0L, 1L, 24L, 21L, 6L, 6L, 11L, 2L, 2L, 11L, 2L, 6L, 1L, 2L, 10L, 11L, 0L, 3L, 4L, 1L, 2L, 0L, 0L, 154L, 62L, 16L, 18L, 40L, 129L, 59L, 114L, 23L, 8L, 44L, 5L, 0L, 2L, 1L, 18L, 21L, 125L, 16L, 31L, 10L, 1L, 18L, 19L, 11L, 17L, 6L, 55L, 19L, 100L, 62L, 70L, 2L, 1L, 7L, 6L, 6L, 3L, 7L, 1L, 4L, 6L, 4L, 1L, 4L, 16L, 16L, 14L, 1L, 5L, 11L, 6L, 2L, 4L, 0L, 0L, 9L, 1L, 1L, 0L, 31L, 9L, 3L, 18L, 36L, 23L, 7L, 5L, 0L, 12L, 92L, 20L, 7L, 12L, 14L, 28L, 10L, 11L, 28L, 23L, 13L, 1L, 12L, 7L, 20L, 11L, 3L, 18L, 1L, 9L, 2L, 10L, 62L, 8L, 25L, 25L, 22L, 9L, 2L, 3L, 3L, 12L, 4L, 8L, 12L, 4L, 15L, 13L, 0L, 6L, 5L, 1L, 8L, 8L, 19L, 0L, 11L, 3L, 3L, 15L, 6L, 14L, 18L, 1L, 2L, 4L, 6L, 10L, 53L, 8L, 2L, 17L, 19L, 28L, 58L, 19L, 32L, 38L, 24L, 22L, 123L, 26L, 86L, 69L, 57L, 10L, 78L, 103L, 40L, 17L, 31L, 25L, 9L, 15L, 16L, 13L, 21L, 3L, 57L, 18L, 7L, 12L, 17L, 48L, 36L, 6L, 28L, 24L, 3L, 32L, 11L, 23L, 6L, 9L, 9L, 6L, 8L, 9L, 2L, 2L, 26L, 19L, 6L, 0L, 5L, 1L, 3L, 7L, 4L, 3L, 22L, 37L, 5L, 14L, 26L, 89L, 69L, 118L, 11L, 52L, 50L, 48L, 81L, 112L, 64L, 59L, 66L, 53L, 69L, 7L, 1L, 4L, 4L, 63L, 29L, 33L, 67L, 18L, 40L, 1L, 10L, 7L, 5L, 20L, 10L, 0L, 0L, 3L, 7L, 11L, 20L, 18L, 7L, 0L, 1L, 10L, 10L, 9L, 5L, 1L, 7L, 2L, 46L, 27L, 2L, 14L, 10L, 8L, 19L, 14L, 8L, 0L, 4L, 27L, 2L, 4L, 3L, 6L, 12L, 2L, 19L, 6L, 7L, 18L, 3L, 1L, 30L, 3L, 3L, 31L, 4L, 18L, 15L, 12L, 5L, 5L, 0L, 5L, 29L, 169L, 32L, 18L, 55L, 7L, 0L, 37L, 52L, 2L, 24L, 3L, 5L, 4L, 0L, 4L, 1L, 3L, 7L, 0L, 4L, 5L, 3L, 14L, 13L, 8L, 1L, 1L, 2L, 4L, 5L), bad = c(2L, 15L, 0L, 6L, 1L, 0L, 3L, 8L, 13L, 3L, 1L, 2L, 14L, 1L, 5L, 2L, 6L, 1L, 29L, 4L, 2L, 7L, 4L, 3L, 0L, 1L, 4L, 5L, 0L, 3L, 2L, 3L, 5L, 3L, 6L, 5L, 0L, 17L, 5L, 5L, 2L, 2L, 2L, 3L, 0L, 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L, 20L, 35L, 18L, 9L, 7L, 146L, 9L, 13L, 3L, 21L, 2L, 6L, 4L, 29L, 15L, 0L, 1L, 21L, 134L, 132L, 321L, 45L, 23L, 33L, 109L, 199L, 295L, 30L, 134L, 31L, 289L, 24L, 39L, 13L, 98L, 30L, 5L, 63L, 23L, 11L, 9L, 26L, 1L, 19L, 31L, 9L, 47L, 16L, 9L, 24L, 266L, 104L, 36L, 66L, 118L, 63L, 1L, 5L, 0L, 7L, 11L, 36L, 6L, 18L, 31L, 1L, 160L, 36L, 11L, 16L, 42L, 370L, 4L, 61L, 6L, 10L, 54L, 79L, 179L, 19L, 91L, 0L, 0L, 100L, 16L, 23L, 15L, 1L, 10L, 13L, 310L, 157L, 6L, 11L, 11L, 6L, 34L, 5L, 13L, 1L, 291L, 22L, 13L, 5L, 16L, 20L, 34L, 16L, 6L, 2L, 6L, 11L, 7L, 14L, 9L, 1L, 4L, 10L, 23L, 18L, 10L, 18L, 4L, 41L, 8L, 9L, 7L, 2L, 5L, 24L, 26L, 28L, 24L, 17L, 10L, 18L, 25L, 17L, 1L, 1L, 6L, 7L, 4L, 1L, 4L, 2L, 4L, 10L, 34L, 368L, 0L, 61L, 29L, 7L, 32L, 20L, 82L, 73L, 35L, 30L, 38L, 13L, 6L, 16L, 16L, 21L, 1L, 15L, 63L, 22L, 5L, 10L, 5L, 7L, 6L, 2L, 0L, 460L, 146L, 35L, 53L, 39L, 572L, 215L, 250L, 319L, 23L, 194L, 69L, 5L, 7L, 23L, 45L, 62L, 586L, 74L, 77L, 24L, 8L, 12L, 63L, 36L, 25L, 11L, 295L, 246L, 237L, 353L, 323L, 23L, 22L, 21L, 29L, 13L, 9L, 20L, 12L, 14L, 29L, 7L, 2L, 11L, 17L, 14L, 6L, 5L, 9L, 10L, 8L, 17L, 52L, 0L, 8L, 16L, 2L, 7L, 25L, 77L, 18L, 6L, 24L, 80L, 74L, 41L, 9L, 2L, 112L, 143L, 55L, 92L, 24L, 5L, 24L, 14L, 5L, 19L, 67L, 46L, 14L, 36L, 12L, 12L, 12L, 5L, 11L, 0L, 33L, 2L, 26L, 253L, 19L, 19L, 16L, 8L, 8L, 16L, 3L, 26L, 25L, 5L, 68L, 49L, 28L, 52L, 27L, 4L, 27L, 7L, 28L, 30L, 22L, 22L, 1L, 4L, 0L, 2L, 19L, 1L, 13L, 44L, 6L, 20L, 30L, 103L, 24L, 214L, 6L, 24L, 42L, 72L, 54L, 159L, 25L, 143L, 28L, 24L, 63L, 270L, 49L, 113L, 16L, 54L, 39L, 287L, 213L, 43L, 81L, 123L, 26L, 16L, 28L, 31L, 25L, 38L, 9L, 77L, 83L, 25L, 14L, 9L, 40L, 135L, 18L, 36L, 43L, 2L, 58L, 10L, 35L, 20L, 20L, 40L, 10L, 4L, 7L, 4L, 9L, 17L, 26L, 5L, 2L, 6L, 3L, 2L, 20L, 26L, 52L, 103L, 42L, 25L, 24L, 50L, 97L, 74L, 66L, 72L, 40L, 108L, 73L, 146L, 57L, 95L, 69L, 48L, 121L, 163L, 9L, 8L, 8L, 7L, 22L, 19L, 18L, 47L, 8L, 13L, 0L, 5L, 13L, 7L, 22L, 26L, 1L, 1L, 4L, 10L, 12L, 4L, 10L, 5L, 0L, 2L, 17L, 17L, 23L, 9L, 0L, 6L, 2L, 11L, 7L, 11L, 8L, 6L, 8L, 23L, 28L, 6L, 0L, 12L, 23L, 8L, 12L, 7L, 7L, 49L, 3L, 28L, 76L, 13L, 26L, 4L, 11L, 69L, 2L, 9L, 178L, 16L, 29L, 164L, 35L, 13L, 13L, 5L, 16L, 186L, 580L, 125L, 89L, 332L, 238L, 14L, 161L, 190L, 44L, 18L, 6L, 15L, 14L, 0L, 7L, 3L, 10L, 28L, 10L, 14L, 14L, 1L, 276L, 30L, 21L, 1L, 8L, 8L, 13L, 28L), couple = c(43L, 76L, 26L, 17L, 11L, 15L, 36L, 20L, 16L, 10L, 24L, 43L, 33L, 31L, 12L, 30L, 30L, 53L, 187L, 33L, 28L, 15L, 3L, 40L, 39L, 60L, 16L, 45L, 12L, 103L, 19L, 62L, 62L, 53L, 14L, 20L, 8L, 52L, 17L, 5L, 11L, 15L, 4L, 3L, 0L, 21L, 16L, 0L, 4L, 52L, 173L, 218L, 288L, 91L, 33L, 86L, 128L, 108L, 196L, 71L, 131L, 79L, 85L, 56L, 88L, 31L, 82L, 84L, 39L, 102L, 100L, 13L, 17L, 51L, 2L, 79L, 40L, 37L, 44L, 41L, 30L, 41L, 64L, 135L, 26L, 24L, 80L, 104L, 0L, 0L, 0L, 7L, 4L, 98L, 13L, 46L, 11L, 7L, 24L, 98L, 14L, 46L, 90L, 215L, 12L, 123L, 18L, 24L, 100L, 69L, 131L, 57L, 123L, 14L, 0L, 126L, 113L, 90L, 75L, 0L, 71L, 15L, 59L, 46L, 14L, 16L, 23L, 4L, 71L, 15L, 14L, 6L, 54L, 94L, 53L, 31L, 31L, 70L, 147L, 43L, 8L, 14L, 27L, 11L, 2L, 16L, 71L, 4L, 6L, 36L, 30L, 88L, 20L, 39L, 31L, 55L, 3L, 25L, 20L, 4L, 32L, 45L, 93L, 100L, 31L, 33L, 33L, 21L, 23L, 47L, 1L, 1L, 30L, 1L, 12L, 1L, 2L, 3L, 5L, 18L, 56L, 97L, 4L, 230L, 84L, 21L, 55L, 60L, 38L, 147L, 79L, 76L, 106L, 31L, 8L, 30L, 16L, 91L, 4L, 54L, 73L, 46L, 5L, 13L, 6L, 8L, 7L, 5L, 0L, 284L, 114L, 88L, 73L, 176L, 122L, 63L, 122L, 66L, 120L, 171L, 55L, 5L, 11L, 8L, 75L, 25L, 114L, 41L, 33L, 45L, 33L, 29L, 141L, 86L, 40L, 23L, 86L, 70L, 107L, 94L, 62L, 63L, 38L, 88L, 89L, 12L, 25L, 23L, 14L, 2L, 22L, 12L, 8L, 45L, 32L, 32L, 64L, 30L, 29L, 23L, 14L, 34L, 54L, 2L, 8L, 29L, 4L, 9L, 30L, 38L, 77L, 15L, 134L, 46L, 148L, 86L, 29L, 1L, 56L, 302L, 120L, 249L, 131L, 15L, 135L, 56L, 20L, 61L, 110L, 127L, 40L, 39L, 30L, 42L, 31L, 15L, 35L, 6L, 90L, 9L, 36L, 75L, 86L, 29L, 42L, 24L, 35L, 36L, 10L, 41L, 73L, 9L, 38L, 31L, 11L, 68L, 29L, 6L, 16L, 17L, 30L, 23L, 86L, 67L, 5L, 20L, 14L, 13L, 57L, 7L, 42L, 174L, 80L, 87L, 124L, 199L, 56L, 83L, 34L, 18L, 96L, 330L, 172L, 76L, 96L, 49L, 58L, 128L, 107L, 229L, 156L, 586L, 57L, 180L, 25L, 397L, 202L, 79L, 84L, 75L, 73L, 25L, 56L, 66L, 77L, 92L, 29L, 216L, 136L, 61L, 51L, 44L, 103L, 100L, 77L, 130L, 137L, 6L, 78L, 43L, 93L, 96L, 35L, 168L, 35L, 25L, 19L, 6L, 34L, 67L, 53L, 31L, 2L, 5L, 1L, 7L, 27L, 29L, 43L, 105L, 142L, 70L, 57L, 256L, 404L, 97L, 215L, 171L, 95L, 360L, 164L, 157L, 211L, 320L, 223L, 94L, 220L, 219L, 22L, 9L, 41L, 24L, 93L, 55L, 54L, 204L, 19L, 66L, 0L, 16L, 5L, 23L, 26L, 10L, 6L, 2L, 2L, 33L, 20L, 23L, 28L, 23L, 2L, 15L, 34L, 28L, 78L, 25L, 11L, 31L, 9L, 32L, 22L, 10L, 43L, 39L, 27L, 61L, 78L, 35L, 2L, 33L, 65L, 33L, 49L, 5L, 37L, 31L, 17L, 42L, 98L, 52L, 51L, 27L, 16L, 73L, 9L, 4L, 169L, 47L, 164L, 238L, 8L, 5L, 31L, 54L, 21L, 72L, 124L, 21L, 51L, 62L, 36L, 23L, 46L, 71L, 90L, 72L, 9L, 2L, 34L, 7L, 13L, 4L, 32L, 33L, 25L, 34L, 13L, 2L, 15L, 33L, 35L, 4L, 5L, 6L, 18L, 9L), single = c(3L, 4L, 2L, 1L, 1L, 0L, 2L, 3L, 0L, 1L, 4L, 3L, 11L, 3L, 2L, 6L, 0L, 3L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L, 3L, 3L, 6L, 3L, 6L, 3L, 8L, 12L, 11L, 0L, 5L, 13L, 4L, 10L, 29L, 2L, 2L, 11L, 6L, 46L, 37L, 27L, 9L, 11L, 11L, 78L, 13L, 44L, 8L, 10L, 10L, 0L, 6L, 12L, 5L, 3L, 1L, 4L, 2L, 0L, 0L, 2L, 0L, 0L, 0L, 18L, 9L, 80L, 36L, 15L, 2L, 8L, 5L, 31L, 67L, 5L, 27L, 6L, 15L, 13L, 19L, 5L, 3L, 17L, 1L, 12L, 13L, 4L, 4L, 20L, 0L, 10L, 6L, 9L, 3L, 1L, 3L, 11L, 23L, 39L, 6L, 10L, 24L, 14L, 0L, 2L, 0L, 0L, 1L, 13L, 0L, 44L, 1L, 0L, 5L, 13L, 3L, 54L, NA, NA, NA, 25L, 1L, 14L, 13L, 16L, 6L, 9L, 15L, 1L, 0L, 5L, 28L, 10L, NA, 3L, 28L, 26L, 9L, 6L, 4L, 6L, 3L, 3L, 72L, 35L, 24L, 4L, 22L, 33L, 14L, 11L, 8L, 71L, 10L, 8L, 9L, 8L, 5L, 9L, 8L, 12L, 15L, 1L, 2L, 16L, 1L, 28L, 0L, 8L, 5L, 7L, 9L, 9L, 16L, 4L, 12L, 8L, 15L, 21L, 2L, 8L, 0L, 2L, 13L, 7L, 0L, 0L, 6L, 3L, 1L, 1L, 0L, 0L, 8L, 4L, 24L, 24L, 1L, 79L, 29L, 5L, 20L, 17L, 2L, 40L, 25L, 18L, 29L, 13L, 7L, 5L, 14L, 17L, 1L, 11L, 19L, 18L, 6L, 5L, 4L, 11L, 2L, 0L, 0L, 66L, 14L, 6L, 8L, 35L, 35L, 2L, 15L, 24L, 34L, 39L, 11L, 6L, 0L, 3L, 25L, 10L, 55L, 6L, 13L, 6L, 7L, 10L, 85L, 45L, 18L, 8L, 17L, 5L, 14L, 19L, 19L, 15L, 12L, 16L, 10L, 8L, 2L, 3L, 5L, 3L, 2L, 5L, 3L, 0L, 13L, 7L, 18L, 3L, 7L, 7L, 1L, 6L, 7L, 0L, 1L, 2L, 5L, 3L, 7L, 14L, 24L, 6L, 24L, 9L, 26L, 16L, 0L, 1L, 20L, 193L, 14L, 38L, 39L, 12L, 26L, 22L, 17L, 11L, 25L, 35L, 6L, 4L, 2L, 11L, 7L, 2L, 0L, 0L, 26L, 0L, 7L, 9L, 89L, 14L, 13L, 12L, 15L, 11L, 2L, 13L, 21L, 3L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 3L, 3L, 4L, 2L, 6L, 9L, 5L, 3L, 2L, 2L, 4L, 16L, 15L, 6L, 20L, 12L, 2L, 5L, 4L, 9L, 3L, 3L, 4L, 2L, 6L, 3L, 1L, 3L, 8L, 13L, 1L, 0L, 2L, 1L, 1L, 2L, 3L, 2L, 20L, 4L, 2L, 5L, 85L, 116L, 56L, 119L, 89L, 17L, 81L, 75L, 44L, 110L, 144L, 55L, 30L, 71L, 87L, 12L, 17L, 35L, 17L, 46L, 2L, 28L, 53L, 7L, 16L, 0L, 6L, NA, 15L, NA, 8L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 11L, 5L, 3L, 4L, 7L, 10L, 4L, 3L, 6L, 3L, 9L, 14L, 5L, 2L, 4L, 2L, 12L, 8L, 17L, 1L, 13L, 7L, NA, 5L, 9L, NA, 13L, 6L, 2L, 3L, 21L, 32L, 6L, 7L, 9L, 22L, 0L, 24L, 10L, 5L, 9L, 3L, 0L, 2L, 0L, 3L, 0L, 12L, 1L, 2L, 2L, 1L, 4L, 3L, 6L, 8L, 2L, 1L, 2L, 15L, 6L), JunAug = c(57L, 108L, 36L, 19L, 21L, 14L, 50L, 28L, 25L, 11L, 43L, 62L, 42L, 40L, 20L, 38L, 38L, 62L, 280L, 50L, 32L, 16L, 16L, 59L, 34L, 50L, 21L, 74L, 0L, 83L, 24L, 65L, 65L, 74L, 31L, 31L, 11L, 131L, 24L, 17L, 9L, 26L, 5L, 14L, 4L, 30L, 30L, 0L, 4L, 64L, 278L, 212L, 515L, 98L, 46L, 112L, 191L, 276L, 335L, 88L, 193L, 130L, 332L, 87L, 106L, 36L, 189L, 107L, 46L, 112L, 78L, 16L, 31L, 63L, 4L, 73L, 41L, 40L, 84L, 55L, 33L, 79L, 322L, 139L, 56L, 50L, 141L, 108L, 1L, 2L, 0L, 15L, 12L, 68L, 16L, 122L, 24L, 3L, 162L, 68L, 28L, 48L, NA, NA, NA, 139L, 19L, 28L, 131L, 94L, 203L, 56L, 190L, 10L, 0L, 119L, 35L, 31L, NA, 0L, 35L, 27L, 344L, 188L, 37L, 22L, 27L, 8L, 80L, 31L, 32L, 5L, 275L, 60L, 62L, 29L, 33L, 84L, 59L, 28L, 11L, 38L, 5L, 17L, 8L, 19L, 27L, 4L, 8L, 38L, 49L, 66L, 37L, 55L, 12L, 79L, 10L, 32L, 19L, 3L, 21L, 51L, 78L, 74L, 38L, 39L, 38L, 36L, 52L, 61L, 1L, 3L, 28L, 5L, 12L, 1L, 5L, 4L, 6L, 22L, 68L, 342L, 1L, 164L, 77L, 23L, 63L, 45L, 131L, 146L, 74L, 81L, 119L, 31L, 11L, 45L, 33L, 93L, 6L, 48L, 81L, 39L, 6L, 16L, 2L, 15L, 8L, 1L, 2L, 640L, 198L, 106L, 102L, 150L, 669L, 280L, 404L, 342L, 98L, 186L, 92L, 6L, 18L, 23L, 93L, 60L, 529L, 85L, 81L, 55L, 31L, 50L, 135L, 83L, 47L, 21L, 317L, 285L, 381L, 397L, 331L, 66L, 40L, 95L, 85L, 18L, 32L, 27L, 18L, 6L, 39L, 12L, 11L, 46L, 43L, 41L, 53L, 34L, 38L, 27L, 24L, 36L, 85L, 1L, 9L, 35L, 3L, 11L, 45L, 81L, 69L, 22L, 55L, 111L, 151L, 79L, 28L, 1L, 109L, 246L, 74L, 34L, 83L, 16L, 136L, 66L, 38L, 85L, 131L, 126L, 44L, 66L, 48L, 37L, 44L, 25L, 46L, 5L, 83L, 13L, 47L, 306L, 51L, 49L, 47L, 32L, 46L, 45L, 16L, 63L, 82L, 9L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 56L, 45L, 92L, 60L, 32L, 21L, 17L, 36L, 28L, 14L, 21L, 31L, 123L, 26L, 66L, 22L, 5L, 79L, 18L, 20L, 29L, 38L, 26L, 33L, 13L, 17L, 6L, 14L, 69L, 34L, 7L, 3L, 3L, 1L, 4L, 20L, 39L, 30L, 114L, 38L, 32L, 87L, 141L, 335L, 114L, 158L, 112L, 98L, 328L, 144L, 253L, 193L, 228L, 202L, 100L, 212L, 247L, 50L, 99L, 77L, 48L, 99L, 70L, 60L, 173L, 17L, 67L, 2L, 23L, NA, 36L, NA, 27L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 34L, 16L, 12L, 15L, 22L, 31L, 11L, 18L, 22L, 10L, 18L, 30L, 41L, 19L, 11L, 13L, 20L, 14L, 24L, 14L, 27L, 14L, NA, 15L, 24L, NA, 22L, 12L, 44L, 30L, 289L, 623L, 97L, 144L, 333L, 234L, 26L, 208L, 220L, 69L, 43L, 15L, 20L, 28L, 5L, 2L, 4L, 22L, 32L, 19L, 28L, 17L, 5L, 291L, 55L, 46L, 7L, 16L, 9L, 22L, 27L), SepNov = c(38L, 49L, 12L, 21L, 7L, 7L, 18L, 11L, 16L, 18L, 21L, 26L, 27L, 20L, 3L, 26L, 13L, 23L, 140L, 9L, 16L, 24L, 4L, 53L, 34L, 29L, 18L, 36L, 1L, 109L, 14L, 53L, 28L, 34L, 15L, 18L, 3L, 90L, 8L, 5L, 5L, 19L, 1L, 5L, 0L, 23L, 27L, 0L, 4L, 26L, 113L, 123L, 226L, 50L, 21L, 47L, 105L, 98L, 195L, 31L, 120L, 40L, 105L, 29L, 36L, 17L, 58L, 35L, 20L, 72L, 39L, 10L, 10L, 29L, 1L, 36L, 37L, 15L, 17L, 18L, 13L, 34L, 121L, 107L, 21L, 37L, 66L, 58L, 0L, 3L, 0L, 3L, 4L, 26L, 9L, 41L, 3L, 6L, 67L, 26L, 8L, 56L, NA, NA, NA, 81L, 14L, 7L, 66L, 56L, 100L, 22L, 77L, 5L, 0L, 39L, 35L, 13L, NA, 0L, 35L, 40L, 111L, 74L, 4L, 8L, 21L, 0L, 88L, 35L, 30L, 3L, 119L, 62L, 15L, 11L, 20L, 70L, 32L, 27L, 3L, 14L, 8L, 5L, 6L, 19L, 24L, 2L, 7L, 20L, 28L, 29L, 10L, 15L, 7L, 53L, 2L, 18L, 11L, 5L, 20L, 28L, 46L, 37L, 25L, 27L, 15L, 10L, 22L, 27L, 1L, 0L, 7L, 6L, 6L, 0L, 3L, 1L, 2L, 12L, 34L, 184L, 2L, 126L, 49L, 6L, 31L, 30L, 33L, 127L, 51L, 46L, 58L, 13L, 6L, 20L, 16L, 43L, 2L, 32L, 56L, 33L, 5L, 11L, 7L, 9L, 13L, 4L, 0L, 317L, 112L, 56L, 46L, 77L, 206L, 94L, 114L, 184L, 44L, 94L, 36L, 5L, 5L, 9L, 44L, 40L, 338L, 54L, 46L, 31L, 12L, 8L, 110L, 32L, 20L, 12L, 114L, 102L, 102L, 166L, 121L, 30L, 31L, 32L, 43L, 8L, 9L, 13L, 13L, 7L, 26L, 9L, 4L, 2L, 19L, 17L, 28L, 9L, 11L, 8L, 8L, 27L, 35L, 2L, 12L, 24L, 2L, 7L, 21L, 46L, 30L, 10L, 34L, 32L, 88L, 55L, 12L, 1L, 69L, 184L, 36L, 34L, 58L, 24L, 53L, 47L, 9L, 27L, 69L, 64L, 18L, 28L, 11L, 28L, 18L, 16L, 18L, 3L, 61L, 3L, 22L, 102L, 3L, 29L, 28L, 12L, 32L, 19L, 2L, 33L, 34L, 7L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 25L, 31L, 18L, 14L, 11L, 9L, 20L, 13L, 12L, 10L, 8L, 10L, 52L, 10L, 56L, 8L, 2L, 30L, 4L, 11L, 13L, 17L, 14L, 8L, 5L, 7L, 5L, 7L, 28L, 9L, 4L, 1L, 2L, 2L, 4L, 12L, 21L, 23L, 36L, 13L, 16L, 26L, 120L, 231L, 94L, 95L, 94L, 67L, 250L, 104L, 138L, 141L, 188L, 139L, 71L, 185L, 152L, 30L, 48L, 49L, 29L, 72L, 43L, 29L, 114L, 13L, 33L, 1L, 9L, NA, 12L, NA, 20L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 8L, 15L, 6L, 14L, 11L, 9L, 12L, 6L, 3L, 8L, 11L, 16L, 5L, 8L, 7L, 7L, 8L, 7L, 15L, 13L, 11L, 13L, NA, 4L, 10L, NA, 13L, 10L, 25L, 13L, 81L, 257L, 79L, 46L, 131L, 87L, 21L, 56L, 90L, 30L, 26L, 4L, 6L, 21L, 1L, 6L, 2L, 11L, 18L, 13L, 21L, 4L, 6L, 69L, 24L, 15L, 3L, 2L, 5L, 6L, 10L ), DecFeb = c(3L, 2L, 0L, 1L, 1L, 1L, 2L, 2L, 4L, 2L, 2L, 7L, 16L, 2L, 1L, 9L, 2L, 5L, 11L, 7L, 4L, 4L, 2L, 7L, 49L, 28L, 8L, 3L, 3L, 81L, 5L, 31L, 8L, 1L, 3L, 0L, 0L, 13L, 1L, 3L, 0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L, 9L, 0L, 3L, 2L, 2L, 6L, 6L, 5L, 10L, 5L, 3L, 2L, 9L, 0L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 2L, 0L, 1L, 0L, 3L, 2L, 0L, 4L, 1L, 2L, 4L, 6L, 10L, 4L, 16L, 4L, 3L, 2L, 2L, 3L, 1L, 4L, 0L, 2L, 0L, 2L, 1L, 1L, 1L, 3L, 0L, 1L, 1L, 0L, 3L, 3L, 3L, 4L, 7L, 2L, 4L, 7L, 89L, 93L, 5L, 83L, 6L, 6L, 17L, 14L, 12L, 62L, 89L, 30L, 5L, 20L, 31L, 3L, 6L, 11L, 8L, 32L, 6L, 6L, 7L, 9L, 7L, 1L, 4L, NA, 6L, NA, 1L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 3L, 3L, 5L, 2L, 8L, 5L, 5L, 0L, 2L, 7L, 9L, 0L, 3L, 6L, 4L, 9L, 9L, 6L, 10L, 10L, 6L, 9L, NA, 6L, 2L, NA, 11L, 8L, 3L, 0L, 4L, 31L, 4L, 7L, 7L, 20L, 0L, 7L, 7L, 8L, 3L, 1L, 0L, 1L, 0L, 0L, 1L, 1L, 4L, 1L, 1L, 2L, 2L, 7L, 1L, 4L, 0L, 1L, 0L, 13L, 0L), location = c(5, 5, 4, 4, 5, 4, 4, 4, 4, 4, 4, 5, 3, 4, 4, 5, 5, 4, 4, 4, 4, 5, 5, 4, 5, 4, 4, 5, 5, 4, 4, 3, 5, 4, 5, 4, 4, 4, 4, 4, 3, 5, 5, 4, 4, 4, 4, 5, 5, 4.5, 4.5, 4.5, 4, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5,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4L, 4L, 3L, 4L, 4L, 4L, 4L, 9L, 10L, 4L, 9L, 4L, 2L, 3L, 5L, 9L, 3L, 4L, 10L, 4L, 4L, 8L, 9L, 9L, 4L, 4L, 4L, 4L, 4L, 4L, 3L, 1L, 4L, 7L, 7L, 5L, 8L, 8L, 6L, 10L, 8L, 2L, 7L, 7L, 3L, NA, NA, NA, NA, 3L, 1L, 9L, 9L, 7L, 7L, NA, 7L, 3L, 10L, 3L, 8L, 9L, 9L, 3L, 4L, 7L, 9L, 2L, 10L, 3L, 4L, 4L, 10L, 1L, 6L, 6L, 1L, 1L, 3L, 3L, 9L, 1L, 9L, 3L, 9L, 3L, 3L, 9L, 3L, 7L, 4L, 9L, 9L, 3L, 4L, 10L, 9L, 4L, 9L, 4L, 4L, 3L, 7L, 4L, 3L, 10L, NA, 3L, 10L, 2L, 4L, 6L, 9L, 9L, 9L, 3L, 3L, 6L, 8L, 10L, 9L, 6L, 10L, 9L, 3L, 9L, 6L, 4L, 10L, NA, 9L, 3L, 7L, 9L, 9L, 9L, 4L, 8L, 3L, 6L, 9L, 9L, 9L, 6L, 2L), .Label = c("breakfast", "cleaning", "location", "overall", "price", "restaurant", "room", "services", "staff", "structure", "WiFi"), class = "factor"), ratebt1 = c(-1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,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 9L, 4L, 10L, 3L, 1L, 1L, 4L, 4L, 4L, 4L, 4L, 4L, 9L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 9L, 6L, 4L, 4L, 10L, 4L, 4L, 4L, 4L, 6L, 2L, 10L, 1L, 3L, 3L, 3L, 5L, 1L, 4L, 4L, 2L, 4L, 4L, 4L, 4L, 4L, 10L, 10L, 6L, 4L, 4L, 4L, 6L, 3L, 2L, 9L, 9L, 9L, 3L, 4L, 9L, 9L, 4L, 9L, 2L, 9L, 7L, NA, NA, NA, NA, 10L, 7L, 7L, 7L, 3L, 2L, NA, 7L, 2L, 9L, 1L, 8L, 9L, 3L, 6L, 4L, 1L, 3L, 3L, 7L, 7L, 7L, 4L, 3L, 3L, 9L, 3L, 9L, 9L, 9L, 9L, 7L, 7L, 3L, 3L, 3L, 2L, 9L, 3L, 2L, 3L, 4L, 9L, 6L, 9L, 9L, 4L, 7L, 4L, 6L, 9L, 2L, 6L, 8L, 2L, 3L, 2L, NA, 9L, 6L, 8L, 3L, 9L, 3L, 6L, 8L, 8L, 3L, 9L, 9L, 9L, 10L, 3L, 6L, 6L, 6L, 3L, 9L, 9L, 9L, NA, 10L, 1L, 6L, 3L, 3L, 6L, 9L, 8L, 7L, 2L, 6L, 2L, 6L, 9L, 9L), .Label = c("breakfast", "cleaning", "location", "overall", "price", "restaurant", "room", "services", "staff", "structure", "Wi-Fi"), class = "factor"), ratebt2 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 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L, 9L, 9L, 9L, 3L, 4L, 9L, 10L, 3L, 1L, 3L, 8L, 9L, 2L, 1L, 4L, 4L, 9L, 4L, 4L, 7L, 8L, 7L, 6L, 9L, 9L, 3L, 9L, 9L, 8L, 2L, 2L, 8L, 8L, 1L, 10L, 9L, 3L, 4L, 4L, 8L, 4L, 4L, 4L, 4L, 9L, 10L, 4L, 4L, 9L, 4L, 4L, 4L, 9L, 4L, 9L, 9L, 4L, 4L, 4L, 9L, 4L, 4L, 4L, 9L, 9L, 3L, 4L, 4L, 4L, 4L, 2L, 4L, 4L, 4L, 9L, 4L, 6L, 4L, 4L, 4L, 9L, 7L, 3L, 2L, 9L, 9L, 4L, 3L, 8L, 9L, 10L, 1L, 3L, 6L, 3L, NA, NA, NA, NA, 4L, 9L, 2L, 6L, 3L, 1L, NA, 9L, 7L, 3L, 2L, 2L, 3L, 7L, 3L, 8L, 3L, 7L, 9L, 2L, 11L, 6L, 3L, 7L, 9L, 9L, 4L, 7L, 3L, 9L, 9L, 6L, 9L, 6L, 9L, 1L, 8L, 2L, 1L, 7L, 10L, 10L, 9L, 8L, 7L, 9L, 2L, 9L, 9L, 4L, 9L, 9L, 11L, 9L, 4L, 4L, 9L, NA, 6L, 8L, 9L, 8L, 6L, 10L, 2L, 8L, 6L, 4L, 3L, 6L, 2L, 9L, 9L, 8L, 4L, 3L, 3L, 8L, 3L, 3L, NA, 2L, 3L, 9L, 10L, 4L, 2L, 2L, 9L, 1L, 9L, 2L, 7L, 10L, 3L, 3L), .Label = c("breakfast", "cleaning", "location", "overall", "price", "restaurant", "room", "services", "staff", "structure", "Wi-Fi"), class = "factor"), ratebt3 = c(1L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, -1L, -1L, -1L, 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7L, 9L, 3L, 9L, 9L, 4L, 9L, 8L, 3L, 7L, 3L, 9L, 7L, 1L, 9L, 4L, 8L, 9L, 8L, 11L, 3L, 4L, 8L, 4L, 8L, 10L, 10L, 10L, 4L, 9L, 3L, 10L, 10L, 2L, 3L, 4L, 3L, 10L, 9L, 4L, 4L, 8L, 9L, 9L, 4L, 9L, 8L, 4L, 8L, 8L, 9L, 10L, 10L, 9L, 9L, 10L, 9L, 2L, 3L, 4L, 10L, 6L, 3L, 3L, 4L, 4L, 4L, 10L, 4L, 9L, 4L, 9L, 4L, 4L, 10L, 4L, 4L, 4L, 9L, 9L, 3L, 9L, 9L, 4L, 9L, 4L, 4L, 4L, 9L, 5L, 4L, 3L, 6L, 4L, 9L, 2L, 10L, 2L, 2L, 10L, 4L, 4L, 4L, 4L, 4L, 3L, 9L, 6L, 1L, 3L, 2L, 9L, 7L, 9L, 3L, 3L, 7L, 10L, 5L, 8L, 8L, NA, NA, NA, NA, 8L, 2L, 1L, 2L, 6L, 9L, NA, 1L, 8L, 4L, 9L, 2L, 7L, 3L, 4L, 4L, 11L, 8L, 6L, 9L, 2L, 9L, 6L, 10L, 7L, 4L, 4L, 4L, 2L, 1L, 1L, 6L, 9L, 9L, 9L, 7L, 7L, 1L, NA, 1L, 9L, 1L, 1L, 4L, 2L, 4L, 4L, 9L, 10L, 8L, 3L, 4L, 8L, 3L, 3L, 5L, 3L, NA, 8L, 2L, 3L, 9L, 4L, 6L, 4L, 8L, 10L, 4L, 4L, 3L, 6L, 4L, 8L, 3L, 4L, 2L, 3L, 9L, 3L, 2L, NA, 7L, 2L, 3L, 2L, 3L, 8L, 7L, 4L, 3L, 3L, 9L, 6L, 4L, 9L, 4L), .Label = c("breakfast", "cleaning", "location", "overall", "price", "restaurant", "room", "services", "staff", "structure", "Wi-Fi"), class = "factor"), ratebt4 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 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3L, 11L, 10L, 11L, 8L, 5L, 9L, 9L, 5L, 8L, 8L, 10L, 10L, 11L, 10L, 8L, 1L, 9L, 11L, 4L, 8L, 11L, 8L, 8L, 3L, 1L, 4L, 7L, 9L, 8L, 7L, 3L, 10L, 7L, 1L, 8L, 7L, 10L, 10L, 11L, 9L, 5L, 10L, 2L, 7L, 4L, 7L, 8L, 10L, 8L, 10L, 10L, 4L, 11L, 11L, 10L, 10L, 4L, 11L, 4L, 10L, 5L, 10L, 4L, 11L, 5L, 11L, 10L, 11L, 9L, 10L, 1L, 4L, 11L, 3L, 3L, 4L, 9L, 4L, 10L, 9L, 4L, 9L, 10L, 4L, 3L, 9L, 6L, 6L, 5L, 5L, 5L, 5L, 4L, 10L, 1L, 10L, 5L, 5L, 5L, 9L, 5L, 3L, 11L, 5L, 11L, 5L, 10L, 5L, 3L, 5L, 5L, 5L, 5L, 3L, 10L, 3L, 10L, 7L, 10L, 5L, 5L, 9L, 5L, 11L, 5L, 5L, 5L, 10L, 5L, 9L, 10L, 1L, 1L, 3L, 4L, 11L, 5L, 5L, 10L, 10L, 4L, 7L, 10L, NA, NA, NA, NA, 5L, 4L, 4L, 9L, 3L, 4L, NA, 7L, 9L, 3L, 10L, 4L, 3L, 11L, 7L, 1L, 10L, 1L, 10L, 9L, 9L, 10L, 10L, 10L, 5L, 5L, 10L, 10L, 5L, 7L, 10L, 4L, 10L, 11L, 5L, 10L, 4L, 4L, NA, 10L, 6L, 4L, 10L, 11L, 6L, 8L, 8L, 5L, 7L, 1L, 8L, 6L, 3L, 8L, 10L, 10L, 4L, NA, 11L, 1L, NA, 11L, 5L, 8L, 4L, 3L, 8L, 3L, 5L, 5L, 4L, 9L, 4L, 10L, 4L, 8L, 5L, 8L, 7L, 12L, NA, 10L, 10L, 3L, 8L, 1L, 4L, 10L, 7L, 7L, 10L, 5L, 5L, 8L, 11L, 9L), .Label = c("breakfast", "camere", "cleaning", "location", "overall", "price", "restaurant", "room", "services", "staff", "structure", "Wi-F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L, 5L, 4L, 4L, 8L, 5L, 7L, 7L), .Label = c("breakfast", "cleaning", "location", "overall", "price", "restaurant", "room", "services", "staff", "structure", "Wi-Fi"), class = "factor"), ratebt6 = c(1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, NA, 1L, -1L, 1L, -1L, -1L, 1L, -1L, 1L, -1L, 1L, 1L, -1L, 1L, -1L, 1L, 1L, -1L, -1L, -1L, 1L, 1L, 1L, 1L, -1L, 1L, -1L, 1L, 1L, 1L, -1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, 1L, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, 1L, NA, NA, NA, 1L, 1L, -1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, -1L, -1L, 1L, 1L, NA, NA, -1L, 1L, 1L, NA, -1L, 1L, -1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, -1L, 1L, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L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, 3L, 8L, 1L, 6L, 7L, 9L, 5L, 6L, 3L, 7L, 6L, 2L, 9L, 8L), .Label = c("breakfast", "cleaning", "location", "overall", "price", "restaurant", "room", "services", "staff", "structure", "Wi-Fi"), class = "factor"), ratebt7 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, -1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, NA, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, -1L, 1L, 1L, 1L, -1L, 1L, -1L, 1L, -1L, -1L, 1L, -1L, 1L, 1L, NA, 1L, NA, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, 1L, NA, NA, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, NA, 1L, NA, 1L, NA, -1L, 1L, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, NA, NA, NA, 1L, 1L, NA, -1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 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, 3L, 5L, 9L, 3L, 10L), .Label = c("breakfast", "cleaning", "location", "overall", "price", "restaurant", "room", "services", "staff", "structure", "Wi-FI"), class = "factor"), ratebt8 = c(-1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, -1L, 1L, -1L, 1L, 1L, -1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, NA, 1L, 1L, 1L, -1L, -1L, 1L, 1L, -1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, NA, -1L, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, 1L, NA, NA, NA, 1L, 1L, -1L, 1L, -1L, 1L, 1L, -1L, 1L, NA, 1L, 1L, 1L, 1L, 1L, NA, NA, 1L, 1L, NA, 1L, NA, 1L, NA, -1L, NA, NA, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, -1L, 1L, 1L, -1L, -1L, 1L, 1L, NA, NA, NA, 1L, 1L, NA, -1L, NA, NA, 1L, 1L, 1L, -1L, 1L, 1L, -1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L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2L, 4L, 4L, 5L, 8L, 4L, 3L, 4L, NA, 2L, 9L, 6L, 4L, 10L, 4L, 7L, 8L, 3L, 6L, 1L, 4L, 9L, 3L, 3L, 8L, 9L, 11L, 6L, 7L, 7L, 3L, 10L, 6L, 8L, 9L, 9L, 10L, 3L, 10L, 1L, 7L, 5L, 10L, 1L, 4L, 7L, 6L, 4L, 7L, 11L, 9L, 8L, 9L, 3L, 1L, 9L, 4L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 9L, 3L, 5L, 6L, 4L, 6L, 3L, 8L, 9L, 2L, 10L, 9L, 4L, 4L, 4L, 3L, 4L, 4L, 4L, 4L, 9L, 2L, 4L, 4L, NA, NA, NA, 9L, 9L, 5L, 4L, NA, NA, 7L, NA, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 8L, 2L, 6L, 11L, 8L, 6L, 3L, 4L, 8L, 7L, 3L, 3L, 1L, 10L, 6L, NA, NA, NA, NA, 7L, 3L, 6L, 8L, 7L, 8L, NA, 4L, 8L, 8L, 3L, 9L, 10L, 6L, 9L, 3L, 9L, 11L, 7L, 6L, 10L, 3L, 4L, 1L, 3L, 10L, 9L, 3L, 9L, 9L, 10L, 9L, 4L, 4L, 9L, 9L, 6L, 9L, NA, 7L, 7L, 9L, 9L, 3L, 9L, 4L, 3L, 4L, 10L, 2L, 7L, 8L, 7L, 7L, 8L, 9L, 10L, NA, 2L, 9L, NA, 8L, 11L, 3L, 8L, 8L, 5L, 10L, 3L, 10L, 8L, 2L, 2L, 4L, 8L, 5L, 2L, 3L, 2L, 9L, NA, 10L, 6L, 5L, 4L, 3L, 9L, 6L, 5L, 9L, 10L, 9L, NA, 9L, 9L, 8L), .Label = c("breakfast", "cleaning", "location", "overall", "price", "restaurant", "room", "services", "staff", "structure", "Wi-Fi"), class = "factor"), ratebt9 = c(1, 1, 1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, NA, NA, -1, 1, -1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, -1, 1, 1, 1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, NA, 1, NA, -1, 1, 1, 1, 1, 1, 1, 1, 1, NA, 1, NA, NA, NA, 1, -1, -1, 1, -1, 1, 1, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, 1, 1, 1, 1, 1, 1, 1, -1, NA, 1, 1, 1, 1, 1, NA, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, 1, NA, NA, NA, 1, -1, NA, 1, NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, 1, -1, -1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, NA, NA, NA, 1, 1, 1, 1, NA, NA, 1, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA, NA, 1, 1, 1, 1, 1, 1, NA, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, 1, 1, 1, 1, NA, 1, 1, NA, 1, -1, 1, 1, 1, -1, 1, 1, 1, 1, -1, 0.1, 1, 1, 1, 1, 1, 1, 1, NA, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, 1, NA, 1, 1, -1), bt10 = structure(c(11L, 8L, 8L, 9L, 6L, 4L, 4L, 9L, 7L, 7L, 4L, 3L, 7L, 9L, 8L, 8L, 8L, 10L, 3L, 8L, 8L, 3L, 10L, 8L, 5L, 9L, 11L, 10L, 4L, 2L, 7L, 4L, 10L, 8L, 10L, 4L, 9L, 8L, 6L, 8L, 10L, 7L, 6L, 8L, 5L, 3L, 11L, NA, NA, 7L, 11L, 8L, 3L, 10L, 8L, 8L, 9L, 4L, 7L, 7L, 2L, 4L, 3L, 5L, 5L, 4L, 10L, 4L, 9L, 11L, 4L, 6L, 4L, 10L, NA, 4L, 4L, 5L, 5L, 9L, 9L, 10L, 9L, 10L, 4L, 10L, 9L, 5L, NA, 9L, NA, 4L, 5L, 9L, 9L, 4L, 7L, 3L, 4L, 9L, NA, 8L, NA, NA, NA, 8L, 11L, 4L, 4L, 6L, 8L, 8L, NA, NA, NA, NA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, NA, NA, NA, NA, 4L, 9L, 10L, 4L, 3L, 3L, 4L, 9L, 7L, 6L, 5L, 3L, 10L, 3L, 4L, 2L, 6L, 3L, 3L, 7L, 1L, 6L, NA, NA, NA, NA, 8L, 8L, 3L, 3L, 5L, 8L, NA, 4L, 7L, 9L, 7L, 7L, 4L, 10L, NA, 10L, 4L, 7L, 7L, 3L, 4L, 8L, 8L, 10L, 4L, 6L, 4L, 8L, 7L, 8L, 9L, 4L, 4L, 4L, 9L, 8L, 8L, 11L, NA, 6L, 7L, 9L, 9L, 6L, 8L, 10L, 4L, 7L, 2L, 4L, 8L, 3L, 6L, 7L, 5L, 3L, 4L, NA, 8L, 11L, NA, 11L, 3L, 4L, 8L, 4L, 2L, 8L, 6L, 8L, 8L, 7L, 9L, 4L, 8L, 7L, 5L, 11L, 3L, 1L, NA, 3L, 5L, 6L, 3L, 2L, 3L, 5L, 3L, 4L, 3L, 9L, 3L, 4L, 5L, 5L), .Label = c("breakfast", "cleaning", "location", "overall", "price", "restaurant", "room", "services", "staff", "structure", "Wi-Fi"), class = "factor"), ratebt10 = c(1L, -1L, -1L, 1L, -1L, 1L, 1L, -1L, -1L, -1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, -1L, 1L, -1L, 1L, 1L, -1L, 1L, 1L, -1L, -1L, -1L, 1L, 1L, -1L, 1L, 1L, -1L, NA, NA, -1L, -1L, 1L, 1L, -1L, 1L, 1L, -1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, -1L, 1L, 1L, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, 1L, NA, 1L, 1L, 1L, 1L, 1L, -1L, 1L, -1L, 1L, NA, -1L, NA, NA, NA, 1L, -1L, -1L, 1L, 1L, 1L, -1L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1L, NA, NA, NA, NA, NA, 1L, 1L, 1L, -1L, 1L, 1L, -1L, -1L, NA, -1L, -1L, -1L, 1L, 1L, NA, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, -1L, -1L, -1L, -1L, -1L, NA, 1L, 1L, NA, NA, NA, 1L, 1L, NA, 1L, NA, NA, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, -1L, -1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, NA, NA, NA, 1L, 1L, NA, 1L, NA, NA, NA, NA, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, NA, NA, NA, 1L, 1L, 1L, 1L, 1L, 1L, NA, -1L, 1L, 1L, 1L, 1L, 1L, -1L, NA, 1L, 1L, 1L, -1L, 1L, 1L, 1L, -1L, -1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, NA, 1L, -1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, NA, 1L, -1L, NA, 1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, -1L, 1L, -1L, 1L, 1L, NA, 1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), .Names = c("municipality", "stars", "area", "seaLocation", "excellent", "good", "average", "bad", "poor", "family", "couple", "single", "business", "MarMay", "JunAug", "SepNov", "DecFeb", "location", "sleepQuality", "room", "services", "priceQualityRate", "cleaning", "bt1", "ratebt1", "bt2", "ratebt2", "bt3", "ratebt3", "bt4", "ratebt4", "bt5", "ratebt5", "bt6", "ratebt6", "bt7", "ratebt7", "bt8", "ratebt8", "bt9", "ratebt9", "bt10", "ratebt10"), row.names = c(NA, -518L ), class = "data.frame")
ordranks <- function(dat.frame, paired = TRUE) { cols <- ncol(dat.frame) half <- cols/2 dat.orig <- as.matrix(dat.frame) j=0; ranks=0; DLmax=0; data.1 <- dat.orig; data.0 <- dat.orig if (paired) { for (i in seq(1, to=(cols-1), by=2)) {j = j+1 data.0[,j] <- dat.orig[,i] data.0[,j+half] <- dat.orig[,i+1] nvec <- colnames(data.0) nvec <- nvec[seq(1, (cols-1), 2)] nvec <- paste("rnk.", nvec, sep="") } } else {data.0 <- dat.orig nvec <- colnames(data.0) nvec <- nvec[1:half] nvec <- paste("rnk.", nvec, sep="") } for (i in 1:half) {DLmax <- max(data.0[,i]*data.0[,i+half]) data.1[,i] <- data.0[,i]*(1-data.0[,i+half]) data.1[,i][data.1[,i] < DLmax] = 0 } data.2 <- data.1[,1:half] r.out <- data.2 for (i in 1:half) {ranks <- rank(data.2[,i]) if (i==1) {r.out <- ranks} else {r.out <- cbind(r.out, ranks)} } colnames(r.out) <- nvec return(r.out) }
library(brokenstick) context("predict.brokenstick()") obj <- fit_200 dat <- smocc_200 n <- nrow(dat) m <- length(unique(dat$id)) k <- length(get_knots(obj)) test_that("returns proper number of rows", { expect_equal(nrow(predict(obj, dat)), n) expect_equal(nrow(predict(obj, dat, x = NA)), m) expect_equal(nrow(predict(obj, x = NA, y = 10)), 1L) expect_equal(nrow(predict(obj, x = c(NA, NA), y = c(-1, 10))), 2L) }) test_that("returns proper number of rows with at = 'knots'", { expect_equal(nrow(predict(obj, dat, x = "knots")), m * k) expect_equal(nrow(predict(obj, dat, x = NA)), m) expect_equal(nrow(predict(obj, x = NA, y = 10)), 1L) }) test_that("returns proper number of rows with both data & knots", { expect_equal(nrow(predict(obj, dat, x = "knots", strip_data = FALSE)), n + k * m) expect_equal(nrow(predict(obj, dat, x = NA, y = 10, group = 10001, strip_data = FALSE)), 11) expect_equal(nrow(predict(obj, dat, x = c(NA, NA), y = c(-1, 10), group = rep(10001, 2), strip_data = FALSE)), 12) }) test_that("output = 'vector' and output = 'long' are consistent", { expect_equivalent( predict(obj, dat)[[".pred"]], predict(obj, dat, shape = "vector") ) expect_equal( predict(obj, dat, x = 1)[[".pred"]], predict(obj, dat, x = 1, shape = "vector") ) expect_equal( predict(obj, x = c(NA, 1), y = c(1, NA))[[".pred"]], predict(obj, x = c(NA, 1), y = c(1, NA), 10, shape = "vector") ) expect_equal( predict(obj, dat, x = "knots")[[".pred"]], predict(obj, dat, x = "knots", shape = "vector") ) expect_equal( predict(obj, dat, strip_data = FALSE)[[".pred"]], predict(obj, dat, strip_data = FALSE, shape = "vector") ) expect_equal( predict(obj, x = NA, y = 10, strip_data = FALSE)[[".pred"]], predict(obj, x = NA, y = 10, strip_data = FALSE, shape = "vector") ) }) exp <- fit_200 dat <- smocc_200 test_that("returns proper number of rows", { expect_equal(nrow(predict(exp, dat, x = NA)), 200L) expect_equal(nrow(predict(exp, dat, x = c(NA, NA))), 400L) expect_equal(nrow(predict(exp, dat, x = NA, y = 1)), 1L) expect_equal(nrow(predict(exp, dat, x = c(NA, NA), y = c(-1, 10))), 2L) expect_equal(nrow(predict(exp, dat, x = "knots")), 2200L) expect_equal(nrow(predict(exp, dat, x = "knots", y = rep(1, 11))), 11L) }) test_that("accepts intermediate NA in x", { expect_equal( unlist(predict(exp, x = 1, y = -1)[1, ]), unlist(predict(exp, x = c(NA, 1), y = c(1, -1))[2, ]) ) expect_equal( unlist(predict(exp, x = c(1, NA), y = c(-1, 1))[1, ]), unlist(predict(exp, x = c(NA, 1), y = c(1, -1))[2, ]) ) expect_equal( unlist(predict(exp, x = c(1, 2, NA), y = c(NA, -1, 1))[2, ]), unlist(predict(exp, x = c(1, NA, 2), y = c(NA, 1, -1))[3, ]) ) }) test_that("accepts unordered x", { expect_equal( round(predict(exp, x = c(1, 2, 3), y = c(-1, 1, 0))[1, 5], 5), round(predict(exp, x = c(2, 3, 1), y = c(1, 0, -1))[3, 5], 5) ) }) xz <- data.frame( id = c(NA_real_, NA_real_), age = c(NA_real_, NA_real_), hgt_z = c(NA_real_, NA_real_) ) test_that("accepts all NA's in newdata", { expect_silent(predict(exp, newdata = xz, x = "knots")) }) context("predict_brokenstick factor") fit <- fit_200 dat <- smocc_200 dat$id <- factor(dat$id) test_that("works if id in newdata is a factor", { expect_silent(predict(obj, newdata = dat)) })
ivif <- function(lmobj) { vif <- diag(vcov(lmobj))*diag(solve(vcov(lmobj))) return(vif) }
betaExpert <- function(best, lower, upper, p = 0.95, method = "mode"){ if (missing(best)) stop("'best' is missing") if (missing(lower) & missing(upper)) stop("at least 'lower' or 'upper' must be specified") checkInput(best, "best", range = c(0, 1)) checkInput(p, "p", range = c(0, 1)) if (!missing(lower)) checkInput(lower, "lower", range = c(0, 1), minEq = 0) if (!missing(upper)) checkInput(upper, "upper", range = c(0, 1), maxEq = 1) if (!missing(lower)) if (lower > best) stop("'lower' cannot be greater than 'best'") if (!missing(upper)) if (upper < best) stop("'upper' cannot be smaller than 'best'") if (!missing(lower) & !missing(upper)) if (lower > upper) stop("'lower' cannot be greater than 'upper'") f_mode <- function(x, mode, p, target){ return( sum( (qbeta(p = p, shape1 = x, shape2 = (x * (1 - mode) + 2 * mode - 1) / mode) - target) ^ 2 )) } f_mode_zero <- function(x, p, target){ return((qbeta(p = p, shape1 = 1, shape2 = x) - target) ^ 2) } f_mode_one <- function(x, p, target){ return((qbeta(p = p, shape1 = x, shape2 = 1) - target) ^ 2) } f_mean <- function(x, mean, p, target){ return( sum( (qbeta(p = p, shape1 = x, shape2 = (x * (1 - mean)) / mean) - target) ^ 2 )) } if (!missing(lower) & missing(upper)){ target <- lower p <- 1 - p } else if (!missing(upper) & missing(lower)){ target <- upper } else if (!missing(upper) & !missing(lower)){ target <- c(lower, upper) p <- c(0, p) + (1 - p) / 2 } if (method == "mode"){ if (best == 0){ a <- 1 b <- optimize(f_mode_zero, c(0, 1000), p = p, target = target)$minimum } else if (best == 1) { a <- optimize(f_mode_one, c(0, 1000), p = p, target = target)$minimum b <- 1 } else { a <- optimize(f_mode, c(0, 1000), mode = best, p = p, target = target)$minimum b <- (a * (1 - best) + 2 * best - 1) / best } } else if (method == "mean"){ a <- optimize(f_mean, c(0, 1000), mean = best, p = p, target = target)$minimum b <- (a * (1 - best)) / best } out <- list(alpha = a, beta = b) class(out) <- "betaExpert" return(out) }
air_dens_cf <- function(T.actual, P.actual, T.ref = 20, P.ref = 760) { T.ref.K <- 273.15 + T.ref T.actual.K <- 273.15 + T.actual T.actual.K / T.ref.K * 760 / P.actual }
context("is.significant") test_that("test significance at 0.05", { expect_equal( is_significant(c(.9, .8, .65, .33, .10, .06, .051, .05, .049, .001), .05), c(rep(FALSE, 7), rep(TRUE, 3))) }) test_that("test significance at 0.05", { expect_equal( is_significant(c(.9, .8, .65, .33, .10, .06, .051, .05, .049, .001), .10), c(rep(FALSE, 4), rep(TRUE, 6))) })
"csiro_cobalt_marine"
context("documentation") test_that("can_read_pkg_description, data_version", { file <- system.file("extdata", "tests", "subsetCars.Rmd", package = "DataPackageR" ) file2 <- system.file("extdata", "tests", "extra.rmd", package = "DataPackageR" ) datapackage_skeleton( name = "subsetCars", path = tempdir(), code_files = c(file, file2), force = TRUE, r_object_names = c("cars_over_20", "pressure") ) DataPackageR:::read_pkg_description(file.path(tempdir(), "subsetCars")) devtools::load_all(file.path(tempdir(), "subsetCars")) expected_version <- structure(list(c(0L, 1L, 0L)), class = c("package_version", "numeric_version") ) expect_equal(data_version("subsetCars"), expected_version) unlink(file.path(tempdir(), "subsetCars"), recursive = TRUE, force = TRUE ) })
knitr::opts_chunk$set( collapse = TRUE, comment = " message = FALSE, warning = FALSE, fig.height = 7, fig.width = 7, dpi = 75 ) check_namespaces <- function(pkgs){ return(all(unlist(sapply(pkgs, requireNamespace,quietly = TRUE)))) } library(geofi) library(dplyr) d <- data(package = "geofi") as_tibble(d$results) %>% select(Item,Title) %>% filter(grepl("municipality_key", Item)) names(geofi::municipality_key_2020) geofi::municipality_key_2021 %>% count(maakunta_code,maakunta_name_fi,maakunta_name_sv,maakunta_name_en) municipalities <- get_municipalities(year = 2020, scale = 4500) plot(municipalities["municipality_name_fi"], border = NA) get_municipality_pop(year = 2020) %>% subset(select = miehet_p) %>% plot() get_municipality_pop(year = 2020) %>% group_by(hyvinvointialue_name_fi) %>% summarise(vaesto = sum(vaesto)) %>% subset(select = vaesto) %>% plot() get_municipality_pop(year = 2020) %>% dplyr::group_by(hyvinvointialue_name_fi) %>% summarise(vaesto = sum(vaesto), miehet = sum(miehet)) %>% mutate(share = miehet/vaesto*100) %>% subset(select = share) %>% plot() zipcodes <- get_zipcodes(year = 2015) plot(zipcodes["nimi"], border = NA) stat_grid <- get_statistical_grid(resolution = 5, auxiliary_data = TRUE) plot(stat_grid["euref_x"], border = NA) pop_grid <- get_population_grid(year = 2018, resolution = 5) plot(pop_grid["kunta"], border = NA) plot(municipality_central_localities["teksti"]) d <- data(package = "geofi") as_tibble(d$results) %>% select(Item,Title) %>% filter(grepl("grid", Item)) %>% print(n = 100) libs <- c("pxweb","geofacet","ggplot2") if (check_namespaces(pkgs = libs)) { library(pxweb) pxweb_query_list <- list("Alue 2019"=c("*"), "Tiedot"=c("M411"), "Vuosi"=c("*")) px_data <- pxweb_get(url = "https://pxnet2.stat.fi/PXWeb/api/v1/fi/Kuntien_avainluvut/2019/kuntien_avainluvut_2019_aikasarja.px", query = pxweb_query_list) px_data <- as.data.frame(px_data, column.name.type = "text", variable.value.type = "text") names(px_data) <- c("kunta_name","year","value") dat <- left_join(geofi::municipality_key_2021 %>% select(-year), px_data) %>% group_by(maakunta_code, maakunta_name_fi,year) %>% summarise(population = sum(value, na.rm = TRUE)) %>% na.omit() %>% ungroup() %>% rename(code = maakunta_code, name = maakunta_name_fi) library(geofacet) library(ggplot2) ggplot(dat, aes(x = year, y = population/1000, group = name)) + geom_line() + facet_geo(facets = ~name, grid = grid_maakunta, scales = "free_y") + theme(axis.text.x = element_text(size = 6)) + scale_x_discrete(breaks = seq.int(from = 1987, to = 2018, by = 5)) + labs(title = "Population 1987-2018", y = "population (1000)") } else { message("'pxweb' not available") }
ReadJAFROCOldFormat <- function(fileName, renumber) { UNINITIALIZED <- RJafrocEnv$UNINITIALIZED wb <- excel_sheets(fileName) sheetNames <- toupper(wb) truthFileIndex <- which(!is.na(match(sheetNames, "TRUTH"))) if (truthFileIndex == 0) stop("TRUTH table cannot be found in the dataset.") truthTable <- data.frame( read_xlsx(fileName, truthFileIndex, range = cell_cols(1:3) ) ) for (i in 1:3){ truthTable[grep("^\\s*$", truthTable[ , i]), i] <- NA } naRows <- colSums(is.na(truthTable)) if (max(naRows) > 0) { if (max(naRows) == min(naRows)) { truthTable <- truthTable[1:(nrow(truthTable) - max(naRows)), ] } } for (i in 1:2) { if (any((as.numeric(as.character(truthTable[, i]))) %% 1 != 0 )) { naLines <- which(!is.integer(as.numeric(as.character(truthTable[, i])))) + 1 errorMsg <- paste0("There are non-integer values(s) for CaseID or LesionID at the line(s) ", paste(naLines, collapse = ", "), " in the TRUTH table.") stop(errorMsg) } } if (any(is.na(as.numeric(as.character(truthTable[, 3]))))) { naLines <- which(is.na(as.numeric(as.character(truthTable[, 3])))) + 1 errorMsg <- paste0("There are non-numeric values(s) for weights at the line(s) ", paste(naLines, collapse = ", "), " in the TRUTH table.") stop(errorMsg) } caseIDColumn <- as.integer(truthTable[[1]]) lesionIDColumn <- as.integer(truthTable[[2]]) weightsColumn <- truthTable[[3]] normalCases <- sort(unique(caseIDColumn[lesionIDColumn == 0])) abnormalCases <- sort(unique(caseIDColumn[lesionIDColumn > 0])) allCases <- c(normalCases, abnormalCases) K1 <- length(normalCases) K2 <- length(abnormalCases) K <- (K1 + K2) if (anyDuplicated(cbind(caseIDColumn, lesionIDColumn))) { naLines <- which(duplicated(cbind(caseIDColumn, lesionIDColumn))) + 1 errorMsg <- paste0("Line(s) ", paste(naLines, collapse = ", "), " in the TRUTH table are duplicated with previous line(s) .") stop(errorMsg) } nlFileIndex <- which(!is.na(match(sheetNames, c("FP", "NL")))) if (nlFileIndex == 0) stop("FP table cannot be found in the dataset.") NLTable <- data.frame( read_xlsx(fileName, nlFileIndex, range = cell_cols(1:4) ) ) for (i in 1:4){ NLTable[grep("^\\s*$", NLTable[ , i]), i] <- NA } naRows <- colSums(is.na(NLTable)) if (max(naRows) > 0) { if (max(naRows) == min(naRows)) { NLTable <- NLTable[1:(nrow(NLTable) - max(naRows)), ] } } for (i in 3:4) { if (any(is.na(as.numeric(as.character(NLTable[, i]))))) { naLines <- which(is.na(as.numeric(as.character(NLTable[, i])))) + 1 errorMsg <- paste0("There are unavailable cell(s) at the line(s) ", paste(naLines, collapse = ", "), " in the FP table.") stop(errorMsg) } } NLReaderID <- as.character(NLTable[[1]]) NLModalityID <- as.character(NLTable[[2]]) NLCaseID <- NLTable[[3]] if (any(!(NLCaseID %in% caseIDColumn))) { naCases <- NLCaseID[which(!(NLCaseID %in% caseIDColumn))] errorMsg <- paste0("Case(s) ", paste(unique(naCases), collapse = ", "), " in the FP table cannot be found in TRUTH table.") stop(errorMsg) } NLRating <- as.numeric(NLTable[[4]]) llFileIndex <- which(!is.na(match(sheetNames, c("TP", "LL")))) if (llFileIndex == 0) stop("TP table cannot be found in the dataset.") LLTable <- data.frame( read_xlsx(fileName, llFileIndex, range = cell_cols(1:5) ) ) for (i in 1:5){ LLTable[grep("^\\s*$", LLTable[ , i]), i] <- NA } naRows <- colSums(is.na(LLTable)) if (max(naRows) > 0) { if (max(naRows) == min(naRows)) { LLTable <- LLTable[1:(nrow(LLTable) - max(naRows)), ] } } for (i in 3:5) { if (any(is.na(as.numeric(as.character(LLTable[, i]))))) { naLines <- which(is.na(as.numeric(as.character(LLTable[, i])))) + 1 errorMsg <- paste0("There are unavailable cell(s) at the line(s) ", paste(naLines, collapse = ", "), " in the TP table.") stop(errorMsg) } } LLReaderID <- as.character(LLTable[[1]]) LLModalityID <- as.character(LLTable[[2]]) LLCaseID <- LLTable[[3]] LLLesionID <- LLTable[[4]] for (i in 1:nrow(LLTable)) { lineNum <- which((caseIDColumn == LLCaseID[i]) & (lesionIDColumn == LLLesionID[i])) if (!length(lineNum)) { errorMsg <- paste0("Modality ", LLTable[i, 2], " Reader(s) ", LLTable[i, 1], " Case(s) ", LLTable[i, 3], " Lesion(s) ", LLTable[i, 4], " cannot be found in TRUTH table .") stop(errorMsg) } } LLRating <- as.numeric(LLTable[[5]]) if (anyDuplicated(LLTable[, 1:4])) { naLines <- which(duplicated(LLTable[, 1:4])) errorMsg <- paste0("Modality ", paste(LLTable[naLines, 2], collapse = ", "), " Reader(s) ", paste(LLTable[naLines, 1], collapse = ", "), " Case(s) ", paste(LLTable[naLines, 3], collapse = ", "), " Lesion(s) ", paste(LLTable[naLines, 4], collapse = ", "), " have multiple ratings in TP table .") stop(errorMsg) } perCase <- as.vector(table(caseIDColumn[caseIDColumn %in% abnormalCases])) weights <- array(dim = c(length(abnormalCases), max(perCase ))) IDs <- array(dim = c(length(abnormalCases), max(perCase ))) for (k2 in 1:length(abnormalCases)) { k <- which(caseIDColumn == abnormalCases[k2]) IDs[k2, ] <- c(sort(lesionIDColumn[k]), rep(UNINITIALIZED, max(perCase ) - length(k))) if (all(weightsColumn[k] == 0)) { weights[k2, 1:length(k)] <- 1/perCase [k2] } else { weights[k2, ] <- c(weightsColumn[k][order(lesionIDColumn[k])], rep(UNINITIALIZED, max(perCase ) - length(k))) sumWeight <- sum(weights[k2, weights[k2, ] != UNINITIALIZED]) if (sumWeight != 1){ if (sumWeight <= 1.01 && sumWeight >= 0.99){ weights[k2, ] <- weights[k2, ] / sumWeight }else{ errorMsg <- paste0("The sum of the weights for Case ", k2, " is not 1.") stop(errorMsg) } } } } modalityID <- as.character(sort(unique(c(NLModalityID, LLModalityID)))) I <- length(modalityID) readerID <- as.character(sort(unique(c(NLReaderID, LLReaderID)))) J <- length(readerID) maxNL <- 0 for (i in modalityID) { for (j in readerID) { k <- (NLModalityID == i) & (NLReaderID == j) if ((sum(k) == 0)) next maxNL <- max(maxNL, max(table(NLCaseID[k]))) } } NL <- array(dim = c(I, J, K, maxNL)) for (i in 1:I) { for (j in 1:J) { k <- (NLModalityID == modalityID[i]) & (NLReaderID == readerID[j]) if ((sum(k) == 0)) next caseNLTable <- table(NLCaseID[k]) temp <- as.numeric(unlist(attr(caseNLTable, "dimnames"))) for (k1 in 1:length(temp)) { for (el in 1:caseNLTable[k1]) { NL[i, j, which(temp[k1] == allCases), el] <- NLRating[k][which(NLCaseID[k] == temp[k1])][el] } } } } LL <- array(dim = c(I, J, K2, max(perCase ))) for (i in 1:I) { for (j in 1:J) { k <- (LLModalityID == modalityID[i]) & (LLReaderID == readerID[j]) if ((sum(k) == 0)) next caseLLTable <- table(LLCaseID[k]) temp <- as.numeric(unlist(attr(caseLLTable, "dimnames"))) for (k1 in 1:length(temp)) { temp1 <- which(temp[k1] == abnormalCases) for (el in 1:caseLLTable[k1]) { temp2 <- which(LLLesionID[k][which(LLCaseID[k] == temp[k1])][el] == IDs[which(temp[k1] == abnormalCases), ]) LL[i, j, temp1, temp2] <- LLRating[k][which(LLCaseID[k] == temp[k1])][el] } } } } weights[is.na(weights)] <- UNINITIALIZED IDs[is.na(IDs)] <- UNINITIALIZED NL[is.na(NL)] <- UNINITIALIZED LL[is.na(LL)] <- UNINITIALIZED isROI <- TRUE for (i in 1:I) { for (j in 1:J) { if (any(NL[i, j, 1:K1, ] == UNINITIALIZED)) { isROI <- FALSE break } temp <- LL[i, j, , ] != UNINITIALIZED dim(temp) <- c(K2, max(perCase )) if (!all(perCase == rowSums(temp))) { isROI <- FALSE break } temp <- NL[i, j, (K1 + 1):K, ] == UNINITIALIZED dim(temp) <- c(K2, maxNL) if (!all(perCase == rowSums(temp))) { isROI <- FALSE break } } } if ((max(table(caseIDColumn)) == 1) && (maxNL == 1) && (all((NL[, , (K1 + 1):K, ] == UNINITIALIZED))) && (all((NL[, , 1:K1, ] != UNINITIALIZED)))) { type <- "ROC" } else { if (isROI) { type <- "ROI" } else { type <- "FROC" } } modalityNames <- modalityID readerNames <- readerID if (renumber){ modalityID <- 1:I readerID <- 1:J } names(modalityID) <- modalityNames names(readerID) <- readerNames truthTableStr <- array(dim = c(I, J, K, (max(lesionIDColumn)+1))) truthTableStr[,,1:K1,1] <- 1 for (k2 in 1:K2) { truthTableStr[,,k2+K1,(1:perCase[k2])+1] <- 1 } name <- NA design <- "FCTRL" return(convert2dataset(NL, LL, LL_IL = NA, perCase, IDs, weights, fileName, type, name, truthTableStr, design, modalityID, readerID)) }
[ { "title": "Data Science Competitions 101: Anatomy and Approach", "href": "https://techandmortals.wordpress.com/2016/07/27/data-science-competitions-101-anatomy-and-approach/" }, { "title": "Getting knitr to work with StatET", "href": "https://danganothererror.wordpress.com/2012/04/13/getting-knitr-to-work-with-statet/" }, { "title": "Maps with R (II)", "href": "https://procomun.wordpress.com/2012/02/20/maps_with_r_2/" }, { "title": "Agent-based modeling in R – habitat diversity and species richness", "href": "https://web.archive.org/web/http://mbjoseph.github.io/blog/2013/04/20/allouche/" }, { "title": "Asher’s enigma", "href": "https://xianblog.wordpress.com/2010/07/26/asher%E2%80%99s%C2%A0enigma/" }, { "title": "RcppArmadillo 0.2.34", "href": "http://dirk.eddelbuettel.com/blog/2011/12/13/" }, { "title": "Why R for Mass Spectrometrist and Computational Proteomics", "href": "http://computationalproteomic.blogspot.com/2012/08/why-r-for-mass-spectrometrist-and.html" }, { "title": "The Mechanics of Data Visualization", "href": "https://trinkerrstuff.wordpress.com/2013/07/02/the-mechanics-of-data-visualization/" }, { "title": "A Visualization of World Cuisines", "href": "https://designdatadecisions.wordpress.com/2015/12/28/a-visualization-of-world-cuisines/" }, { "title": "What’s new in Revolution R Enterprise 6.1", "href": "http://blog.revolutionanalytics.com/2012/11/whats-new-in-revolution-r-enterprise-61.html" }, { "title": "Aggregation with dplyr: summarise and summarise_each", "href": "http://www.milanor.net/blog/aggregation-dplyr-summarise-summarise_each/" }, { "title": "Hierarchical Linear Model", "href": "http://www.r-tutor.com/gpu-computing/rbayes/rhierlmc" }, { "title": "Reminder: Abstract submission for the 2014 ‘R in Insurance’ conference will close this Friday", "href": "http://www.magesblog.com/2014/03/reminder-abstract-submission-for-2014-r.html" }, { "title": "Notice that even though output is in a log scale, output is…", "href": "https://web.archive.org/web/http://isomorphism.es//post/615285554" }, { "title": "Predictive Analytics with R, PMML, ADAPA, and Excel", "href": "http://www.predictive-analytics.info/2011/01/predictive-analytics-with-r-pmml-adapa.html" }, { "title": "Ganglia welcomes Google Summer of Code students for 2014", "href": "https://danielpocock.com/ganglia-welcomes-gsoc-2014-students" }, { "title": "Sharing my work for “Advanced Methods III”", "href": "https://feedproxy.google.com/~r/FellgernonBit-rstats/~3/8Q1ju_r44EE/sharing-my-work-for-advanced-methods-iii" }, { "title": "Exploring the Market with Hurst", "href": "http://timelyportfolio.blogspot.com/2011/06/exploring-market-with-hurst.html" }, { "title": "Introductions to R and predictive analytics", "href": "http://blog.revolutionanalytics.com/2016/03/introductions-to-r-and-predictive-analytics.html" }, { "title": "R Day at Strata NYC", "href": "https://blog.rstudio.org/2014/07/08/r-day-at-strata-nyc/" }, { "title": "Quantitative Candlestick Pattern Recognition (Part 2 — What’s this Natural Language Processing stuff?)", "href": "http://intelligenttradingtech.blogspot.com/2010/08/quantitative-candlestick-pattern.html" }, { "title": "Simple user interface in R to get login details", "href": "http://www.magesblog.com/2014/07/simple-user-interface-in-r-to-get-login.html" }, { "title": "More Command-Line Text Munging Utilities", "href": "http://www.gettinggeneticsdone.com/2011/05/more-command-line-text-munging.html" }, { "title": "Restaurant Inspection Results", "href": "https://statofmind.wordpress.com/2014/02/04/restaurant-inspection-results/" }, { "title": "EARL2016, London – Deadline for Abstracts – 29th April", "href": "http://www.mango-solutions.com/wp/2016/04/earl2016-london-deadline-for-abstracts-29th-april/" }, { "title": "More Haskell: a bootstrap", "href": "https://martinsbioblogg.wordpress.com/2013/02/16/more-haskell-a-bootstrap/" }, { "title": "New Zealand school performance: beyond the headlines", "href": "http://www.quantumforest.com/2012/09/new-zealand-school-performance-beyond-the-headlines/" }, { "title": "What is your favorite R feature?", "href": "https://web.archive.org/web/http://cloudnumbers.com/what-is-your-favorite-r-feature" }, { "title": "Install and load missing specified/needed packages on the fly", "href": "http://rscriptsandtips.blogspot.com/2014/02/install-and-load-missing.html" }, { "title": "Assessing Model Fit Through Simulation", "href": "https://web.archive.org/web/http://polstat.org/blog/2011/12/assessing-model-fit-through-simulation" }, { "title": "rOpenSci awarded $300k from the Sloan Foundation", "href": "http://ropensci.org/blog/2014/06/10/new-sloan-award/" }, { "title": "Installing StatET", "href": "https://web.archive.org/web/http://flyordie.sin.khk.be/2011/03/16/installing-statet/" }, { "title": "R: microbenchmark, reshaping big data features", "href": "http://hack-r.com/r-microbenchmark-reshaping-big-data-features/" }, { "title": "An Introduction to Collaborative Filtering", "href": "http://www.tatvic.com/blog/an-introduction-to-collaborative-filtering/" }, { "title": "A Checkpoint Of Spanish Football League", "href": "https://aschinchon.wordpress.com/2016/01/20/a-checkpoint-of-spanish-football-league/" }, { "title": "Learn to Manage Data at useR! 2014 or Online April 25", "href": "http://r4stats.com/2014/03/18/learn-to-manage-data-at-user-2014-or-online-april-25/" }, { "title": "An xpd-tion into R plot margins", "href": "https://feedproxy.google.com/~r/FellgernonBit-rstats/~3/fH97-LBa7Mw/add-logo-in-R" }, { "title": "R-based data maps in PowerBI", "href": "http://blog.revolutionanalytics.com/2016/02/r-maps-in-powerbi.html" }, { "title": "Multiple cores in R, revisited", "href": "http://zvfak.blogspot.com/2011/08/multiple-cores-in-r-revisited.html" }, { "title": "4 Tips to Learn More About ACS Data", "href": "http://www.arilamstein.com/blog/2015/11/14/4-tips-learn-acs-data/" }, { "title": "A dirty hack for importing packages that use Depends", "href": "http://r2d2.quartzbio.com/posts/package-depends-dirty-hack-solution.html" }, { "title": "The winds of Winter [Bayesian prediction]", "href": "https://xianblog.wordpress.com/2014/10/07/the-winds-of-winter-bayesian-prediction/" }, { "title": "Making Static/Interactive Voronoi Map Layers In ggplot/leaflet", "href": "http://rud.is/b/2015/07/26/making-staticinteractive-voronoi-map-layers-in-ggplotleaflet/" }, { "title": "Beautiful table-outputs: Summarizing mixed effects models "href": "https://strengejacke.wordpress.com/2015/06/05/beautiful-table-outputs-summarizing-mixed-effects-models-rstats/" }, { "title": "The Rebirth", "href": "http://dancingeconomist.blogspot.com/2011/07/rebirth.html" }, { "title": "Using R in Excel", "href": "http://www.mathfinance.cn/using-R-in-excel/" }, { "title": "Easier Database Querying with R", "href": "https://anrprogrammer.wordpress.com/2013/07/27/easier-database-querying-with-r/" }, { "title": "End User Computing and why R can help meeting Solvency II", "href": "http://www.magesblog.com/2012/05/end-user-computing-and-why-r-can-help.html" }, { "title": "Big Data Bytes: How Open Source is Changing Business", "href": "http://blog.revolutionanalytics.com/2013/09/big-data-bytes-replay.html" }, { "title": "Interactive Heatmaps (and Dendrograms) – A Shiny App", "href": "https://imdevsoftware.wordpress.com/2013/07/07/interactive-heatmaps-and-dendrograms-a-shiny-app/" } ]
"are.pargev.valid" <- function(para,nowarn=FALSE) { if(! is.gev(para)) return(FALSE) if(any(is.na(para$para))) return(FALSE) A <- para$para[2] G <- para$para[3] op <- options() GO <- TRUE if(nowarn == TRUE) options(warn=-1) if(A <= 0) { warning("Parameter A is not > 0, invalid") GO <- FALSE } if(G <= -1) { warning("Parameter G is not > -1, invalid") GO <- FALSE } options(op) if(GO) return(TRUE) return(FALSE) }
context("as_package") test_that("it throws error if no package", { expect_error(as_package("arst11234"), "`path` is invalid:.*arst11234") }) test_that("it returns the package if given the root or child directory", { expect_equal(as_package("TestS4")$package, "TestS4") expect_equal(as_package("TestS4/")$package, "TestS4") expect_equal(as_package("TestS4/R")$package, "TestS4") expect_equal(as_package("TestS4/tests")$package, "TestS4") expect_equal(as_package("TestS4/tests/testthat")$package, "TestS4") }) context("local_branch") test_that("it works as expected", { with_mock(`covr:::system_output` = function(...) { "test_branch " }, { expect_equal(local_branch("TestSummary"), "test_branch") }) }) context("current_commit") test_that("it works as expected", { with_mock(`covr:::system_output` = function(...) { " test_hash" }, { expect_equal(current_commit("TestSummary"), "test_hash") }) }) context("get_source_filename") test_that("it works", { skip_if(getRversion() >= "4.0.0") x <- eval(bquote(function() 1)) expect_identical(getSrcFilename(x), character()) expect_identical(get_source_filename(x), "") }) test_that("per_line removes blank lines and lines with only punctuation ( skip_on_cran() cov <- package_coverage(test_path("testFunctional")) line_cov <- per_line(cov) expect_equal(line_cov[[1]]$coverage, c(NA, 0, 0, 2, NA, 1, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA)) })
expected <- eval(parse(text="0L")); test(id=0, code={ argv <- eval(parse(text="list(integer(0), 1L)")); .Internal(`tabulate`(argv[[1]], argv[[2]])); }, o=expected);
llsearch.QQ.D <- function(x, y, n, jlo, jhi) { fj <- matrix(0, n) fxy <- matrix(0, jhi - jlo + 1) jgrid <- expand.grid(jlo:jhi) k.ll <- apply(jgrid, 1, p.estFUN.QQ.D, x = x, y = y, n = n) fxy <- matrix(k.ll, nrow = jhi-jlo+1) rownames(fxy) <- jlo:jhi z <- findmax(fxy) jcrit <- z$imax + jlo - 1 list(jhat = jcrit, value = max(fxy)) } p.estFUN.QQ.D <- function(j, x, y, n){ a <- p.est.QQ.D(x,y,n,j) s2 <- a$sigma2 t2<- a$tau2 return(p.ll.D(n, j, s2,t2)) } p.est.QQ.D <- function(x,y,n,j){ xa <- x[1:j] ya <- y[1:j] jp1 <- j+1 xb <- x[jp1:n] yb <- y[jp1:n] g1 <- lm(ya ~ xa + I(xa^2)) g2 <- lm(yb ~ xb + I(xb^2)) beta <-c(g1$coef[1],g1$coef[2],g1$coef[3],g2$coef[1],g2$coef[2],g2$coef[3]) s2 <- sum((ya-g1$fit)^2)/j t2 <- sum((yb-g2$fit)^2)/(n-j) list(a0=beta[1],a1=beta[2],a2=beta[3],b0=beta[4],b1=beta[5],b2=beta[6],sigma2=s2,tau2=t2,xj=x[j]) } p.ll.D <- function(n, j, s2, t2){ q1 <- n * log(sqrt(2 * pi)) q2 <- 0.5 * j * (1 + log(s2)) q3 <- 0.5 * (n - j) * (1 + log(t2)) - (q1 + q2+ q3) } findmax <-function(a) { maxa<-max(a) imax<- which(a==max(a),arr.ind=TRUE)[1] jmax<-which(a==max(a),arr.ind=TRUE)[2] list(imax = imax, jmax = jmax, value = maxa) }
handle_noise <- function(global_membership, timeID, minPts, minTime) { cli::cli_div(theme = list(span.vrb = list(color = "yellow", `font-weight` = "bold"), span.unit = list(color = "magenta"), .val = list(digits = 3), span.side = list(color = "grey"))) cli::cli_h3("{.field minPts} = {.val {minPts}} {.unit hot spot{?s}} | {.field minTime} = {.val {minTime}} {.unit time index{?es}}") n <- timelen <- NULL `%>%` <- dplyr::`%>%` membership_count <- data.frame(id = 1:length(global_membership), timeID, global_membership) %>% dplyr::group_by(global_membership) %>% dplyr::summarise(n = dplyr::n(), timelen = max(timeID) - min(timeID)) noise_clusters <- dplyr::filter(membership_count, n < minPts | timelen < minTime) noise_clusters <- noise_clusters[['global_membership']] indexes <- global_membership %in% noise_clusters global_membership[indexes] <- -1 if (all_noise_bool(global_membership)) { cli::cli_alert_warning("All observations are noise!!!") } else { global_membership[!indexes] <- adjust_membership(global_membership[!indexes], 0) } cli::cli_alert_success("{.vrb Handle} {.field noise}") cli::cli_alert_info("{.val {max(c(global_membership, 0))}} cluster{?s} {.side left}") cli::cli_alert_info("noise {.side proportion} : {.val {mean(global_membership == -1)*100} %} ") cli::cli_end() return(global_membership) }
setGeneric("distsumlp", function(o, x=0, y=0, p=2) standardGeneric("distsumlp")) setMethod("distsumlp", "loca.p", function(o, x=0, y=0, p=2) { if (p>=1) return(sum(o@w*(abs(o@x-x)^p+abs(o@y-y)^p)^(1/p))) else stop(paste(p, gettext("is not a valid value for p, use 1 <= p", domain = "R-orloca"))) } ) setGeneric("distsumlpgra", function(o, x=0, y=0, p=2, partial=F) standardGeneric("distsumlpgra")) setMethod("distsumlpgra", "loca.p", function(o, x=0, y=0, p=2, partial=F) { if (p>=1) { n<- o@w*(abs(x-o@x)^p+abs(y-o@y)^p)^(1/p-1) c(sum(sign(x-o@x)*abs(x-o@x)^(p-1)*n, na.rm=partial), sum(sign(y-o@y)*abs(y-o@y)^(p-1)*n, na.rm=partial)) } else stop(paste(p, gettext("is not a valid value for p, use 1 <= p", domain = "R-orloca"))) } )
REB3m2<-function(andar,m2and,cbaixo,cand,nand,m2apt,nm21=0,nm22=0,nm23=0,nm24=0,nm25=0,nm26=0,nm27=0,nm28=0,nm29=0){ if(andar<=nand) if(nand<9){ custo = cbaixo+cand*nand custop = cbaixo+cand*andar nm2 = nm21+nm22+nm23+nm24+nm25+nm26+nm27+nm28+nm29 sumci = ((cbaixo+cand)*nm21)+((cbaixo+2*cand)*nm22)+((cbaixo+3*cand)*nm23)+((cbaixo+4*cand)*nm24)+((cbaixo+5*cand)*nm25)+((cbaixo+6*cand)*nm26)+((cbaixo+7*cand)*nm27)+((cbaixo+8*cand)*nm28)+((cbaixo+9*cand)*nm29) resultado=m2apt*(custop+((custo-sumci)/(m2and*nand))) return(resultado) } else{ print("nand non debe superar 9") } else{ print("O nivel do andar non pode ser maior que nand") } }
compileCode <- TRUE library(rstan) ; library(HRW) nWarm <- 10000 nKept <- 10000 nThin <- 10 fTrue <- function(x) return(3*exp(-78*(x-0.38)^2)+exp(-200*(x-0.75)^2) - x) muXTrue <- 0.5 ; sigmaXTrue <- 1/6 sigmaEpsTrue <- 0.7 phiTrue <- c(3,-3) set.seed(2) n <- 1000 x <- rnorm(n,muXTrue,sigmaXTrue) y <- fTrue(x) + sigmaEpsTrue*rnorm(n) probxObs <- 1/(1+exp(-(phiTrue[1]+phiTrue[2]*y))) indicxObsTmp <- rbinom(n,1,probxObs) xObs <- x[indicxObsTmp == 1] nObs <- length(xObs) yxObs <- fTrue(xObs) + sigmaEpsTrue*rnorm(nObs) indicxObs <- rep(1,nObs) xUnobsTrue <- x[indicxObsTmp == 0] nUnobs <- length(xUnobsTrue) yxUnobs <- fTrue(xUnobsTrue) + sigmaEpsTrue*rnorm(nUnobs) indicxUnobs <- rep(0,nUnobs) r <- c(indicxObs,indicxUnobs) ncZ <- 30 knots <- seq(min(xObs),max(xObs),length=(ncZ+2))[-c(1,ncZ+2)] ZxObs <- outer(xObs,knots,"-") ZxObs <- ZxObs*(ZxObs>0) npRegMARModel <- 'data { int<lower=1> nObs; int<lower=1> nUnobs; int<lower=1> n; int<lower=1> ncZ; vector[nObs] yxObs; vector[nUnobs] yxUnobs; vector[nObs] xObs; vector[ncZ] knots; matrix[nObs,ncZ] ZxObs; int<lower=0,upper=1> r[n]; real<lower=0> sigmaBeta; real<lower=0> sigmaMu; real<lower=0> sigmaPhi; real<lower=0> Ax; real<lower=0> Aeps; real<lower=0> Au; } transformed data { vector[n] y; matrix[n,2] Y; for (i in 1:nObs) { y[i] = yxObs[i]; Y[i,1] = 1 ; Y[i,2] = yxObs[i]; } for (i in 1:nUnobs) { y[i+nObs] = yxUnobs[i]; Y[i+nObs,1] = 1 ; Y[i+nObs,2] = yxObs[i]; } } parameters { vector[2] beta; vector[ncZ] u; vector[2] phi; real muX; real<lower=0> sigmaX; real<lower=0> sigmaEps; real<lower=0> sigmaU; real xUnobs[nUnobs]; } transformed parameters { matrix[n,2] X; matrix[n,ncZ] Z; for (i in 1:nObs) { X[i,1] = 1 ; X[i,2] = xObs[i] ; Z[i] = ZxObs[i]; } for (i in 1:nUnobs) { X[i+nObs,1] = 1 ; X[i+nObs,2] = xUnobs[i]; for (k in 1:ncZ) Z[i+nObs,k] = (xUnobs[i]-knots[k])*step(xUnobs[i]-knots[k]); } } model { y ~ normal(X*beta+Z*u,sigmaEps); r ~ bernoulli_logit(Y*phi); col(X,2) ~ normal(muX,sigmaX); u ~ normal(0,sigmaU) ; beta ~ normal(0,sigmaBeta); muX ~ normal(0,sigmaMu); phi ~ normal(0,sigmaPhi); sigmaX ~ cauchy(0,Ax); sigmaEps ~ cauchy(0,Aeps); sigmaU ~ cauchy(0,Au); }' allData <- list(nObs = nObs,nUnobs = nUnobs,n = (nObs+nUnobs), ncZ = ncZ,xObs = xObs,yxObs = yxObs,yxUnobs = yxUnobs,knots = knots, ZxObs = ZxObs,r = r,sigmaMu = 1e5,sigmaBeta = 1e5,sigmaPhi = 1e5, sigmaEps = 1e5,sigmaX = 1e5,Ax = 1e5,Aeps = 1e5,Au = 1e5) if (compileCode) stanCompilObj <- stan(model_code = npRegMARModel,data = allData, iter = 1,chains = 1) stanObj <- stan(model_code = npRegMARModel,data = allData,warmup = nWarm, iter = (nWarm + nKept),chains = 1,thin = nThin,refresh = 10, fit = stanCompilObj) betaMCMC <- NULL for (j in 1:2) { charVar <- paste("beta[",as.character(j),"]",sep = "") betaMCMC <- rbind(betaMCMC,extract(stanObj,charVar,permuted = FALSE)) } uMCMC <- NULL for (k in 1:ncZ) { charVar <- paste("u[",as.character(k),"]",sep = "") uMCMC <- rbind(uMCMC,extract(stanObj,charVar,permuted = FALSE)) } muXMCMC <- as.vector(extract(stanObj,"muX",permuted = FALSE)) sigmaXMCMC <- as.vector(extract(stanObj,"sigmaX",permuted = FALSE)) sigmaEpsMCMC <- as.vector(extract(stanObj,"sigmaEps",permuted = FALSE)) sigmaUMCMC <- as.vector(extract(stanObj,"sigmaU",permuted = FALSE)) phiMCMC <- NULL for (j in 1:2) { charVar <- paste("phi[",as.character(j),"]",sep="") phiMCMC <- rbind(phiMCMC,extract(stanObj,charVar,permuted = FALSE)) } xUnobsMCMC <- NULL for (i in 1:nUnobs) { charVar <- paste("xUnobs[",as.character(i),"]",sep = "") xUnobsMCMC <- rbind(xUnobsMCMC,extract(stanObj,charVar,permuted = FALSE)) } cexVal <- 0.3 obsCol <- "darkblue" ; misCol <- "lightskyblue" estFunCol <- "darkgreen"; trueFunCol <- "indianred3" varBandCol <- "palegreen" ng <- 101 xg <- seq(min(x),max(x),length = ng) Xg <- cbind(rep(1,ng),xg) Zg <- outer(xg,knots,"-") Zg <- Zg*(Zg>0) fMCMC <- Xg%*%betaMCMC + Zg%*%uMCMC credLower <- apply(fMCMC,1,quantile,0.025) credUpper <- apply(fMCMC,1,quantile,0.975) fg <- apply(fMCMC,1,mean) par(mfrow = c(1,1),mai = c(1.02,0.82,0.82,0.42)) plot(xg,fg,type = "n",bty = "l",xlab = "x",ylab = "y",xlim = range(c(xObs,xUnobsTrue)), ylim = range(c(yxObs,yxUnobs))) polygon(c(xg,rev(xg)),c(credLower,rev(credUpper)),col = varBandCol,border = FALSE) lines(xg,fg,lwd = 2,col = estFunCol) lines(xg,fTrue(xg),lwd = 2,col = trueFunCol) points(xObs,yxObs,col = obsCol,cex = cexVal) points(xUnobsTrue,yxUnobs,col = misCol,cex = cexVal) legend(0.75,1.5,c("fully observed","x value unobserved"),col = c(obsCol,misCol), pch = rep(1,2),pt.lwd = rep(2,2)) legend(0.467,-1.2,c("true f","estimated f"),col = c(trueFunCol,estFunCol), lwd = rep(2,2)) indQ1 <- length(xg[xg <= quantile(xObs,0.25)]) fQ1MCMC <- fMCMC[indQ1,] indQ2 <- length(xg[xg <= quantile(xObs,0.50)]) fQ2MCMC <- fMCMC[indQ2,] indQ3 <- length(xg[xg <= quantile(xObs,0.75)]) fQ3MCMC <- fMCMC[indQ3,] parms <- list(cbind(muXMCMC,sigmaXMCMC,sigmaEpsMCMC,phiMCMC[1,],phiMCMC[2,], fQ1MCMC,fQ2MCMC,fQ3MCMC)) parNamesVal <- list(c(expression(mu[x])),c(expression(sigma[x])), c(expression(sigma[epsilon])), c(expression(phi[0])),c(expression(phi[1])), c("first quartile","of x"), c("second quart.","of x"), c("third quartile","of x")) summMCMC(parms,parNames = parNamesVal,numerSummCex = 1, KDEvertLine = FALSE,addTruthToKDE = c(muXTrue,sigmaXTrue,sigmaEpsTrue, phiTrue[1],phiTrue[2],fTrue(xg[indQ1]), fTrue(xg[indQ2]),fTrue(xg[indQ3]))) parms <- list(t(xUnobsMCMC[1:5,])) parNamesVal <- list(c(expression(x[1]^{"unobs"})), c(expression(x[2]^{"unobs"})), c(expression(x[3]^{"unobs"})), c(expression(x[4]^{"unobs"})), c(expression(x[5]^{"unobs"}))) summMCMC(parms,parNames = parNamesVal,KDEvertLine = FALSE,addTruthToKDE = xUnobsTrue[1:5])
"plot.potd" <- function(x, ...) { rawdata <- x$data n <- length(as.numeric(rawdata)) times <- attributes(rawdata)$times if(is.character(times) || inherits(times, "POSIXt") || inherits(x, "date") || inherits(x, "dates")) { times <- as.POSIXlt(times) gaps <- as.numeric(difftime(times[2:n], times[1:(n-1)], units = "days")) * x$intensity } else gaps <- as.numeric(diff(times)) * x$intensity data <- as.numeric(rawdata) threshold <- x$threshold par.ests <- x$par.ests xi <- par.ests[1] beta <- par.ests[4] residuals <- logb(1 + (xi * (data - threshold))/beta)/xi choices <- c("Point Process of Exceedances", "Scatterplot of Gaps", "Qplot of Gaps", "ACF of Gaps", "Scatterplot of Residuals", "Qplot of Residuals", "ACF of Residuals", "Go to GPD Plots") tmenu <- paste("plot:", choices) pick <- 1 lastcurve <- NULL while(pick > 0) { pick <- menu(tmenu, title = "\nMake a plot selection (or 0 to exit):") if(pick %in% 1:7) lastcurve <- NULL switch(pick, { plot(times, rawdata, type = "h", sub = paste("Point process of", length(as.numeric(rawdata)), "exceedances of threshold", format(signif(threshold, 3))), ...) }, { plot(gaps, ylab = "Gaps", xlab = "Ordering", ...) lines(lowess(1:length(gaps), gaps)) }, qplot(gaps, ...), acf(gaps, lag.max = 20, ...), { plot(residuals, ylab = "Residuals", xlab = "Ordering", ...) lines(lowess(1:length(residuals), residuals)) }, qplot(residuals, ...), acf(residuals, lag.max = 20, ...), lastcurve <- plot.gpd(x, ...)) } invisible(lastcurve) } "pot" <- function(data, threshold = NA, nextremes = NA, run = NA, picture = TRUE, ...) { n <- length(as.numeric(data)) times <- attributes(data)$times if(is.null(times)) { times <- 1:n attributes(data)$times <- times start <- 1 end <- n span <- end - start } else { start <- times[1] end <- times[n] span <- as.numeric(difftime(as.POSIXlt(times)[n], as.POSIXlt(times)[1], units = "days")) } if(is.na(nextremes) && is.na(threshold)) stop("Enter either a threshold or the number of upper extremes") if(!is.na(nextremes) && !is.na(threshold)) stop("Enter EITHER a threshold or the number of upper extremes") if(!is.na(nextremes)) threshold <- findthresh(as.numeric(data), nextremes) if(threshold > 10) { factor <- 10^(floor(log10(threshold))) cat(paste("If singularity problems occur divide data", "by a factor, perhaps", factor, "\n")) } exceedances.its <- structure(data[data > threshold], times = times[data > threshold]) n.exceed <- length(as.numeric(exceedances.its)) p.less.thresh <- 1 - n.exceed/n if(!is.na(run)) { exceedances.its <- decluster(exceedances.its, run, picture) n.exceed <- length(exceedances.its) } intensity <- n.exceed/span exceedances <- as.numeric(exceedances.its) xbar <- mean(exceedances) - threshold s2 <- var(exceedances) shape0 <- -0.5 * (((xbar * xbar)/s2) - 1) extra <- ((length(exceedances)/span)^( - shape0) - 1)/shape0 betahat <- 0.5 * xbar * (((xbar * xbar)/s2) + 1) scale0 <- betahat/(1 + shape0 * extra) loc0 <- 0 theta <- c(shape0, scale0, loc0) negloglik <- function(theta, exceedances, threshold, span) { if((theta[2] <= 0) || (min(1 + (theta[1] * (exceedances - theta[3])) / theta[2]) <= 0)) f <- 1e+06 else { y <- logb(1 + (theta[1] * (exceedances - theta[3])) / theta[2]) term3 <- (1/theta[1] + 1) * sum(y) term1 <- span * (1 + (theta[1] * (threshold - theta[3])) / theta[2])^(-1/theta[1]) term2 <- length(y) * logb(theta[2]) f <- term1 + term2 + term3 } f } fit <- optim(theta, negloglik, hessian = TRUE, ..., exceedances = exceedances, threshold = threshold, span = span) if(fit$convergence) warning("optimization may not have succeeded") par.ests <- fit$par varcov <- solve(fit$hessian) par.ses <- sqrt(diag(varcov)) beta <- par.ests[2] + par.ests[1] * (threshold - par.ests[3]) par.ests <- c(par.ests, beta) out <- list(n = length(data), period = c(start, end), data = exceedances.its, span = span, threshold = threshold, p.less.thresh = p.less.thresh, n.exceed = n.exceed, run = run, par.ests = par.ests, par.ses = par.ses, varcov = varcov, intensity = intensity, nllh.final = fit$value, converged = fit$convergence) names(out$par.ests) <- c("xi", "sigma", "mu", "beta") names(out$par.ses) <- c("xi", "sigma", "mu") class(out) <- "potd" out }
check_tabulated_yield <- function(x, exclusive = TRUE, order = TRUE, x_name = substitute(x)) { x_name <- deparse(x_name) chk::check_data( x, values = list( Type = c("actual", "actual", "optimal"), pi = c(0, 1), u = c(0, 1), Yield = c(0, .Machine$double.xmax), Age = c(0, 100), Length = c(0, .Machine$double.xmax), Weight = c(0, .Machine$double.xmax), Effort = c(0, .Machine$double.xmax) ), nrow = TRUE, exclusive = exclusive, order = order, x_name = x_name ) x } test_that("ypr_tabulate_yield", { yield <- ypr_tabulate_yield(ypr_population()) expect_identical(check_tabulated_yield(yield), yield) expect_identical(yield$Type, c("actual", "optimal")) yield <- ypr_tabulate_yield(ypr_population(), all = TRUE) expect_identical(check_tabulated_yield(yield, exclusive = FALSE), yield) expect_identical(ncol(yield), 38L) expect_identical(yield$Linf, c(100, 100)) yield <- ypr_tabulate_yield(ypr_populations(Rk = c(3, 5))) expect_identical(check_tabulated_yield(yield, exclusive = FALSE), yield) expect_identical(colnames(yield), c("Type", "pi", "u", "Yield", "Age", "Length", "Weight", "Effort", "Rk")) expect_identical(nrow(yield), 4L) yield <- ypr_tabulate_yield(ypr_populations(Rk = c(3, 5)), all = TRUE) expect_identical(check_tabulated_yield(yield, exclusive = FALSE), yield) expect_identical(ncol(yield), 38L) expect_identical(nrow(yield), 4L) yields <- ypr_tabulate_yields(ypr_population(n = ypr:::inst2inter(0.2)), pi = seq(0, 1, length.out = 10)) expect_identical(colnames(yields), c("pi", "u", "Yield", "Age", "Length", "Weight", "Effort")) expect_identical(nrow(yields), 10L) expect_error(chk::check_data( yields, values = list( pi = c(0, 1), u = c(0, 1), Yield = c(0, .Machine$double.xmax), Age = c(0, 100, NA), Length = c(0, .Machine$double.xmax, NA), Weight = c(0, .Machine$double.xmax, NA), Effort = c(0, Inf) ), nrow = TRUE, exclusive = TRUE, order = TRUE ), NA) expect_identical(yields$pi[1:2], c(0, 1 / 9)) expect_equal(yields$Effort[1:2], c(0, 1.117905), tolerance = 1e-07) expect_equal(yields$Yield[1:2], c(0, 0.0738), tolerance = 1e-04) expect_equal(yields$Weight[1:2], c(NA, 3057.662), tolerance = 1e-07) yields <- ypr_tabulate_yields(ypr_populations(Rk = c(3, 5)), pi = seq(0, 1, length.out = 2)) expect_identical(ncol(yields), 8L) expect_identical(nrow(yields), 4L) yields <- ypr_tabulate_yields(ypr_populations(Rk = c(3, 5)), pi = seq(0, 1, length.out = 2), all = TRUE ) expect_identical(ncol(yields), 37L) expect_identical(nrow(yields), 4L) sr <- ypr_tabulate_sr(ypr_population()) expect_error(chk::check_data( sr, values = list( Type = c("unfished", "actual", "optimal"), pi = c(0, 1), u = c(0, 1), Eggs = c(0, .Machine$double.xmax), Recruits = c(0, .Machine$double.xmax), Spawners = c(0, .Machine$double.xmax), Fecundity = c(0, .Machine$double.xmax) ), nrow = TRUE, exclusive = TRUE, order = TRUE ), NA) expect_identical(sr$Type, c("unfished", "actual", "optimal")) fish <- ypr_tabulate_fish(ypr_population(n = ypr:::inst2inter(0.2))) expect_identical(colnames(fish), c( "Age", "Survivors", "Spawners", "Caught", "Harvested", "Released", "HandlingMortalities" )) expect_identical(fish[[1]], as.double(1:20)) expect_equal(fish$Survivors[1:2], c(0.134, 0.110), tolerance = 0.001) fish <- ypr_tabulate_fish(ypr_population(), x = "Length") expect_identical(colnames(fish), c( "Length", "Survivors", "Spawners", "Caught", "Harvested", "Released", "HandlingMortalities" )) expect_identical(fish$Length[1:2], c(14, 26)) sr <- ypr_tabulate_sr(ypr_populations(Rk = c(3, 5))) expect_error(chk::check_data( sr, values = list( Type = c("unfished", "actual", "optimal"), pi = c(0, 1), u = c(0, 1), Eggs = c(0, .Machine$double.xmax), Recruits = c(0, .Machine$double.xmax), Spawners = c(0, .Machine$double.xmax), Fecundity = c(0, .Machine$double.xmax), Rk = c(3, 3, 5) ), nrow = TRUE, exclusive = TRUE, order = TRUE ), NA) expect_identical(colnames(sr), c( "Type", "pi", "u", "Eggs", "Recruits", "Spawners", "Fecundity", "Rk" )) expect_identical(sr$Rk, c(3, 3, 3, 5, 5, 5)) skip_if(length(tools::Rd_db("ypr")) == 0) parameters <- ypr_tabulate_parameters(ypr_population()) expect_identical(parameters$Description[1], "The maximum age (yr).") expect_error(chk::check_data( parameters, values = list( Parameter = ypr:::.parameters$Parameter, Value = c(min(ypr:::.parameters$Lower), max(ypr:::.parameters$Upper)), Description = "" ), exclusive = TRUE, order = TRUE, nrow = nrow(ypr:::.parameters), key = "Parameter" ), NA) expect_identical( ypr_detabulate_parameters(ypr_tabulate_parameters(ypr_population(BH = 1L))), ypr_population(BH = 1L) ) }) test_that("ypr_tabulate_yield extinct population", { yield <- ypr_tabulate_yield(ypr_population(Linf = 130), all = TRUE) expect_equal(yield$pi, c(0.2, 0.102752704683603)) expect_equal(yield$Yield, c(0.0273043505036034, 0.0770860806461869)) yield <- ypr_tabulate_yield(ypr_population(Linf = 140), all = TRUE) expect_equal(yield$pi, c(0.2, 0.0926725376181979)) expect_equal(yield$Yield, c(0, 0.0857039391276462)) }) test_that("ypr_tabulate_biomass", { biomass <- ypr_tabulate_biomass(ypr_population()) expect_error(chk::check_data( biomass, values = list( Age = c(1L, 100L), Length = c(0, .Machine$double.xmax), Weight = c(0, .Machine$double.xmax), Fecundity = c(0, .Machine$double.xmax), Survivors = c(0, 1), Spawners = c(0, .Machine$double.xmax), Biomass = c(0, .Machine$double.xmax), Eggs = c(0, .Machine$double.xmax) ), nrow = TRUE, exclusive = TRUE, order = TRUE ), NA) })
system <- function(command, intern = FALSE, ignore.stdout = FALSE, ignore.stderr = FALSE, wait = TRUE, input = NULL, show.output.on.console = TRUE, minimized = FALSE, invisible = TRUE) { if(!missing(show.output.on.console) || !missing(minimized) || !missing(invisible)) message("arguments 'show.output.on.console', 'minimized' and 'invisible' are for Windows only") if(!is.logical(intern) || is.na(intern)) stop("'intern' must be TRUE or FALSE") if(!is.logical(ignore.stdout) || is.na(ignore.stdout)) stop("'ignore.stdout' must be TRUE or FALSE") if(!is.logical(ignore.stderr) || is.na(ignore.stderr)) stop("'ignore.stderr' must be TRUE or FALSE") if(!is.logical(wait) || is.na(wait)) stop("'wait' must be TRUE or FALSE") if(ignore.stdout) command <- paste(command, ">/dev/null") if(ignore.stderr) command <- paste(command, "2>/dev/null") if(!is.null(input)) { if(!is.character(input)) stop("'input' must be a character vector or 'NULL'") f <- tempfile() on.exit(unlink(f)) writeLines(input, f) command <- paste("<", shQuote(f), command) } if(!wait && !intern) command <- paste(command, "&") .Internal(system(command, intern)) } system2 <- function(command, args = character(), stdout = "", stderr = "", stdin = "", input = NULL, env = character(), wait = TRUE, minimized = FALSE, invisible = TRUE) { if(!missing(minimized) || !missing(invisible)) message("arguments 'minimized' and 'invisible' are for Windows only") if(!is.logical(wait) || is.na(wait)) stop("'wait' must be TRUE or FALSE") intern <- FALSE command <- paste(c(env, shQuote(command), args), collapse = " ") if(is.null(stdout)) stdout <- FALSE if(is.null(stderr)) stderr <- FALSE else if (isTRUE(stderr)) { if (!isTRUE(stdout)) warning("setting stdout = TRUE") stdout <- TRUE } if (identical(stdout, FALSE)) command <- paste(command, ">/dev/null") else if(isTRUE(stdout)) intern <- TRUE else if(is.character(stdout)) { if(length(stdout) != 1L) stop("'stdout' must be of length 1") if(nzchar(stdout)) { command <- if (identical(stdout, stderr)) paste (command, ">", shQuote(stdout), "2>&1") else paste(command, ">", shQuote(stdout)) } } if (identical(stderr, FALSE)) command <- paste(command, "2>/dev/null") else if(isTRUE(stderr)) { command <- paste(command, "2>&1") } else if(is.character(stderr)) { if(length(stderr) != 1L) stop("'stderr' must be of length 1") if(nzchar(stderr) && !identical(stdout, stderr)) command <- paste(command, "2>", shQuote(stderr)) } if(!is.null(input)) { if(!is.character(input)) stop("'input' must be a character vector or 'NULL'") f <- tempfile() on.exit(unlink(f)) writeLines(input, f) command <- paste(command, "<", shQuote(f)) } else if (nzchar(stdin)) command <- paste(command, "<", stdin) if(!wait && !intern) command <- paste(command, "&") .Internal(system(command, intern)) } Sys.which <- function(names) { res <- character(length(names)); names(res) <- names which <- "@WHICH@" if (!nzchar(which)) { warning("'which' was not found on this platform") return(res) } for(i in seq_along(names)) { if(is.na(names[i])) {res[i] <- NA; next} ans <- suppressWarnings(system(paste(which, shQuote(names[i])), intern = TRUE, ignore.stderr = TRUE)) if(grepl("solaris", R.version$os)) { tmp <- strsplit(ans[1], " ", fixed = TRUE)[[1]] if(identical(tmp[1:3], c("no", i, "in"))) ans <- "" } res[i] <- if(length(ans)) ans[1] else "" if(!file.exists(res[i])) res[i] <- "" } res }
draw_pie <- function(x = 0.5, y = 0.5, radius = 1, cols = c("red", "green"), border_col = "black", node_border_lwd = 1, labels = NULL, edges = 200, label_cex = 1, xlim = NULL, ylim = NULL, add = TRUE){ pies <- rep(1, length(cols)) init_angle = 0 if(is.null(labels)){labels <- rep("", length(cols))} pies <- c(0, cumsum(pies)/sum(pies)) d_pie <- diff(pies) n_pie <- length(d_pie) twopi <- 2 * pi t2xy <- function(x,y,t){ t2p <- twopi * t + init_angle * pi/180 list(x = (radius * cos(t2p))+x, y = (radius * sin(t2p))+y) } if(!add){ plot.new() if(is.null(xlim)){xlim = c(x-radius, x+radius)} if(is.null(ylim)){ylim = c(y-radius, y+radius)} plot.window(xlim = xlim, ylim = ylim) } for(i in 1:n_pie){ n <- max(2, floor(edges * d_pie[i])) P <- t2xy(x = x, y = y, seq.int(pies[i], pies[i + 1], length.out = n)) polygon(c(P$x, x), c(P$y, y), col = cols[i], border = border_col, lwd = node_border_lwd) text_x <- mean(c(min(P$x), max(P$x))) text_y <- mean(c(min(P$y), max(P$y))) lab <- as.character(labels[i]) if (!is.na(lab) && nzchar(lab)){ text(text_x, text_y, labels[i], xpd = TRUE, adj = 0.5, cex = label_cex) } } }
fSquared <- function(seminr_model, iv, dv) { if (length(seminr_model$constructs) == 2) { rsq <- (seminr_model$rSquared["Rsq", dv]) return((rsq - 0) / (1 - rsq)) } with_sm <- seminr_model$smMatrix without_sm <- subset(with_sm, !((with_sm[, "source"] == iv) & (with_sm[, "target"] == dv))) suppressMessages( without_pls <- estimate_pls(data = seminr_model$rawdata, measurement_model = seminr_model$measurement_model, structural_model = without_sm, inner_weights = seminr_model$inner_weights, missing = seminr_model$settings$missing, missing_value = seminr_model$settings$missing_value, maxIt = seminr_model$settings$maxIt, stopCriterion = seminr_model$settings$stopCriterion) ) with_r2 <- seminr_model$rSquared["Rsq", dv] ifelse(any(without_sm[,"target"] == dv), without_r2 <- without_pls$rSquared["Rsq", dv], without_r2 <- 0) return((with_r2 - without_r2) / (1 - with_r2)) } model_fsquares <- function(seminr_model) { path_matrix <- seminr_model$path_coef fsquared_matrix <- path_matrix for (dv in all_endogenous(seminr_model$smMatrix)) { ifelse(length(interactions_of(dv, seminr_model$smMatrix) ) > 0, int_components <- unique(unlist(strsplit(interactions_of(dv, seminr_model$smMatrix), "\\*"))), int_components <- NA) for (iv in setdiff(all_exogenous(seminr_model$smMatrix), int_components)) { fsquared_matrix[iv, dv] <- fSquared(seminr_model = seminr_model, iv = iv, dv = dv) fsquared_matrix[int_components,dv] <- NA } } if (length(all_interactions(seminr_model$smMatrix) > 0)) { comment(fsquared_matrix) <- "The fSquare for certain relationships cannot be calculated as the model contains an interaction term and omitting either the antecedent or moderator in the interaction term will cause model estimation to fail" } convert_to_table_output(fsquared_matrix) }
qln3 <- function(u = NULL, RP = 1/(1 - u), para){ if (is.null(u) & length(RP) >= 1) {u <- 1 - 1/RP} x <- qualn3(f = u, para = para) return(x) }
inspect_data_dichotomous <- function(data, success, allow_nas = TRUE, warning_nas = FALSE) { inspect_true_or_false(allow_nas) inspect_true_or_false(warning_nas) data_output_name <- deparse(substitute(data)) s_output_name <- deparse(substitute(success)) if (is.null(data)) { stop(paste("Invalid argument:", data_output_name, "is NULL.")) } if (is.null(success)) { stop(paste("Invalid argument:", s_output_name, "is NULL.")) } if (isFALSE(is.atomic(data))) { stop(paste("Invalid argument:", data_output_name, "must be atomic.")) } if (length(data) == 0) { stop(paste("Invalid argument:", data_output_name, "is empty.")) } if (any(isFALSE(is.atomic(success)), isFALSE(length(success) == 1))) { stop(paste( "Invalid argument:", s_output_name, "must be atomic and have length 1." )) } if (isFALSE(typeof(data) %in% c("logical", "integer", "double", "character"))) { stop( paste( "Invalid argument: the type of", data_output_name, "must be 'logical', 'integer', 'double' or 'character'." ) ) } if (isFALSE(typeof(success) %in% c("logical", "integer", "double", "character"))) { stop( paste( "Invalid argument: the type of", s_output_name, "must be 'logical', 'integer', 'double' or 'character'." ) ) } if (is.na(success)) { stop(paste("Invalid argument:", s_output_name, "is NA or NaN")) } data_factor <- factor(data, levels = unique(c(levels(factor( success )), levels(factor( unique(data) ))))) if (isTRUE(nlevels(data_factor) > 2)) { stop(paste("Invalid argument: there are more than two levels'.")) } if (all(is.na(data))) { stop(paste( "Invalid argument: all elements of", data_output_name, "are NA or NaN." )) } if (any(is.na(data))) { if (isFALSE(allow_nas)) { stop(paste( "Invalid argument: there are NA or NaN values in ", paste0(data_output_name, ".") )) } else { if (isTRUE(warning_nas)) { warning(paste( "There are NA or NaN values in", paste0(data_output_name, ".") )) } } } if (isFALSE(success %in% unique(data))) { warning(paste( s_output_name, "not observed in", paste0(data_output_name, ".") )) } } inspect_data_categorical <- function(data, allow_nas = TRUE, warning_nas = FALSE) { inspect_true_or_false(allow_nas) inspect_true_or_false(warning_nas) data_output_name <- deparse(substitute(data)) if (is.null(data)) { stop(paste("Invalid argument:", data_output_name, "is NULL.")) } if (isFALSE(is.atomic(data))) { stop(paste("Invalid argument:", data_output_name, "must be atomic.")) } if (length(data) == 0) { stop(paste("Invalid argument:", data_output_name, "is empty.")) } if (isFALSE(typeof(data) %in% c("logical", "integer", "double", "character"))) { stop( paste( "Invalid argument: the type of", data_output_name, "must be 'logical', 'integer', 'double' or 'character'." ) ) } if (all(is.na(data))) { stop(paste( "Invalid argument: all elements of", data_output_name, "are NA or NaN." )) } if (any(is.na(data))) { if (isFALSE(allow_nas)) { stop(paste( "Invalid argument: there are NA or NaN values in ", paste0(data_output_name, ".") )) } else { if (isTRUE(warning_nas)) { warning(paste( "There are NA or NaN values in", paste0(data_output_name, ".") )) } } } } inspect_data_cat_as_dichotom <- function(data, success, allow_nas = TRUE, warning_nas = FALSE) { inspect_true_or_false(allow_nas) inspect_true_or_false(warning_nas) data_output_name <- deparse(substitute(data)) s_output_name <- deparse(substitute(success)) if (is.null(data)) { stop(paste("Invalid argument:", data_output_name, "is NULL.")) } if (is.null(success)) { stop(paste("Invalid argument:", s_output_name, "is NULL.")) } if (isFALSE(is.atomic(data))) { stop(paste("Invalid argument:", data_output_name, "must be atomic.")) } if (length(data) == 0) { stop(paste("Invalid argument:", data_output_name, "is empty.")) } if (any(isFALSE(is.atomic(success)), isFALSE(length(success) == 1))) { stop(paste( "Invalid argument:", s_output_name, "must be atomic and have length 1." )) } if (isFALSE(typeof(data) %in% c("logical", "integer", "double", "character"))) { stop( paste( "Invalid argument: the type of", data_output_name, "must be 'logical', 'integer', 'double' or 'character'." ) ) } if (isFALSE(typeof(success) %in% c("logical", "integer", "double", "character"))) { stop( paste( "Invalid argument: the type of", s_output_name, "must be 'logical', 'integer', 'double' or 'character'." ) ) } if (all(is.na(data))) { stop(paste( "Invalid argument: all elements of", data_output_name, "are NA or NaN." )) } if (is.na(success)) { stop(paste("Invalid argument:", s_output_name, "is NA or NaN.")) } if (any(is.na(data))) { if (isFALSE(allow_nas)) { stop(paste( "Invalid argument: there are NA or NaN values in ", paste0(data_output_name, ".") )) } else { if (isTRUE(warning_nas)) { warning(paste( "There are NA or NaN values in", paste0(data_output_name, ".") )) } } } if (isFALSE(success %in% unique(data))) { warning(paste( s_output_name, "not observed in", paste0(data_output_name, ".") )) } }
update_membership <- function(lon, lat, global_membership, local_membership, indexes) { if (sum(global_membership[indexes]) == 0) { global_membership[indexes] <- adjust_membership(local_membership, max(global_membership)) return(global_membership) } if (all(global_membership[indexes] != 0)) { return(global_membership) } fin_membership <- global_membership[indexes] local_lon <- lon[indexes] local_lat <- lat[indexes] new_p <- which(fin_membership == 0) old_p <- which(fin_membership != 0) shared_clusteres <- unique(local_membership[old_p]) type1 <- new_p[local_membership[new_p] %in% shared_clusteres] type2 <- new_p[!local_membership[new_p] %in% shared_clusteres] for (i in type1) { bool <- local_membership[old_p] == local_membership[i] current_old <- old_p[bool] dist_vector <- dist_point_to_vector(local_lon[i], local_lat[i], local_lon[current_old], local_lat[current_old]) target <- current_old[which.min(dist_vector)] fin_membership[i] <- fin_membership[target] } if (length(type2) != 0) { fin_membership[type2] <- adjust_membership(local_membership[type2], max(global_membership)) } global_membership[indexes] <- fin_membership return(global_membership) }
InterVA5 <- function (Input, HIV, Malaria, write = TRUE, directory = NULL, filename = "VA5_result", output = "classic", append = FALSE, groupcode = FALSE, sci = NULL, returnCheckedData = FALSE, ...) { va5 <- function(ID, MALPREV, HIVPREV, PREGSTAT, PREGLIK, CAUSE1, LIK1, CAUSE2, LIK2, CAUSE3, LIK3, INDET, COMCAT, COMNUM, wholeprob, ...) { ID <- ID MALPREV <- as.character(MALPREV) HIVPREV <- as.character(HIVPREV) PREGSTAT <- PREGSTAT PREGLIK <- PREGLIK COMCAT <- as.character(COMCAT) COMNUM <- COMNUM wholeprob <- wholeprob va5.out <- list(ID = ID, MALPREV = MALPREV, HIVPREV = HIVPREV, PREGSTAT = PREGSTAT, PREGLIK = PREGLIK, CAUSE1 = CAUSE1, LIK1 = LIK1, CAUSE2 = CAUSE2, LIK2 = LIK2, CAUSE3 = CAUSE3, LIK3 = LIK3, INDET = INDET, COMCAT = COMCAT, COMNUM = COMNUM, wholeprob = wholeprob) va5.out } save.va5 <- function(x, filename, write) { if (!write) { return() } x <- x[-15] x <- as.matrix(x) filename <- paste(filename, ".csv", sep = "") write.table(t(x), file = filename, sep = ",", append = TRUE, row.names = FALSE, col.names = FALSE) } save.va5.prob <- function(x, filename, write) { if (!write) { return() } prob <- unlist(x[15]) x <- x[-15] x <- unlist(c(as.matrix(x), as.matrix(prob))) filename <- paste(filename, ".csv", sep = "") write.table(t(x), file = filename, sep = ",", append = TRUE, row.names = FALSE, col.names = FALSE) } if (is.null(directory) & write) stop("error: please provide a directory (required when write = TRUE)") if (is.null(directory)) directory = getwd() dir.create(directory, showWarnings = FALSE) globle.dir <- getwd() setwd(directory) if (is.null(sci)) { data("probbaseV5", envir = environment()) probbaseV5 <- get("probbaseV5", envir = environment()) probbaseV5 <- as.matrix(probbaseV5) probbaseV5Version <- probbaseV5[1,3] } if (!is.null(sci)) { validSCI <- TRUE if (!is.data.frame(sci) & !is.matrix(sci)) validSCI <- FALSE if (nrow(sci) != 354) validSCI <- FALSE if (ncol(sci) != 87) validSCI <- FALSE if (!validSCI) { stop("error: invalid sci (must be data frame or matrix with 354 rows and 87 columns).") } probbaseV5 <- as.matrix(sci) probbaseV5Version <- probbaseV5[1,3] } message("Using Probbase version: ", probbaseV5Version) data("causetextV5", envir = environment()) causetextV5 <- get("causetextV5", envir = environment()) if (groupcode) { causetextV5 <- causetextV5[, -2] } else { causetextV5 <- causetextV5[, -3] } if (write) { cat(paste("Error & warning log built for InterVA5", Sys.time(), "\n"), file = "errorlogV5.txt", append = FALSE) } if ( "i183o" %in% colnames(Input)) { colnames(Input)[which(colnames(Input) == "i183o")] <- "i183a" message("Due to the inconsistent names in the early version of InterVA5, the indicator 'i183o' has been renamed as 'i183a'.") } Input <- as.matrix(Input) if (dim(Input)[1] < 1) { stop("error: no data input") } N <- dim(Input)[1] S <- dim(Input)[2] if (S != dim(probbaseV5)[1]) { stop("error: invalid data input format. Number of values incorrect") } if (tolower(colnames(Input)[S]) != "i459o") { stop("error: the last variable should be 'i459o'") } data("RandomVA5", envir = environment()) RandomVA5 <- get("RandomVA5", envir = environment()) valabels = colnames(RandomVA5) count.changelabel = 0 for (i in 1:S) { if (tolower(colnames(Input)[i]) != tolower(valabels)[i]) { warning(paste("Input column '", colnames(Input)[i], "' does not match InterVA5 standard: '", valabels[i], "'", sep = ""), call. = FALSE, immediate. = TRUE) count.changelabel = count.changelabel + 1 } } if (count.changelabel > 0) { warning(paste(count.changelabel, "column names changed in input. \n If the change in undesirable, please change in the input to match standard InterVA5 input format."), call. = FALSE, immediate. = TRUE) colnames(Input) <- valabels } probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "I" ] <- 1 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "A+" ] <- 0.8 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "A" ] <- 0.5 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "A-" ] <- 0.2 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "B+" ] <- 0.1 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "B" ] <- 0.05 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "B-" ] <- 0.02 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "B -"] <- 0.02 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "C+" ] <- 0.01 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "C" ] <- 0.005 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "C-" ] <- 0.002 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "D+" ] <- 0.001 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "D" ] <- 5e-04 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "D-" ] <- 1e-04 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "E" ] <- 1e-05 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "N" ] <- 0 probbaseV5[,18:ncol(probbaseV5)][probbaseV5[,18:ncol(probbaseV5)] == "" ] <- 0 probbaseV5[1, 1:17] <- rep(0, 17) Sys_Prior <- as.numeric(probbaseV5[1, ]) D <- length(Sys_Prior) HIV <- tolower(HIV) Malaria <- tolower(Malaria) if (!(HIV %in% c("h", "l", "v")) || !(Malaria %in% c("h","l", "v"))) { stop("error: the HIV and Malaria indicator should be one of the three: 'h', 'l', and 'v'") } if (HIV == "h") Sys_Prior[23] <- 0.05 if (HIV == "l") Sys_Prior[23] <- 0.005 if (HIV == "v") Sys_Prior[23] <- 1e-05 if (Malaria == "h") { Sys_Prior[25] <- 0.05 Sys_Prior[45] <- 0.05 } if (Malaria == "l") { Sys_Prior[25] <- 0.005 Sys_Prior[45] <- 1e-05 } if (Malaria == "v") { Sys_Prior[25] <- 1e-05 Sys_Prior[45] <- 1e-05 } ID.list <- rep(NA, N) VAresult <- vector("list", N) if (write && append == FALSE) { header = c("ID", "MALPREV", "HIVPREV", "PREGSTAT", "PREGLIK", "CAUSE1", "LIK1", "CAUSE2", "LIK2", "CAUSE3", "LIK3", "INDET", "COMCAT", "COMNUM") if (output == "extended") header = c(header, as.character(causetextV5[, 2])) write.table(t(header), file = paste(filename, ".csv", sep = ""), row.names = FALSE, col.names = FALSE, sep = ",") } nd <- max(1, round(N/100)) np <- max(1, round(N/10)) if (write) { cat(paste("\n\n", "the following records are incomplete and excluded from further processing:", "\n\n", sep=""), file = "errorlogV5.txt", append = TRUE) } firstPass <- NULL secondPass <- NULL errors <- NULL if (returnCheckedData) { checkedData <- NULL idInputs <- Input[,1] } for (i in 1:N) { if (i%%nd == 0) { cat(".") } if (i%%np == 0) { cat(paste(round(i/N * 100), "% completed\n", sep = "")) } if (i == N) { cat(paste("100% completed\n", sep = "")) } index.current <- as.character(Input[i, 1]) Input[i, which(toupper(Input[i, ]) == "N")] <- "0" Input[i, which(toupper(Input[i, ]) == "Y")] <- "1" Input[i, which(Input[i, ] != "1" & Input[i, ] != "0")] <- NA input.current <- as.numeric(Input[i, ]) input.current[1] <- 0 if (sum(input.current[6:12], na.rm=TRUE) < 1) { if (write) { errors <- rbind(errors, paste(index.current, " Error in age indicator: Not Specified ")) } next } if (sum(input.current[4:5], na.rm=TRUE) < 1) { if (write) { errors <- rbind(errors, paste(index.current, " Error in sex indicator: Not Specified ")) } next } if (sum(input.current[21:328], na.rm=TRUE) < 1) { if (write) { errors <- rbind(errors, paste(index.current, " Error in indicators: No symptoms specified ")) } next } tmp <- DataCheck5(input.current, id=index.current, probbaseV5=probbaseV5, write=write) if (returnCheckedData) { checkedData <- rbind(checkedData, c(idInputs[i], tmp$Output[2:S])) } input.current <- tmp$Output firstPass <- rbind(firstPass, tmp$firstPass) secondPass <- rbind(secondPass, tmp$secondPass) subst.vector <- rep(NA, length=S) subst.vector[probbaseV5[,6]=="N"] <- 0 subst.vector[probbaseV5[,6]=="Y"] <- 1 new.input <- rep(0, S) for (y in 2:S) { if (!is.na(input.current[y])) { if (input.current[y]==subst.vector[y]) { new.input[y] <- 1 } } } input.current[input.current==0] <- 1 input.current[1] <- 0 input.current[is.na(input.current)] <- 0 reproductiveAge <- 0 preg_state <- " " lik.preg <- " " if (input.current[5] == 1 && (input.current[17] == 1 || input.current[18] == 1 || input.current[19] == 1)) { reproductiveAge <- 1 } prob <- Sys_Prior[18:D] temp <- which(new.input[2:length(input.current)] == 1) for (jj in 1:length(temp)) { temp_sub <- temp[jj] for (j in 18:D) { prob[j - 17] <- prob[j - 17] * as.numeric(probbaseV5[temp_sub + 1, j]) } if (sum(prob[1:3]) > 0) prob[1:3] <- prob[1:3]/sum(prob[1:3]) if (sum(prob[4:64]) > 0) prob[4:64] <- prob[4:64]/sum(prob[4:64]) if (sum(prob[65:70]) > 0) prob[65:70] <- prob[65:70]/sum(prob[65:70]) } names(prob) <- causetextV5[, 2] prob_A <- prob[ 1: 3] prob_B <- prob[ 4:64] prob_C <- prob[65:70] if (sum(prob_A) == 0 || reproductiveAge == 0) { preg_state <- "n/a" lik.preg <- " " } if (max(prob_A) < 0.1 & reproductiveAge == 1) { preg_state <- "indeterminate" lik.preg <- " " } if (which.max(prob_A) == 1 && prob_A[1] >= 0.1 && reproductiveAge == 1) { preg_state <- "Not pregnant or recently delivered" lik.preg <- as.numeric(round(prob_A[1]/sum(prob_A) * 100)) } if (which.max(prob_A) == 2 && prob_A[2] >= 0.1 && reproductiveAge == 1) { preg_state <- "Pregnancy ended within 6 weeks of death" lik.preg <- as.numeric(round(prob_A[2]/sum(prob_A) * 100)) } if (which.max(prob_A) == 3 && prob_A[3] >= 0.1 && reproductiveAge == 1) { preg_state <- "Pregnant at death" lik.preg <- as.numeric(round(prob_A[3]/sum(prob_A) * 100)) } prob.temp <- prob_B if (max(prob.temp) < 0.4) { cause1 <- lik1 <- cause2 <- lik2 <- cause3 <- lik3 <- " " indet <- 100 } if (max(prob.temp) >= 0.4) { lik1 <- round(max(prob.temp) * 100) cause1 <- names(prob.temp)[which.max(prob.temp)] prob.temp <- prob.temp[-which.max(prob.temp)] lik2 <- round(max(prob.temp) * 100) cause2 <- names(prob.temp)[which.max(prob.temp)] if (max(prob.temp) < 0.5 * max(prob_B)) lik2 <- cause2 <- " " prob.temp <- prob.temp[-which.max(prob.temp)] lik3 <- round(max(prob.temp) * 100) cause3 <- names(prob.temp)[which.max(prob.temp)] if (max(prob.temp) < 0.5 * max(prob_B)) lik3 <- cause3 <- " " top3 <- as.numeric(c(lik1, lik2, lik3)) indet <- round(100 - sum(top3, na.rm=TRUE)) } if (sum(prob_C) > 0) prob_C <- prob_C/sum(prob_C) if (max(prob_C)<.5) { comcat <- "Multiple" comnum <- " " } if (max(prob_C)>=.5) { comcat <- names(prob_C)[which.max(prob_C)] comnum <- round(max(prob_C)*100) } ID.list[i] <- index.current VAresult[[i]] <- va5(ID = index.current, MALPREV = Malaria, HIVPREV = HIV, PREGSTAT = preg_state, PREGLIK = lik.preg, CAUSE1 = cause1, LIK1 = lik1, CAUSE2 = cause2, LIK2 = lik2, CAUSE3 = cause3, LIK3 = lik3, INDET = indet, COMCAT=comcat, COMNUM=comnum, wholeprob = c(prob_A, prob_B, prob_C)) if (output == "classic") save.va5(VAresult[[i]], filename = filename, write) if (output == "extended") save.va5.prob(VAresult[[i]], filename = filename, write) } if (write) { cat(errors, paste("\n", "the following data discrepancies were identified and handled:", "\n"), firstPass, paste("\n", "Second pass", "\n"), secondPass, sep="\n", file="errorlogV5.txt", append=TRUE) } setwd(globle.dir) if (!returnCheckedData) { checkedData <- "returnCheckedData = FALSE" } else { colnames(checkedData) <- colnames(Input) } out <- list(ID = ID.list[which(!is.na(ID.list))], VA5 = VAresult[which(!is.na(ID.list))], Malaria = Malaria, HIV = HIV, checkedData = checkedData) class(out) <- "interVA5" return(out) }
rm(list=ls()); gc() setwd("C:/Users/Tom/Documents/Kaggle/Santander") library(data.table) library(bit64) library(xgboost) library(Matrix) library(Ckmeans.1d.dp) library(beepr) library(ggplot2) library(stringr) set.seed(14) targetDate <- "12-11-2016" trainModelFolder <- "train" saveFolderExtension <- " Top 100 monthProduct 200 rounds 20 Folds" testModel <- grepl("test", trainModelFolder) overwrite <- FALSE featureSelection <- TRUE topFeatures <- 100 featureSelectionMode <- c("monthProduct", "product")[1] targetIds <- 0:24 excludeNoNewProducts <- FALSE jointModelNoNewProducts <- FALSE excludeNoPosFlanks <- FALSE excludeString <- ifelse(excludeNoNewProducts, "", ifelse(excludeNoPosFlanks, "PosFlankCusts", "TrainAll")) underSampleNomPensNoNomina <- FALSE maxMonthNomPensNoNomina <- 150 nrounds <- 2e2 hyperparSetSimple <- list(nrounds = nrounds, etaC = 10, subsample = 1, colsample_bytree = 0.5, max.depth = 6, min_child_weight = 0, gamma = 0) hyperparSetExtended <- list(nrounds = nrounds, etaC = 10, subsample = 1, colsample_bytree = 0.5, max.depth = 8, min_child_weight = 0, gamma = 0.1) baseK <- 20 if(baseK <= 1) browser() K <- 20 saveBaseModels <- TRUE skipCommonModel <- TRUE bootstrap <- FALSE nbBoots <- ifelse(bootstrap, 5, 1) extraBootstrapDepth <- ifelse(bootstrap, 1, 0) if(bootstrap && K>1){ stop("Please Tom, don't combine bootstrap with cross validation") } useStackingFolds <- TRUE stackingIdsFn <- paste("first level ncodpers", baseK, "folds.rds") maxTrainRecords <- Inf showVariableImportance <- FALSE showMeanLabelByMayFlag <- FALSE timeRange <- c(0, 24) simpleModeling <- FALSE dropProductFeaturesPosFlankProd <- FALSE dropOtherIndFeatures <- FALSE baseProducts <- c("ahor_fin", "aval_fin", "cco_fin", "cder_fin", "cno_fin", "ctju_fin", "ctma_fin", "ctop_fin", "ctpp_fin", "deco_fin", "deme_fin", "dela_fin", "ecue_fin", "fond_fin", "hip_fin", "plan_fin", "pres_fin", "reca_fin", "tjcr_fin", "valo_fin", "viv_fin", "nomina", "nom_pens", "recibo" ) targetVars <- paste0("ind_", baseProducts, "_ult1") featuresPath <- file.path(getwd(), "Feature engineering", targetDate, trainModelFolder) featureFiles <- list.files(featuresPath)[c(3, 10)] featureFiles <- featureFiles[grepl(paste0(ifelse(testModel, "Lag17 ", ""), "features.rds$"), featureFiles)] trainFnBases <- gsub(" features.rds$", "", featureFiles) batchFeatures <- all(grepl("batch", trainFnBases, ignore.case = TRUE)) nbFeatureFiles <- length(featureFiles) trainFeaturePaths <- paste(featuresPath, featureFiles, sep="/") if(!excludeNoNewProducts || testModel){ targetIds <- targetIds[targetIds!=0] } firstNonZeroTarget <- which(targetIds!=0)[1] inspectVarImpTopModels <- FALSE inspectIds <- c(3, 5, 7, 13, 18, 19, 22, 23, 24) lowPriorityIds <- NULL nbTargetIds <- length(targetIds) dropPredictors <- c( "trainWeight" , "hasNewProduct", "nbNewProducts", "hasAnyPosFlank" , "ncodpers" , "lastDate" , "gapsFrac", "dataMonths", "monthsFrac", "nbLagRecords " , "grossIncome" , "seniorityDensity" , paste0(targetVars, "MAPRatioJune15") , paste0(targetVars, "RelMAP") , "familyId" , targetVars ) source("Common/getModelWeights.R") source("Common/getHyperParDescr.R") while(TRUE){ if(as.numeric(format(Sys.time(),"%H")) >= timeRange[1] && as.numeric(format(Sys.time(),"%H")) <= timeRange[2]){ break } cat(paste0("Invalid time range, sleeping for five minutes @"), as.character(Sys.time()), "\n") Sys.sleep(300) } dateTargetWeights <- readRDS(file.path(getwd(), "Model weights", targetDate, "model weights first.rds")) if(featureSelection){ if(featureSelectionMode == "monthProduct"){ featureOrders <- readRDS(file.path(getwd(), "first level learners", targetDate, "product month feature order.rds")) } else{ featureOrders <- readRDS(file.path(getwd(), "first level learners", targetDate, "product feature order.rds")) } } if(useStackingFolds && K>1){ stackingFoldsPath <- file.path(getwd(), "Second level learners", targetDate, stackingIdsFn) stackingFolds <- readRDS(stackingFoldsPath) } for(modelGroupId in 1:nbFeatureFiles){ cat("Learning xgboost models for month", modelGroupId, "of", nbFeatureFiles , "@", as.character(Sys.time()), "\n\n") trainOrig <- readRDS(trainFeaturePaths[modelGroupId]) if(testModel){ submission <- readRDS(bestSubmissionFn) submissionProds <- sort(unique(submission$product)) for(i in 1:length(submissionProds)){ targetSubmissionProduct <- submissionProds[i] submissionProdRows <- submission[product == targetSubmissionProduct, ] trainOrig[[targetSubmissionProduct]] <- submissionProdRows[match(trainOrig$ncodpers, submissionProdRows$ncodpers), totalProb] } } predictors <- setdiff(names(trainOrig), unique(dropPredictors)) predictorsOrig <- predictors saveDir <- file.path(getwd(), "First level learners", targetDate) dir.create(saveDir, showWarnings = FALSE) baseModelDir <- file.path(saveDir, paste0(trainModelFolder, excludeString, saveFolderExtension)) dir.create(baseModelDir, showWarnings = FALSE) if(nbFeatureFiles==1){ saveModelDir <- baseModelDir } else{ saveModelDir <- file.path(baseModelDir, trainFnBases[modelGroupId]) dir.create(saveModelDir, showWarnings = FALSE) } if(excludeNoNewProducts && min(targetIds)>0){ trainOrig <- trainOrig[hasNewProduct == TRUE, ] } posFlankClientsFn <- file.path(getwd(), "Feature engineering", targetDate, "positive flank clients.rds") posFlankClients <- readRDS(posFlankClientsFn) if(excludeNoPosFlanks && min(targetIds)>0){ trainOrig <- trainOrig[ncodpers %in% posFlankClients, ] } meanPosFlanks <- rep(NA, nbTargetIds) for(targetIndex in 1:nbTargetIds){ targetId <- targetIds[targetIndex] if(targetId==0){ targetVar <- "hasNewProduct" } else{ targetVar <- targetVars[targetId] } cat("Learning xgboost models for target variable", targetVar, targetIndex, "of", nbTargetIds , "@", as.character(Sys.time()), "\n") if(!is.null(firstNonZeroTarget) && targetIndex==firstNonZeroTarget && excludeNoNewProducts && jointModelNoNewProducts && !testModel && nbFeatureFiles>1){ if(modelGroupId==1){ trainOrig <- trainOrig[hasNewProduct == TRUE, ] trainOrig[, trainWeight := NULL] for(j in 2:nbFeatureFiles){ trainBatch <- readRDS(trainFeaturePaths[j]) trainOrig <- rbind(trainOrig, trainBatch[hasNewProduct == TRUE, ]) } } else{ break } } observationWeights <- getModelWeights(trainOrig$lastDate, targetVar, dateTargetWeights) trainOrig[, trainWeight := observationWeights] saveDirFiles <- list.files(saveModelDir) if(overwrite || !any(grepl(targetVar, saveDirFiles) & ( !bootstrap | grepl("Boot", saveDirFiles)))){ predictors <- predictorsOrig if(simpleModeling){ consideredFeatures <- c(grep(targetVar, predictors, ignore.case=TRUE, value = TRUE), paste0(targetVars, "Lag1")) predictors <- unique(consideredFeatures) } if(targetId == 0 && dropProductFeaturesPosFlankProd){ predictors <- predictors[!grepl("ult1", predictors)] } if(dropOtherIndFeatures && targetId != 0){ predictors <- predictors[!grepl("ult1", predictors) | grepl(baseProducts[targetId], predictors)] } if(featureSelection){ targetVarLoop <- targetVar monthsBackLoop <- 12*2016 + 5 - 12*year(trainOrig$lastDate[1]) - month(trainOrig$lastDate[1]) if(featureSelectionMode == "monthProduct"){ featureOrder <- featureOrders[targetVar == targetVarLoop & monthsBack == monthsBackLoop, feature] } else{ featureOrder <- featureOrders[targetVar == targetVarLoop, feature] } featureOrder <- featureOrder[featureOrder %in% predictors] if(topFeatures < length(featureOrder)){ excludedFeatures <- featureOrder[-(1:topFeatures)] predictors <- setdiff(predictors, excludedFeatures) } } for(bootId in 1:nbBoots){ bootExtension <- ifelse(bootstrap, paste0(" - Boot ", bootId), "") if(nbBoots>1){ cat("Bootstrap replicate", bootId, "of", nbBoots, "@", as.character(Sys.time()), "\n") } if(excludeNoNewProducts){ train <- trainOrig[targetId==0 | (hasNewProduct == TRUE), ] } else{ if(excludeNoPosFlanks){ train <- trainOrig[targetId==0 | (ncodpers %in% posFlankClients), ] } else{ train <- trainOrig } } if(targetId==0 && nrow(train)>maxTrainRecords){ train <- train[sample(1:nrow(train), maxTrainRecords)] } gc() if(targetId>0){ dropTarget <- is.na(train[[targetVar]]) | (train[[paste0(targetVar, "Lag1")]] == 1) train <- train[!dropTarget, ] } if(underSampleNomPensNoNomina && targetVar=="ind_nom_pens_ult1"){ posFlankIdsNpNoNom <- which(train[[paste0(targetVar, "Lag1")]] == 0 & train[[targetVar]] == 1 & !is.na(train[["ind_nomina_ult1"]]) & (train[["ind_nomina_ult1"]] == 0 | train[["ind_nomina_ult1Lag1"]] == 1)) if(length(posFlankIdsNpNoNom)>maxMonthNomPensNoNomina){ keepTarget <- sample(posFlankIdsNpNoNom, maxMonthNomPensNoNomina) dropTarget <- setdiff(posFlankIdsNpNoNom, keepTarget) train <- train[-dropTarget, ] } } nbPosFlanks <- sum(train[[targetVar]]) plotTitle <- paste0(targetId, " - ", targetVar, " (", nbPosFlanks, ")") if(showMeanLabelByMayFlag){ plotData <- data.frame(MayFlag = train$hasMay15Data, JuneFlag = train$hasJune15Data, labels = as.numeric(train[[targetVar]])) p <- ggplot(plotData, aes(x=MayFlag, y=labels, fill=MayFlag)) + stat_summary(fun.y="mean", geom="bar") + ggtitle(plotTitle) print(p) } meanPosFlanks[targetIndex] <- sum(train[[targetVar]])/nrow(trainOrig) if(bootstrap){ train <- train[sample(1:nrow(train), nrow(train), replace = TRUE), ] } nbModels <- ifelse(K==1, 1, ifelse(skipCommonModel, K, K+1)) foldIds <- vector(mode = "list", length = nbModels) allNcodpers <- sort(unique(train$ncodpers)) if(K>1){ if(useStackingFolds){ for(j in 1:K){ stackingFold <- stackingFolds[[j]] foldIds[[j]] <- stackingFold[stackingFold %in% allNcodpers] } } else{ folds <- sample(cut(seq(1, length(allNcodpers)), breaks = K, labels = FALSE)) for(j in 1:K){ foldIds[[j]] <- allNcodpers[folds==j] } } } allPredictions <- rep(NA, nrow(train)) for(i in 1:nbModels){ excludeIds <- foldIds[[i]] if(nbModels>1){ cat("Learning xgboost model for fold", i, "of", nbModels , "@", as.character(Sys.time()), "\n") } features <- train[!ncodpers %in% excludeIds,] predictorData <- features[, predictors, with=FALSE] labels <- features[, targetVar, with=FALSE][[1]] trainWeights <- features[, "trainWeight", with=FALSE][[1]] if(all(trainWeights==0)){ trainWeights <- rep(1, length(trainWeights)) } predictorData <- data.matrix(predictorData) if(sum(labels)>=1e3){ hyperpar <- hyperparSetExtended } else{ hyperpar <- hyperparSetSimple } hyperpar$max.depth <- hyperpar$max.depth + extraBootstrapDepth foldRounds <- hyperpar$nrounds * (1 + ifelse(i==nbModels & (K==1 | !skipCommonModel), 1/baseK, 0)) if(targetId %in% lowPriorityIds){ foldRounds <- round(foldRounds/10) } else{ foldRounds <- round(foldRounds) } model <- xgboost(data = predictorData, label = labels , eta = hyperpar$etaC/foldRounds , nrounds = foldRounds , subsample = hyperpar$subsample , colsample_bytree = hyperpar$colsample_bytree , max.depth = hyperpar$max.depth , min_child_weight = hyperpar$min_child_weight , gamma = hyperpar$gamma , objective = "reg:logistic" , eval_metric = "logloss" , missing = NA , verbose = 0 , save_period = NULL , weight = (trainWeights/mean(trainWeights)) ) oobFeatures <- train[train$ncodpers %in% excludeIds,] predictorDataOob <- oobFeatures[, predictors, with=FALSE] predictorDataOob <- data.matrix(predictorDataOob) if(nrow(predictorDataOob)>0){ predOob <- predict(model, predictorDataOob, missing=NA) allPredictions[train$ncodpers %in% excludeIds] <- predOob } if(nrow(predictorDataOob)>0){ foldPredIds <- train$ncodpers %in% excludeIds analyzedPreds <- allPredictions[foldPredIds] analyzedLabels <- train[[targetVar]][foldPredIds] foldLL <- -(sum(log(analyzedPreds[analyzedLabels==1])) + sum(log(1-analyzedPreds[analyzedLabels==0]))) cat("Fold log loss:", foldLL, "\n") foldTP <- sum(analyzedLabels==1) foldPredRatio <- round(mean(analyzedPreds[analyzedLabels==1])/ mean(analyzedPreds[analyzedLabels==0]), 2) cat("Fold prediction ratio TP/FP:", foldPredRatio, "\n") } else{ foldPredRatio <- NA foldTP <- NA } assessFeatureImportance <- showVariableImportance || (inspectVarImpTopModels && targetId %in% inspectIds) if(assessFeatureImportance){ importanceMatrix <- xgb.importance(predictors, model = model) p <- xgb.plot.importance(importanceMatrix) print(p) } if((i==nbModels || saveBaseModels) && !assessFeatureImportance){ importanceMatrix <- xgb.importance(predictors, model = model) } if(saveBaseModels && i<(K+1) && (!(i==1 && K==1))){ hyperParDescr <- getHyperParDescr(hyperpar) saveBasePath <- file.path(saveModelDir, paste0(targetVar, " Fold ", i, " of ", baseK, " - ", hyperParDescr, bootExtension, ".rds")) saveRDS(list(targetVar=targetVar, model=model, predictors=predictors, hyperpar=hyperpar, importanceMatrix=importanceMatrix, timeStamp = as.character(Sys.time()), foldPredRatio = foldPredRatio, foldTP = foldTP), saveBasePath) } } nbPosFlanks <- sum(train[[targetVar]]) foldPredRatio <- NA foldTP <- NA if(any(!is.na(allPredictions))){ if(testModel){ newProductIds <- !is.na(allPredictions) } else{ newProductIds <- !is.na(allPredictions) & (train$hasNewProduct | (targetId == 0) | !excludeNoNewProducts) } analyzeRecordIds <- newProductIds & (train$trainWeight == max(train$trainWeight)) analyzedPreds <- allPredictions[analyzeRecordIds] analyzedLabels <- train[[targetVar]][analyzeRecordIds] nbPosFlanks <- sum(analyzedLabels) if(testModel){ predLabelCorr <- cor(analyzedPreds, analyzedLabels) plot(analyzedPreds, analyzedLabels, main = paste("Predicted vs label correlation:", round(predLabelCorr, 3))) } else{ boxplot(analyzedPreds ~ analyzedLabels, main=paste0(targetIndex, " - ", targetVar, " (", nbPosFlanks, ")")) meanLL <- -(sum(log(analyzedPreds[analyzedLabels==1])) + sum(log(1-analyzedPreds[analyzedLabels==0]))) / length(analyzedPreds) cat("Out of bag mean log loss for", paste0(targetVar, ":"), meanLL, "\n") foldTP <- sum(analyzedLabels==1) foldPredRatio <- round(mean(analyzedPreds[analyzedLabels==1])/ mean(analyzedPreds[analyzedLabels==0]), 2) cat("Prediction ratio TP/FP:", foldPredRatio, "\n") cat("(Mean predictions, mean target)", c(mean(allPredictions[analyzeRecordIds]), mean(train[[targetVar]][analyzeRecordIds])), "\n") } } cat("\n") if(K==1 || !skipCommonModel){ savePath <- file.path(saveModelDir, paste0(targetVar, bootExtension, ".rds")) saveRDS(list(targetVar=targetVar, model=model, predictors=predictors, hyperpar=hyperpar, importanceMatrix=importanceMatrix, timeStamp=as.character(Sys.time()), foldPredRatio=foldPredRatio, foldTP=foldTP), savePath) } } } } } beep(sound = "fanfare")
test_that('print.dg treats variable as categorical if guide has length > 1',{ file <- system.file(package = 'yamlet', 'extdata','quinidine.csv') library(ggplot2) library(dplyr) library(magrittr) file %>% decorate %>% filter(!is.na(conc)) %>% ggplot(aes(x = time, y = conc, color = Heart)) + geom_point() }) test_that('print.dg uses conditional labels and guides',{ file <- system.file(package = 'yamlet', 'extdata','phenobarb.csv') file %>% decorate %>% filter(event == 'conc') %>% ggplot(aes(x = time, y = value, color = ApgarInd)) + geom_point() }) test_that('ggplot.decorated works with multiple layers',{ library(yamlet) library(ggplot2) library(magrittr) library(csv) a <- io_csv(system.file(package = 'yamlet', 'extdata','phenobarb.csv')) b <- io_csv(system.file(package = 'yamlet', 'extdata','quinidine.csv')) c <- as.csv(system.file(package = 'yamlet', 'extdata','phenobarb.csv')) d <- as.csv(system.file(package = 'yamlet', 'extdata','quinidine.csv')) x <- a %>% filter(event == 'conc') %>% ggplot(aes(x = time, y = value, color = ApgarInd)) + geom_point() + b %>% filter(!is.na(conc)) %>% geom_point(data = ., aes(x = time/10, y = conc*10, color = Heart)) y <- c %>% filter(event == 'conc') %>% ggplot2:::ggplot.default(aes(x = time, y = value, color = ApgarInd)) + geom_point() + d %>% filter(!is.na(conc)) %>% geom_point(data = ., aes(x = time/10, y = conc*10, color = Heart)) }) test_that('ggready supports axis label line breaks',{ library(yamlet) library(ggplot2) library(magrittr) library(dplyr) library(encode) data(mtcars) mtcars %>% select(mpg, vs, am) %>% data.frame %>% mutate( plotgroup = case_when( vs == 0 & am == 0 ~ 'v-shaped\nautomatic', vs == 0 & am == 1 ~ 'v-shaped\nmanual', vs == 1 & am == 0 ~ 'straight\nautomatic', vs == 1 & am == 1 ~ 'straight\nmanual' ) ) %>% redecorate(" mpg: [ milage, mi/gal ] plotgroup: [ engine\\ntransmission, [v-shaped\n\nautomatic,v-shaped\n\nmanual,straight\n\nautomatic,straight\n\nmanual]] ") %>% ggready %>% ggplot(aes(x = plotgroup, y = mpg)) + geom_boxplot() }) test_that('subplots respect metadata assignments',{ library(ggplot2) library(magrittr) library(dplyr) library(gridExtra) a <- io_csv(system.file(package = 'yamlet', 'extdata','phenobarb.csv')) b <- io_csv(system.file(package = 'yamlet', 'extdata','quinidine.csv')) c <- as.csv(system.file(package = 'yamlet', 'extdata','phenobarb.csv')) d <- as.csv(system.file(package = 'yamlet', 'extdata','quinidine.csv')) x <- a %>% filter(event == 'conc') %>% ggplot(aes(x = time, y = value, color = ApgarInd)) + geom_point() + b %>% filter(!is.na(conc)) %>% geom_point(data = ., aes(x = time/10, y = conc*10, color = Heart)) y <- a %>% filter(event == 'conc') %>% ggplot2:::ggplot.default(aes(x = time, y = value, color = ApgarInd)) + geom_point() + d %>% filter(!is.na(conc)) %>% geom_point(data = ., aes(x = time/10, y = conc*10, color = Heart)) grid.arrange(x, y) p <- x %>% ggplot_build q <- p %>% ggplot_gtable plot(q) expect_equal_to_reference(file = '098.rds', p) })
workingDir <- getwd() dataDir <- paste(workingDir, "data-publisher/", sep = "/") modelDir <- paste(workingDir, "model", sep = "/") fundyDir <- paste(workingDir, "fundamentals", sep = "/") setwd(modelDir) n.days <- 30 just.today <- T n.sims <- 50000 source("senate-model-2014.R") if (just.today) source("combine-data.R")
local_bru_testthat_setup() test_that("2D LGCP fitting and prediction: Plot sampling", { skip_on_cran() local_bru_safe_inla() options <- list( control.inla = list( int.strategy = "eb" ) ) data(gorillas, package = "inlabru", envir = environment()) matern <- INLA::inla.spde2.pcmatern(gorillas$mesh, prior.sigma = c(0.1, 0.01), prior.range = c(5, 0.01) ) cmp <- coordinates ~ my.spde(main = coordinates, model = matern) fit <- lgcp(cmp, data = gorillas$plotsample$nests, samplers = gorillas$plotsample$plots, domain = list(coordinates = gorillas$mesh), options = options ) expect_equal( sum(fit$bru_info$lhoods[[1]]$E), 7.096605, tolerance = lowtol ) expect_snapshot_value( fit$summary.fixed["Intercept", "mean"] + fit$summary.random$my.spde$mean[c(19, 100, 212)], tolerance = midtol, style = "serialize" ) expect_snapshot_value( fit$summary.fixed["Intercept", "sd"] + fit$summary.random$my.spde$sd[c(19, 100, 212)], tolerance = hitol, style = "serialize" ) })
sfacross <- function(formula, muhet, uhet, vhet, logDepVar = TRUE, data, subset, S = 1L, udist = "hnormal", scaling = FALSE, start = NULL, method = "bfgs", hessianType = 1L, simType = "halton", Nsim = 100, prime = 2L, burn = 10, antithetics = FALSE, seed = 12345, itermax = 2000, printInfo = FALSE, tol = 1e-12, gradtol = 1e-06, stepmax = 0.1, qac = "marquardt") { udist <- tolower(udist) if (!(udist %in% c( "hnormal", "exponential", "tnormal", "rayleigh", "uniform", "gamma", "lognormal", "weibull", "genexponential", "tslaplace" ))) { stop("Unknown inefficiency distribution: ", paste(udist), call. = FALSE ) } if (length(Formula(formula))[2] != 1) { stop("argument 'formula' must have one RHS part", call. = FALSE) } cl <- match.call() mc <- match.call(expand.dots = FALSE) m <- match(c("formula", "data", "subset"), names(mc), nomatch = 0L) mc <- mc[c(1L, m)] mc$drop.unused.levels <- TRUE formula <- interCheckMain(formula = formula) if (!missing(muhet)) { muhet <- lhsCheck_mu(formula = muhet, scaling = scaling) } else { muhet <- ~1 } if (!missing(uhet)) { uhet <- lhsCheck_u(formula = uhet, scaling = scaling) } else { uhet <- ~1 } if (!missing(vhet)) { vhet <- lhsCheck_v(formula = vhet) } else { vhet <- ~1 } formula <- formDist_sfacross( udist = udist, formula = formula, muhet = muhet, uhet = uhet, vhet = vhet ) if (missing(data)) { data <- environment(formula) } mc$formula <- formula mc$na.action <- na.pass mc[[1L]] <- quote(model.frame) mc <- eval(mc, parent.frame()) validObs <- rowSums(is.na(mc) | is.infinite.data.frame(mc)) == 0 Yvar <- model.response(mc, "numeric") Yvar <- Yvar[validObs] mtX <- terms(formula, data = data, rhs = 1) Xvar <- model.matrix(mtX, mc) Xvar <- Xvar[validObs, , drop = FALSE] nXvar <- ncol(Xvar) N <- nrow(Xvar) if (N == 0L) { stop("0 (non-NA) cases", call. = FALSE) } if (length(Yvar) != nrow(Xvar)) { stop(paste("the number of observations of the dependent variable (", length(Yvar), ") must be the same to the number of observations of the exogenous variables (", nrow(Xvar), ")", sep = "" ), call. = FALSE) } if (udist %in% c("tnormal", "lognormal")) { mtmuH <- delete.response(terms(formula, data = data, rhs = 2 )) muHvar <- model.matrix(mtmuH, mc) muHvar <- muHvar[validObs, , drop = FALSE] nmuZUvar <- ncol(muHvar) mtuH <- delete.response(terms(formula, data = data, rhs = 3)) uHvar <- model.matrix(mtuH, mc) uHvar <- uHvar[validObs, , drop = FALSE] nuZUvar <- ncol(uHvar) mtvH <- delete.response(terms(formula, data = data, rhs = 4)) vHvar <- model.matrix(mtvH, mc) vHvar <- vHvar[validObs, , drop = FALSE] nvZVvar <- ncol(vHvar) } else { mtuH <- delete.response(terms(formula, data = data, rhs = 2)) uHvar <- model.matrix(mtuH, mc) uHvar <- uHvar[validObs, , drop = FALSE] nuZUvar <- ncol(uHvar) mtvH <- delete.response(terms(formula, data = data, rhs = 3)) vHvar <- model.matrix(mtvH, mc) vHvar <- vHvar[validObs, , drop = FALSE] nvZVvar <- ncol(vHvar) } if (length(S) != 1 || !(S %in% c(-1L, 1L))) { stop("argument 'S' must equal either 1 or -1: 1 for production or profit frontier and -1 for cost frontier", call. = FALSE ) } typeSfa <- if (S == 1L) { "Stochastic Production/Profit Frontier, e = v - u" } else { "Stochastic Cost Frontier, e = v + u" } if (length(scaling) != 1 || !is.logical(scaling[1])) { stop("argument 'scaling' must be a single logical value", call. = FALSE ) } if (scaling) { if (udist != "tnormal") { stop("argument 'udist' must be 'tnormal' when scaling option is TRUE", call. = FALSE ) } if (nuZUvar != nmuZUvar) { stop("argument 'muhet' and 'uhet' must have the same length", call. = FALSE ) } if (!all(colnames(uHvar) == colnames(muHvar))) { stop("argument 'muhet' and 'uhet' must contain the same variables", call. = FALSE ) } if (nuZUvar == 1 || nmuZUvar == 1) { if (attr(terms(muhet), "intercept") == 1 || attr( terms(uhet), "intercept" ) == 1) { stop("at least one exogeneous variable must be provided for the scaling option", call. = FALSE ) } } } if (length(logDepVar) != 1 || !is.logical(logDepVar[1])) { stop("argument 'logDepVar' must be a single logical value", call. = FALSE ) } nParm <- if (udist == "tnormal") { if (scaling) { if (attr(terms(muhet), "intercept") == 1 || attr( terms(uhet), "intercept" ) == 1) { nXvar + (nmuZUvar - 1) + 2 + nvZVvar } else { nXvar + nmuZUvar + 2 + nvZVvar } } else { nXvar + nmuZUvar + nuZUvar + nvZVvar } } else { if (udist == "lognormal") { nXvar + nmuZUvar + nuZUvar + nvZVvar } else { if (udist %in% c("gamma", "weibull", "tslaplace")) { nXvar + nuZUvar + nvZVvar + 1 } else { nXvar + nuZUvar + nvZVvar } } } if (!is.null(start)) { if (length(start) != nParm) { stop("Wrong number of initial values: model has ", nParm, " parameters", call. = FALSE ) } } if (nParm > N) { stop("Model has more parameters than observations", call. = FALSE) } method <- tolower(method) if (!(method %in% c( "ucminf", "bfgs", "bhhh", "nr", "nm", "sr1", "mla", "sparse", "nlminb" ))) { stop("Unknown or non-available optimization algorithm: ", paste(method), call. = FALSE ) } if (length(hessianType) != 1 || !(hessianType %in% c( 1L, 2L, 3L ))) { stop("argument 'hessianType' must equal either 1 or 2 or 3", call. = FALSE ) } if (udist %in% c("gamma", "lognormal", "weibull")) { if (!(simType %in% c("halton", "ghalton", "sobol", "uniform"))) { stop("Unknown or non-available random draws method", call. = FALSE ) } if (!is.numeric(Nsim) || length(Nsim) != 1) { stop("argument 'Nsim' must be a single numeric scalar", call. = FALSE ) } if (!is.numeric(burn) || length(burn) != 1) { stop("argument 'burn' must be a single numeric scalar", call. = FALSE ) } if (!is_prime(prime)) { stop("argument 'prime' must be a single prime number", call. = FALSE ) } if (length(antithetics) != 1 || !is.logical(antithetics[1])) { stop("argument 'antithetics' must be a single logical value", call. = FALSE ) } if (antithetics && (Nsim %% 2) != 0) { Nsim <- Nsim + 1 } simDist <- if (simType == "halton") { "Halton" } else { if (simType == "ghalton") { "Generalized Halton" } else { if (simType == "sobol") { "Sobol" } else { if (simType == "uniform") { "Uniform" } } } } cat("Initialization of", Nsim, simDist, "draws per observation ...\n") FiMat <- drawMat( N = N, Nsim = Nsim, simType = simType, prime = prime, burn = burn + 1, antithetics = antithetics, seed = seed ) } if (!is.numeric(itermax) || length(itermax) != 1) { stop("argument 'itermax' must be a single numeric scalar", call. = FALSE ) } if (itermax != round(itermax)) { stop("argument 'itermax' must be an integer", call. = FALSE) } if (itermax <= 0) { stop("argument 'itermax' must be positive", call. = FALSE) } itermax <- as.integer(itermax) if (length(printInfo) != 1 || !is.logical(printInfo[1])) { stop("argument 'printInfo' must be a single logical value", call. = FALSE ) } if (!is.numeric(tol) || length(tol) != 1) { stop("argument 'tol' must be numeric", call. = FALSE) } if (tol < 0) { stop("argument 'tol' must be non-negative", call. = FALSE) } if (!is.numeric(gradtol) || length(gradtol) != 1) { stop("argument 'gradtol' must be numeric", call. = FALSE) } if (gradtol < 0) { stop("argument 'gradtol' must be non-negative", call. = FALSE) } if (!is.numeric(stepmax) || length(stepmax) != 1) { stop("argument 'stepmax' must be numeric", call. = FALSE) } if (stepmax < 0) { stop("argument 'stepmax' must be non-negative", call. = FALSE) } if (!(qac %in% c("marquardt", "stephalving"))) { stop("argument 'qac' must be either 'marquardt' or 'stephalving'", call. = FALSE ) } olsRes <- if (colnames(Xvar)[1] == "(Intercept)") { lm(Yvar ~ ., data = as.data.frame(Xvar[, -1])) } else { lm(Yvar ~ -1 + ., data = as.data.frame(Xvar)) } if (any(is.na(olsRes$coefficients))) { stop("at least one of the OLS coefficients is NA: ", paste(colnames(Xvar)[is.na(olsRes$coefficients)], collapse = ", " ), "This may be due to a singular matrix due to potential perfect multicollinearity", call. = FALSE ) } olsParam <- c(olsRes$coefficients) olsSigmasq <- summary(olsRes)$sigma^2 olsStder <- sqrt(diag(vcov(olsRes))) olsLoglik <- logLik(olsRes)[1] if (inherits(data, "plm.dim")) { dataTable <- data[validObs, 1:2] } else { dataTable <- data.frame(IdObs = c(1:sum(validObs))) } dataTable <- as_tibble(cbind(dataTable, data[validObs, all.vars(terms(formula))])) dataTable <- mutate(dataTable, olsResiduals = residuals(olsRes), olsFitted = fitted(olsRes) ) olsSkew <- skewness(dataTable[["olsResiduals"]]) olsM3Okay <- if (S * olsSkew < 0) { "Residuals have the expected skeweness" } else { "Residuals do not have the expected skeweness" } if (S * olsSkew > 0) { warning("The residuals of the OLS are ", if (S == 1) { " right" } else { "left" }, "-skewed. This may indicate the absence of inefficiency or model misspecification or sample 'bad luck'", call. = FALSE ) } CoelliM3Test <- c(z = moment(dataTable[["olsResiduals"]], order = 3 ) / sqrt(6 * moment(dataTable[["olsResiduals"]], order = 2 )^3 / N), p.value = 2 * pnorm(-abs(moment(dataTable[["olsResiduals"]], order = 3 ) / sqrt(6 * moment(dataTable[["olsResiduals"]], order = 2 )^3 / N)))) AgostinoTest <- dagoTest(dataTable[["olsResiduals"]]) class(AgostinoTest) <- "dagoTest" FunArgs <- if (udist == "tnormal") { if (scaling) { list( start = start, olsParam = olsParam, dataTable = dataTable, nXvar = nXvar, nuZUvar = nuZUvar, nvZVvar = nvZVvar, uHvar = uHvar, vHvar = vHvar, Yvar = Yvar, Xvar = Xvar, S = S, method = method, printInfo = printInfo, itermax = itermax, stepmax = stepmax, tol = tol, gradtol = gradtol, hessianType = hessianType, qac = qac ) } else { list( start = start, olsParam = olsParam, dataTable = dataTable, nXvar = nXvar, nmuZUvar = nmuZUvar, nuZUvar = nuZUvar, nvZVvar = nvZVvar, muHvar = muHvar, uHvar = uHvar, vHvar = vHvar, Yvar = Yvar, Xvar = Xvar, S = S, method = method, printInfo = printInfo, itermax = itermax, stepmax = stepmax, tol = tol, gradtol = gradtol, hessianType = hessianType, qac = qac ) } } else { if (udist == "lognormal") { list( start = start, olsParam = olsParam, dataTable = dataTable, nXvar = nXvar, nmuZUvar = nmuZUvar, nuZUvar = nuZUvar, nvZVvar = nvZVvar, muHvar = muHvar, uHvar = uHvar, vHvar = vHvar, Yvar = Yvar, Xvar = Xvar, S = S, N = N, FiMat = FiMat, method = method, printInfo = printInfo, itermax = itermax, stepmax = stepmax, tol = tol, gradtol = gradtol, hessianType = hessianType, qac = qac ) } else { if (udist %in% c("gamma", "weibull")) { list( start = start, olsParam = olsParam, dataTable = dataTable, nXvar = nXvar, nuZUvar = nuZUvar, nvZVvar = nvZVvar, uHvar = uHvar, vHvar = vHvar, Yvar = Yvar, Xvar = Xvar, S = S, N = N, FiMat = FiMat, method = method, printInfo = printInfo, itermax = itermax, stepmax = stepmax, tol = tol, gradtol = gradtol, hessianType = hessianType, qac = qac ) } else { list( start = start, olsParam = olsParam, dataTable = dataTable, nXvar = nXvar, nuZUvar = nuZUvar, nvZVvar = nvZVvar, uHvar = uHvar, vHvar = vHvar, Yvar = Yvar, Xvar = Xvar, S = S, method = method, printInfo = printInfo, itermax = itermax, stepmax = stepmax, tol = tol, gradtol = gradtol, hessianType = hessianType, qac = qac ) } } } mleList <- tryCatch(switch(udist, hnormal = do.call( halfnormAlgOpt, FunArgs ), exponential = do.call(exponormAlgOpt, FunArgs), tnormal = if (scaling) { do.call(truncnormscalAlgOpt, FunArgs) } else { do.call( truncnormAlgOpt, FunArgs ) }, rayleigh = do.call(raynormAlgOpt, FunArgs), gamma = do.call(gammanormAlgOpt, FunArgs), uniform = do.call( uninormAlgOpt, FunArgs ), lognormal = do.call(lognormAlgOpt, FunArgs), weibull = do.call(weibullnormAlgOpt, FunArgs), genexponential = do.call( genexponormAlgOpt, FunArgs ), tslaplace = do.call(tslnormAlgOpt, FunArgs) ), error = function(e) e ) if (inherits(mleList, "error")) { stop("The current error occurs during optimization:\n", mleList$message, call. = FALSE ) } mleList$invHessian <- vcovObj( mleObj = mleList$mleObj, hessianType = hessianType, method = method, nParm = nParm ) mleList <- c(mleList, if (method == "ucminf") { list( type = "ucminf max.", nIter = unname(mleList$mleObj$info["neval"]), status = mleList$mleObj$message, mleLoglik = -mleList$mleObj$value, gradient = mleList$mleObj$gradient ) } else { if (method %in% c("bfgs", "bhhh", "nr", "nm")) { list( type = substr(mleList$mleObj$type, 1, 27), nIter = mleList$mleObj$iterations, status = mleList$mleObj$message, mleLoglik = mleList$mleObj$maximum, gradient = mleList$mleObj$gradient ) } else { if (method == "sr1") { list( type = "SR1 max.", nIter = mleList$mleObj$iterations, status = mleList$mleObj$status, mleLoglik = -mleList$mleObj$fval, gradient = mleList$mleObj$gradient ) } else { if (method == "mla") { list( type = "Lev. Marquardt max.", nIter = mleList$mleObj$ni, status = switch(mleList$mleObj$istop, `1` = "convergence criteria were satisfied", `2` = "maximum number of iterations was reached", `4` = "algorithm encountered a problem in the function computation" ), mleLoglik = -mleList$mleObj$fn.value, gradient = mleList$mleObj$grad ) } else { if (method == "sparse") { list( type = "Sparse Hessian max.", nIter = mleList$mleObj$iterations, status = mleList$mleObj$status, mleLoglik = -mleList$mleObj$fval, gradient = mleList$mleObj$gradient ) } else { if (method == "nlminb") { list( type = "nlminb max.", nIter = mleList$mleObj$iterations, status = mleList$mleObj$message, mleLoglik = -mleList$mleObj$objective, gradient = mleList$mleObj$gradient ) } } } } } }) if (udist %in% c("tnormal", "lognormal")) { names(mleList$startVal) <- fName_mu_sfacross( Xvar = Xvar, udist = udist, muHvar = muHvar, uHvar = uHvar, vHvar = vHvar, scaling = scaling ) } else { names(mleList$startVal) <- fName_uv_sfacross( Xvar = Xvar, udist = udist, uHvar = uHvar, vHvar = vHvar ) } names(mleList$mlParam) <- names(mleList$startVal) rownames(mleList$invHessian) <- colnames(mleList$invHessian) <- names(mleList$mlParam) names(mleList$gradient) <- names(mleList$mlParam) colnames(mleList$mleObj$gradL_OBS) <- names(mleList$mlParam) mlDate <- format(Sys.time(), "Model was estimated on : %b %a %d, %Y at %H:%M") dataTable$mlResiduals <- Yvar - as.numeric(crossprod( matrix(mleList$mlParam[1:nXvar]), t(Xvar) )) dataTable$mlFitted <- as.numeric(crossprod( matrix(mleList$mlParam[1:nXvar]), t(Xvar) )) dataTable$logL_OBS <- mleList$mleObj$logL_OBS returnObj <- list() returnObj$call <- cl returnObj$formula <- formula returnObj$S <- S returnObj$typeSfa <- typeSfa returnObj$Nobs <- N returnObj$nXvar <- nXvar if (udist %in% c("tnormal", "lognormal")) { returnObj$nmuZUvar <- nmuZUvar } returnObj$scaling <- scaling returnObj$logDepVar <- logDepVar returnObj$nuZUvar <- nuZUvar returnObj$nvZVvar <- nvZVvar returnObj$nParm <- nParm returnObj$udist <- udist returnObj$startVal <- mleList$startVal returnObj$dataTable <- dataTable returnObj$olsParam <- olsParam returnObj$olsStder <- olsStder returnObj$olsSigmasq <- olsSigmasq returnObj$olsLoglik <- olsLoglik returnObj$olsSkew <- olsSkew returnObj$olsM3Okay <- olsM3Okay returnObj$CoelliM3Test <- CoelliM3Test returnObj$AgostinoTest <- AgostinoTest returnObj$optType <- mleList$type returnObj$nIter <- mleList$nIter returnObj$optStatus <- mleList$status returnObj$startLoglik <- mleList$startLoglik returnObj$mlLoglik <- mleList$mleLoglik returnObj$mlParam <- mleList$mlParam returnObj$gradient <- mleList$gradient returnObj$gradL_OBS <- mleList$mleObj$gradL_OBS returnObj$gradientNorm <- sqrt(sum(mleList$gradient^2)) returnObj$invHessian <- mleList$invHessian returnObj$hessianType <- if (hessianType == 1) { "Analytic/Numeric Hessian" } else { if (hessianType == 2) { "BHHH Hessian" } else { if (hessianType == 3) { "Robust Hessian" } } } returnObj$mlDate <- mlDate if (udist %in% c("gamma", "lognormal", "weibull")) { returnObj$simDist <- simDist returnObj$Nsim <- Nsim returnObj$FiMat <- FiMat } rm(mleList) class(returnObj) <- "sfacross" return(returnObj) } print.sfacross <- function(x, ...) { cat("Call:\n") cat(deparse(x$call )) cat("\n\n") cat("Likelihood estimates using", x$optType, "\n") cat(sfadist(x$udist), "\n") cat("Status:", x$optStatus, "\n\n") cat(x$typeSfa, "\n") print.default(format(x$mlParam), print.gap = 2, quote = FALSE) invisible(x) }
NULL ReducedDimensionPlot <- function(...) { new("ReducedDimensionPlot", ...) } setMethod("initialize", "ReducedDimensionPlot", function(.Object, ...) { args <- list(...) args <- .emptyDefault(args, .redDimType, NA_character_) args <- .emptyDefault(args, .redDimXAxis, 1L) args <- .emptyDefault(args, .redDimYAxis, 2L) do.call(callNextMethod, c(list(.Object), args)) }) setMethod(".cacheCommonInfo", "ReducedDimensionPlot", function(x, se) { if (!is.null(.getCachedCommonInfo(se, "ReducedDimensionPlot"))) { return(se) } se <- callNextMethod() if (is(se, "SingleCellExperiment")) { available <- reducedDimNames(se) for (y in seq_along(available)) { if (ncol(reducedDim(se, y))==0L) { available[y] <- NA_character_ } } available <- available[!is.na(available)] } else { available <- character(0) } .setCachedCommonInfo(se, "ReducedDimensionPlot", valid.reducedDim.names=available) }) setMethod(".refineParameters", "ReducedDimensionPlot", function(x, se) { x <- callNextMethod() if (is.null(x)) { return(NULL) } available <- .getCachedCommonInfo(se, "ReducedDimensionPlot")$valid.reducedDim.names if (!is.na(chosen <- slot(x, .redDimType)) && chosen %in% available && slot(x, .redDimXAxis) <= ncol(reducedDim(se, chosen)) && slot(x, .redDimYAxis) <= ncol(reducedDim(se, chosen))) { } else { if (length(available)==0L) { warning(sprintf("no 'reducedDims' with non-zero dimensions for '%s'", class(x)[1])) return(NULL) } y <- available[1] slot(x, .redDimType) <- y slot(x, .redDimXAxis) <- 1L slot(x, .redDimYAxis) <- min(ncol(reducedDim(se, y)), 2L) } x }) setValidity2("ReducedDimensionPlot", function(object) { msg <- character(0) msg <- .singleStringError(msg, object, .redDimType) for (field in c(.redDimXAxis, .redDimYAxis)) { if (length(val <- object[[field]])!=1 || is.na(val) || val <= 0L) { msg <- c(msg, sprintf("'%s' must be a single positive integer", field)) } } if (length(msg)>0) { return(msg) } TRUE }) setMethod(".defineDataInterface", "ReducedDimensionPlot", function(x, se, select_info) { cur_reddim <- slot(x, .redDimType) max_dim <- ncol(reducedDim(se, cur_reddim)) choices <- seq_len(max_dim) .addSpecificTour(class(x)[1], .redDimType, function(plot_name) { data.frame( rbind( c( element=paste0(" intro="Here, we can select the type of dimensionality reduction result to show. The choices are extracted from the <code>reducedDims</code> of a <code>SingleCellExperiment</code> object. These results should be loaded into the object prior to calling <strong>iSEE</strong> - they are not computed on the fly." ) ) ) }) .addSpecificTour(class(x)[1], .redDimXAxis, function(plot_name) { data.frame( rbind( c( element=paste0(" intro="Given a particular <code>reducedDim</code> entry to visualize, this field specifies the dimension to show on the x-axis." ) ) ) }) .addSpecificTour(class(x)[1], .redDimYAxis, function(plot_name) { data.frame( rbind( c( element=paste0(" intro="Given a particular <code>reducedDim</code> entry to visualize, this field specifies the dimension to show on the y-axis." ) ) ) }) list( .selectInput.iSEE(x, .redDimType, label="Type:", choices=.getCachedCommonInfo(se, "ReducedDimensionPlot")$valid.reducedDim.names, selected=cur_reddim), .selectInput.iSEE(x, .redDimXAxis, label="Dimension 1:", choices=choices, selected=slot(x, .redDimXAxis)), .selectInput.iSEE(x, .redDimYAxis, label="Dimension 2:", choices=choices, selected=slot(x, .redDimYAxis)) ) }) setMethod(".createObservers", "ReducedDimensionPlot", function(x, se, input, session, pObjects, rObjects) { callNextMethod() plot_name <- .getEncodedName(x) .createProtectedParameterObservers(plot_name, fields=c(.redDimXAxis, .redDimYAxis), input=input, pObjects=pObjects, rObjects=rObjects) cur_field <- paste0(plot_name, "_", .redDimType) dim_fieldX <- paste0(plot_name, "_", .redDimXAxis) dim_fieldY <- paste0(plot_name, "_", .redDimYAxis) observeEvent(input[[cur_field]], { matched_input <- as(input[[cur_field]], typeof(pObjects$memory[[plot_name]][[.redDimType]])) if (identical(matched_input, pObjects$memory[[plot_name]][[.redDimType]])) { return(NULL) } pObjects$memory[[plot_name]][[.redDimType]] <- matched_input new_max <- ncol(reducedDim(se, matched_input)) capped_X <- pmin(new_max, pObjects$memory[[plot_name]][[.redDimXAxis]]) capped_Y <- pmin(new_max, pObjects$memory[[plot_name]][[.redDimYAxis]]) pObjects$memory[[plot_name]][[.redDimXAxis]] <- capped_X pObjects$memory[[plot_name]][[.redDimYAxis]] <- capped_Y new_choices <- seq_len(new_max) updateSelectInput(session, dim_fieldX, choices=new_choices, selected=capped_X) updateSelectInput(session, dim_fieldY, choices=new_choices, selected=capped_Y) .requestCleanUpdate(plot_name, pObjects, rObjects) }, ignoreInit=TRUE) invisible(NULL) }) setMethod(".fullName", "ReducedDimensionPlot", function(x) "Reduced dimension plot") setMethod(".panelColor", "ReducedDimensionPlot", function(x) " setMethod(".generateDotPlotData", "ReducedDimensionPlot", function(x, envir) { data_cmds <- list() data_cmds[["reducedDim"]] <- sprintf( "red.dim <- reducedDim(se, %s);", deparse(slot(x, .redDimType))) data_cmds[["xy"]] <- sprintf( "plot.data <- data.frame(X=red.dim[, %i], Y=red.dim[, %i], row.names=colnames(se));", slot(x, .redDimXAxis), slot(x, .redDimYAxis)) plot_title <- slot(x, .redDimType) x_lab <- sprintf("Dimension %s", slot(x, .redDimXAxis)) y_lab <- sprintf("Dimension %s", slot(x, .redDimYAxis)) data_cmds <- unlist(data_cmds) .textEval(data_cmds, envir) list(commands=data_cmds, labels=list(title=plot_title, X=x_lab, Y=y_lab)) }) setMethod(".definePanelTour", "ReducedDimensionPlot", function(x) { collated <- character(0) collated <- rbind( c(paste0(" .addTourStep(x, .dataParamBoxOpen, "The <i>Data parameters</i> box shows the available parameters that can be tweaked in this plot.<br/><br/><strong>Action:</strong> click on this box to open up available options.") ) rbind( data.frame(element=collated[,1], intro=collated[,2], stringsAsFactors=FALSE), callNextMethod() ) })
timestamp <- Sys.time() library(caret) library(plyr) library(recipes) library(dplyr) model <- "svmLinearWeights2" set.seed(2) training <- twoClassSim(50, linearVars = 2) testing <- twoClassSim(500, linearVars = 2) trainX <- training[, -ncol(training)] trainY <- training$Class rec_cls <- recipe(Class ~ ., data = training) %>% step_center(all_predictors()) %>% step_scale(all_predictors()) cctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all") cctrl2 <- trainControl(method = "LOOCV") cctrl3 <- trainControl(method = "none") set.seed(849) test_class_cv_model <- train(trainX, trainY, method = "svmLinearWeights2", trControl = cctrl1, tuneLength = 2, preProc = c("center", "scale")) set.seed(849) test_class_cv_form <- train(Class ~ ., data = training, method = "svmLinearWeights2", trControl = cctrl1, tuneLength = 2, preProc = c("center", "scale")) test_class_pred <- predict(test_class_cv_model, testing[, -ncol(testing)]) test_class_pred_form <- predict(test_class_cv_form, testing[, -ncol(testing)]) set.seed(849) test_class_loo_model <- train(trainX, trainY, method = "svmLinearWeights2", trControl = cctrl2, tuneLength = 2, preProc = c("center", "scale")) set.seed(849) test_class_none_model <- train(trainX, trainY, method = "svmLinearWeights2", trControl = cctrl3, tuneGrid = test_class_cv_model$bestTune, preProc = c("center", "scale")) test_class_none_pred <- predict(test_class_none_model, testing[, -ncol(testing)]) set.seed(849) test_class_rec <- train(x = rec_cls, data = training, method = "svmLinearWeights2", tuneLength = 2, trControl = cctrl1) if( !isTRUE( all.equal(test_class_cv_model$results, test_class_rec$results)) ) stop("CV weights not giving the same results") test_class_imp_rec <- varImp(test_class_rec) test_class_pred_rec <- predict(test_class_rec, testing[, -ncol(testing)]) test_levels <- levels(test_class_cv_model) if(!all(levels(trainY) %in% test_levels)) cat("wrong levels") test_class_predictors1 <- predictors(test_class_cv_model) test_class_predictors2 <- predictors(test_class_cv_model$finalModel) tests <- grep("test_", ls(), fixed = TRUE, value = TRUE) sInfo <- sessionInfo() timestamp_end <- Sys.time() save(list = c(tests, "sInfo", "timestamp", "timestamp_end"), file = file.path(getwd(), paste(model, ".RData", sep = ""))) if(!interactive()) q("no")
abc = 123 ghi <- 456
gen_new_active_sets <- function(s, delta) { k <- length(s) Z <- list() if (length(delta) == 0) { return (Z) } delta_k <- list() counter <- 1 for (i in seq_along(delta)) { if (length(delta[[i]]) == k) { delta_k[[counter]] <- delta[[i]] counter <- counter + 1 } } delta_k[[counter]] <- s supp <- table(unlist(delta_k)) omega <- setdiff(strtoi(names(supp[supp >= k])), s) counter <- 1 if (all(supp[match(s, names(supp))] >= k)) { for (a in omega) { r <- sort(c(s, a)) if (all(combn(r, k, simplify = FALSE) %in% delta_k)) { Z[[counter]] <- r counter <- counter + 1 } } } return(Z) }
RunModel_GR4J <- function(InputsModel, RunOptions, Param) { NParam <- 4 FortranOutputs <- .FortranOutputs(GR = "GR4J")$GR if (!inherits(InputsModel, "InputsModel")) { stop("'InputsModel' must be of class 'InputsModel'") } if (!inherits(InputsModel, "daily")) { stop("'InputsModel' must be of class 'daily'") } if (!inherits(InputsModel, "GR")) { stop("'InputsModel' must be of class 'GR'") } if (!inherits(RunOptions, "RunOptions")) { stop("'RunOptions' must be of class 'RunOptions'") } if (!inherits(RunOptions, "GR")) { stop("'RunOptions' must be of class 'GR'") } if (!is.vector(Param) | !is.numeric(Param)) { stop("'Param' must be a numeric vector") } if (sum(!is.na(Param)) != NParam) { stop(paste("'Param' must be a vector of length", NParam, "and contain no NA")) } Param <- as.double(Param) Param_X1X3_threshold <- 1e-2 Param_X4_threshold <- 0.5 if (Param[1L] < Param_X1X3_threshold) { warning(sprintf("Param[1] (X1: production store capacity [mm]) < %.2f\n X1 set to %.2f", Param_X1X3_threshold, Param_X1X3_threshold)) Param[1L] <- Param_X1X3_threshold } if (Param[3L] < Param_X1X3_threshold) { warning(sprintf("Param[3] (X3: routing store capacity [mm]) < %.2f\n X3 set to %.2f", Param_X1X3_threshold, Param_X1X3_threshold)) Param[3L] <- Param_X1X3_threshold } if (Param[4L] < Param_X4_threshold) { warning(sprintf("Param[4] (X4: unit hydrograph time constant [d]) < %.2f\n X4 set to %.2f", Param_X4_threshold, Param_X4_threshold)) Param[4L] <- Param_X4_threshold } if (identical(RunOptions$IndPeriod_WarmUp, 0L)) { RunOptions$IndPeriod_WarmUp <- NULL } IndPeriod1 <- c(RunOptions$IndPeriod_WarmUp, RunOptions$IndPeriod_Run) LInputSeries <- as.integer(length(IndPeriod1)) if ("all" %in% RunOptions$Outputs_Sim) { IndOutputs <- as.integer(1:length(FortranOutputs)) } else { IndOutputs <- which(FortranOutputs %in% RunOptions$Outputs_Sim) } IndPeriod2 <- (length(RunOptions$IndPeriod_WarmUp)+1):LInputSeries ExportDatesR <- "DatesR" %in% RunOptions$Outputs_Sim ExportStateEnd <- "StateEnd" %in% RunOptions$Outputs_Sim if (!is.null(RunOptions$IniResLevels)) { RunOptions$IniStates[1] <- RunOptions$IniResLevels[1] * Param[1] RunOptions$IniStates[2] <- RunOptions$IniResLevels[2] * Param[3] } RESULTS <- .Fortran("frun_gr4j", PACKAGE = "airGR", LInputs = LInputSeries, InputsPrecip = InputsModel$Precip[IndPeriod1], InputsPE = InputsModel$PotEvap[IndPeriod1], NParam = as.integer(length(Param)), Param = Param, NStates = as.integer(length(RunOptions$IniStates)), StateStart = RunOptions$IniStates, NOutputs = as.integer(length(IndOutputs)), IndOutputs = IndOutputs, Outputs = matrix(as.double(-99e9), nrow = LInputSeries, ncol = length(IndOutputs)), StateEnd = rep(as.double(-99e9), length(RunOptions$IniStates)) ) RESULTS$Outputs[RESULTS$Outputs <= -99e8] <- NA RESULTS$StateEnd[RESULTS$StateEnd <= -99e8] <- NA if (ExportStateEnd) { RESULTS$StateEnd[-3L] <- ifelse(RESULTS$StateEnd[-3L] < 0, 0, RESULTS$StateEnd[-3L]) RESULTS$StateEnd <- CreateIniStates(FUN_MOD = RunModel_GR4J, InputsModel = InputsModel, ProdStore = RESULTS$StateEnd[1L], RoutStore = RESULTS$StateEnd[2L], ExpStore = NULL, UH1 = RESULTS$StateEnd[(1:20) + 7], UH2 = RESULTS$StateEnd[(1:40) + (7+20)], GCemaNeigeLayers = NULL, eTGCemaNeigeLayers = NULL, verbose = FALSE) } if (!ExportDatesR & !ExportStateEnd) { OutputsModel <- lapply(seq_len(RESULTS$NOutputs), function(i) RESULTS$Outputs[IndPeriod2, i]) names(OutputsModel) <- FortranOutputs[IndOutputs] } if (ExportDatesR & !ExportStateEnd) { OutputsModel <- c(list(InputsModel$DatesR[RunOptions$IndPeriod_Run]), lapply(seq_len(RESULTS$NOutputs), function(i) RESULTS$Outputs[IndPeriod2, i])) names(OutputsModel) <- c("DatesR", FortranOutputs[IndOutputs]) } if (!ExportDatesR & ExportStateEnd) { OutputsModel <- c(lapply(seq_len(RESULTS$NOutputs), function(i) RESULTS$Outputs[IndPeriod2, i]), list(RESULTS$StateEnd)) names(OutputsModel) <- c(FortranOutputs[IndOutputs], "StateEnd") } if ((ExportDatesR & ExportStateEnd) | "all" %in% RunOptions$Outputs_Sim) { OutputsModel <- c(list(InputsModel$DatesR[RunOptions$IndPeriod_Run]), lapply(seq_len(RESULTS$NOutputs), function(i) RESULTS$Outputs[IndPeriod2, i]), list(RESULTS$StateEnd)) names(OutputsModel) <- c("DatesR", FortranOutputs[IndOutputs], "StateEnd") } rm(RESULTS) class(OutputsModel) <- c("OutputsModel", "daily", "GR") return(OutputsModel) }
skip_on_cran() test_that("The ouput is correct", { data <- SDMtune:::t data@data <- data@data[, 1:4] m <- trainANN(data = data, size = 3) pred <- predict(m@model, data@data) expect_equal(sum(pred >= 0), nrow(data@data)) expect_equal(sum(pred <= 1), nrow(data@data)) })
library(tidyverse) library(fs) library(here) library(glue) library(magick) image_table <- tibble(path = dir_ls(here(), glob = "*.png", recurse = 2)) %>% mutate(file = basename(path), year = as.numeric(str_extract(path, "[0-9]{4}(?=\\/)")), week = as.numeric(str_extract(path, "(?<=week)\\d{1,2}"))) %>% arrange(year, week, file, path) %>% group_by(year, week) %>% mutate(idx = row_number()) %>% ungroup() %>% mutate(tag = glue("tt_{year}_{week}{ifelse(length(idx) > 1, glue('_{idx}'), '')}.png")) %>% mutate(path = as.character(path))
rsq.f <- function(x) { n1<-dim(x)[1] n2<-dim(x)[2] return(.Fortran("rs_rsq",r=as.double(0),as.matrix(x), as.integer(n1),as.integer(n2),PACKAGE="stima")$r) }
require(OpenMx) require(MASS) set.seed(200) a2<-0.5 c2<-0.3 e2<-0.2 rMZ <- a2+c2 rDZ <- .5*a2+c2 DataMZ <- mvtnorm::rmvnorm (1000, c(0,0), matrix(c(1,rMZ,rMZ,1),2,2)) DataDZ <- mvtnorm::rmvnorm (1000, c(0,0), matrix(c(1,rDZ,rDZ,1),2,2)) selVars <- c('t1','t2') dimnames(DataMZ) <- list(NULL,selVars) dimnames(DataDZ) <- list(NULL,selVars) summary(DataMZ) summary(DataDZ) colMeans(DataMZ,na.rm=TRUE) colMeans(DataDZ,na.rm=TRUE) cov(DataMZ,use="complete") cov(DataDZ,use="complete") twinSatModel <- mxModel("twinSat", mxModel("MZ", mxMatrix("Full", 1, 2, T, c(0,0), name="expMeanMZ"), mxMatrix("Lower", 2, 2, T, .5, name="CholMZ"), mxAlgebra(CholMZ %*% t(CholMZ), name="expCovMZ"), mxData(DataMZ, type="raw"), mxFitFunctionML(),mxExpectationNormal("expCovMZ", "expMeanMZ", selVars)), mxModel("DZ", mxMatrix("Full", 1, 2, T, c(0,0), name="expMeanDZ"), mxMatrix("Lower", 2, 2, T, .5, name="CholDZ"), mxAlgebra(CholDZ %*% t(CholDZ), name="expCovDZ"), mxData(DataDZ, type="raw"), mxFitFunctionML(),mxExpectationNormal("expCovDZ", "expMeanDZ", selVars)), mxAlgebra(MZ.objective + DZ.objective, name="twin"), mxFitFunctionAlgebra("twin")) twinSatFit <- mxRun(twinSatModel, suppressWarnings=TRUE) ExpMeanMZ <- mxEval(MZ.expMeanMZ, twinSatFit) ExpCovMZ <- mxEval(MZ.expCovMZ, twinSatFit) ExpMeanDZ <- mxEval(DZ.expMeanDZ, twinSatFit) ExpCovDZ <- mxEval(DZ.expCovDZ, twinSatFit) LL_Sat <- mxEval(objective, twinSatFit) twinSatModelSub1 <- twinSatModel twinSatModelSub1$MZ$expMeanMZ <- mxMatrix("Full", 1, 2, T, 0, "mMZ", name="expMeanMZ") twinSatModelSub1$DZ$expMeanDZ <- mxMatrix("Full", 1, 2, T, 0, "mDZ", name="expMeanDZ") twinSatFitSub1 <- mxRun(twinSatModelSub1, suppressWarnings=TRUE) twinSatModelSub2 <- twinSatModelSub1 twinSatModelSub2$MZ$expMeanMZ <- mxMatrix("Full", 1, 2, T, 0, "mean", name="expMeanMZ") twinSatModelSub2$DZ$expMeanDZ <- mxMatrix("Full", 1, 2, T, 0, "mean", name="expMeanDZ") twinSatFitSub2 <- mxRun(twinSatModelSub2, suppressWarnings=TRUE) LL_Sat <- mxEval(objective, twinSatFit) LL_Sub1 <- mxEval(objective, twinSatFitSub1) LRT1 <- LL_Sub1 - LL_Sat LL_Sub2 <- mxEval(objective, twinSatFitSub2) LRT2 <- LL_Sub2 - LL_Sat twinACEModel <- mxModel("twinACE", mxMatrix("Full", 1, 2, T, 20, "mean", name="expMean"), mxMatrix("Full", nrow=1, ncol=1, free=TRUE, values=.6, label="a", name="X"), mxMatrix("Full", nrow=1, ncol=1, free=TRUE, values=.6, label="c", name="Y"), mxMatrix("Full", nrow=1, ncol=1, free=TRUE, values=.6, label="e", name="Z"), mxAlgebra(X * t(X), name="A"), mxAlgebra(Y * t(Y), name="C"), mxAlgebra(Z * t(Z), name="E"), mxAlgebra(rbind(cbind(A+C+E , A+C), cbind(A+C , A+C+E)), name="expCovMZ"), mxModel("MZ", mxData(DataMZ, type="raw"), mxFitFunctionML(),mxExpectationNormal("twinACE.expCovMZ", "twinACE.expMean",selVars)), mxAlgebra(rbind(cbind(A+C+E , .5%x%A+C), cbind(.5%x%A+C , A+C+E)), name="expCovDZ"), mxModel("DZ", mxData(DataDZ, type="raw"), mxFitFunctionML(),mxExpectationNormal("twinACE.expCovDZ", "twinACE.expMean",selVars)), mxAlgebra(MZ.objective + DZ.objective, name="twin"), mxFitFunctionAlgebra("twin")) twinACEFit <- mxRun(twinACEModel, suppressWarnings=TRUE) LL_ACE <- mxEval(objective, twinACEFit) LRT_ACE= LL_ACE - LL_Sat MZc <- mxEval(expCovMZ, twinACEFit) DZc <- mxEval(expCovDZ, twinACEFit) M <- mxEval(expMean, twinACEFit) A <- mxEval(A, twinACEFit) C <- mxEval(C, twinACEFit) E <- mxEval(E, twinACEFit) V <- (A+C+E) a2 <- A/V c2 <- C/V e2 <- E/V ACEest <- rbind(cbind(A,C,E),cbind(a2,c2,e2)) ACEest <- data.frame(ACEest, row.names=c("Variance Components","Standardized VC")) names(ACEest)<-c("A", "C", "E") ACEest; LL_ACE; LRT_ACE twinAEModel <- twinACEModel twinAEModel$twinACE$Y <- mxMatrix("Full", 1, 1, F, 0, "c", name="Y") twinAEFit <- mxRun(twinAEModel, suppressWarnings=TRUE) LL_AE <- mxEval(objective, twinAEFit) MZc <- mxEval(expCovMZ, twinAEFit) DZc <- mxEval(expCovDZ, twinAEFit) M <- mxEval(expMean, twinAEFit) A <- mxEval(A, twinAEFit) C <- mxEval(C, twinAEFit) E <- mxEval(E, twinAEFit) V <- (A+C+E) a2 <- A/V c2 <- C/V e2 <- E/V AEest <- rbind(cbind(A,C,E),cbind(a2,c2,e2)) AEest <- data.frame(ACEest, row.names=c("Variance Components","Standardized VC")) names(ACEest)<-c("A", "C", "E") AEest; LL_AE; LRT_ACE_AE <- LL_AE - LL_ACE LRT_ACE_AE
test_that( desc = "checking gghistostats plot and parametric stats - data with NAs", code = { skip_on_cran() set.seed(123) p <- gghistostats( data = dplyr::starwars, x = height, xlab = "character height", title = "starwars: character heights", binwidth = 20, bin.args = list( col = "black", fill = "orange", alpha = 0.7 ), test.value = 150, bf.prior = 0.9 ) pb <- ggplot2::ggplot_build(p) set.seed(123) expect_snapshot(pb$data) expect_null(pb$layout$panel_params[[1]]$y.sec.labels, NULL) set.seed(123) p_subtitle <- statsExpressions::one_sample_test( data = dplyr::starwars, x = height, type = "p", test.value = 150 )$expression[[1]] set.seed(123) p_cap <- statsExpressions::one_sample_test( data = dplyr::starwars, x = height, type = "bayes", test.value = 150, bf.prior = 0.9 )$expression[[1]] expect_equal(pb$plot$labels$subtitle, p_subtitle, ignore_attr = TRUE) expect_equal(pb$plot$labels$caption, p_cap, ignore_attr = TRUE) expect_snapshot(within(pb$plot$labels, rm(subtitle, caption))) } ) test_that( desc = "checking gghistostats and non-parametric stats - data without NAs", code = { skip_on_cran() set.seed(123) p <- gghistostats( data = ggplot2::mpg, x = cty, xlab = "city miles per gallon", title = "fuel economy", caption = "source: government website", binwidth = 5, test.value = 20, k = 3, type = "np", results.subtitle = FALSE ) pb <- ggplot2::ggplot_build(p) set.seed(123) expect_snapshot(pb$data) expect_equal(pb$layout$panel_params[[1]]$x$limits, c(7.5, 37.5)) expect_equal( pb$layout$panel_params[[1]]$x$breaks, c(NA, 10, 20, 30, NA) ) expect_equal( pb$layout$panel_params[[1]]$y$breaks, c(0, 25, 50, 75, 100) ) expect_snapshot(pb$layout$panel_params[[1]]$y.sec$break_info) expect_snapshot(pb$plot$labels) } ) test_that( desc = "checking robust stats and proportions", code = { skip_on_cran() set.seed(123) p <- gghistostats( data = mtcars, x = wt, binwidth = 0.5, test.value = 2.5, type = "r" ) + scale_x_continuous(limits = c(1, 6)) pb <- ggplot2::ggplot_build(p) set.seed(123) p_subtitle <- statsExpressions::one_sample_test( data = mtcars, x = wt, test.value = 2.5, type = "r" )$expression[[1]] expect_equal(pb$plot$labels$subtitle, p_subtitle, ignore_attr = TRUE) set.seed(123) expect_snapshot(pb$data) expect_snapshot(within(pb$plot$labels, rm(subtitle))) } ) test_that( desc = "checking if normal curve work", code = { skip_on_cran() set.seed(123) p1 <- gghistostats( data = ggplot2::msleep, x = awake, binwidth = 1, results.subtitle = FALSE, normal.curve = TRUE, normal.curve.args = list( color = "red", size = 0.8 ) ) pb1 <- ggplot2::ggplot_build(p1) set.seed(123) expect_snapshot(pb1$data) expect_snapshot(pb1$plot$labels) } ) test_that( desc = "subtitle output", code = { skip_on_cran() set.seed(123) p_sub <- gghistostats( data = ggplot2::msleep, x = brainwt, type = "np", output = "subtitle", test.value = 0.25 ) set.seed(123) sub <- statsExpressions::one_sample_test( data = ggplot2::msleep, x = brainwt, type = "np", test.value = 0.25 )$expression[[1]] expect_equal(p_sub, sub, ignore_attr = TRUE) } )
do_stats_teams <- function(df_games, season, competition, type_season){ Compet <- Season <- Type_season <- Name <- CombinID <- NULL Position <- Nationality <- Type_season <- Type_stats <- NULL GP <- GS <- MP <- Team <- Game <- Type <- PTSrv <- PTSrv_mean <- NULL FGPerc <- FGA <- FG <- TwoPPerc <- TwoPA <- TwoP <- NULL ThreePPerc <- ThreePA <- ThreeP <- FTPerc <- FTA <- NULL FT <- EFGPerc <- PTS <- NULL if (type_season == "All") { df_games1 <- df_games %>% filter(Compet == competition, Season == season) }else{ df_games1 <- df_games %>% filter(Compet == competition, Season == season, Type_season == type_season) } df_games1 <- do_add_adv_stats(df_games1) games_played <- df_games1 %>% group_by(Team) %>% distinct(Game) %>% count() if (type_season == "All") { df_games2 <- do_stats(df_games1, "Total", unique(df_games1$Season), unique(df_games1$Compet), "All") }else{ df_games2 <- do_stats(df_games1, "Total", unique(df_games1$Season), unique(df_games1$Compet), unique(df_games1$Type_season)) } df_team <- df_games2 %>% ungroup() %>% select(-c(Name, CombinID, Position, Nationality, Season, Compet, Type_season, Type_stats)) %>% select(-GP, -GS, -MP, -contains("Perc")) %>% group_by(Team) %>% summarise_all(sum) df_team1 <- left_join(df_team, games_played) %>% rename(GP = n) df_team2 <- df_team1 %>% select(Team, GP, everything()) %>% mutate(FGPerc = ifelse(FGA == 0, 0, round((FG / FGA) * 100))) %>% mutate(TwoPPerc = ifelse(TwoPA == 0, 0, round((TwoP / TwoPA) * 100))) %>% mutate(ThreePPerc = ifelse(ThreePA == 0, 0, round((ThreeP / ThreePA) * 100))) %>% mutate(FTPerc = ifelse(FTA == 0, 0, round((FT / FTA) * 100))) %>% mutate(EFGPerc = ifelse(FGA == 0, 0, (FG + 0.5 * ThreeP) / FGA)) %>% mutate(EFGPerc = round(EFGPerc * 100)) %>% mutate(EFGPerc = ifelse(EFGPerc > 100, 100, EFGPerc)) %>% select(1:5, FGPerc, 6:7, TwoPPerc, 8:9, ThreePPerc, 10:11, FTPerc, 12:27, EFGPerc, everything()) df_team_mean <- df_team2 %>% select(-contains("Perc")) df_team_mean_aux <- apply(df_team_mean[,-c(1,2)], 2, "/", df_team_mean$GP) df_team_mean_aux1 <- as.data.frame(df_team_mean_aux) df_team_mean1 <- cbind(df_team_mean[,1:2], df_team_mean_aux1) df_team_mean2 <- df_team_mean1 %>% mutate(FGPerc = ifelse(FGA == 0, 0, round((FG / FGA) * 100))) %>% mutate(TwoPPerc = ifelse(TwoPA == 0, 0, round((TwoP / TwoPA) * 100))) %>% mutate(ThreePPerc = ifelse(ThreePA == 0, 0, round((ThreeP / ThreePA) * 100))) %>% mutate(FTPerc = ifelse(FTA == 0, 0, round((FT / FTA) * 100))) %>% mutate(EFGPerc = ifelse(FGA == 0, 0, (FG + 0.5 * ThreeP) / FGA)) %>% mutate(EFGPerc = round(EFGPerc * 100)) %>% mutate(EFGPerc = ifelse(EFGPerc > 100, 100, EFGPerc)) %>% select(1:5, FGPerc, 6:7, TwoPPerc, 8:9, ThreePPerc, 10:11, FTPerc, 12:27, EFGPerc, everything()) df_team_mean2[, 3:ncol(df_team_mean2)] <- round(df_team_mean2[, 3:ncol(df_team_mean2)], 1) teams <- df_team_mean2$Team df_defense <- data.frame() for (i in teams) { team_Game <- unique(df_games1$Game[df_games1$Team == i]) df_defense_team <- df_games1 %>% filter(Game %in% team_Game) %>% group_by(Team) %>% mutate(Type = ifelse(Team == i, "Offense", "Defense")) df_defense_team1 <- df_defense_team %>% filter(Type == "Defense") %>% ungroup() %>% summarise(PTSrv = sum(PTS)) %>% mutate(Team = i) %>% mutate(PTSrv_mean = round(PTSrv / games_played$n[games_played$Team == i], 1)) df_defense <- bind_rows(df_defense, df_defense_team1) } df_team3 <- left_join(df_team2, df_defense) %>% select(-PTSrv_mean) %>% select(Team, GP, PTS, PTSrv, everything()) df_team_mean3 <- left_join(df_team_mean2, df_defense) %>% select(-PTSrv) %>% select(Team, GP, PTS, PTSrv_mean, everything()) %>% rename(PTSrv = PTSrv_mean) return(list(df_team_total = df_team3, df_team_mean = df_team_mean3)) }
bias_correction <- function(components, b){ A <- grab_bread(components) A_i <- grab_bread_list(components) B_i <- grab_meat_list(components) Ainv <- solve(A) H_i <- lapply(A_i, function(m){ diag( (1 - pmin(b, diag(m %*% Ainv) ) )^(-0.5) ) }) Bbc_i <- lapply(seq_along(B_i), function(i){ H_i[[i]] %*% B_i[[i]] %*% H_i[[i]] }) Bbc <- apply(simplify2array(Bbc_i), 1:2, sum) compute_sigma(A = A, B = Bbc) } gee_eefun <- function(data, formula, family){ X <- model.matrix(object = formula, data = data) Y <- model.response(model.frame(formula = formula, data = data)) n <- nrow(X) function(theta, alpha, psi){ mu <- family$linkinv(X %*% theta) Dt <- t(X) %*% diag(as.numeric(mu), nrow = n) A <- diag(as.numeric(family$variance(mu)), nrow = n) R <- matrix(alpha, nrow = n, ncol = n) diag(R) <- 1 V <- psi * (sqrt(A) %*% R %*% sqrt(A)) Dt %*% solve(V) %*% (Y - mu) } } g <- gee::gee(breaks~tension, id=wool, data=warpbreaks, corstr="exchangeable") guo <- saws::geeUOmega(g) library(geex) results <- m_estimate( estFUN = gee_eefun, data = warpbreaks, units = 'wool', roots = coef(g), compute_roots = FALSE, outer_args = list(formula = breaks ~ tension, family = gaussian()), inner_args = list(alpha = g$working.correlation[1,2], psi = g$scale), corrections = list( bias_correction_.1 = correction(bias_correction, b = .1), bias_correction_.3 = correction(bias_correction, b = .3))) saws::saws(guo, method = 'd1')$V vcov(results) saws::saws(guo, method = 'd4', bound = 0.1)$V get_corrections(results)[[1]] saws::saws(guo, method = 'd4', bound = 0.3)$V get_corrections(results)[[2]]
aovperm_rnd <- function( formula, data, method, type, np, P, coding_sum, rnd_rotation, new_method = NULL){ if(is.null(coding_sum)){coding_sum = T} if(is.null(new_method)){new_method = F} if(is.null(method)){method = "Rd_kheradPajouh_renaud"} if(!new_method){ method = match.arg(method,c("Rd_kheradPajouh_renaud","Rde_kheradPajouh_renaud","Rd_replic_kheradPajouh_renaud")) } switch(method, "Rd_kheradPajouh_renaud"={funP=function(...){fisher_Rd_kheradPajouh_renaud_rnd(...)}}, "Rde_kheradPajouh_renaud"={funP=function(...){fisher_Rde_kheradPajouh_renaud_rnd(...)}}, "Rd_replic_kheradPajouh_renaud" = {funP=function(...){fisher_Rd_replic_kheradPajouh_renaud_rnd(...)}}, {warning(paste("the method",method, "is not defined. Choose between Rd_kheradPajouh_renaud or Rde_kheradPajouh_renaud. Set new_method = TRUE to allow user-defined functions.")) funP=function(...){eval(parse(text=paste("fisher_",method,"_rnd(...)",sep="",collpase="")))}}) terms<-terms(formula,special="Error",data=data) ind_error <- attr(terms, "specials")$Error error_term <- attr(terms, "variables")[[1 + ind_error]] formula_f <- update(formula, paste(". ~ .-",deparse(error_term, width.cutoff = 500L, backtick = TRUE))) e_term <- deparse(error_term[[2L]], width.cutoff = 500L,backtick = TRUE) formula_allfixed <- as.formula(paste(c(formula_f[[2]],"~",formula_f[[3]],"+",e_term),collapse="")) formula_within <- formula(paste("~", e_term, collapse = "")) formula_within<- formula(paste("~",deparse(error_term[[2]][[3]]),collapse="")) formula_id <- formula(paste("~",deparse(error_term[[2]][[2]]),collapse = "")) mf <- model.frame(formula = formula_allfixed, data = data) if(coding_sum){mf <- changeContrast(mf, contr = contr.sum)} mf_f <- model.frame(formula = formula_f, data = mf) mf_id <- model.frame(formula = formula_id, data = as.data.frame(lapply(mf,function(col){ col = as.factor(col) contrasts(col) = contr.sum col}))) y <- model.response(mf) link = link(formula_f=formula_f,formula_within=formula_within) mm_f <- model.matrix(attr(mf_f, "terms"), data = mf_f) mm_id <- model.matrix(attr(mf_id, "terms"), data = mf_id)[,-1,drop=F] name <- colnames(mm_f) checkBalancedData(fixed_formula = formula_f, data = cbind(y,mf)) if (is.null(P)) {P = Pmat(np = np, n = length(y), type = type)} type = attr(P,"type") np = np(P) args <- list(y = y, mm = mm_f, mm_id = mm_id, link = link, P = P) distribution<-sapply(1:max(attr(mm_f,"assign")),function(i){ args$i = i funP(args = args)}) distribution = matrix(distribution,nrow=np) colnames(distribution) = attr(attr(mf_f,"terms"),"term.labels") check_distribution(distribution = distribution, digits = 10, n_unique = 200) table = anova_table_rnd(args) rownames(table) = attr(attr(mf_f,"terms"),"term.labels") permutation_pvalue = apply(distribution,2,function(d){compute_pvalue(distribution = d,alternative="two.sided", na.rm = T)}) table$'resampled P(>F)' = permutation_pvalue table = table[order(link[3,], link[1,]),] distribution = distribution[,order(link[3,], link[1,])] attr(table,"type") <- paste0("Resampling test using ",method," to handle nuisance variables and ",np," ", attr(P,"type"),"s.") out=list() out$y = y out$model.matrix = mm_f out$model.matrix_id = mm_id = mm_id out$link = link out$P = P out$np = np out$table = table out$distribution = distribution out$data=mf out$method = method out$coding_sum = coding_sum class(out)<-"lmperm" return(out) }
context("Check dashes") test_that("Does not error in math mode", { expect_null(check_dashes(filename = "./check-dashes/ok-despite-math.tex")) expect_null(check_dashes(filename = "./check-dashes/ok-despite-math-2.tex")) expect_null(check_dashes(filename = "./check-dashes/ok-despite-math-3.tex")) expect_null(check_dashes(filename = "./check-dashes/ok-despite-math-4.tex")) }) test_that("Errors if hyphen wrongly typed", { expect_error(check_dashes(filename = "./check-dashes/bad-hyphen.tex"), regexp = "[Hh]yphen") expect_error(check_dashes(filename = "./check-dashes/bad-outside-math-1.tex"), regexp = "[Hh]yphen") }) test_that("Hyphens adjacent are noticed", { expect_error(check_dashes("./check-dashes/hyphens-adj-dash-1.tex"), regexp = "[Hh]yphen adjacent to en-dash.") expect_error(check_dashes("./check-dashes/hyphens-adj-dash-2.tex"), regexp = "[Hh]yphen adjacent to en-dash.") }) test_that("Emdashes detected", { expect_error(check_dashes("./check-dashes/has-emdash-1.tex"), regexp = "[Ee]m-dash") }) test_that("emdashes are ok when protasis", { expect_error(check_dashes("./check-dashes/ok-if-protasis.tex", protases_ok = FALSE), regexp = "[Ee]m-dash") expect_null(check_dashes("./check-dashes/ok-if-protasis.tex", protases_ok = TRUE)) }) test_that("emdashes are ok when requested", { skip_on_cran() tempf <- tempfile(fileext = ".tex") writeLines(c("A -- B", "C---D", "x-y", "\\(x - y\\)"), tempf) expect_error(check_dashes(tempf), "Em") expect_null(check_dashes(tempf, dash.consistency = c("en-dash", "em-dash"))) expect_error(check_dashes(tempf, dash.consistency = c("em-dash")), "En") })
selectnhighest <- function(dif, inputter, nlim) { rnk <- rank(dif) if (length(nlim) > length(inputter)) { stop(paste("cannot rake on", nlim, "variables. Too few targets specified")) } found <- inputter[rnk <= nlim] found }
simTermTaxa <- function(ntaxa, sumRate = 0.2){ tree <- deadTree(ntaxa = ntaxa, sumRate = sumRate) termEdge <- sapply(tree$edge[,2],function(x) any(x == (1:ntaxa)) ) taxonDurations <- tree$edge.length[termEdge] nodeDist <- node.depth.edgelength(tree) taxonLADs <- tree$root.time-nodeDist[1:ntaxa] taxonFADs <- taxonLADs+taxonDurations taxonRanges <- cbind(taxonFADs,taxonLADs) rownames(taxonRanges) <- tree$tip.label[tree$edge[termEdge,2]] res <- list(taxonRanges = taxonRanges,tree = tree) return(res) } simTermTaxaAdvanced <- function( p = 0.1, q = 0.1, mintaxa = 1, maxtaxa = 1000, mintime = 1,maxtime = 1000, minExtant = 0,maxExtant = NULL, min.cond = TRUE ){ record <- simFossilRecord( p = p, q = q, r = 0, nruns = 1, nTotalTaxa = c(mintaxa,maxtaxa), totalTime = c(mintime,maxtime), nExtant = c(minExtant,maxExtant), anag.rate = 0, prop.bifurc = 0, prop.cryptic = 0, modern.samp.prob = 1, startTaxa = 1, nSamp = c(0, 1000), tolerance = 10^-4, maxStepTime = 0.01, shiftRoot4TimeSlice = "withExtantOnly", count.cryptic = FALSE, negRatesAsZero = TRUE, print.runs = FALSE, sortNames = FALSE, plot = FALSE ) taxa <- fossilRecord2fossilTaxa(record) tree <- dropZLB(taxa2phylo(taxa)) ntaxa <- Ntip(tree) termEdge <- sapply(tree$edge[,2], function(x) any(x == (1:ntaxa)) ) termNodes <- tree$edge[termEdge,2] taxonDurations <- tree$edge.length[termEdge] nodeDist <- node.depth.edgelength(tree) taxonLADs <- tree$root.time-nodeDist[termNodes] taxonFADs <- taxonLADs+taxonDurations taxonRanges <- cbind(taxonFADs,taxonLADs) rownames(taxonRanges) <- tree$tip.label[termNodes] res <- list(taxonRanges = taxonRanges,tree = tree) return(res) } trueTermTaxaTree <- function(TermTaxaRes,time.obs){ taxR <- TermTaxaRes$taxonRanges nameMatch <- match(names(time.obs),rownames(taxR)) if(any(is.na(nameMatch))){ stop("ERROR: names on time.obs and in TermTaxaRes don't match") } timeObsOutsideRanges <- sapply(1:length(time.obs),function(x) if(is.na(time.obs[x])){ FALSE }else{ (time.obs[x]>taxR[nameMatch[x],1])|(time.obs[x]<taxR[nameMatch[x],2]) }) if(any(timeObsOutsideRanges)){ stop("ERROR: Given time.obs are outside of the original taxon ranges") } tree1 <- TermTaxaRes$tree newDurations <- taxR[nameMatch,1]-time.obs if(is.null(names(time.obs))){ stop("ERROR: No taxon names on observation vector?") } tipMatch <- sapply(1:Ntip(tree1),function(x) which(tree1$tip.label[x] == names(time.obs))) dropTaxa <- character() for(i in 1:Ntip(tree1)){ newDur <- newDurations[tipMatch[i]] if(!is.na(newDur)){ if(tree1$edge.length[tree1$edge[,2] == i]<newDur){ stop("New duration longer than original taxon ranges?") } tree1$edge.length[tree1$edge[,2] == i] <- newDur }else{ dropTaxa <- c(dropTaxa,tree1$tip.label[i]) } } treeNoDrop <- tree1 if(length(dropTaxa)>0){ tree1 <- drop.tip(tree1,dropTaxa) } tree1 <- fixRootTime(treeNoDrop,tree1) return(tree1) } deadTree <- function(ntaxa,sumRate = 0.2){ tree <- ape::rtree(ntaxa) tree$edge.length <- rexp(ntaxa+ntaxa-2,sumRate) tree$root.time <- max(node.depth.edgelength(tree))+200 return(tree) }
tam_np_2pl_irf_probs <- function(x, par0, index, desmat, ...) { par0[index] <- x pred <- desmat %*% par0 TP <- nrow(desmat) p1 <- as.vector( stats::plogis(pred) ) probs <- matrix(0, nrow=2, ncol=TP) probs[2,] <- p1 probs[1,] <- 1 - p1 return(probs) }
render.sigr_cortest <- function(statistic, ..., format, statDigits=4, sigDigits=4, pLargeCutoff=0.05, pSmallCutoff=1.0e-5) { wrapr::stop_if_dot_args(substitute(list(...)), "sigr::render.sigr_cortest") if (missing(format) || is.null(format)) { format <- getRenderingFormat() } if(!isTRUE(format %in% formats)) { format <- "ascii" } fsyms <- syms[format,] stat_format_str <- paste0('%.',statDigits,'g') ct <- statistic$ct pString <- render(wrapSignificance(ct$p.value, symbol='p'), format=format, pLargeCutoff=pLargeCutoff, pSmallCutoff=pSmallCutoff) formatStr <- paste0(fsyms['startB'],ct$method,fsyms['endB'], ': (',fsyms['startI'],'r',fsyms['endI'], '=',sprintf(stat_format_str,ct$estimate), ', ',pString,').') formatStr } wrapCorTest <- function(x,...) { UseMethod('wrapCorTest') } wrapCorTest.htest <- function(x, ...) { wrapr::stop_if_dot_args(substitute(list(...)), "sigr::wrapCorTest.htest") r <- list(ct=x, test='cor.test') class(r) <- c('sigr_cortest', 'sigr_statistic') r } wrapCorTest.data.frame <- function(x, Column1Name, Column2Name, ..., alternative = c("two.sided", "less", "greater"), method = c("pearson", "kendall", "spearman"), exact = NULL, conf.level = 0.95, continuity = FALSE, na.rm= FALSE) { if(!is.numeric(x[[Column1Name]])) { stop("wrapr::wrapCorTest.data.frame column 1 must be numeric") } if(!is.numeric(x[[Column2Name]])) { stop("wrapr::wrapCorTest.data.frame column 2 must be numeric") } c1 <- x[[Column1Name]] c2 <- x[[Column2Name]] nNA <- sum(is.na(c1) | is.na(c2)) if(na.rm) { goodPosns <- (!is.na(c1)) & (!is.na(c2)) c1 <- c1[goodPosns] c2 <- c2[goodPosns] } n <- length(c1) ct <- stats::cor.test(x=c1,y=c2, alternative = alternative, method = method, exact = exact, conf.level = conf.level, continuity = continuity, ...) r <- list(ct=ct, test='cor.test', Column1Name=Column1Name, Column2Name=Column2Name, n=n, nNA=nNA) class(r) <- c('sigr_cortest', 'sigr_statistic') r }
Stacked <- function(data, id.vars = NULL, var.stubs, sep, keep.all = TRUE, keyed = TRUE, keep.rownames = FALSE, ...) { temp1 <- vGrep(var.stubs, names(data)) s <- sort.list(sapply(names(temp1), nchar), decreasing = TRUE) for (i in s) { matches <- temp1[[i]] for (j in 1:length(temp1)) { if (j != i && any(matches %in% temp1[[j]])) { temp1[[j]] <- temp1[[j]][-which(temp1[[j]] %in% matches)] } } } temp <- Names(data, unlist(temp1)) if (sep == ".") sep <- "\\." if (sep == "var.stubs") sep <- .collapseMe(var.stubs, ...) if (is.null(id.vars)) { id.vars <- othernames(data, temp) } else { id.vars <- Names(data, id.vars) } onames <- othernames(data, c(id.vars, temp)) if (!isTRUE(keep.all)) onames <- NULL if (length(onames) == 0) onames <- NULL if (!isTRUE(is.data.table(data))) { data <- as.data.table(data, keep.rownames = keep.rownames) } else { data <- copy(data) } ZZ <- vector("list", length(var.stubs)) names(ZZ) <- var.stubs .SD <- .N <- count <- a <- NULL TimeCols <- lapply(seq_along(var.stubs), function(i) { x <- do.call(rbind, strsplit(names(data)[temp1[[i]]], sep)) if (ncol(x) == 1L) { colnames(x) <- ".time_1" x } else { colnames(x) <- c( ".var", paste(".time", 1:(ncol(x)-1), sep = "_")) x[, -1, drop = FALSE] } }) for (i in seq_along(var.stubs)) { ZZ[[i]] <- cbind( data[, c(id.vars, onames), with = FALSE], data[, list(.values = unlist(.SD, use.names=FALSE)), .SDcols = temp1[[i]]]) setnames(ZZ[[i]], ".values", var.stubs[[i]]) setkeyv(ZZ[[i]], id.vars) ZZ[[i]] <- cbind(ZZ[[i]], TimeCols[[i]]) if (isTRUE(keyed)) { setkeyv(ZZ[[i]], c(key(ZZ[[i]]), colnames(TimeCols[[i]]))) setcolorder(ZZ[[i]], c(key(ZZ[[i]]), var.stubs[[i]], onames)) } } if (length(ZZ) == 1) ZZ[[1]] else ZZ } NULL merged.stack <- function(data, id.vars = NULL, var.stubs, sep, keep.all = TRUE, ...) { temp <- Stacked(data = data, id.vars = id.vars, var.stubs = var.stubs, sep = sep, keep.all = keep.all, keyed = TRUE, ...) if (!is.null(dim(temp))) temp else Reduce(function(x, y) merge(x, y, all = TRUE), temp) }
calc_APA_factor <- function(pRes, Res){ pRes_selection <- pRes[pRes$Source %in% Res$Source, ] pRes_selection$Source <- as.vector(pRes_selection$Source) Res_selection <- Res[Res$Source %in% pRes_selection$Source, ] APA <- by(Res_selection, Res_selection$Source, nrow) / by(pRes_selection, pRes_selection$Source, nrow) APAfactor <- round(as.numeric(apply(Res, 1, function(x) APA[which(names(APA) == x["Source"])])), 2) return(APAfactor) }
CountsEPPM <- function(formula,data,subset=NULL,na.action=NULL,weights=NULL, model.type="mean and scale-factor",model.name="general", link="log",initial=NULL,ltvalue=NA,utvalue=NA, method="Nelder-Mead",control=NULL, fixed.b=NA) { if (model.type!="mean only") { if ((model.name!="general") & (model.name!="general fixed b") & (model.name!="limiting")) { cat("\n","unknown model.name for this model.type","\n") return(object=NULL) } } else { if ((model.name!="Poisson") & (model.name!="negative binomial") & (model.name!="negative binomial fixed b") & (model.name!="Faddy distribution") & (model.name!="Faddy distribution fixed b")) { cat("\n","unknown model.name for this model.type","\n") return(object=NULL) } } if ((method!="Nelder-Mead") & (method!="BFGS")) { cat("\n","unknown function optim method","\n") return(object=NULL) } if ((is.data.frame(data)==FALSE) & (is.list(data)==FALSE)) { cat("\n","Input data is neither data frame nor list.","\n") return(object=NULL) } cl <- match.call() if ((link!="log")) { cat("\n","unknown link function","\n") return(object=NULL) } else { attr(link, which="mean") <- make.link(link) } if (missing(data)) { data <- environment(formula) } mf <- match.call(expand.dots = FALSE) m <- match(c("formula", "data", "subset", "na.action", "weights"), names(mf), 0L) mf <- mf[c(1L, m)] mf$drop.unused.levels <- TRUE FBoth <- Formula(formula) lenFB <- length(FBoth) mf[[1L]] <- as.name("model.frame") wk.name <- attr(FBoth, which="lhs") if (length(wk.name)>1) { cat("\n","more than one variable name on lhs of the formula","\n") return(object=NULL) } if (is.data.frame(data)==TRUE) { data.type <- TRUE mfBoth <- model.frame(FBoth,data=data) resp.var <- model.part(FBoth,data=mfBoth,lhs=1) nvar <- length(data) nobs <- length(data[[1]]) if (nvar==1) { covariates <- NULL } else { covariates <- data } list.data <- lapply(1:nobs, function(i) c(rep(0,resp.var[[1]][i]),1) ) mean.obs <- resp.var[[1]] variance.obs <- rep(0,nobs) scalef.obs <- rep(1,nobs) wkdata <- data.frame(mean.obs,scalef.obs,data) } else { data.type <- FALSE wk.name <- attr(FBoth, which="lhs") nvar <- length(data) nobs <- length(data[[1]]) if (nvar==1) { covariates <- NULL } if ((nvar==1) & (is.list(data[[1]])==TRUE)) { if ((wk.name==names(data)[1])==TRUE) { list.set <- TRUE list.data <- data[[1]] } else { cat("\n","single list with list of data is not named ",wk.name,"\n") return(object=NULL) } } else { list.set <- FALSE for ( i in 1:nvar ) { if (is.list(data[[i]])==TRUE) { if ((wk.name==names(data)[i])==TRUE) { if (list.set==TRUE) { cat("\n","More than one list named ",wk.name," within list of data so","\n") cat("not clear which is the dependent variable.","\n") return(object=NULL) } else { list.data <- data[[i]] list.set <- TRUE } } } else { if (i==1) { covariates <- data.frame(data[1]) names(covariates[1]) <- names(data[1]) } else { if ((i==2) & ((list.set)==TRUE)) { covariates <- data.frame(data[2]) names(covariates[1]) <- names(data[2]) } else { wks <- length(covariates) + 1 covariates <- data.frame(covariates,data[i]) names(covariates[wks]) <- names(data[i]) }}} } } if (list.set==FALSE) { cat("\n","No list named ",wk.name," within list of data.","\n") return(object=NULL) } mean.obs <- rep(0,nobs) variance.obs <- rep(0,nobs) scalef.obs <- rep(1,nobs) for ( i in 1:nobs ) { count <- list.data[[i]] ncount <- sum(count) nmax1 <- length(count) nmax <- nmax1 - 1 cnum <- 0:nmax if (ncount==1) { mean.obs[i] <- t(cnum)%*%count } else { mean.obs[i] <- t(cnum)%*%count/ncount variance.obs[i] <- (t(cnum*cnum)%*%count - ncount*mean.obs[i]*mean.obs[i]) / (ncount - 1) if (mean.obs[i]>0) { scalef.obs[i] <- variance.obs[i]/mean.obs[i] } if (is.na(variance.obs[i])==TRUE) { variance.obs[i] <- 0 } if (is.na(scalef.obs[i])==TRUE) { scalef.obs[i] <- 1 } } } if (is.null(covariates)==TRUE) { wkdata <- data.frame(mean.obs,scalef.obs) } else { wkdata <- data.frame(mean.obs,scalef.obs,covariates) } } if (is.null(weights)==FALSE) { if (is.null(attributes(weights))==TRUE) { attr(weights, which="normalize") <- FALSE } if (attr(weights, which="normalize")==TRUE) { wkv <- c(rep(0, nobs)) wkv <- sapply(1:nobs, function(i) { wkv[i] <- sum(list.data[[i]]) } ) total.n <- sum(wkv) if (is.null(attr(weights, which="norm.to.n"))==FALSE) { total.n <- as.numeric(attr(weights, which="norm.to.n")) } if (data.type==TRUE) { weights <- total.n*weights/sum(weights) } else { weights <- lapply(1:nobs, function(i) { weights[[i]] <- (list.data[[i]]>0)*weights[[i]] } ) wkv <- sapply(1:nobs, function(i) { wkv[i] <- sum(as.numeric(list.data[[i]]*weights[[i]])) } ) weights <- lapply(1:nobs, function(i) { weights[[i]] <- total.n*weights[[i]] / sum(wkv) } ) } } } vnmax <- sapply(list.data,length) - 1 mf$data <- wkdata mf$resp.var <- mean.obs mf$formula <- update(formula(FBoth,lhs=NULL,rhs=1), mean.obs ~ . ) if (data.type==FALSE) { mf$weights=vnmax } wkdata <- eval(mf, parent.frame()) if (model.type=="mean and scale-factor") { mf.scalef <- mf mf.scalef$resp.var <- scalef.obs if (lenFB[2]==2) { mf.scalef$formula <- update(formula(FBoth,lhs=NULL,rhs=2), scalef.obs ~ . ) } else { mf.scalef$formula <- update(formula(FBoth,lhs=NULL,rhs=NULL), scalef.obs ~ 1 ) } temp.wkdata <- eval(mf.scalef, parent.frame()) intersection.var <- intersect(names(wkdata), names(temp.wkdata)) dup.var <- duplicated(c(intersection.var, names(temp.wkdata))) wks <- length(intersection.var) + 1 wke <- length(dup.var) dup.var <- dup.var[wks:wke] temp.wkdata <- subset(temp.wkdata, select=(dup.var==FALSE)) wkdata <- merge(wkdata, temp.wkdata, by=0, incomparables=TRUE, sort=FALSE) } wkdata <- subset(wkdata, select=((names(wkdata)!="(resp.var)") & (names(wkdata)!="Row.names"))) if (is.null(subset)==FALSE) { mean.obs <- mean.obs[subset] variance.obs <- variance.obs[subset] scalef.obs <- scalef.obs[subset] weights <- weights[subset] list.data <- list.data[subset] if (data.type==TRUE) { resp.var <- resp.var[subset] n.var <- n.var[subset] } } if (data.type==TRUE) { wkdata <- data.frame(wkdata, resp.var) } if (is.null(subset)==FALSE) { nobs <- length(wkdata[[1]]) } if (is.null(subset)==FALSE) { nobs <- length(wkdata[[1]]) list.data <- list.data[subset] } offset.var <- NULL wks <- length(wkdata) for ( i in 1:wks) { nchar <- nchar(names(wkdata[i])) if ((nchar>7) & (((substr(names(wkdata[i]), 1, 7)=="offset(")==TRUE) | (substr(names(wkdata[i]), 1, 7)=="offset.")==TRUE)) { offset.var <- wkdata[i] names(offset.var) <- substr(names(wkdata[i]), 8, (nchar-1)) wkdata <- data.frame(wkdata, offset.var) } } wks <- length(wkdata) names(wkdata) <- sapply(1:wks, function(i) { nchar <- nchar(names(wkdata[i])) if ((nchar>7) & ((substr(names(wkdata[i]), 1, 7)=="offset.")==TRUE)) { new.label <- paste("offset(", substr(names(wkdata[i]), 8, (nchar-1)), ")", sep="") names(wkdata[i]) <- new.label } else { names(wkdata[i]) <- names(wkdata[i]) } } ) on.exit(rm(wkdata)) if ((model.type!="mean only") & (model.type!="mean and scale-factor")) { cat("\n","unknown model.type","\n") return(object=NULL) } if (model.type=="mean only") { if (lenFB[2]==2) { cat("\n","model.type is mean only but rhs of formula has two parts to it") cat("\n","2nd part of rhs of formula is ignored","\n") } FBoth <- update(FBoth,mean.obs ~ .) } if (model.type=="mean and scale-factor") { if (lenFB[2]==1) { cat("\n","Model for scale-factor set to intercept only.","\n") FBoth <- update(FBoth,mean.obs | scalef.obs ~ . | 1 ) } else { FBoth <- update(FBoth,mean.obs | scalef.obs ~ . | . ) } } terms.mean <- terms(formula(FBoth,lhs=1,rhs=1)) if (model.type=="mean only") { terms.scalef <- terms(formula( 0 ~ 1 )) } else { if (lenFB[2]==1) { terms.scalef <- terms(formula( 0 ~ 1 )) } else { terms.scalef <- terms(formula(FBoth,lhs=1,rhs=2)) } } terms.full <- terms(formula(FBoth)) if (is.list(list.data)==FALSE) { cat("\n","list.data is not a list","\n") return(object=NULL) } mf.mean <- model.frame(formula(FBoth,lhs=1,rhs=1), data=wkdata) covariates.matrix.mean <- model.matrix(mf.mean, data=wkdata) offset.mean <- model.offset(mf.mean) covariates.matrix.scalef <- matrix(c(rep(1,nrow(covariates.matrix.mean))),ncol=1) offset.scalef <- NULL if (model.type=="mean and scale-factor") { if (lenFB[2]==2) { mf.scalef <- model.frame(formula(FBoth,lhs=2,rhs=2), data=wkdata) covariates.matrix.scalef <- model.matrix(mf.scalef, data=wkdata) offset.scalef <- model.offset(mf.scalef) } } if (is.null(offset.mean)==TRUE) { offset.mean <- c(rep(0,nobs)) } if (is.null(offset.scalef)==TRUE) { offset.scalef <- c(rep(0,nobs)) } if (is.null(initial)==TRUE) { options(warn=-1) if (data.type==TRUE) { if (is.null(weights)==TRUE) { glm.Results <- glm(formula(FBoth,lhs=1,rhs=1),family=poisson(link=link), data=wkdata) } else { wkdata <- data.frame(wkdata, weights) glm.Results <- glm(formula(FBoth,lhs=1,rhs=1),family=poisson(link=link), data=wkdata, weights=weights) } } else { weights.mean <- c(rep(1,nobs)) if (is.null(weights)==FALSE) { weights.mean <- as.vector(sapply(1:nobs, function(i) { weights.mean[i] <- t(weights[[i]])%*%list.data[[i]] } ) ) } weights.mean <- weights.mean*vnmax wkdata <- data.frame(wkdata, weights.mean) glm.Results <- glm(formula(FBoth,lhs=1,rhs=1),family=poisson(link=link), data=wkdata, weights=weights.mean) } options(warn=0) initial.mean <- coefficients(glm.Results) names(initial.mean) <- names(coefficients(glm.Results)) if (model.type=="mean and scale-factor") { glm.Results <- glm(formula(FBoth,lhs=2,rhs=2), family=gaussian(link="log"), subset=(scalef.obs>0), data=wkdata) initial.scalef <- coefficients(glm.Results) names(initial.scalef) <- names(coefficients(glm.Results)) if (model.name=="general") { parameter <- c(initial.mean,initial.scalef,0) names(parameter) <- c(names(initial.mean),names(initial.scalef),"log(b)") } if ((model.name=="general fixed b") | (model.name=="limiting")) { parameter <- c(initial.mean,initial.scalef) names(parameter) <- c(names(initial.mean),names(initial.scalef)) } loglikelihood <- LL.Regression.Counts(parameter,model.type,model.name, link=link,list.data,covariates.matrix.mean,covariates.matrix.scalef, offset.mean,offset.scalef,ltvalue,utvalue,fixed.b,weights,grad.method) wks <- length(initial.scalef) if (model.name=="general") { wk.parameter <- c(initial.mean,rep(0,wks),0) names(wk.parameter) <- c(names(initial.mean),names(initial.scalef),"log(b)") } if ((model.name=="general fixed b") | (model.name=="limiting")) { wk.parameter <- c(initial.mean,rep(0,wks)) names(wk.parameter) <- c(names(initial.mean),names(initial.scalef)) } wk.loglikelihood <- LL.Regression.Counts(wk.parameter,model.type,model.name, link=link,list.data,covariates.matrix.mean,covariates.matrix.scalef, offset.mean,offset.scalef,ltvalue,utvalue,fixed.b,weights,grad.method) if (wk.loglikelihood>loglikelihood) { parameter <- wk.parameter } } if (model.type=="mean only") { if ((model.name=="Poisson") | (model.name=="negative binomial fixed b")) { parameter <- initial.mean names(parameter) <- names(initial.mean) } if (model.name=="negative binomial") { parameter <- c(initial.mean,0) names(parameter) <- c(names(initial.mean),"log(b)") } if (model.name=="Faddy distribution") { parameter <- c(initial.mean,0,0) names(parameter) <- c(names(initial.mean),"c","log(b)") } if (model.name=="Faddy distribution fixed b") { parameter <- c(initial.mean,0) names(parameter) <- c(names(initial.mean),"c") } } } else { npar.one <- ncol(covariates.matrix.mean) numpar <- length(initial) if (model.type=="mean only") { npar <- npar.one loc.c <- npar + 1 if ((model.name=="negative binomial") | (model.name=="Faddy distribution fixed b")) { npar <- loc.c } if (model.name=="Faddy distribution") { npar <- npar + 2 } } if (model.type=="mean and scale-factor") { npar.two <- ncol(covariates.matrix.scalef) npar <- npar.one + npar.two if (model.name=="general") { npar <- npar + 1 } } if (numpar!=npar) { cat("\n","number of parameters error","\n") return(object=NULL) } parameter <- initial if (is.null(names(initial))==TRUE) { cat("\n","WARNING: initial has no associated names","\n") names(parameter) <- 1:numpar } } start <- parameter wks <- length(list.data) if (wks!=nobs) { cat("\n","number of rows of covariates.matrix.mean not equal to length of list.data","\n") return(object=NULL) } output <- Model.Counts(parameter,model.type,model.name,link=link,covariates.matrix.mean, covariates.matrix.scalef,offset.mean,offset.scalef, fixed.b,vnmax) for ( i in 1:nobs) { probability <- output$probabilities[[i]] nmax1 <- vnmax[i] + 1 wks <- sum(probability) if (is.finite(wks)==TRUE) { wks <- round(sum(probability),digits=10) if ((wks<0) | (wks>1)) { cat("\n","improper distribution produced by initial estimates","\n") return(object=NULL) } wks <- sum((round(probability,digits=10)<0) | (round(probability,digits=10)>1)) if (wks>0) { cat("\n","improper distribution produced by initial estimates","\n") return(object=NULL) } } else { cat("\n","improper distribution produced by initial estimates","\n") return(object=NULL) } } if (((model.name=="general fixed b") | (model.name=="negative binomial fixed b") | (model.name=="Faddy distribution fixed b")) & ((is.na(fixed.b)==TRUE) | (fixed.b<=0))) { cat("\n","value of fixed.b is NA or <=0","\n") return(object=NULL) } if ((is.null(initial)==FALSE) & ((model.name=="Faddy distribution") | (model.name=="Faddy distribution fixed b"))) { if (round(parameter[loc.c],digits=4)>=1) { cat("\n","initial c>=1 is not allowed for the Faddy distribution","\n") return(object=NULL) }} npar.mean <- ncol(covariates.matrix.mean) npar <- npar.mean r.parameter.mean <- parameter[1:npar.mean] lp.mean <- covariates.matrix.mean%*%r.parameter.mean + offset.mean if (model.type=="mean and scale-factor") { npar.scalef <- ncol(covariates.matrix.scalef) npar <- npar.mean + npar.scalef wks <- npar.mean + 1 r.parameter.scalef <- parameter[wks:npar] lp.scalef <- covariates.matrix.scalef%*%r.parameter.scalef + offset.scalef } if (method=="BFGS") { if (is.null(attr(method,which="grad.method"))==TRUE) { attr(method,which="grad.method") <- "simple" } if ((attr(method,which="grad.method")!="simple") & (attr(method,which="grad.method")!="Richardson")) { cat("\n","unknown gradient method with method BFGS so reset to simple","\n") attr(method,which="grad.method") <- "simple" } grad.method <- attr(method,which="grad.method") } else { grad.method <- NULL } if (is.null(control)==TRUE) { control=list(fnscale=-1, trace=0) } else { ncontrol <- length(control) wk.control=list(fnscale=-1, trace=0) for ( i in 1:ncontrol) { if ((names(control[i])!="fnscale") & (names(control[i])!="trace") & (names(control[i])!="maxit") & (names(control[i])!="abstol") & (names(control[i])!="reltol") & (names(control[i])!="alpha") & (names(control[i])!="beta") & (names(control[i])!="gamma") & (names(control[i])!="REPORT")) { wkname <- names(control[i]) cat("\n","WARNING: Argument in control is unknown so ignored.","\n") } if (names(control[i])=="fnscale") { wk.control$fnscale <- control[[i]] } if (names(control[i])=="trace") { wk.control$trace <- control[[i]] } if (names(control[i])=="maxit") { wk.control$maxit <- control[[i]] } if (names(control[i])=="abstol") { wk.control$abstol <- control[[i]] } if (names(control[i])=="reltol") { wk.control$reltol <- control[[i]] } if (names(control[i])=="alpha") { wk.control$alpha <- control[[i]] } if (names(control[i])=="beta") { wk.control$beta <- control[[i]] } if (names(control[i])=="gamma") { wk.control$gamma <- control[[i]] } if (names(control[i])=="REPORT") { wk.control$REPORT <- control[[i]] } } control <- wk.control } if (length(parameter)==1) { options(warn=-1) if (data.type==TRUE) { if (is.null(weights)==TRUE) { FBoth_one <- update(FBoth, mean.obs ~ .) glm.Results <- glm(formula(FBoth_one,lhs=1,rhs=1),family=poisson(link=link), data=wkdata) } else { wkdata <- data.frame(wkdata, weights) FBoth_one <- update(FBoth, mean.obs ~ .) glm.Results <- glm(formula(FBoth_one,lhs=1,rhs=1),family=poisson(link=link), data=wkdata, weights=weights) } } else { weights.mean <- c(rep(1,nobs)) if (is.null(weights)==FALSE) { weights.mean <- as.vector(sapply(1:nobs, function(i) { weights.mean[i] <- t(weights[[i]])%*%list.data[[i]] } ) ) } weights.mean <- weights.mean*vnmax wkdata <- data.frame(wkdata, weights.mean) FBoth_one <- update(FBoth, mean.obs ~ . ) glm.Results <- glm(formula(FBoth_one,lhs=1,rhs=1),family=poisson(link=link), data=wkdata, weights=weights.mean) } estimates <- coefficients(glm.Results) options(warn=0) wks <- LL.Regression.Counts(parameter,model.type,model.name,link,list.data, covariates.matrix.mean,covariates.matrix.scalef,offset.mean,offset.scalef, ltvalue,utvalue,fixed.b,weights,grad.method) converged <- FALSE attr(converged, which="code") <- 0 iterations <- glm.Results$iter wk.optim <- list(par=glm.Results$coefficients,value=wks,counts=c(glm.Results$iter, NA), convergence=0,message=NULL) } else { if (method=="Nelder-Mead") { wk.method <- "Nelder-Mead" } else { wk.method <- "BFGS" } wk.optim <- optim(parameter,fn=LL.Regression.Counts,gr=LL.gradient, model.type,model.name,link=link,list.data, covariates.matrix.mean,covariates.matrix.scalef, offset.mean,offset.scalef,ltvalue,utvalue, fixed.b,weights,grad.method, method=wk.method,hessian=FALSE,control=control) if (wk.optim$convergence==0) { converged <- TRUE } else { converged <- FALSE } attr(converged, which="code") <- wk.optim$convergence if (is.null(wk.optim$message)==FALSE) { cat(" message ",wk.optim$message,"\n") } iterations <- wk.optim$counts[1] estimates <- wk.optim$par } names(estimates) <- names(parameter) npar <- length(wk.optim$par) nobs <- nrow(covariates.matrix.mean) mean.par <- rep(0,nobs) variance.par <- rep(1,nobs) variance.limit <- rep(0,nobs) npar.mean <- ncol(covariates.matrix.mean) r.parameter.mean <- rep(0,npar.mean) r.parameter.mean <- wk.optim$par[1:npar.mean] mean.par <- attr(link, which="mean")$linkinv(lp.mean) if (model.type=="mean only") { if ((model.name=="Poisson") | (model.name=="negative binomial fixed b")) { wkv.coefficients <- list(mean.est=wk.optim$par[1:npar.mean], scalef.est=NULL) } else { wks <- npar.mean + 1 wkv.coefficients <- list(mean.est=wk.optim$par[1:npar.mean], scalef.est=wk.optim$par[wks:npar]) } } else { npar.scalef <- ncol(covariates.matrix.scalef) wks <- npar.mean + 1 wkv.coefficients <- list(mean.est=wk.optim$par[1:npar.mean], scalef.est=wk.optim$par[wks:npar]) scalef.par <- exp(lp.scalef) } model.hessian <- hessian(LL.Regression.Counts,x=wk.optim$par, method="Richardson",method.args=list(r=6,eps=1.e-4), model.type=model.type,model.name=model.name,link=link, list.data=list.data, covariates.matrix.mean=covariates.matrix.mean, covariates.matrix.scalef=covariates.matrix.scalef, offset.mean=offset.mean,offset.scalef=offset.scalef, ltvalue=ltvalue,utvalue=utvalue,fixed.b=fixed.b, weights=weights,grad.method=grad.method) if ((model.name=="Faddy distribution") | (model.name=="Faddy distribution fixed b")) { nparm1 <- npar - 1 nparm1sq <- nparm1*nparm1 nparm2 <- nparm1 - 1 wk.hessian <- matrix(c(rep(0,nparm1sq)),ncol=nparm1) if (model.name=="Faddy distribution") { wk.c <- round(estimates[nparm1],digits=7) } else { wk.c <- round(estimates[npar],digits=7) } if ((model.name=="Faddy distribution") & (wk.c==1)) { wk.hessian[1:nparm2,1:nparm2] <- model.hessian[1:nparm2,1:nparm2] wk.hessian[nparm1,] <- c(model.hessian[npar,1:nparm2],model.hessian[npar,npar]) wk.hessian[,nparm1] <- c(model.hessian[1:nparm2,npar],model.hessian[npar,npar]) model.hessian <- wk.hessian } if ((model.name=="Faddy distribution fixed b") & (wk.c==1)) { wk.hessian[1:nparm1,1:nparm1] <- model.hessian[1:nparm1,1:nparm1] model.hessian <- wk.hessian } } deter <- det(model.hessian) wk.npar <- nrow(model.hessian) if ((is.finite(deter)==FALSE) | (deter==0)) { vcov <- matrix(c(rep(NA,(wk.npar*wk.npar))),ncol=wk.npar) } else { if (wk.npar==1) { vcov <- -1/model.hessian } else { condition <- rcond(model.hessian) if (condition>1e-16) { vcov <- - solve(model.hessian) } else { vcov <- matrix(c(rep(NA,(wk.npar*wk.npar))),ncol=wk.npar) }}} colnames(vcov) <- rownames(vcov) <- names(wk.optim$par[1:wk.npar]) output.model <- Model.Counts(wk.optim$par,model.type,model.name,link,covariates.matrix.mean, covariates.matrix.scalef,offset.mean,offset.scalef, fixed.b,vnmax) mean.prob <- rep(0, nobs) vone <- rep(1,nobs) if (model.name=="limiting") { valpha <- output.model$FDparameters$out.valpha vbeta <- output.model$FDparameters$out.vbeta } else { va <- output.model$FDparameters$out.va vb <- output.model$FDparameters$out.vb vc <- output.model$FDparameters$out.vc v1mc <- vone - output.model$FDparameters$out.vc } if ((model.name=="Poisson") | (model.name=="negative binomial") | (model.name=="negative binomial fixed b")) { if (model.name=="Poisson") { mean.prob <- va } else { mean.prob <- vb*(attr(link,which="mean")$linkinv(va) - vone) } } else { if (model.name=="limiting") { mean.prob <- sapply(1:nobs, function(j) mean.prob[j] <- - log(1 - valpha[j]*vbeta[j]) / vbeta[j] ) } else { mean.prob <- sapply(1:nobs, function(j) if ((abs(v1mc[j])<1.e-6)==TRUE) { mean.prob[j] <- vb[j]*(attr(link,which="mean")$linkinv(va[j]) - 1) } else { mean.prob[j] <- vb[j]*((1+va[j]*v1mc[j]/(vb[j]**v1mc[j]))**(1/v1mc[j])-1) } ) } } if (data.type==TRUE) { total.ninlist <- nobs } else { vninlist <- c(rep(0,length(list.data))) vninlist <- sapply(1:length(list.data), function(ilist) vninlist[ilist] <- sum(list.data[[ilist]]) ) total.ninlist <- sum(vninlist) } object <- list(data.type=data.type, list.data=list.data, call=cl, formula=formula, model.type=model.type, model.name=model.name, link=link,covariates.matrix.mean=covariates.matrix.mean, covariates.matrix.scalef=covariates.matrix.scalef, offset.mean=offset.mean,offset.scalef=offset.scalef, ltvalue=ltvalue,utvalue=utvalue,fixed.b=fixed.b, coefficients=wkv.coefficients,loglik=wk.optim$value,vcov=vcov, n=nobs, nobs=nobs, df.null=total.ninlist, df.residual=(total.ninlist-length(wk.optim$par)), vnmax=vnmax, weights=weights,converged=converged, method=method, start=start, optim=wk.optim, control=control, fitted.values=mean.prob, y=mean.obs, terms=list(mean=terms.mean,scale.factor=terms.scalef,full=terms.full)) attr(object, "class") <- c("CountsEPPM") return(object) }
NMixPlugDensMarg.GLMM_MCMC <- function(x, grid, lgrid=500, scaled=FALSE, ...) { if (x$prior.b$priorK != "fixed") stop("only implemented for models with fixed number of components") if (missing(grid)){ grid <- list() if (scaled){ if (x$dimb == 1){ rangeGrid <- 0 + c(-3.5, 3.5)*1 grid[[1]] <- seq(rangeGrid[1], rangeGrid[2], length=lgrid) }else{ for (i in 1:x$dimb){ rangeGrid <- 0 + c(-3.5, 3.5)*1 grid[[i]] <- seq(rangeGrid[1], rangeGrid[2], length=lgrid) } } }else{ if (x$dimb == 1){ rangeGrid <- x$summ.b.Mean["Median"] + c(-3.5, 3.5)*x$summ.b.SDCorr["Median"] grid[[1]] <- seq(rangeGrid[1], rangeGrid[2], length=lgrid) }else{ for (i in 1:x$dimb){ rangeGrid <- x$summ.b.Mean["Median", i] + c(-3.5, 3.5)*x$summ.b.SDCorr["Median", (i-1)*(2*x$dimb - i + 2)/2 + 1] grid[[i]] <- seq(rangeGrid[1], rangeGrid[2], length=lgrid) } } } names(grid) <- paste("b", 1:x$dimb, sep="") } if (x$dimb == 1) if (is.numeric(grid)) grid <- list(b1=grid) if (!is.list(grid)) stop("grid must be a list") if (scaled) scale <- list(shift=0, scale=1) else scale <- x$scale.b return(NMixPlugDensMarg.default(x=grid, scale=scale, w=x$poster.mean.w_b, mu=x$poster.mean.mu_b, Sigma=x$poster.mean.Sigma_b)) }
bimonotone <- function( x, w = matrix( 1, nrow( x ), ncol( x ) ), maxiter = 65536, eps = 1.4901161193847656e-08 ) { n <- nrow( x ) m <- ncol( x ) return( matrix( .C( "bimonotoneC", as.integer( n ), as.integer( m ), x = as.double( x ), as.double( w ), as.integer( maxiter ), as.double( eps ), PACKAGE = "monotone" )$x, n, m ) ) }
.getRawData <- function() { name <- tclvalue(tkgetOpenFile( filetypes = "{ {RData Files} {.RData} {.rda}} { {All Files} * }")) if (name == "") return(data.frame()) temp=print(load(name)) dat=eval(parse(text=temp)) assign("DF", dat, envir = .JFEEnv) importedFileName=last(unlist(strsplit(name,"/"))) assign("importedFileName", importedFileName, envir = .JFEEnv) print(paste("You are loading ",importedFileName,sep=" ")) print(head(dat,3)) } .saveWorkSpace<-function() { file_name <- tkgetSaveFile(defaultextension = "Rsave") if(nchar(fname <- as.character(file_name))) save.image(file = file_name) } .getJFE <- function(x, mode="any", fail=TRUE){ if ((!fail) && (!exists(x, mode=mode, envir=.JFEEnv, inherits=FALSE))) return(NULL) get(x, envir=.JFEEnv, mode=mode, inherits=FALSE) } .variable.list.height=6 .variable.list.width=c(20,Inf) .title.color = as.character(.Tcl("ttk::style lookup TLabelframe.Label -foreground")) .getFrame <- function(object) UseMethod(".getFrame") .getFrame.listbox <- function(object){ object$frame } .defmacro <- function(..., expr){ expr <- substitute(expr) len <- length(expr) expr[3:(len+1)] <- expr[2:len] expr[[2]] <- quote(on.exit(remove(list=objects(pattern="^\\.\\.", all.names=TRUE)))) a <- substitute(list(...))[-1] nn <- names(a) if (is.null(nn)) nn <- rep("", length(a)) for (i in seq(length.out=length(a))){ if (nn[i] == "") { nn[i] <- paste(a[[i]]) msg <- paste(a[[i]], gettext("not supplied", domain="R-JFE")) a[[i]] <- substitute(stop(foo), list(foo = msg)) } } names(a) <- nn a <- as.list(a) ff <- eval(substitute( function(){ tmp <- substitute(body) eval(tmp, parent.frame()) }, list(body = expr))) formals(ff) <- a mm <- match.call() mm$expr <- NULL mm[[1]] <- as.name("macro") expr[[2]] <- NULL attr(ff, "source") <- c(deparse(mm), deparse(expr)) ff } .variableListBox <- function(parentWindow, variableList, bg="white",selectmode="single", export="FALSE", initialSelection=NULL, listHeight=.variable.list.height, title){ if (selectmode == "multiple") selectmode <- .getJFE("multiple.select.mode") if (length(variableList) == 1 && is.null(initialSelection)) initialSelection <- 0 frame <- tkframe(parentWindow) minmax <- .variable.list.width listbox <- tklistbox(frame, height=min(listHeight, length(variableList)), selectmode=selectmode, background=bg, exportselection=export, width=min(max(minmax[1], nchar(variableList)), minmax[2])) scrollbar <- tkscrollbar(frame, command=function(...) tkyview(listbox, ...),repeatinterval=5) tkconfigure(listbox, yscrollcommand=function(...) tkset(scrollbar, ...)) for (var in variableList) tkinsert(listbox, "end", var) if (is.numeric(initialSelection)) for (sel in initialSelection) tkselection.set(listbox, sel) firstChar <- tolower(substr(variableList, 1, 1)) len <- length(variableList) onClick <- function() tkfocus(listbox) toggleSelection <- function(){ active <- tclvalue(tkindex(listbox, "active")) selected <- tclvalue(tkcurselection(listbox)) if (selected == active) tkselection.clear(listbox, "active") else tkselection.set(listbox, "active") } tkbind(listbox, "<ButtonPress-1>", onClick) if (selectmode == "single") tkbind(listbox, "<Control-ButtonPress-1>", toggleSelection) tkgrid(tklabel(frame, text=title, fg=.title.color, font="JFETitleFont"), columnspan=2, sticky="w") tkgrid(listbox, scrollbar, sticky="nw") tkgrid.configure(scrollbar, sticky="wns") tkgrid.configure(listbox, sticky="ewns") result <- list(frame=frame, listbox=listbox, scrollbar=scrollbar, selectmode=selectmode, varlist=variableList) class(result) <- "listbox" result } .getSelection <- function(object) UseMethod(".getSelection") .getSelection.listbox <- function(object){ object$varlist[as.numeric(tkcurselection(object$listbox)) + 1] } .radioButtons <- .defmacro(window, name, buttons, values=NULL, initialValue=..values[1], labels, title="", title.color=.title.color, right.buttons=FALSE, command=function(){}, expr={ ..values <- if (is.null(values)) buttons else values ..frame <- paste(name, "Frame", sep="") assign(..frame, tkframe(window)) ..variable <- paste(name, "Variable", sep="") assign(..variable, tclVar(initialValue)) if(title != ""){ tkgrid(tklabel(eval(parse(text=..frame)), text=title, foreground=.title.color, font="JFETitleFont"), columnspan=2, sticky="w") } for (i in 1:length(buttons)) { ..button <- paste(buttons[i], "Button", sep="") if (right.buttons) { assign(..button, ttkradiobutton(eval(parse(text=..frame)), variable=eval(parse(text=..variable)), value=..values[i], command=command)) tkgrid(tklabel(eval(parse(text=..frame)), text=labels[i], justify="left"), eval(parse(text=..button)), sticky="w") } else{ assign(..button, ttkradiobutton(eval(parse(text=..frame)), variable=eval(parse(text=..variable)), value=..values[i], text=labels[i], command=command)) tkgrid(eval(parse(text=..button)), sticky="w") } } } ) .seriesPlotX <- function(x, labels = TRUE, type = "l", col = "indianred2",title = TRUE, grid = TRUE, box = TRUE, rug = TRUE, ...) { N = NCOL(x) Units = colnames(x) if (length(col) == 1) col = rep(col, times = N) for (i in 1:N) { X = x[, i] plot(x = X, type = type, col = col[i], ann = FALSE, ...) if (title) { title(main = Units[i]) } else { title(...) } if(grid) grid() if(box) box() if(rug) rug(as.vector(X), ticksize = 0.01, side = 2, quiet = TRUE) } invisible() } downloadStockAI <- function (key="5edl69aag5", var.name="TWECO", from="2006-01-01", to="2015-12-31", showdata=TRUE){ path<-"https://stock-ai.com/history-data-download?symbol=" url<-paste0(path,var.name, "&export=csv&startDate=",from,"&endDate=",to,"&key=", key,"&export=.csv") filname<-paste0(var.name,".csv") temp0 <- read.csv(filname) timeID<-temp0[,1] y<-as.matrix(temp0[,2]) colnames(y)<-var.name row.names(y)<-timeID y<-timeSeries::as.timeSeries(y) return(y) if (showdata) { print(head(y)) print(tail(y)) } } ttsDS <- function (y,x=NULL, arOrder=2,xregOrder=0,type=NULL) { if (!is.null(x)) { x=timeSeries::as.timeSeries(x) if ( nrow(y) != nrow(x) ) {print("Variables must have the same rows.")} } if (!timeSeries::is.timeSeries(y)) {stop("Data must be a timeSeries object.")} if (is.null(type)) {type="none" } p=max(arOrder,xregOrder) colNAMES=c(outer(paste0(names(x),"_L"),0:p,FUN=paste0)) if (p==0) { y=y datasetX=x ar0=NULL } else { datasetY=timeSeries::as.timeSeries(embed(y,p+1),timeSeries::time(y)[-c(1:p)]) y=datasetY[,1] ar0=datasetY[,-1] colnames(ar0)=paste0("ar",1:p) if (is.null(x)) {datasetX=NULL } else { datasetX=timeSeries::as.timeSeries(embed(x,p+1),timeSeries::time(x)[-c(1:p)]) colnames(datasetX)=colNAMES } } colnames(y)="y" if (min(arOrder)==0) {ar=NULL } else {ar=ar0[,paste0("ar",arOrder)]} if (is.null(x)) {X=datasetX} else { L.ID=paste0("L",xregOrder) IDx=NULL for (i in L.ID) {IDx=c(IDx,grep(colNAMES,pattern=i))} X=datasetX[,IDx] } DF <- na.omit(cbind(y,ar,X)) trend <- 1:nrow(DF) if (timeSeries::isRegular(y)) { seasonDummy <- data.frame(forecast::seasonaldummy(as.ts(y))) DF0 <- cbind(ar0,X,seasonDummy,trend) } else {DF0 <- cbind(ar0,X,trend)} if (type=="trend") {DF<-cbind(DF,trend)} else if (type=="sesaon") {DF<-cbind(DF,seasonDummy) } else if (type=="both") {DF<-cbind(DF,trend,seasonDummy) } else {DF <- DF} return(DF) }
gl2related <- function(x, outfile="related.txt", outpath=tempdir(), save=TRUE) { gd <- as.matrix(x) mm <- matrix(NA, nrow=nrow(gd), ncol =ncol(gd)*2 ) mm[, seq(1,nLoc(x)*2,2)] <- gd mm <- ifelse(mm==1,0,mm) mm[, seq(2,nLoc(x)*2,2)] <- gd mm <- ifelse(mm==1,2,mm) mm <- mm+1 mm <- ifelse(is.na(mm),0,mm) gtd <- data.frame(V1=as.character(indNames(x)), mm) gtd$V1 <- as.character(gtd$V1) fn <- file.path(outpath, outfile) if (save) write.table(gtd, file = fn, sep = "\t",col.names = F, row.names = F) return(gtd) }
"iwres.dist.qq" <- function(object, ...) { if(is.null(check.vars(c("iwres"),object))) { return(NULL) } xplot <- xpose.plot.qq(xvardef("iwres",object), object, ...) return(xplot) }
with_mock_api({ test_that("dp_values are fetched", { skippy() values <- dp_values() player_values <- dp_values("values-players.csv") player_ids <- dp_playerids() expect_tibble(values, min.rows = 1) expect_tibble(player_ids, min.rows = 1) expect_tibble(player_values, min.rows = 1) }) }) test_that("dp_cleannames removes periods, apostrophes, and suffixes", { player_names <- c("A.J. Green", "Odell Beckham Jr.", "Le'Veon Bell Sr.") cleaned_names <- dp_cleannames(player_names) lowercase_clean <- dp_cleannames(player_names, lowercase = TRUE) expect_equal(cleaned_names, c("AJ Green", "Odell Beckham", "LeVeon Bell")) expect_equal(lowercase_clean, c("aj green", "odell beckham", "leveon bell")) }) test_that("dp_cleannames fixes MFL names and does custom name substitutions", { mixed_names <- c( "Trubisky, Mitch", "Chatarius Atwell", "Zeke Elliott", "Devante Parker", "A.J. Green", "Beckham Jr., Odell" ) custom_cleaned_names <- dp_cleannames(mixed_names, convert_lastfirst = TRUE, use_name_database = TRUE) expect_equal( custom_cleaned_names, c("Mitchell Trubisky", "Tutu Atwell", "Ezekiel Elliott", "DeVante Parker", "AJ Green", "Odell Beckham") ) })
`scores.symcoca` <- function(x, choices = c(1, 2), display = c("sites", "species"), scaling = FALSE, ...) { if (!inherits(x, "symcoca")) stop("x must be of class \"symcoca\"") opts <- c("species", "sites", "loadings", "xmatrix") names(opts) <- c("species", "sites", "loadings", "xmatrix") take <- opts[display] retval <- list() if ("species" %in% take) { retval$species <- if(scaling) { rescale(x, choices = choices, display = "species") } else { list(Y = x$scores$species$Y[, choices, drop = FALSE], X = x$scores$species$X[, choices, drop = FALSE]) } } if ("sites" %in% take) { retval$sites <- if(scaling) { rescale(x, choices = choices, display = "sites") } else { list(Y = x$scores$site$Y[, choices, drop = FALSE], X = x$scores$site$X[, choices, drop = FALSE]) } } retval$loadings <- if ("loadings" %in% take) list(Y = x$loadings$Y[, choices, drop = FALSE], X = x$loadings$X[ choices, drop = FALSE]) retval$xmatrix <- if ("xmatrix" %in% take) x$X[, choices, drop = FALSE] retval }
stopifnot(require("tikzDevice")) require("sfsmisc") x <- (-3:10) * 10^10 y <- abs(x / 1e9) (t.file <- tempfile("tikz-eaxis", fileext = ".tex")) tikz(file = t.file, standAlone=TRUE) plot(x, y, axes=FALSE, type = "b") eaxis(1, at=x, lab.type="latex") eaxis(2, lab.type="latex") dev.off() helvet.lns <- c("\\renewcommand{\\familydefault}{\\sfdefault}", "\\usepackage{helvet}") str(ll <- readLines(t.file)) writeLines(c(ll[1:4], "", "%% Added from R (pkg 'sfsmisc', demo 'pretty-lab'):", helvet.lns, "", ll[-(1:5)]), t.file) system(paste(paste0("pdflatex -output-directory=", dirname(t.file)), t.file)) if(file.exists(p.file <- sub("tex$", "pdf", t.file)) && interactive()) system(paste(getOption("pdfviewer"), p.file), wait=FALSE)
download_format <- function(country, urls, ess_email = NULL, only_download = FALSE, output_dir = NULL) { if (is.null(ess_email)) ess_email <- get_email() authenticate(ess_email) ess_round <- string_extract(urls, "ESS[[:digit:]]") if (only_download && is.null(output_dir)) { stop("`output_dir` should be a valid directory") } alt_dir <- ifelse(only_download, output_dir, tempdir()) if (!missing(country)) { td <- file.path(alt_dir, paste0("ESS_", country), ess_round) } else { td <- file.path(alt_dir, ess_round) } for (dire in td) dir.create(dire, recursive = TRUE, showWarnings = FALSE) mapply(round_downloader, urls, ess_round, td) if (only_download) message("All files saved to ", normalizePath(output_dir)) td } authenticate <- function(ess_email) { if(missing(ess_email)) { stop( "`ess_email` parameter must be specified. Create an account at https://www.europeansocialsurvey.org/user/new" ) } if (nchar(ess_email) == 0) { stop( "The email address you provided is not associated with any registered user. Create an account at https://www.europeansocialsurvey.org/user/new" ) } values <- list(u = ess_email) url_login <- paste0(.global_vars$ess_website, .global_vars$path_login) authen <- httr::POST(url_login, body = values) check_authen <- safe_GET(url_login, query = values) authen_xml <- xml2::read_html(check_authen) error_node <- xml2::xml_find_all(authen_xml, '//p [@class="error"]') if (length(error_node) != 0) { stop(xml2::xml_text(error_node), " Create an account at https://www.europeansocialsurvey.org/user/new") } } round_downloader <- function(each_url, which_round, which_folder) { message(paste("Downloading", which_round)) temp_download <- file.path(which_folder, paste0(which_round, ".zip")) current_file <- safe_GET(each_url, httr::progress()) writeBin(httr::content(current_file, as = "raw") , temp_download) utils::unzip(temp_download, exdir = which_folder) } safe_GET <- function(url, config = list(), ...) { resp_conn <- httr::GET(url = url, config = config, ...) if (httr::status_code(resp_conn) > 300) { stop("We're unable to reach 'www.europeansocialsurvey.org'. Are you connected to the internet or is the website down?'") } resp_conn }
library(RUnit) run_tests <- function() { dirs <- "analysis/R" test_suite <- defineTestSuite("rappor", dirs, testFileRegexp = "_test.R$", testFuncRegexp = "^Test") stopifnot(isValidTestSuite(test_suite)) test_result <- runTestSuite(test_suite) printTextProtocol(test_result) result <- test_result[[1]] if (result$nTestFunc == 0) { cat("No tests found.\n") return(FALSE) } if (result$nFail != 0 || result$nErr != 0) { cat("Some tests failed.\n") return(FALSE) } return(TRUE) } if (!run_tests()) { quit(status = 1) }
emf <- function(file = "Rplot.emf", width=7, height=7, bg = "transparent", fg = "black", pointsize=12, family = "Helvetica", coordDPI = 300, custom.lty=emfPlus, emfPlus=TRUE, emfPlusFont = FALSE, emfPlusRaster = FALSE, emfPlusFontToPath = FALSE) { if (is.na(width) || width < 0 || is.na(height) || height < 0) { stop("emf: both width and height must be positive numbers."); } if (emfPlusFont && emfPlusFontToPath) { stop("emf: at most one of 'emfPlusFont' and 'emfPlusFontToPath' can be TRUE") } .External(devEMF, file, bg, fg, width, height, pointsize, family, coordDPI, custom.lty, emfPlus, emfPlusFont, emfPlusRaster, emfPlusFontToPath) invisible() }
posterior_summary <- function(RD_est, RR_est, OR_est) { RD_mean = mean(RD_est) RD_se = stats::sd(RD_est) RD_lower = stats::quantile(RD_est, probs=0.025, na.rm = T) RD_upper = stats::quantile(RD_est, probs=0.975, na.rm = T) RR_mean = mean(RR_est) RR_se = stats::sd(RR_est) RR_lower = stats::quantile(RR_est, probs=0.025, na.rm = T) RR_upper = stats::quantile(RR_est, probs=0.975, na.rm = T) OR_mean = mean(OR_est) OR_se = stats::sd(OR_est) OR_lower = stats::quantile(OR_est, probs=0.025, na.rm = T) OR_upper = stats::quantile(OR_est, probs=0.975, na.rm = T) RD = c(RD_mean, RD_se, RD_lower, RD_upper) RR = c(RR_mean, RR_se, RR_lower, RR_upper) OR = c(OR_mean, OR_se, OR_lower, OR_upper) res = rbind(RD, RR, OR) colnames(res) = c("EST","SE","LOWER","UPPER") return(res) }
test_that("`plot.see_p_direction()` works", { if (require("bayestestR") && require("rstanarm") && require("ggridges")) { set.seed(123) m <<- stan_glm(Sepal.Length ~ Petal.Width * Species, data = iris, refresh = 0 ) result <- p_direction(m) expect_s3_class(plot(result), "gg") } })
discrepancyCriteria <- function(design, type='all'){ X <- as.matrix(design) dimension <- dim(X)[2] n <- dim(X)[1] if ( n < dimension ){ stop('Warning : the number of points is lower than the dimension.') } if ( min(X)<0 || max(X)>1 ){ warning("The design is rescaling into the unit cube [0,1]^d.") M <- apply(X,2,max) m <- apply(X,2,min) for (j in 1:dim(X)[2]){ X[,j] <- (X[,j]-m[j])/(M[j]-m[j]) } } R <- list() DisC2 <- FALSE DisL2 <- FALSE DisL2star <- FALSE DisM2 <- FALSE DisS2 <- FALSE DisW2 <- FALSE DisMix2 <- FALSE if (length(type)==1 && type=='all'){ type <- c('C2','L2','L2star','M2','S2','W2','Mix2') } for(i in 1:length(type)){ type_ <- type[i] switch(type_, C2 = {DisC2 <- TRUE}, L2 = {DisL2 <- TRUE}, L2star = {DisL2star <- TRUE}, M2 = {DisM2 <- TRUE}, S2 = {DisS2 <- TRUE}, W2 = {DisW2 <- TRUE}, Mix2 = {DisMix2 <- TRUE}) } if(DisC2 == TRUE){ s1 <- 0; s2 <- 0 for (i in 1:n){ p <- prod((1+0.5*abs(X[i,]-0.5)-0.5*((abs(X[i,]-0.5))^2))) s1 <- s1+p for (k in 1:n){ q <- prod((1+0.5*abs(X[i,]-0.5)+0.5*abs(X[k,]-0.5)-0.5*abs(X[i,]-X[k,]))) s2 <- s2+q } } R <- c(R,DisC2 = sqrt(((13/12)^dimension)-((2/n)*s1) + ((1/n^2)*s2))) } if(DisL2 == TRUE){ s1 <- 0; s2 <- 0 for (i in 1:n){ p <- prod(X[i,]*(1-X[i,])) s1 <- s1+p for (k in 1:n){ q <- 1 for (j in 1:dimension){ q <- q*(1-max(X[i,j],X[k,j]))*min(X[i,j],X[k,j]) } s2 <- s2+q } } R <- c(R,DisL2 = sqrt(12^(-dimension) - (((2^(1-dimension))/n)*s1) + ((1/n^2)*s2))) } if(DisL2star == TRUE){ dL2<-0 for (j in 1:n){ for (i in 1:n){ if(i!=j){ t<-c() for (l in 1:dimension) t<-c(t,1-max(X[i,l],X[j,l])) t<-(prod(t))/(n^2) } else{ t1<-1-X[i,] t1<-prod(t1) t2<-1-X[i,]^2 t2<-prod(t2) t<-t1/(n^2)-((2^(1-dimension))/n)*t2 } dL2<-dL2+t} } R <- c(R,DisL2star = sqrt(3^(-dimension)+dL2)) } if(DisM2 == TRUE){ s1 <- 0; s2 <- 0 for (i in 1:n){ p <- 1 p <- prod((3-(X[i,]*X[i,]))) s1 <- s1+p for (k in 1:n){ q <- 1 for (j in 1:dimension){ q <- q*(2-max(X[i,j],X[k,j])) } s2 <- s2+q } } R <- c(R,DisM2 = sqrt(((4/3)^dimension) - (((2^(1-dimension))/n)*s1) + ((1/n^2)*s2))) } if(DisS2 == TRUE){ s1 <- 0; s2 <- 0 for (i in 1:n){ p <- prod((1+(2*X[i,])-(2*X[i,]*X[i,]))) s1 <- s1+p for (k in 1:n){ q <- prod((1-abs(X[i,]-X[k,]))) s2 <- s2+q } } R <- c(R,DisS2 = sqrt(((4/3)^dimension) - ((2/n)*s1) + ((2^dimension/n^2)*s2))) } if(DisW2 == TRUE){ s1 <- 0 for (i in 1:n){ for (k in 1:n){ p <- prod((1.5-((abs(X[i,]-X[k,]))*(1-abs(X[i,]-X[k,]))))) s1 <- s1+p } } R <- c(R , DisW2 = sqrt((-((4/3)^dimension) + ((1/n^2)*s1)))) } if(DisMix2 == TRUE){ s1 <- 0; s2 <- 0 for (i in 1:n){ p <- prod((5/3-0.25*abs(X[i,]-0.5)-0.25*((abs(X[i,]-0.5))^2))) s1 <- s1+p for (k in 1:n){ q <- prod((15/8-0.25*abs(X[i,]-0.5)-0.25*abs(X[k,]-0.5)-0.75*abs(X[i,]-X[k,])+0.5*((abs(X[i,]-X[k,]))^2))) s2 <- s2+q } } R <- c(R,DisMix2 = sqrt(((19/12)^dimension)-((2/n)*s1) + ((1/n^2)*s2))) } return(R) }
ctStanPlotPost<-function(obj, rows='all', npp=6,priorwidth=TRUE, smoothness=1,priorsamples=10000, plot=TRUE,wait=FALSE,...){ if(!(class(obj) %in% c('ctStanFit','ctStanModel'))) stop('not a ctStanFit or ctStanModel object!') plots <- list() densiter <- 1e5 ps <- cbind(obj$setup$popsetup, obj$setup$popvalues) ps <- ps[ps$when %in% c(0,-1) & ps$param > 0 & ps$copyrow < 1 & ps$matrix < 11,] ps <- ps[!duplicated(ps$param),] ps<-ps[order(ps$param),] e<-ctExtract(obj) priors <- ctStanGenerate(cts = obj,parsonly=TRUE,nsamples=priorsamples,...) priors <- priors$stanfit$transformedpars posteriors <- ctExtract(obj) if(rows[1]=='all') rows<-1:nrow(ps) nplots<-ceiling(length(rows) /4) if(1==99) Par.Value <- type <- quantity <- Density <- NULL quantity <- c('Posterior','Prior') for(ploti in 1:nplots){ dat <- data.table(quantity='',Par.Value=0, Density=0,type='',param='') for(ri in if(length(rows) > 1) rows[as.integer(cut_number(rows,nplots))==ploti] else rows){ pname <- ps$parname[ri] pari <- ps[ri,'param'] meanpost <- posteriors$popmeans[,pari] meanprior <- priors$popmeans[,pari] if(priorwidth) xlimsindex <- 'all' else xlimsindex <- 1 mdens <- ctDensityList(list(meanpost, meanprior),probs=c(.05,.95),plot=FALSE, xlimsindex=xlimsindex,cut=TRUE) quantity <- c('Posterior','Prior') for(i in 1:length(mdens$density)){ dat <- rbind(dat,data.table(quantity=quantity[i],Par.Value=mdens$density[[i]]$x, Density=mdens$density[[i]]$y, type='Pop. Mean',param=pname)) } if(ps[ri,'indvarying']>0){ posteriorsd <- posteriors$popsd[,ps$indvarying[ri]] priorsd <- priors$popsd[,ps$indvarying[ri]] sddens <- ctDensityList(list(posteriorsd, priorsd),probs=c(.05,.95),plot=FALSE, xlimsindex=xlimsindex) for(i in 1:length(sddens$density)){ dat <- rbind(dat,data.table(quantity=quantity[i],Par.Value=sddens$density[[i]]$x, Density=sddens$density[[i]]$y, type='Pop. SD',param=pname)) } } } dat <- dat[-1,] plots<-c(plots,list( ggplot(dat,aes(x=Par.Value,fill=quantity,ymax=Density,y=Density) )+ geom_line(alpha=.3) + geom_ribbon(alpha=.4,ymin=0) + scale_fill_manual(values=c('red','blue')) + theme_minimal()+ theme(legend.title = element_blank(), panel.grid.minor = element_line(size = 0.1), panel.grid.major = element_line(size = .2), strip.text.x = element_text(margin = margin(.01, 0, .01, 0, "cm"))) + facet_wrap(vars(type,param),scales='free') )) } if(plot) { firstplot=TRUE lapply(plots,function(x){ if(wait && !firstplot) readline("Press [return] for next plot.") firstplot <<- FALSE suppressWarnings(print(x)) }) return(invisible(NULL)) } else return(plots) }
library(parallel) library(hamcrest) test.detectCores <- function() { cores <- detectCores() print(cores) assertTrue(detectCores() > 0) }
material_spinner_show <- function(session, output_id){ js_code <- paste0( "$(' ) js_code <- gsub(pattern = "DOUBLEQUOTE", replacement = '"', x = js_code) session$sendCustomMessage( type = "shinymaterialJS", js_code ) } material_spinner_hide <- function(session, output_id){ session$sendCustomMessage( type = "shinymaterialJS", paste0( "$(' ) ) session$sendCustomMessage( type = "shinymaterialJS", paste0( "$(' ) ) }
library(sparklyr) rsApiUpdateDialog <- function(code) { if (exists(".rs.api.updateDialog")) { updateDialog <- get(".rs.api.updateDialog") updateDialog(code = code) } } rsApiShowDialog <- function(title, message, url = "") { if (exists(".rs.api.showDialog")) { showDialog <- get(".rs.api.showDialog") showDialog(title, message, url) } } rsApiShowPrompt <- function(title, message, default) { if (exists(".rs.api.showPrompt")) { showPrompt <- get(".rs.api.showPrompt") showPrompt(title, message, default) } } rsApiShowQuestion <- function(title, message, ok, cancel) { if (exists(".rs.api.showQuestion")) { showPrompt <- get(".rs.api.showQuestion") showPrompt(title, message, ok, cancel) } } rsApiReadPreference <- function(name, default) { if (exists(".rs.api.readPreference")) { readPreference <- get(".rs.api.readPreference") value <- readPreference(name) if (is.null(value)) default else value } } rsApiWritePreference <- function(name, value) { if (!is.character(value)) { stop("Only character preferences are supported") } if (exists(".rs.api.writePreference")) { writePreference <- get(".rs.api.writePreference") writePreference(name, value) } } rsApiVersionInfo <- function() { if (exists(".rs.api.versionInfo")) { versionInfo <- get(".rs.api.versionInfo") versionInfo() } } is_java_available <- function() { nzchar(spark_get_java()) } spark_home <- function() { home <- Sys.getenv("SPARK_HOME", unset = NA) if (is.na(home)) home <- NULL home } spark_ui_avaliable_versions <- function() { tryCatch({ spark_available_versions(show_hadoop = TRUE, show_minor = TRUE) }, error = function(e) { warning(e) spark_installed_versions()[,c("spark","hadoop")] }) } spark_ui_spark_choices <- function() { availableVersions <- spark_ui_avaliable_versions() selected <- spark_default_version()[["spark"]] choiceValues <- unique(availableVersions[["spark"]]) choiceNames <- choiceValues choiceNames <- lapply( choiceNames, function(e) if (e == selected) paste(e, "(Default)") else e ) names(choiceValues) <- choiceNames choiceValues } spark_ui_hadoop_choices <- function(sparkVersion) { availableVersions <- spark_ui_avaliable_versions() selected <- spark_install_find(version = sparkVersion, installed_only = FALSE)$hadoopVersion choiceValues <- unique(availableVersions[availableVersions$spark == sparkVersion,][["hadoop"]]) choiceNames <- choiceValues choiceNames <- lapply( choiceNames, function(e) if (length(selected) > 0 && e == selected) paste(e, "(Default)") else e ) names(choiceValues) <- choiceNames choiceValues } spark_ui_default_connections <- function() { getOption( "sparklyr.ui.connections", getOption("rstudio.spark.connections") ) } connection_spark_ui <- function() { elementSpacing <- if (.Platform$OS.type == "windows") 2 else 7 tags$div( tags$head( tags$style( HTML(paste(" body { background: none; font-family : \"Lucida Sans\", \"DejaVu Sans\", \"Lucida Grande\", \"Segoe UI\", Verdana, Helvetica, sans-serif; font-size : 12px; -ms-user-select : none; -moz-user-select : none; -webkit-user-select : none; user-select : none; margin: 0; margin-top: 7px; } select { background: } .shiny-input-container { min-width: 100%; margin-bottom: ", elementSpacing, "px; } .shiny-input-container > .control-label { display: table-cell; width: 195px; } .shiny-input-container > div { display: table-cell; width: 300px; } display: none; } ", sep = "")) ) ), div(style = "table-row", selectInput( "master", "Master:", choices = c( list("local" = "local"), spark_ui_default_connections(), list("Cluster..." = "cluster") ), selectize = FALSE ), selectInput( "dbinterface", "DB Interface:", choices = c( "dplyr" = "dplyr", "(None)" = "none" ), selectize = FALSE, selected = rsApiReadPreference("sparklyr_dbinterface", "dplyr") ) ), div( style = paste("display: table-row; height: 10px") ), conditionalPanel( condition = "!output.notShowVersionsUi", div(style = "table-row", selectInput( "sparkversion", "Spark version:", choices = spark_ui_spark_choices(), selected = spark_default_version()$spark, selectize = FALSE ), selectInput( "hadoopversion", "Hadoop version:", choices = spark_ui_hadoop_choices(spark_default_version()$spark), selected = spark_default_version()$hadoop, selectize = FALSE ) ) ) ) } connection_spark_server <- function(input, output, session) { hasDefaultSparkVersion <- reactive({ input$sparkversion == spark_default_version()$spark }) hasDefaultHadoopVersion <- reactive({ input$hadoopversion == spark_default_version()$hadoop }) output$notShowVersionsUi <- reactive({ !identical(spark_home(), NULL) }) userInstallPreference <- NULL checkUserInstallPreference <- function(master, sparkSelection, hadoopSelection, prompt) { if (identical(master, "local") && identical(rsApiVersionInfo()$mode, "desktop") && identical(spark_home(), NULL)) { installed <- spark_installed_versions() isInstalled <- nrow(installed[installed$spark == sparkSelection & installed$hadoop == hadoopSelection, ]) if (!isInstalled) { if (prompt && identical(userInstallPreference, NULL)) { userInstallPreference <<- rsApiShowQuestion( "Install Spark Components", paste( "Spark ", sparkSelection, " for Hadoop ", hadoopSelection, " is not currently installed.", "\n\n", "Do you want to install this version of Spark?", sep = "" ), ok = "Install", cancel = "Cancel" ) userInstallPreference } else if (identical(userInstallPreference, NULL)) { FALSE } else { userInstallPreference } } else { FALSE } } else { FALSE } } generateCode <- function(master, dbInterface, sparkVersion, hadoopVersion, installSpark) { paste( "library(sparklyr)\n", if(dbInterface == "dplyr") "library(dplyr)\n" else "", if(installSpark) paste( "spark_install(version = \"", sparkVersion, "\", hadoop_version = \"", hadoopVersion, "\")\n", sep = "" ) else "", "sc ", "<- ", "spark_connect(master = \"", master, "\"", if (!hasDefaultSparkVersion()) paste( ", version = \"", sparkVersion, "\"", sep = "" ) else "", if (!hasDefaultHadoopVersion()) paste( ", hadoop_version = \"", hadoopVersion, "\"", sep = "" ) else "", ")", sep = "" ) } stateValuesReactive <- reactiveValues(codeInvalidated = 1) codeReactive <- reactive({ master <- input$master dbInterface <- input$dbinterface sparkVersion <- input$sparkversion hadoopVersion <- input$hadoopversion codeInvalidated <- stateValuesReactive$codeInvalidated installSpark <- checkUserInstallPreference(master, sparkVersion, hadoopVersion, FALSE) generateCode(master, dbInterface, sparkVersion, hadoopVersion, installSpark) }) installLater <- reactive({ master <- input$master sparkVersion <- input$sparkversion hadoopVersion <- input$hadoopversion }) %>% debounce(200) observe({ installLater() isolate({ master <- input$master sparkVersion <- input$sparkversion hadoopVersion <- input$hadoopversion checkUserInstallPreference(master, sparkVersion, hadoopVersion, TRUE) }) }) observe({ rsApiUpdateDialog(codeReactive()) }) observe({ if (identical(input$master, "cluster")) { if (identical(rsApiVersionInfo()$mode, "desktop")) { rsApiShowDialog( "Connect to Spark", paste( "Connecting with a remote Spark cluster requires ", "an RStudio Server instance that is either within the cluster ", "or has a high bandwidth connection to the cluster.</p>", "<p>Please see the <strong>Using Spark with RStudio</strong> help ", "link below for additional details.</p>", sep = "" ) ) updateSelectInput( session, "master", selected = "local" ) } else if (identical(spark_home(), NULL)) { rsApiShowDialog( "Connect to Spark", paste( "Connecting with a Spark cluster requires that you are on a system ", "able to communicate with the cluster in both directions, and ", "requires that the SPARK_HOME environment variable refers to a ", "locally installed version of Spark that is configured to ", "communicate with the cluster.", "<p>Your system doesn't currently have the SPARK_HOME environment ", "variable defined. Please contact your system administrator to ", "ensure that the server is properly configured to connect with ", "the cluster.<p>", sep = "" ) ) updateSelectInput( session, "master", selected = "local" ) } else { master <- rsApiShowPrompt( "Connect to Cluster", "Spark master:", "spark://local:7077" ) updateSelectInput( session, "master", choices = c( list(master = "master"), master, spark_ui_default_connections(), list("Cluster..." = "cluster") ), selected = master ) } } }) currentSparkSelection <- NULL session$onFlushed(function() { if (!is_java_available()) { url <- "" message <- paste( "In order to connect to Spark ", "your system needs to have Java installed (", "no version of Java was detected or installation ", "is invalid).", sep = "" ) if (identical(rsApiVersionInfo()$mode, "desktop")) { message <- paste( message, "<p>Please contact your server administrator to request the ", "installation of Java on this system.</p>", sep = "") url <- java_install_url() } else { message <- paste( message, "<p>Please contact your server administrator to request the ", "installation of Java on this system.</p>", sep = "") } rsApiShowDialog( "Java Required for Spark Connections", message, url ) } currentSparkSelection <<- spark_default_version()$spark }) observe({ sparkVersion <- input$sparkversion master <- input$master if (!identical(currentSparkSelection, NULL)) { currentSparkSelection <<- sparkVersion hadoopDefault <- spark_install_find(version = currentSparkSelection, installed_only = FALSE)$hadoopVersion updateSelectInput( session, "hadoopversion", choices = spark_ui_hadoop_choices(currentSparkSelection), selected = hadoopDefault ) stateValuesReactive$codeInvalidated <<- isolate({ stateValuesReactive$codeInvalidated + 1 }) } }) observe({ rsApiWritePreference("sparklyr_dbinterface", input$dbinterface) }) outputOptions(output, "notShowVersionsUi", suspendWhenHidden = FALSE) } shinyApp(connection_spark_ui, connection_spark_server)
create_participantgroup_widedata <- function(raw_df, n_trials_per_grapheme=3, participant_col_name, symbol_col_regex, color_col_regex="colou*r", time_col_regex=NULL, testdate_col_name=NULL, color_space_spec="Luv") { new_pgroup <- ParticipantGroup$new() participant_vector <- as.character(raw_df[[participant_col_name]]) symbol_col_bool <- grepl(symbol_col_regex, colnames(raw_df)) symbol_mat <- as.matrix(raw_df[, symbol_col_bool]) color_col_bool <- grepl(color_col_regex, colnames(raw_df)) color_mat <- as.matrix(raw_df[, color_col_bool]) if (!is.null(time_col_regex)) { time_col_bool <- grepl(time_col_regex, colnames(raw_df)) time_mat <- as.matrix(raw_df[, time_col_bool]) } if (!is.null(testdate_col_name)) { testdate_vector <- raw_df[[testdate_col_name]] } unique_symbols <- unique(as.vector(symbol_mat)) for (row_index in 1:nrow(raw_df)) { participant_id <- participant_vector[row_index] symbol_vector <- as.vector(symbol_mat[row_index, ]) color_vector <- as.vector(color_mat[row_index, ]) if (!is.null(time_col_regex)) { time_vector <- as.vector(time_mat[row_index, ]) } else {time_vector <- NULL} if (!is.null(testdate_col_name)) { test_date <- testdate_vector[row_index] } else {test_date <- NULL} new_p <- create_participant(participant_id=participant_id, grapheme_symbols=unique_symbols, n_trials_per_grapheme=n_trials_per_grapheme, trial_symbols=symbol_vector, response_times=time_vector, response_colors=color_vector, color_space_spec=color_space_spec, test_date=test_date) new_pgroup$add_participant(new_p) } return(new_pgroup) }
"checkPackageLoadability" <- function (pkg, quiet) { RevoIOQ:::testPackageLoadability(pkg = pkg, lib.loc = .Library, quiet = quiet) }
context("checks large data warning in rCompare") test_that("Silent for small data", { expect_silent(warnLargeData(nrow(iris),ncol(iris),nrow(iris),ncol(iris))) expect_silent(warnLargeData(nrow(iris),ncol(iris),nrow(pressure),ncol(pressure))) expect_silent(warnLargeData(nrow(pressure),ncol(pressure), nrow(pressure),ncol(pressure))) expect_silent(warnLargeData(2E2,1E3,1E3,5E3)) }) test_that("Warns for large data", { expect_message(warnLargeData(1E9,1E9,1E9,1E9)) expect_message(warnLargeData(5E6,5E6,5E6,6E6)) })
OUwie.sim <- function(phy=NULL, data=NULL, simmap.tree=FALSE, root.age=NULL, scaleHeight=FALSE, alpha=NULL, sigma.sq=NULL, theta0=NULL, theta=NULL, mserr="none", shift.point=0.5, fitted.object=NULL){ if(!is.null(fitted.object)) { if(grepl("BM", fitted.object$model) | grepl("OU1", fitted.object$model)) { stop(paste("not implemented yet for ", fitted.object$model)) } if(!is.null(alpha) | !is.null(theta0) | !is.null(theta)) { stop("You're passing in parameters to simulate from AND a fitted object to simulate under. You can do one or the other") } phy <- fitted.object$phy data <- cbind(phy$tip.label, fitted.object$data) alpha <- fitted.object$solution['alpha',] alpha[which(is.na(alpha))] <- 0 sigma.sq <- fitted.object$solution['sigma.sq',] if(mserr != "none"){ warning("measurement error is not yet handled for simulations from fitted.object") } if (fitted.object$root.station == TRUE | fitted.object$root.station==FALSE){ if (fitted.object$model == "OU1"){ theta <- matrix(t(fitted.object$theta[1,]), 2, length(levels(fitted.object$tot.states)))[1,] theta0 <- theta[phy$node.label[1]] } } if (fitted.object$root.station == TRUE | !grepl("OU", fitted.object$model)){ if (fitted.object$model != "OU1"){ theta <- matrix(t(fitted.object$theta), 2, length(levels(fitted.object$tot.states)))[1,] theta0 <- theta[phy$node.label[1]] } } if (fitted.object$root.station == FALSE & grepl("OU", fitted.object$model)){ if (fitted.object$model != "OU1"){ if(fitted.object$get.root.theta == TRUE){ theta.all <- matrix(t(fitted.object$theta), 2, 1:length(levels(fitted.object$tot.states))+1)[1,] theta <- theta.all[2:length(theta.all)] theta0 <- theta.all[1] }else{ theta <- matrix(t(fitted.object$theta), 2, length(levels(fitted.object$tot.states)))[1,] theta0 <- theta[phy$node.label[1]] } } } } if(is.null(root.age)){ if(any(branching.times(phy)<0)){ stop("Looks like your tree is producing negative branching times. Must input known root age of tree.", .call=FALSE) } } if(simmap.tree == FALSE){ if(mserr == "none"){ data <- data.frame(data[,2], data[,2], row.names=data[,1]) } if(mserr == "known"){ data <- data.frame(data[,2], data[,3], row.names=data[,1]) } data <- data[phy$tip.label,] n <- max(phy$edge[,1]) ntips <- length(phy$tip.label) int.states <- factor(phy$node.label) phy$node.label <- as.numeric(int.states) tip.states <- factor(data[,1]) data[,1] <- as.numeric(tip.states) tot.states <- factor(c(phy$node.label,as.character(data[,1]))) k <- length(levels(tot.states)) regime <- matrix(rep(0,(n-1)*k), n-1, k) root.state <- phy$node.label[1] int.state <- phy$node.label[-1] edges <- cbind(c(1:(n-1)),phy$edge,MakeAgeTable(phy, root.age=root.age)) if(scaleHeight == TRUE){ edges[,4:5] <- edges[,4:5]/max(MakeAgeTable(phy, root.age=root.age)) root.age <- 1 } edges <- edges[sort.list(edges[,3]),] mm <- c(data[,1],int.state) regime <- matrix(0,nrow=length(mm),ncol=length(unique(mm))) for (i in 1:length(mm)) { regime[i,mm[i]] <- 1 } edges <- cbind(edges,regime) edges <- edges[sort.list(edges[,1]),] oldregime <- root.state alpha <- alpha alpha[alpha==0] <- 1e-10 sigma <- sqrt(sigma.sq) theta <- theta x <- matrix(0, n, 1) TIPS <- 1:ntips ROOT <- ntips + 1L x[ROOT,] <- theta0 for(i in 1:length(edges[,1])){ anc <- edges[i,2] desc <- edges[i,3] oldtime <- edges[i,4] newtime <- edges[i,5] if(anc%in%edges[,3]){ start <- which(edges[,3]==anc) oldregime <- which(edges[start,6:(k+5)]==1) }else{ oldregime <- root.state } newregime=which(edges[i,6:(k+5)]==1) if(oldregime==newregime){ x[edges[i,3],] <- (x[edges[i,2],]*exp(-alpha[oldregime]*(newtime-oldtime))) + (theta[oldregime]*(1-exp(-alpha[oldregime]*(newtime-oldtime)))) + (sigma[oldregime]*rnorm(1,0,1)*sqrt((1-exp(-2*alpha[oldregime]*(newtime-oldtime)))/(2*alpha[oldregime]))) }else{ shifttime <- newtime-((newtime-oldtime) * shift.point) epoch1 <- (x[edges[i,2],]*exp(-alpha[oldregime]*(shifttime-oldtime))) + (theta[oldregime]*(1-exp(-alpha[oldregime]*(shifttime-oldtime)))) + (sigma[oldregime]*rnorm(1,0,1)*sqrt((1-exp(-2*alpha[oldregime]*(shifttime-oldtime)))/(2*alpha[oldregime]))) oldtime <- shifttime newtime <- newtime x[edges[i,3],] <- (epoch1*exp(-alpha[newregime]*(newtime-oldtime))) + (theta[newregime]*(1-exp(-alpha[newregime]*(newtime-oldtime)))) + (sigma[newregime]*rnorm(1,0,1)*sqrt((1-exp(-2*alpha[newregime]*(newtime-oldtime)))/(2*alpha[newregime]))) } } sim.dat <- matrix(,ntips,3) sim.dat <- data.frame(sim.dat) sim.dat[,1] <- phy$tip.label sim.dat[,2] <- data[,1] sim.dat[,3] <- x[TIPS] if(mserr == "known"){ for(i in TIPS){ sim.dat[i,3] <- rnorm(1,sim.dat[i,3],data[i,2]) } } colnames(sim.dat)<-c("Genus_species","Reg","X") } if(simmap.tree==TRUE){ n=max(phy$edge[,1]) ntips=length(phy$tip.label) k=length(colnames(phy$mapped.edge)) regimeindex <- colnames(phy$mapped.edge) branch.lengths=rep(0,(n-1)) branch.lengths[(ntips+1):(n-1)]=branching.times(phy)[-1]/max(branching.times(phy)) root.state<-which(colnames(phy$mapped.edge)==names(phy$maps[[1]][1])) edges=cbind(c(1:(n-1)),phy$edge,MakeAgeTable(phy, root.age=root.age)) if(scaleHeight==TRUE){ edges[,4:5]<-edges[,4:5]/max(MakeAgeTable(phy, root.age=root.age)) root.age <- max(MakeAgeTable(phy, root.age=root.age)) phy$maps <- lapply(phy$maps, function(x) x/root.age) root.age = 1 } edges=edges[sort.list(edges[,3]),] edges=edges[sort.list(edges[,1]),] oldregime=root.state oldtime=0 alpha=alpha sigma=sqrt(sigma.sq) theta=theta n.cov=matrix(rep(0,n*n), n, n) nodecode=matrix(c(ntips+1,1),1,2) x <- matrix(0, n, 1) TIPS <- 1:ntips ROOT <- ntips + 1L x[ROOT,] <- theta0 for(i in 1:length(edges[,1])){ currentmap<-phy$maps[[i]] oldtime=edges[i,4] if(length(phy$maps[[i]])==1){ regimeduration<-currentmap[1] newtime<-oldtime+regimeduration regimenumber<-which(colnames(phy$mapped.edge)==names(currentmap)[1]) x[edges[i,3],]=x[edges[i,2],]*exp(-alpha[regimenumber]*(newtime-oldtime))+(theta[regimenumber])*(1-exp(-alpha[regimenumber]*(newtime-oldtime)))+sigma[regimenumber]*rnorm(1,0,1)*sqrt((1-exp(-2*alpha[regimenumber]*(newtime-oldtime)))/(2*alpha[regimenumber])) } if(length(phy$maps[[i]])>1){ regimeduration<-currentmap[1] newtime<-oldtime+regimeduration regimenumber<-which(colnames(phy$mapped.edge)==names(currentmap)[1]) x[edges[i,3],]=x[edges[i,2],]*exp(-alpha[regimenumber]*(newtime-oldtime))+(theta[regimenumber])*(1-exp(-alpha[regimenumber]*(newtime-oldtime)))+sigma[regimenumber]*rnorm(1,0,1)*sqrt((1-exp(-2*alpha[regimenumber]*(newtime-oldtime)))/(2*alpha[regimenumber])) oldtime<-newtime for (regimeindex in 2:length(currentmap)){ regimeduration<-currentmap[regimeindex] newtime<-oldtime+regimeduration regimenumber<-which(colnames(phy$mapped.edge)==names(currentmap)[regimeindex]) x[edges[i,3],]=x[edges[i,3],]*exp(-alpha[regimenumber]*(newtime-oldtime))+(theta[regimenumber])*(1-exp(-alpha[regimenumber]*(newtime-oldtime)))+sigma[regimenumber]*rnorm(1,0,1)*sqrt((1-exp(-2*alpha[regimenumber]*(newtime-oldtime)))/(2*alpha[regimenumber])) oldtime<-newtime newregime<-regimenumber } } } sim.dat<-matrix(,ntips,2) sim.dat<-data.frame(sim.dat) sim.dat[,1]<-phy$tip.label sim.dat[,2]<-x[TIPS,] if(mserr == "known"){ for(i in TIPS){ sim.dat[i,2] <- rnorm(1,sim.dat[i,2],data[i,3]) } } colnames(sim.dat)<-c("Genus_species","X") } sim.dat }
downloadCloudData <- function(pathRemote = "https://raw.githubusercontent.com/kurator-org", pathGithub = "/kurator-validation/master/packages/kurator_dwca/data/vocabularies/", pathFile = "darwin_cloud.txt", columnField = "fieldname", columnStand = "standard") { pathCloud <- paste0(pathRemote, pathGithub, pathFile) data <- read.csv(pathCloud, sep = "\t") data <- subset(data, select = c(columnField, columnStand)) colnames(data) <- c(columnField, columnStand) return(data) }
checkMatrix = function(x, mode = NULL, any.missing = TRUE, all.missing = TRUE, min.rows = NULL, max.rows = NULL, min.cols = NULL, max.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) { .Call(c_check_matrix, x, mode, any.missing, all.missing, min.rows, max.rows, min.cols, max.cols, nrows, ncols, row.names, col.names, null.ok) } check_matrix = checkMatrix assertMatrix = makeAssertionFunction(checkMatrix, c.fun = "c_check_matrix", use.namespace = FALSE) assert_matrix = assertMatrix testMatrix = makeTestFunction(checkMatrix, c.fun = "c_check_matrix") test_matrix = testMatrix expect_matrix = makeExpectationFunction(checkMatrix, c.fun = "c_check_matrix", use.namespace = FALSE)
CExp <- function(m, Time, x, sign=1.) { return(0.5*(exp(-m*(Time-x)) + sign*exp(-m*x))) } dCExpdm <- function(m, Time, x, sign=1.) { return(0.5*(-(Time-x)*exp(-m*(Time-x)) -x* sign*exp(-m*x))) }