code
stringlengths
1
13.8M
geneViz_Granges2dataframe <- function(gr) { range <- as.data.frame(IRanges::ranges(gr)) meta <- as.data.frame(GenomicRanges::mcols(gr)) genomic_data <- cbind(range, meta) genomic_data <- genomic_data[,c('start', 'end', 'GC', 'width', 'txname')] return(genomic_data) }
globalVariables('i') run.all.scripts <- function( output.directory, stages.to.run = c('alignment', 'qc', 'calling', 'annotation', 'merging'), variant.callers = NULL, quiet = FALSE ) { script.directory <- file.path(output.directory, 'code') log.directory <- file.path(output.directory, 'log/') config <- read.yaml(save.config()) num.cores <- config[['num_cpu']] doParallel::registerDoParallel(cores = num.cores) print('Note: due to the nature of using multiple cores, jobs may complete out of order') if ('alignment' %in% stages.to.run){ print('Aligning...') script.files <- list.files(pattern = '.*align.*\\.sh$', path = script.directory, full.names = TRUE) script.names <- list.files(pattern = '.*align.*\\.sh$', path = script.directory, full.names = FALSE) if (length(script.files) > 0) { foreach::foreach(i=1:length(script.files)) %dopar% { if (quiet) { print(paste0('bash ', script.files[i], ' &> ', log.directory, script.names[i], '.out')) } else { system(paste0('bash ', script.files[i], ' &> ', log.directory, script.names[i], '.out')) print(paste0('Completed job ', i, ' of ', length(script.files), ' alignment jobs')) } } } } if ('qc' %in% stages.to.run){ print('Running QC...') script.files <- list.files(pattern = '.*target_qc.*\\.sh$', path = script.directory, full.names = TRUE) script.names <- list.files(pattern = '.*target_qc.*\\.sh$', path = script.directory, full.names = FALSE) if (length(script.files) > 0) { foreach::foreach(i=1:length(script.files)) %dopar% { if (quiet) { print(paste0('bash ', script.files[i], ' &> ', log.directory, script.names[i], '.out')) } else { system(paste0('bash ', script.files[i], ' &> ', log.directory, script.names[i], '.out')) print(paste0('Completed job ', i, ' of ', length(script.files), ' QC jobs')) } } } } if ('calling' %in% stages.to.run){ if ('mutect' %in% variant.callers){ print('Running Mutect...') script.files <- list.files(pattern = '.*mutect.*\\.sh$', path = script.directory, full.names = TRUE) script.names <- list.files(pattern = '.*mutect.*\\.sh$', path = script.directory, full.names = FALSE) if (length(script.files) > 0) { foreach::foreach(i=1:length(script.files)) %dopar% { if (quiet) { print(paste0('bash ', script.files[i], ' &> ', log.directory, script.names[i], '.out')) } else { system(paste0('bash ', script.files[i], ' &> ', log.directory, script.names[i], '.out')) print(paste0('Completed job ', i, ' of ', length(script.files), ' MuTect jobs')) } } } } if ('vardict' %in% variant.callers) { print('Running VarDict...') script.files <- list.files(pattern = '.*vardict.*\\.sh$', path = script.directory, full.names = TRUE) script.names <- list.files(pattern = '.*vardict.*\\.sh$', path = script.directory, full.names = FALSE) if (length(script.files) > 0) { foreach::foreach(i=1:length(script.files)) %dopar% { if (quiet) { print(paste0('bash ', script.files[i], ' &> ', log.directory, script.names[i], '.out')) } else { system(paste0('bash ', script.files[i], ' &> ', log.directory, script.names[i], '.out')) print(paste0('Completed job ', i, ' of ', length(script.files), ' VarDict jobs')) } } } } } if ('annotation' %in% stages.to.run){ print('Annotating...') script.files <- list.files(pattern = '.*annotate.*\\.sh$', path = script.directory, full.names = TRUE) script.names <- list.files(pattern = '.*annotate.*\\.sh$', path = script.directory, full.names = FALSE) if (length(script.files) > 0) { foreach::foreach(i=1:length(script.files)) %dopar% { if (quiet) { print(paste0('bash ', script.files[i], ' &> ', log.directory, script.names[i], '.out')) } else { system(paste0('bash ', script.files[i], ' &> ', log.directory, script.names[i], '.out')) print(paste0('Completed job ', i, ' of ', length(script.files), ' annotation jobs')) } } } } if ('merging' %in% stages.to.run){ print('Merging...') script.files <- list.files(pattern = '.*post_processing.*\\.sh$', path = file.path(script.directory, '..'), full.names = TRUE) script.names <- list.files(pattern = '.*post_processing.*\\.sh$', path = script.directory, full.names = FALSE) foreach::foreach(i=1:length(script.files)) %dopar% { if (quiet) { print(paste0('bash ', script.files[i], ' &> ', log.directory, script.names[i], '.out')) } else { system(paste0('bash ', script.files[i], ' &> ', log.directory, script.names[i], '.out')) } } } print('All jobs executed') }
SlideDeck <- function(slideSep = rep("", 3), newSlide = Slide) { modules::module({ modules::export("new") new <- function(rawText) { slideDeck <- splitRawTextIntoSlides(rawText, slideSep) map(slideDeck ~ seq_along(slideDeck) ~ length(slideDeck), newSlide) } splitRawTextIntoSlides <- function(rawText, slideSep) { ind <- numeric(length(rawText)) ind[seq_along(slideSep)] <- 0 for (i in seq_along(rawText)[-seq_along(slideSep)]) { pos <- (i - length(slideSep) + 1):i if (identical(rawText[pos], slideSep)) ind[i] <- 1 else ind[i] <- 0 } split(rawText, cumsum(ind)) } }) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(data.table) library(DTSg) data(flow) flow summary(flow) TS <- DTSg$new( values = flow, ID = "River Flow" ) TS <- new( Class = "DTSg", values = flow, ID = "River Flow" ) TS$print() TS$summary() TS$nas(cols = "flow") if (requireNamespace("dygraphs", quietly = TRUE) && requireNamespace("RColorBrewer", quietly = TRUE)) { TS$plot(cols = "flow") } flow[date >= as.POSIXct("2007-10-09", tz = "UTC") & date <= as.POSIXct("2007-11-13", tz = "UTC"), ] TS <- TS$colapply(fun = interpolateLinear) TS$nas() TS$cols() TS$cols(class = "numeric") TS$cols(class = "character") TS$cols(class = c("double", "integer")) TS$cols(pattern = "f.*w") TS$cols(pattern = "temp") TS <- TS$alter(from = "2007-01-01", to = "2008-12-31") TS TSm <- TS$aggregate(funby = byYm____, fun = mean) TSm TSQ <- TS$aggregate(funby = by_Q____, fun = mean) TSQ TSs <- TS$rollapply(fun = mean, na.rm = TRUE, before = 2, after = 2) TSs TS <- TS$merge(y = TSs, suffixes = c("_orig", "_movavg")) TS$values() TS$ID TSassigned <- TS TScloned <- TS$clone(deep = TRUE) TS$ID <- "Two River Flows" TS TSassigned TScloned
context("kinematics functions") test_that("half.wave works fine", { x <- seq(0,pi,0.01) y <- sin(x^2*pi) w <- halfwave(x,y,method="zeros",fit=TRUE,smoothing="spline") expect_is(w,"list") expect_named(w,c("method", "names", "dat")) expect_type(w$names$x,type= "double") expect_type(w$dat$wave.begin,type = "double") expect_true(w$method[1]== "zeros") expect_true(is.na(w$dat$amp2[1]) & is.na(w$dat$pos2[1])) expect_error(halfwave(x,y,method="foo",fit=TRUE,smoothing="spline"),"method must be set to") expect_error(halfwave(x,y,method="zeros",fit=TRUE,smoothing="foo"), "should be set to") expect_error(halfwave(x,y+1.1,method="zeros",fit=TRUE,smoothing="spline"),"1 or fewer zero crossings found") w2 <- halfwave(x,y+1.1,method="p2t",fit=TRUE,smoothing="spline") expect_is(w2,"list") expect_named(w2,c("method", "names", "dat")) expect_type(w2$names$x,type= "double") expect_type(w2$dat$wave.begin,type = "double") expect_true(w2$method[1]== "p2t") expect_true(is.na(w2$dat$zeros[1])) }) test_that("wave works fine", { x <- seq(0,pi,0.01) y <- sin(x^2*pi) w <- wave(x,y,method="zeros",fit=TRUE,smoothing="spline") expect_is(w,"list") expect_named(w,c("method", "names", "dat")) expect_type(w$names$x,type= "double") expect_type(w$dat$wave.begin,type = "double") expect_true(w$method[1]== "zeros") expect_true(!is.na(w$dat$amp2[1]) & !is.na(w$dat$pos2[1])) expect_error(wave(x,y,method="foo",fit=TRUE,smoothing="spline"),"method must be set to") expect_error(wave(x,y,method="zeros",fit=TRUE,smoothing="foo"), "should be set to") expect_error(wave(x,y+1.1,method="zeros",fit=TRUE,smoothing="spline")) w2 <- wave(x,y+1.1,method="p2p",fit=TRUE,smoothing="spline") expect_is(w2,"list") expect_named(w2,c("method", "names", "dat")) expect_type(w2$names$x,type= "double") expect_type(w2$dat$wave.begin,type = "double") expect_true(w2$method[1]== "p2p") expect_true(is.na(w2$dat$zeros[1])) w3 <- wave(x,y+1.1,method="t2t",fit=F,smoothing="spline") expect_is(w3,"list") expect_named(w3,c("method", "names", "dat")) expect_type(w3$names$x,type= "double") expect_type(w3$dat$wave.begin,type = "double") expect_true(w3$method[1]== "t2t") expect_true(is.na(w3$dat$zeros[1])) }) test_that("amp.freq works fine", { x <- seq(0,pi,0.1) y <- sin(x^1.3*pi) af <- amp.freq(x=x,y=y) expect_is(af,"list") expect_equivalent(round(af$f,1), 69.4) expect_equivalent(af$snr,38.76) expect_named(af,c("a", "f", "a.f","snr")) x <- seq(0.2,pi,0.1) y <- sin(x^0.3*pi) af2 <- amp.freq(x,y) expect_is(af2,"list") expect_identical(af2$a,numeric(0)) expect_identical(af2$f,numeric(0)) expect_identical(af2$a.f,numeric(0)) })
rotmean <- function(X, ..., origin, padzero=TRUE, Xname, result=c("fv", "im"), adjust=1) { if(missing(Xname)) Xname <- sensiblevarname(short.deparse(substitute(X)), "X") trap.extra.arguments(..., .Context="rotmean") stopifnot(is.im(X)) if(!missing(origin)) { X <- shift(X, origin=origin) backshift <- -getlastshift(X) } else { backshift <- NULL } result <- match.arg(result) rmax <- with(vertices(Frame(X)), sqrt(max(x^2+y^2))) Xunpad <- X if(padzero) X <- padimage(na.handle.im(X, 0), 0, W=square(c(-1,1)*rmax)) Xdata <- as.data.frame(X) values <- Xdata$value radii <- with(Xdata, sqrt(x^2+y^2)) ra <- pmin(range(radii), rmax) bw <- adjust * 0.1 * sqrt(X$xstep^2 + X$ystep^2) a <- unnormdensity(radii, from=ra[1], to=ra[2], bw=bw) b <- unnormdensity(radii, weights=values, from=ra[1], to=ra[2], bw=a$bw) df <- data.frame(r=a$x, f=b$y/a$y) FUN <- fv(df, argu="r", ylab=substitute(bar(X)(r), list(X=as.name(Xname))), valu="f", fmla=(. ~ r), alim=ra, labl=c("r", "%s(r)"), desc=c("distance argument r", "rotational average"), unitname=unitname(X), fname=paste0("bar", paren(Xname))) attr(FUN, "dotnames") <- "f" unitname(FUN) <- unitname(X) if(result == "fv") return(FUN) FUN <- as.function(FUN) XX <- as.im(Xunpad, na.replace=1) IM <- as.im(function(x,y,FUN){ FUN(sqrt(x^2+y^2)) }, XX, FUN=FUN) if(!is.null(backshift)) IM <- shift(IM,backshift) unitname(IM) <- unitname(X) return(IM) }
rwrappednormal <- function(n, mu=circular(0), rho=NULL, sd=1, control.circular=list()) { if (is.circular(mu)) { datacircularp <- circularp(mu) } else { datacircularp <- list(type="angles", units="radians", template="none", modulo="asis", zero=0, rotation="counter") } dc <- control.circular if (is.null(dc$type)) dc$type <- datacircularp$type if (is.null(dc$units)) dc$units <- datacircularp$units if (is.null(dc$template)) dc$template <- datacircularp$template if (is.null(dc$modulo)) dc$modulo <- datacircularp$modulo if (is.null(dc$zero)) dc$zero <- datacircularp$zero if (is.null(dc$rotation)) dc$rotation <- datacircularp$rotation mu <- conversion.circular(mu, units="radians", zero=0, rotation="counter") attr(mu, "class") <- attr(mu, "circularp") <- NULL if (is.null(rho)) rho <- exp(-sd^2/2) if (rho < 0 | rho > 1) stop("rho must be between 0 and 1") result <- RwrappednormalRad(n, mu, rho) result <- conversion.circular(circular(result), dc$units, dc$type, dc$template, dc$modulo, dc$zero, dc$rotation) return(result) } RwrappednormalRad <- function(n, mu, rho) { if (rho == 0) result <- runif(n, 0, 2*pi) else if (rho == 1) result <- rep(mu, n) else { sd <- sqrt(-2 * log(rho)) result <- rnorm(n, mu, sd) %% (2*pi) } return(result) } dwrappednormal <- function(x, mu=circular(0), rho=NULL, sd=1, K=NULL, min.k=10) { x <- conversion.circular(x, units="radians", zero=0, rotation="counter") mu <- conversion.circular(mu, units="radians", zero=0, rotation="counter") attr(x, "class") <- attr(x, "circularp") <- NULL attr(mu, "class") <- attr(mu, "circularp") <- NULL if (is.null(rho)) rho <- exp(-sd^2/2) if (rho < 0 | rho > 1) stop("rho must be between 0 and 1") if (length(mu)!=1) stop("is implemented only for scalar 'mean'") result <- DwrappednormalRad(x, mu, rho, K, min.k) return(result) } DwrappednormalRad <- function(x, mu, rho, K, min.k=10) { var <- -2 * log(rho) sd <- sqrt(var) if (is.null(K)) { range <- abs(mu-x) K <- (range+6*sqrt(var))%/%(2*pi)+1 K <- max(min.k, K) } n <- length(x) z <- .Fortran("dwrpnorm", as.double(x), as.double(mu), as.double(sd), as.integer(n), as.integer(length(mu)), as.integer(K), d=mat.or.vec(length(mu), n), PACKAGE="circular" ) d <- t(z$d/sqrt(var * 2 * pi)) if (ncol(d)==1) d <- c(d) return(d) } pwrappednormal <- function(q, mu=circular(0), rho=NULL, sd=1, from=NULL, K=NULL, min.k=10, ...) { q <- conversion.circular(q, units="radians", zero=0, rotation="counter", modulo="2pi") mu <- conversion.circular(mu, units="radians", zero=0, rotation="counter", modulo="2pi") if (is.null(from)) { from <- mu - pi } else { from <- conversion.circular(from, units="radians", zero=0, rotation="counter", modulo="2pi") } attr(q, "class") <- attr(q, "circularp") <- NULL attr(mu, "class") <- attr(mu, "circularp") <- NULL attr(from, "class") <- attr(from, "circularp") <- NULL n <- length(q) if (length(mu) != 1) stop("is implemented only for scalar 'mean'") mu <- (mu-from)%%(2*pi) q <- (q-from)%%(2*pi) if (is.null(rho)) { rho <- exp(-sd^2/2) } if (rho < 0 | rho > 1) stop("rho must be between 0 and 1") intDwrappednormalRad <- function(q) { if (is.na(q)) { return(NA) } else { return(integrate(DwrappednormalRad, mu=mu, rho=rho, K=K, min.k=min.k, lower=0, upper=q, ...)$value) } } value <- sapply(X=q, FUN=intDwrappednormalRad) return(value) } qwrappednormal <- function(p, mu=circular(0), rho=NULL, sd=1, from=NULL, K=NULL, min.k=10, tol=.Machine$double.eps^(0.6), control.circular=list(), ...) { epsilon <- 10 * .Machine$double.eps if (any(p>1) | any(p<0)) stop("p must be in [0,1]") if (is.circular(mu)) { datacircularp <- circularp(mu) } else { datacircularp <- list(type="angles", units="radians", template="none", modulo="asis", zero=0, rotation="counter") } dc <- control.circular if (is.null(dc$type)) dc$type <- datacircularp$type if (is.null(dc$units)) dc$units <- datacircularp$units if (is.null(dc$template)) dc$template <- datacircularp$template if (is.null(dc$modulo)) dc$modulo <- datacircularp$modulo if (is.null(dc$zero)) dc$zero <- datacircularp$zero if (is.null(dc$rotation)) dc$rotation <- datacircularp$rotation mu <- conversion.circular(mu, units="radians", zero=0, rotation="counter", modulo="2pi") if (is.null(from)) { from <- mu - pi } else { from <- conversion.circular(from, units="radians", zero=0, rotation="counter", modulo="2pi") } attr(mu, "class") <- attr(mu, "circularp") <- NULL attr(from, "class") <- attr(from, "circularp") <- NULL n <- length(p) if (length(mu) != 1) stop("is implemented only for scalar 'mean'") mu <- (mu-from)%%(2*pi) if (is.null(rho)) rho <- exp(-sd^2/2) if (rho < 0 | rho > 1) stop("rho must be between 0 and 1") zeroPwrappednormalRad <- function(x, p, mu, rho, K, min.k) { if (is.na(x)) { y <- NA } else { y <- integrate(DwrappednormalRad, mu=mu, rho=rho, K=K, min.k=min.k, lower=0, upper=x)$value - p } return(y) } value <- rep(NA, length(p)) sem <- options()$show.error.messages options(show.error.messages=FALSE) for (i in 1:length(p)) { res <- try(uniroot(zeroPwrappednormalRad, p=p[i], mu=mu, rho=rho, K=K, min.k=min.k, lower=0, upper=2*pi-epsilon, tol=tol)) if (is.list(res)) { value[i] <- res$root } else if (p[i] < 10*epsilon) { value[i] <- 0 } else if (p[i] > 1-10*epsilon) { value[i] <- 2*pi-epsilon } } options(show.error.messages=sem) value <- value + from value <- conversion.circular(circular(value), dc$units, dc$type, dc$template, dc$modulo, dc$zero, dc$rotation) return(value) }
"select.range" <- function (data, groupvec, min, max) { min.cond <- (groupvec >= min) max.cond <- (groupvec < max) cond <- min.cond & max.cond return(data[cond]) }
skip_on_cran() skip_if_not(requireNamespace("survey")) library(dplyr) tbl_summary_noby <- trial %>% tbl_summary() tbl_summary_by <- trial %>% tbl_summary(by = trt) tbl_svysummary_by <- survey::svydesign(~1, data = as.data.frame(Titanic), weights = ~Freq) %>% tbl_svysummary(by = Survived) test_that("input checks", { expect_error( tbl_summary_noby %>% modify_header(stat_0 = "test"), NA ) expect_error( tbl_summary_noby %>% modify_header(stat_0 ~ "test"), NA ) expect_error( tbl_summary_noby %>% modify_header(), NA ) }) test_that("checking glue inserts to headers", { expect_error( tbl1 <- tbl_summary_by %>% modify_header( list( all_stat_cols() ~ "{level} ({n}/{N}; {style_percent(p)}%)", label ~ "Variable (N = {N})" ) ), NA ) expect_equal( tbl1$table_styling$header %>% dplyr::filter(hide == FALSE) %>% dplyr::pull(label), c("Variable (N = 200)", "Drug A (98/200; 49%)", "Drug B (102/200; 51%)") ) expect_error( tbl2 <- tbl_svysummary_by %>% modify_header( list( all_stat_cols() ~ "{level} ({n}/{N}; {style_percent(p)}%): Unweighted {n_unweighted}/{N_unweighted}; {style_percent(p_unweighted)}%", label ~ "Variable (N = {N}: Unweighted {N_unweighted})" ) ), NA ) expect_equal( tbl2$table_styling$header %>% dplyr::filter(hide == FALSE) %>% dplyr::pull(label), c( "Variable (N = 2201: Unweighted 32)", "No (1490/2201; 68%): Unweighted 16/32; 50%", "Yes (711/2201; 32%): Unweighted 16/32; 50%" ) ) expect_error( tbl3 <- lm(mpg ~ hp, mtcars) %>% tbl_regression() %>% modify_header(label ~ "Variable (N = {N})"), NA ) expect_equal( tbl3$table_styling$header %>% dplyr::filter(column == "label") %>% dplyr::pull(label), c("Variable (N = 32)") ) }) test_that("deprecated argument still works", { expect_equal( trial %>% tbl_summary(by = trt, include = age) %>% modify_header(stat_by = "{level}") %>% as_tibble() %>% select(-1) %>% names(), c("Drug A", "Drug B") ) })
plot_joint_marginal <- function(parameter1,parameter2,percent.burnin=0,thinning=1,param.name1=deparse(substitute(parameter1)),param.name2=deparse(substitute(parameter2))){ burnin <- (percent.burnin/100)*length(which(parameter1!=0)) x <- seq(from = burnin,to = length(which(parameter1!=0)),by = thinning) plot(parameter1[x],parameter2[x], col=rainbow(start=0.5,end=1.0,length(parameter1[x]),alpha=0.4), pch=19, main=paste("Joint Marginal Density of",paste(param.name1,param.name2,sep=" and "),sep=" "), xlab=param.name1, ylab=param.name2, ylim=c(min(parameter2[x])-abs(min(parameter2[x])-max(parameter2[x]))/5,max(parameter2[x]))) legend(x="bottomright", cex=0.6, pt.cex=1, pch=21, col=1, pt.bg=c(rainbow(start=0.5,end=1.0,length(parameter1[x]),alpha=0.8)[c(1,floor(length(parameter1[x])/2),length(parameter1[x]))]), legend=c("MCMC sampled generation 1", paste("MCMC sampled generation",floor(length(parameter1[x])/2)), paste("MCMC sampled generation",length(parameter1[x])))) }
fieldByYear <- function(M, field = "ID", timespan = NULL, min.freq = 2, n.items = 5, labelsize = NULL, dynamic.plot = FALSE, graph = TRUE) { A <- cocMatrix(M, Field = field, binary = FALSE) n <- colSums(as.array(A)) trend_med <- apply(A, 2, function(x) { round(quantile(rep(M$PY, x), c(0.25,0.50,0.75), na.rm=TRUE)) }) trend_med <- as_tibble(t(trend_med)) %>% rename("year_q1"='25%', "year_med"='50%', "year_q3"='75%') %>% mutate(item=rownames(t(trend_med)), freq=n) %>% relocate(c(.data$item,.data$freq), .data$year_q1) if (is.null(timespan) | length(timespan)!=2){ timespan <- as.numeric(range(trend_med$year_med, na.rm = TRUE)) } df <- trend_med %>% mutate(item = tolower(.data$item)) %>% group_by(.data$year_med) %>% arrange(desc(.data$freq), .data$item) %>% arrange(desc(.data$year_med)) %>% dplyr::slice_head(n=n.items) %>% dplyr::filter(.data$freq >= min.freq) %>% dplyr::filter(between(.data$year_med, timespan[1],timespan[2])) %>% mutate(item = fct_reorder(.data$item, .data$freq)) data("logo",envir=environment()) logo <- grid::rasterGrob(logo,interpolate = TRUE) yrange <- range(unlist(df[,which(regexpr("year",names(df))>-1)])) x <- c(0+0.5,0.05+length(levels(df$item))*0.125)+1 y <- c(yrange[2]-0.02-diff(yrange)*0.125,yrange[2]-0.02) g <- ggplot(df, aes(x=.data$item, y=.data$year_med, text = paste("Term: ", .data$item,"\nYear: ", .data$year_med ,"\nTerm frequency: ",.data$freq )))+ geom_point(aes(size = .data$freq), alpha=0.6, color="dodgerblue4")+ scale_size(range=c(2,6))+ scale_y_continuous(breaks = seq(min(df$year_q1),max(df$year_q3), by=2))+ guides(size = guide_legend(order = 1, "Term frequency"), alpha = guide_legend(order = 2, "Term frequency"))+ theme(legend.position = 'right' ,text = element_text(color = " ,panel.background = element_rect(fill = 'gray98') ,panel.grid.minor = element_line(color = ' ,panel.grid.major = element_line(color = ' ,plot.title = element_text(size = 24) ,axis.title = element_text(size = 14, color = ' ,axis.title.y = element_text(vjust = 1, angle = 90, face="bold") ,axis.title.x = element_text(hjust = .95,face="bold") ,axis.text.x = element_text(face="bold", angle = 90) ,axis.text.y = element_text(face="bold") ) + annotation_custom(logo, xmin = x[1], xmax = x[2], ymin = y[1], ymax = y[2]) if (!isTRUE(dynamic.plot)){ g <- g+geom_vline(xintercept=nrow(df)-(which(c(diff(df$year_med))==-1)-0.5), color="grey70",alpha=0.6, linetype=6)+ geom_point(aes(y=.data$year_q1), alpha=0.6, size = 3, color="royalblue4", shape="|")+ geom_point(aes(y=.data$year_q3), alpha=0.6, size = 3, color="royalblue4", shape="|") } g <- g+ labs(title="Trend Topics", x="Term", y="Year")+ geom_segment(data=df, aes(x = .data$item, y = .data$year_q1, xend = .data$item, yend = .data$year_q3), size=1.0, color="royalblue4", alpha=0.3) + coord_flip() if (isTRUE(graph)) { print(g) } results <- list(df = trend_med, df_graph = df, graph = g) return(results) }
niceLLtix<-function(rcoords) { K = 10 scoords = sort(range(rcoords) ) dms1 = dms(scoords) if(diff(dms1$d)<=1) { dm = diff(dms1$m) if(abs(dm)<=1) { dsec = diff(dms1$m*60+dms1$s) K = goodticdivs(dsec) secstart = K*trunc(dms1$s[1]/K) secend = secstart+60*(dm+1) print(paste(sep=" ","sec", secstart, secend, K)) isec = seq(from=secstart, to=secend, by=K) FDEGcoord = rep(dms1$d[1], times=length(isec)) FMINcoord = rep(dms1$m[1], times=length(isec)) FSECcoord = isec } else { dmin = diff(dms1$d*60+dms1$m) K = goodticdivs(dmin) minstart = K*trunc(dms1$m[1]/K) minend = minstart+(dmin+1) print(paste(sep=" ", "min", minstart, minend, K)) imin = seq(from=minstart, to=minend, by=K) FDEGcoord = rep(dms1$d[1], times=length(imin)) FMINcoord = imin FSECcoord = rep(0, times=length(imin)) } } else { ddeg = diff(dms1$d) K = 15 K = goodticdivs(ddeg) degstart = K*trunc(dms1$d[1]/K) degend =degstart+(ddeg+1) print(paste(sep=" ", "deg", degstart, degend, K)) ideg = seq(from=degstart, to=degend, by=K) FDEGcoord = ideg FMINcoord = rep(0, times=length(ideg)) FSECcoord = rep(0, times=length(ideg)) } DDcoord = FDEGcoord+FMINcoord/60+FSECcoord/3600 w = which(DDcoord>=scoords[1] & DDcoord<=scoords[2]) DDcoord =DDcoord[w] si = sign(DDcoord) final = dms(abs(DDcoord)) return(list(DD=DDcoord, deg=final$d, min=final$m, sec=final$s, si=si)) }
get_bridging <- function(graph) { fcn_name <- get_calling_fcn() if (graph_object_valid(graph) == FALSE) { emit_error( fcn_name = fcn_name, reasons = "The graph object is not valid") } ig_graph <- to_igraph(graph) bridging_scores <- influenceR::bridging(ig_graph) data.frame( id = bridging_scores %>% names() %>% as.integer(), bridging = bridging_scores, stringsAsFactors = FALSE) }
LCSSDistance <- function(x, y, epsilon, sigma) { if (class(try(LCSSInitialCheck(x, y, epsilon, sigma)))=="try-error") { return(NA) } else { tamx <- length(x) tamy <- length(y) subcost <- as.numeric(as.vector(t(proxy::dist(x, y, method="euclidean") > epsilon))) cost.matrix <- c(1:((tamx + 1) * (tamy + 1))) * 0 if (missing(sigma)) { resultList <- .C("lcssnw", as.integer(tamx), as.integer(tamy), as.double(cost.matrix), as.double(subcost)) cost.matrix <- resultList[[3]] } else { resultList <- .C("lcss", as.integer(tamx), as.integer(tamy), as.integer(sigma), as.double(cost.matrix), as.double(subcost)) cost.matrix <- resultList[[4]] } d <- cost.matrix[length(cost.matrix)] return(d) } } LCSSInitialCheck <- function(x, y, epsilon, sigma) { if (! is.numeric(x) | ! is.numeric(y)) { stop('The series must be numeric', call.=FALSE) } if (! is.vector(x) | ! is.vector(y)) { stop('The series must be univariate vectors', call.=FALSE) } if (length(x) < 1 | length(y) < 1) { stop('The series must have at least one point', call.=FALSE) } if (! is.numeric(epsilon)) { stop('The threshold must be numeric', call.=FALSE) } if (epsilon < 0) { stop('The threshold must be positive', call.=FALSE) } if (any(is.na(x)) | any(is.na(y))) { stop('There are missing values in the series', call.=FALSE) } if (!missing(sigma)) { if ((sigma) <= 0) { stop('The window size must be positive', call.=FALSE) } if (sigma < abs(length(x) - length(y))) { stop('The window size can not be lower than the difference between the series lengths', call.=FALSE) } } }
source('../gsDesign_independent_code.R') testthat::test_that("test : checking basic graph layout", { x <- hGraph() save_plot_obj <- save_gg_plot(x) local_edition(3) expect_snapshot_file(save_plot_obj, "plot_hGraph_1.png") }) testthat::test_that("test : checking note clockwise ordering", { x <- hGraph(5) save_plot_obj <- save_gg_plot(x) local_edition(3) expect_snapshot_file(save_plot_obj, "plot_hGraph_2.png") }) testthat::test_that("test : Add colors (default is 3 gray shades)", { x <- hGraph(3, fill = 1:3) save_plot_obj <- save_gg_plot(x) local_edition(3) expect_snapshot_file(save_plot_obj, "plot_hGraph_3.png") }) testthat::test_that("test : Use a hue palette ", { x <- hGraph(4, fill = factor(1:4), palette = scales::hue_pal(l = 75)(4)) save_plot_obj <- save_gg_plot(x) local_edition(3) expect_snapshot_file(save_plot_obj, "plot_hGraph_4.png") }) testthat::test_that("test: different alpha allocation, hypothesis names and transitions", { alphaHypotheses <- c(.005, .007, .013) nameHypotheses <- c("ORR", "PFS", "OS") m <- matrix(c( 0, 1, 0, 0, 0, 1, 1, 0, 0 ), nrow = 3, byrow = TRUE) x <- hGraph(3, alphaHypotheses = alphaHypotheses, nameHypotheses = nameHypotheses, m = m) save_plot_obj <- save_gg_plot(x) local_edition(3) expect_snapshot_file(save_plot_obj, "plot_hGraph_5.png") }) testthat::test_that("test: Custom position and size of ellipses, change text to multi-line text", { cbPalette <- c( " " x <- hGraph(3, x = sqrt(0:2), y = c(1, 3, 1.5), size = 6, halfWid = .3, halfHgt = .3, trhw = 0.6, palette = cbPalette[2:4], fill = c(1, 2, 2), legend.position = c(.95, .45), legend.name = "Legend:", labels = c("Group 1", "Group 2"), nameHypotheses = c("H1:\n Long name", "H2:\n Longer name", "H3:\n Longest name")) save_plot_obj <- save_gg_plot(x) local_edition(3) expect_snapshot_file(save_plot_obj, "plot_hGraph_6.png") }) testthat::test_that("test: number of digits to show for alphaHypotheses", { x <- hGraph(nHypotheses = 3, size = 5, halfWid = 1.25, trhw = 0.25, radianStart = pi/2, offset = pi/20, arrowsize = .03, digits = 3) save_plot_obj <- save_gg_plot(x) local_edition(3) expect_snapshot_file(save_plot_obj, "plot_hGraph_7.png") })
interval_pull <- function(x) { UseMethod("interval_pull") } interval_pull.default <- function(x) { dont_know(x, "interval_pull()") } interval_pull.POSIXt <- function(x) { dttm <- as.double(x) nhms <- gcd_interval(dttm) period <- split_period(nhms) new_interval( hour = period$hour, minute = period$minute, second = period$second %/% 1, millisecond = (period$second %% 1 * 1e3) %/% 1, microsecond = (period$second %% 1 * 1e3) %% 1 * 1e3 ) } interval_pull.nanotime <- function(x) { nano <- as.numeric(x) int <- gcd_interval(nano) new_interval(nanosecond = int) } interval_pull.difftime <- function(x) { t_units <- units(x) if (t_units == "weeks") { nweeks <- gcd_interval(unclass(x)) new_interval(week = nweeks) } else { dttm <- as.double(x, units = "secs") nhms <- gcd_interval(dttm) period <- split_period(nhms) new_interval( day = period$day, hour = period$hour, minute = period$minute, second = period$second ) } } interval_pull.hms <- function(x) { dttm <- as.double(x) nhms <- gcd_interval(dttm) period <- split_period(nhms) new_interval( hour = period$hour + period$day * 24, minute = period$minute, second = period$second %/% 1, millisecond = period$second %% 1 %/% 1e-3, microsecond = period$second %% 1 %/% 1e-6 %% 1e+3 ) } interval_pull.Period <- function(x) { second_int <- gcd_interval(x$second) new_interval( year = gcd_interval(x$year), month = gcd_interval(x$month), day = gcd_interval(x$day), hour = gcd_interval(x$hour), minute = gcd_interval(x$minute), second = second_int %/% 1, millisecond = round(second_int %% 1 %/% 1e-3), microsecond = round(second_int %% 1 %/% 1e-6 %% 1e+3) ) } interval_pull.Date <- function(x) { dttm <- as.numeric(x) ndays <- gcd_interval(dttm) new_interval(day = ndays) } interval_pull.yearweek <- function(x) { wk <- as.double(x) nweeks <- gcd_interval(wk) new_interval(week = nweeks) } interval_pull.yearmonth <- function(x) { mon <- as.double(x) nmonths <- gcd_interval(mon) new_interval(month = nmonths) } interval_pull.yearquarter <- function(x) { qtr <- as.double(x) nqtrs <- gcd_interval(qtr) new_interval(quarter = nqtrs) } interval_pull.numeric <- function(x) { nunits <- gcd_interval(x) if (is_empty(x)) { new_interval(unit = nunits) } else if (min0(x) > 1581 && max0(x) < 2500) { new_interval(year = nunits) } else { new_interval(unit = nunits) } } interval_pull.ordered <- function(x) { interval_pull(as.integer(x)) } new_interval <- function(..., .regular = TRUE, .others = list()) { stopifnot(is.logical(.regular)) stopifnot(is.list(.others)) default <- list2(...) names_default <- names(default) names_unit <- fn_fmls_names(default_interval) pidx <- pmatch(names_default, names_unit) if (anyNA(pidx)) { x_units <- paste(names_default[is.na(pidx)], collapse = ", ") abort(sprintf("Invalid argument: %s.", x_units)) } default <- eval_bare(call2("default_interval", !!!default)) out <- dots_list(!!!default, !!!.others, .homonyms = "error") if (!(all(map_lgl(out, function(x) has_length(x, 1))))) { abort("Only accepts one input for each argument, not empty or multiple.") } new_rcrd(fields = out, .regular = .regular, class = "interval") } is_regular_interval <- function(x) { abort_not_interval(x) x %@% ".regular" } default_interval <- function(year = 0, quarter = 0, month = 0, week = 0, day = 0, hour = 0, minute = 0, second = 0, millisecond = 0, microsecond = 0, nanosecond = 0, unit = 0) { list( year = year, quarter = quarter, month = month, week = week, day = day, hour = hour, minute = minute, second = second, millisecond = millisecond, microsecond = microsecond, nanosecond = nanosecond, unit = unit ) } irregular <- function() { new_interval(.regular = FALSE) } unknown_interval <- function(x) { is_regular_interval(x) && sum(vec_c(!!!vec_data(x))) == 0 } `[[.interval` <- function(x, i, ...) { field(x, i) } `$.interval` <- `[[.interval` format.interval <- function(x, ...) { if (!is_regular_interval(x)) return("!") if (unknown_interval(x)) return("?") n <- n_fields(x) micro <- ifelse(is_utf8_output(), "\U00B5s", "us") defaults <- vec_c("Y", "Q", "M", "W", "D", "h", "m", "s", "ms", micro, "ns", "") n_defaults <- vec_size(defaults) misc <- if (n > n_defaults) vec_slice(fields(x), (n_defaults + 1):n) else NULL fmt_names <- vec_c(defaults, misc) val <- vec_c(!!!vec_data(x)) paste0(val[val != 0], fmt_names[val != 0], collapse = " ") } default_time_units <- function(x) { abort_not_interval(x) x <- vec_data(x) x[["microsecond"]] <- x[["microsecond"]] * 1e-6 x[["millisecond"]] <- x[["millisecond"]] * 1e-3 x[["minute"]] <- x[["minute"]] * 60 x[["hour"]] <- x[["hour"]] * 3600 sum(vec_c(!!!x)) } abort_not_interval <- function(x) { if (is_false(inherits(x, "interval"))) { abort("`x` must be class 'interval'.") } } gcd_interval <- function(x) { if (length(x) < 2) { 0 } else { unique_x <- vec_unique(round(abs(diff(x)), digits = 6)) gcd_vector(unique_x) } } gcd <- function(a, b) { if (isTRUE(all.equal(b, 0))) a else gcd(b, a %% b) } gcd_vector <- function(x) Reduce(gcd, x) split_period <- function(x) { output <- seconds_to_period(x) list( year = output$year, month = output$month, day = output$day, hour = output$hour, minute = output$minute, second = output$second ) } has_tz <- function(x) { tz <- attr(x, "tzone")[[1]] !(is_null(tz) && !inherits(x, "POSIXt")) } setOldClass(c("interval", "vctrs_rcrd", "vctrs_vctr")) setMethod("as.period", "interval", function(x, ...) { period( year = x$year, month = x$quarter * 3 + x$month, week = x$week, day = x$day, hour = x$hour, minute = x$minute, second = x$second + x$millisecond / 1e3 + x$microsecond / 1e6 + x$nanosecond / 1e9) }) setMethod("as.duration", "interval", function(x, ...) { as.duration(as.period(x)) })
setMethodS3("getRelativePath", "default", function(pathname, relativeTo=getwd(), caseSensitive=NULL, ...) { getWindowsDrivePattern <- function(fmtstr, ...) { drives <- "ABCDEFGHIJKLMNOPQRSTUVWXYZ" drives <- paste(c(drives, tolower(drives)), collapse="") sprintf(fmtstr, drives) } pathname <- as.character(pathname) pathname <- .getPathIfEmpty(pathname, where="getRelativePath") nPathnames <- length(pathname) if (nPathnames == 0L) return(logical(0L)) if (nPathnames > 1L) { res <- sapply(pathname, FUN=getRelativePath, relativeTo=relativeTo, caseSensitive=caseSensitive, ...) return(res) } if (is.na(pathname)) return(NA_character_) if (isUrl(pathname)) return(pathname) pathname <- getAbsolutePath(pathname, expandTilde=TRUE) if (!isAbsolutePath(pathname)) return(pathname) if (is.null(relativeTo)) relativeTo <- "." if (length(relativeTo) > 1L) { throw("Argument 'relativeTo' must be a single character string: ", hpaste(relativeTo)) } if (is.null(caseSensitive)) { pattern <- getWindowsDrivePattern("^[%s]:") isWindows <- (regexpr(pattern, relativeTo) != -1L) caseSensitive <- !isWindows } else { caseSensitive <- as.logical(caseSensitive) if (!caseSensitive %in% c(FALSE, TRUE)) throw("Argument 'caseSensitive' must be logical: ", caseSensitive) } relativeTo <- getAbsolutePath(relativeTo, expandTilde=TRUE) relativeTo <- unlist(strsplit(relativeTo, split="[\\/]")) pathname <- unlist(strsplit(pathname, split="[\\/]")) pathnameC <- pathname if (!caseSensitive) { relativeTo <- tolower(relativeTo) pathnameC <- tolower(pathnameC) } if (!identical(relativeTo[1L], pathnameC[1L])) { pathname <- paste(pathname, collapse="/") return(pathname) } for (kk in seq_along(relativeTo)) { aPart <- relativeTo[1] bPart <- pathnameC[1] if (!identical(aPart, bPart)) break relativeTo <- relativeTo[-1L] pathname <- pathname[-1L] pathnameC <- pathnameC[-1L] } prefix <- rep("..", length.out=length(relativeTo)) pathname <- c(prefix, pathname) pathname <- paste(pathname, collapse="/") if (pathname == "") pathname <- "." pathname })
est_irt <- function(x=NULL, data, D=1, model=NULL, cats=NULL, item.id=NULL, fix.a.1pl=FALSE, fix.a.gpcm=FALSE, fix.g=FALSE, a.val.1pl=1, a.val.gpcm=1, g.val=.2, use.aprior=FALSE, use.bprior=FALSE, use.gprior=TRUE, aprior=list(dist="lnorm", params=c(0.0, 0.5)), bprior=list(dist="norm", params=c(0.0, 1.0)), gprior=list(dist="beta", params=c(5, 16)), missing=NA, Quadrature=c(49, 6.0), weights=NULL, group.mean=0.0, group.var=1.0, EmpHist=FALSE, use.startval=FALSE, Etol=1e-04, MaxE=500, control=list(iter.max=200), fipc=FALSE, fipc.method="MEM", fix.loc=NULL, verbose=TRUE) { cl <- match.call() if(!fipc) { est_par <- est_irt_em(x=x, data=data, D=D, model=model, cats=cats, item.id=item.id, fix.a.1pl=fix.a.1pl, fix.a.gpcm=fix.a.gpcm, fix.g=fix.g, a.val.1pl=a.val.1pl, a.val.gpcm=a.val.gpcm, g.val=g.val, use.aprior=use.aprior, use.bprior=use.bprior, use.gprior=use.gprior, aprior=aprior, bprior=bprior, gprior=gprior, missing=missing, Quadrature=Quadrature, weights=weights, group.mean=group.mean, group.var=group.var, EmpHist=EmpHist, use.startval=use.startval, Etol=Etol, MaxE=MaxE, control=control, verbose=verbose) } else { est_par <- est_irt_fipc(x=x, data=data, D=D, item.id=item.id, fix.a.1pl=fix.a.1pl, fix.a.gpcm=fix.a.gpcm, fix.g=fix.g, a.val.1pl=a.val.1pl, a.val.gpcm=a.val.gpcm, g.val=g.val, use.aprior=use.aprior, use.bprior=use.bprior, use.gprior=use.gprior, aprior=aprior, bprior=bprior, gprior=gprior, missing=missing, Quadrature=Quadrature, weights=weights, group.mean=group.mean, group.var=group.var, EmpHist=EmpHist, use.startval=use.startval, Etol=Etol, MaxE=MaxE, control=control, fipc=TRUE, fipc.method=fipc.method, fix.loc=fix.loc, verbose=verbose) } class(est_par) <- "est_irt" est_par$call <- cl est_par } est_irt_em <- function(x=NULL, data, D=1, model=NULL, cats=NULL, item.id=NULL, fix.a.1pl=FALSE, fix.a.gpcm=FALSE, fix.g=FALSE, a.val.1pl=1, a.val.gpcm=1, g.val=.2, use.aprior=FALSE, use.bprior=FALSE, use.gprior=TRUE, aprior=list(dist="lnorm", params=c(0.0, 0.5)), bprior=list(dist="norm", params=c(0.0, 1.0)), gprior=list(dist="beta", params=c(5, 16)), missing=NA, Quadrature=c(49, 6.0), weights=NULL, group.mean=0, group.var=1, EmpHist=FALSE, use.startval=FALSE, Etol=1e-04, MaxE=500, control=list(eval.max=200, iter.max=200), verbose=TRUE) { start.time <- Sys.time() if(use.startval & is.null(x)) { stop("To use starting values for item parameter estimation, the item metadata must be specified in the argument 'x'.", call.=FALSE) } if(verbose) { cat("Parsing input...", '\n') } if(!is.null(x)) { x <- data.frame(x) colnames(x) <- c("id", "cats", "model", paste0("par.", 1:(ncol(x) - 3))) if(ncol(x[, -c(1, 2, 3)]) == 2) { x <- data.frame(x, par.3=NA) } x <- back2df(metalist2(x)) id <- x[, 1] cats <- x[, 2] model <- as.character(x[, 3]) %>% toupper() if(!use.startval) { x <- startval_df(cats=cats, model=model) x$id <- id } } else { model <- toupper(model) if(length(model) == 1) { model <- rep(model, ncol(data)) } if(is.null(cats)) { if(all(model %in% c("1PLM", "2PLM", "3PLM", "DRM"))) { cats <- rep(2, ncol(data)) } else { stop("The number of score categories for the items should be specified in the argument 'cats'.", call.=FALSE) } } if(length(cats) == 1) { cats <- rep(cats, ncol(data)) } x <- startval_df(cats=cats, model=model, item.id=item.id) id <- x$id } if(nrow(x) != ncol(data)) stop("The number of items included in 'x' and 'data' must be the same.", call.=FALSE) if("DRM" %in% model) { model[model == "DRM"] <- "3PLM" x$model <- model memo <- "All 'DRM' items were considered as '3PLM' items during the item parameter estimation. \n" warning(memo, call.=FALSE) } if(!is.na(missing)) { data[data == missing] <- NA } data <- data.matrix(data) n.resp <- colSums(!is.na(data)) loc_allmiss <- which(n.resp == 0L) if(length(loc_allmiss) > 0L) { memo2 <- paste0(paste0("item ", loc_allmiss, collapse = ", "), " has/have no item response data. \n") stop(memo2, call.=FALSE) } if("1PLM" %in% model & !fix.a.1pl) { loc_1p_const <- which(model == "1PLM") loc_else <- which(model != "1PLM") } else { loc_1p_const <- NULL loc_else <- 1:nrow(x) } param_loc <- parloc(x=x, loc_1p_const=loc_1p_const, loc_else=loc_else, fix.a.1pl=fix.a.1pl, fix.a.gpcm=fix.a.gpcm, fix.g=fix.g) nstd <- nrow(data) if(is.null(weights)) { quadpt <- seq(-Quadrature[2], Quadrature[2], length.out=Quadrature[1]) weights <- gen.weight(dist="norm", mu=group.mean, sigma=sqrt(group.var), theta=quadpt) } else { quadpt <- weights[, 1] } resp <- purrr::map2(.x=data.frame(data), .y=cats, .f=function(k, m) factor(k, levels=(seq_len(m) - 1))) std.id <- 1:nstd freq.cat <- purrr::map(.x=resp, .f=function(k) stats::xtabs(~ std.id + k, na.action=stats::na.pass, addNA = FALSE)) freq.cat <- purrr::map(.x=freq.cat, .f=function(k) data.matrix(k) %>% unname()) rm(resp, envir=environment(), inherits = FALSE) datlist <- divide_data(data=data, cats=cats, freq.cat=freq.cat) data1_drm <- datlist$data1_drm data2_drm <- datlist$data2_drm data_plm <- datlist$data_plm rm(datlist, envir=environment(), inherits = FALSE) if(verbose) { cat("Estimating item parameters...", '\n') } time1 <- Sys.time() par.history <- list() for(r in 1:MaxE) { estep <- Estep(x=x, data1_drm=data1_drm, data2_drm=data2_drm, data_plm=data_plm, freq.cat=freq.cat, weights=weights, D=D) mstep <- Mstep(estep=estep, id=id, cats=cats, model=model, quadpt=quadpt, D=D, loc_1p_const=loc_1p_const, loc_else=loc_else, EmpHist=EmpHist, weights=weights, fix.a.1pl=fix.a.1pl, fix.a.gpcm=fix.a.gpcm, fix.g=fix.g, a.val.1pl=a.val.1pl, a.val.gpcm=a.val.gpcm, g.val=g.val, use.aprior=use.aprior, use.bprior=use.bprior, use.gprior=use.gprior, aprior=aprior, bprior=bprior, gprior=gprior, group.mean=group.mean, group.var=group.var, nstd=nstd, Quadrature=Quadrature, use.startval=TRUE, control=control, iter=r, fipc=FALSE, reloc.par=param_loc$reloc.par, info.mstep=FALSE) diff_par <- mstep$par_df[, -c(1, 2, 3)] - x[, -c(1, 2, 3)] max.diff <- abs(max(diff_par, na.rm=TRUE)) llike <- mstep$loglike if(verbose) { cat("\r", paste0("EM iteration: ", r, ", Loglike: ", format(round(mstep$loglike, 4), nsmall=4), ", Max-Change: ", format(round(max.diff, 6), nsmall=5))) } converge <- max.diff <= Etol if(converge | r == MaxE) { par_df <- mstep$par_df par.history[[r]] <- mstep$par_vec weights <- mstep$weights break } else { x <- mstep$par_df par.history[[r]] <- mstep$par_vec weights <- mstep$weights } } if(verbose) { cat("", "\n") } time2 <- Sys.time() est_time1 <- round(as.numeric(difftime(time2, time1, units = "secs")), 2) test_1st <- all(c(all(mstep$convergence == 0L), r < MaxE)) if(test_1st) { memo3 <- "Convergence criteria are satisfied." } else { memo3 <- "Convergence criteria are not satisfied." warning(paste0(memo3, " \n"), call.=FALSE) } estep <- Estep(x=x, data1_drm=data1_drm, data2_drm=data2_drm, data_plm=data_plm, freq.cat=freq.cat, weights=weights, D=D) llike <- sum(log(estep$likehd %*% matrix(weights[, 2]))) meta <- metalist2(par_df) post_dist <- estep$post_dist if(verbose) { cat("Computing item parameter var-covariance matrix...", '\n') } time1 <- Sys.time() info.data <- info_xpd(meta=meta, freq.cat=freq.cat, post_dist=post_dist, cats=cats, model=model, quadpt=quadpt, D=D, loc_1p_const=loc_1p_const, loc_else=loc_else, nstd=nstd, fix.a.1pl=fix.a.1pl, fix.a.gpcm=fix.a.gpcm, fix.g=fix.g, a.val.1pl=a.val.1pl, a.val.gpcm=a.val.gpcm, g.val=g.val, reloc.par=param_loc$reloc.par) info.prior <- info_prior(meta=meta, cats=cats, model=model, D=D, loc_1p_const=loc_1p_const, loc_else=loc_else, nstd=nstd, fix.a.1pl=fix.a.1pl, fix.a.gpcm=fix.a.gpcm, fix.g=fix.g, a.val.1pl=a.val.1pl, a.val.gpcm=a.val.gpcm, g.val=g.val, aprior=aprior, bprior=bprior, gprior=gprior, use.aprior=use.aprior, use.bprior=use.bprior, use.gprior=use.gprior, reloc.par=param_loc$reloc.par) info.mat <- info.data + info.prior test_2nd <- all(eigen(info.mat, only.values=TRUE)$values > 1e-20) if(test_2nd) { if(test_1st) { memo4 <- "Solution is a possible local maximum." } else { memo4 <- "Information matrix of item parameter estimates is positive definite." } } else { memo4 <- "Information matrix of item parameter estimates is not positive definite; unstable solution." warning(paste0(memo4, " \n"), call.=FALSE) } cov_mat <- suppressWarnings(tryCatch({solve(info.mat, tol=1e-200)}, error = function(e) {NULL})) if(is.null(cov_mat)) { se_par <- rep(99999, length(diag(info.mat))) memo5 <- "Variance-covariance matrix of item parameter estimates is not obtainable; unstable solution." warning(paste0(memo5, " \n"), call.=FALSE) } else { se_par <- suppressWarnings(sqrt(diag(cov_mat))) memo5 <- "Variance-covariance matrix of item parameter estimates is obtainable." } if(any(is.nan(se_par))) { se_par[is.nan(se_par)] <- 99999 } se_par <- ifelse(se_par > 99999, 99999, se_par) time2 <- Sys.time() est_time2 <- round(as.numeric(difftime(time2, time1, units = "secs")), 2) se_df <- loc.par <- param_loc$loc.par for(i in 1:nrow(loc.par)) { num.loc <- which(!is.na(loc.par[i, ])) se.loc <- loc.par[i, ][num.loc] se_df[i, num.loc] <- se_par[se.loc] } se_df <- data.frame(par_df[, 1:3], se_df) colnames(se_df) <- c("id", "cats", "model", paste0("se.", 1:ncol(loc.par))) loc_df <- data.frame(par_df[, 1:3], loc.par) colnames(loc_df) <- c("id", "cats", "model", paste0("par.", 1:ncol(loc.par))) all_df <- data.frame(matrix(NA, nrow=nrow(loc.par), ncol=2*ncol(loc.par))) all_df[, seq(1, 2*ncol(loc.par), 2)] <- par_df[, -c(1:3)] all_df[, seq(2, 2*ncol(loc.par), 2)] <- se_df[, -c(1:3)] col.names <- rep(NA, 2*ncol(loc.par)) col.names[seq(1, 2*ncol(loc.par), 2)] <- paste0("par.", 1:ncol(loc.par)) col.names[seq(2, 2*ncol(loc.par), 2)] <- paste0("se.", 1:ncol(loc.par)) colnames(all_df) <- col.names full_all_df <- data.frame(x[, 1:3], all_df) moments <- c(mu=group.mean, sigma2=group.var, sigma=sqrt(group.var)) moments.se <- rep(NA, 3) group.par <- data.frame(rbind(moments, moments.se)) colnames(group.par) <- c("mu", "sigma2", "sigma") rownames(group.par) <- c("estimates", "se") if(use.aprior) aprior.dist <- aprior else aprior.dist <- NULL if(use.bprior) bprior.dist <- bprior else bprior.dist <- NULL if(use.gprior) gprior.dist <- gprior else gprior.dist <- NULL npar.est=length(param_loc$reloc.par) neg2llke <- - 2 * llike aic <- 2 * npar.est + neg2llke bic <- npar.est * log(nstd) + neg2llke end.time <- Sys.time() est_time3 <- round(as.numeric(difftime(end.time, start.time, units = "secs")), 2) rst <- list(estimates=full_all_df, par.est=par_df, se.est=se_df, pos.par=loc_df, covariance=cov_mat, loglikelihood=llike, aic=aic, bic=bic, group.par=group.par, weights=weights, posterior.dist=post_dist, data=data, scale.D=D, ncase=nstd, nitem=nrow(par_df), Etol=Etol, MaxE=MaxE, aprior=aprior.dist, bprior=bprior.dist, gprior=gprior.dist, npar.est=npar.est, niter=r, maxpar.diff=max.diff, EMtime=est_time1, SEtime=est_time2, TotalTime=est_time3, test.1=memo3, test.2=memo4, var.note=memo5, fipc=FALSE, fipc.method=NULL, fix.loc=NULL) if(verbose) { cat("Estimation is finished in", est_time3, "seconds.",'\n') } return(rst) } est_irt_fipc <- function(x=NULL, data, D=1, item.id=NULL, fix.a.1pl=FALSE, fix.a.gpcm=FALSE, fix.g=FALSE, a.val.1pl=1, a.val.gpcm=1, g.val=.2, use.aprior=FALSE, use.bprior=FALSE, use.gprior=TRUE, aprior=list(dist="lnorm", params=c(0.0, 0.5)), bprior=list(dist="norm", params=c(0.0, 1.0)), gprior=list(dist="beta", params=c(5, 16)), missing=NA, Quadrature=c(49, 6.0), weights=NULL, group.mean=0.0, group.var=1.0, EmpHist=FALSE, use.startval=FALSE, Etol=1e-04, MaxE=500, control=list(eval.max=200, iter.max=200), fipc=TRUE, fipc.method="MEM", fix.loc=NULL, verbose=TRUE) { start.time <- Sys.time() if(is.null(x)) { stop("To implement the fixed item parameter calibration, the item metadata must be specified in the argument 'x'.", call.=FALSE) } if(verbose) { cat("Parsing input...", '\n') } x <- data.frame(x) colnames(x) <- c("id", "cats", "model", paste0("par.", 1:(ncol(x) - 3))) if(ncol(x[, -c(1, 2, 3)]) == 2) { x <- data.frame(x, par.3=NA) } if(!is.null(item.id)) { x$id <- item.id } x <- back2df(metalist2(x)) x$model <- as.character(x$model) %>% toupper() if("DRM" %in% x$model) { x$model[x$model == "DRM"] <- "3PLM" memo <- "All 'DRM' items were considered as '3PLM' items during the item parameter estimation. \n" warning(memo, call.=FALSE) } nitem <- nrow(x) nofix.loc <- c(1:nitem)[!c(1:nitem) %in% fix.loc] if(length(nofix.loc) == 0L) {nofix.loc <- NULL} x_fix <- x[fix.loc, ] if(!is.null(nofix.loc)) { x_new <- x[nofix.loc, ] } else { x_new <- NULL } x_fix <- back2df(metalist2(x_fix)) if(!is.null(nofix.loc)) { x_new <- back2df(metalist2(x_new)) } if(!is.null(x_new)) { id <- x_new$id cats <- x_new$cats model <- x_new$model } else { id <- x_fix$id cats <- x_fix$cats model <- x_fix$model } if(!is.null(x_new) && !use.startval) { x_new <- startval_df(cats=cats, model=model, item.id=id) } x_all <- startval_df(cats=x$cats, model=x$model, item.id=x$id) x_all[fix.loc, 1:ncol(x_fix)] <- x_fix if(!is.null(nofix.loc)) { x_all[nofix.loc, 1:ncol(x_new)] <- x_new } if(nrow(x_all) != ncol(data)) stop("The number of items included in 'x' and 'data' must be the same.", call.=FALSE) if(!is.na(missing)) { data[data == missing] <- NA } data <- data.matrix(data) n.resp <- colSums(!is.na(data)) loc_allmiss <- which(n.resp == 0L) if(length(loc_allmiss) > 0L) { memo2 <- paste0(paste0("item ", loc_allmiss, collapse = ", "), " has/have no item response data. \n") stop(memo2, call.=FALSE) } data_all <- data rm(data, envir=environment(), inherits = FALSE) data_fix <- data_all[, fix.loc, drop=FALSE] if(!is.null(x_new)) { data_new <- data_all[, nofix.loc, drop=FALSE] } else { data_new <- NULL } if("1PLM" %in% model & !fix.a.1pl) { loc_1p_const <- which(model == "1PLM") loc_else <- which(model != "1PLM") } else { loc_1p_const <- NULL if(!is.null(x_new)) { loc_else <- 1:nrow(x_new) } else { loc_else <- 1:nrow(x_all) } } if(!is.null(x_new)) { param_loc <- parloc(x=x_new, loc_1p_const=loc_1p_const, loc_else=loc_else, fix.a.1pl=fix.a.1pl, fix.a.gpcm=fix.a.gpcm, fix.g=fix.g) } else { param_loc <- parloc(x=x_all, loc_1p_const=loc_1p_const, loc_else=loc_else, fix.a.1pl=FALSE, fix.a.gpcm=FALSE, fix.g=FALSE) param_loc$loc.par[!is.na(param_loc$loc.par)] <- NA_real_ param_loc$reloc.par <- NULL } nstd <- nrow(data_all) if(is.null(weights)) { quadpt <- seq(-Quadrature[2], Quadrature[2], length.out=Quadrature[1]) weights <- gen.weight(dist="norm", mu=group.mean, sigma=sqrt(group.var), theta=quadpt) } else { quadpt <- weights[, 1] } if(!is.null(x_new)) { resp_new <- purrr::map2(.x=data.frame(data_new), .y=cats, .f=function(k, m) factor(k, levels=(seq_len(m) - 1))) resp_fix <- purrr::map2(.x=data.frame(data_fix), .y=x_fix$cats, .f=function(k, m) factor(k, levels=(seq_len(m) - 1))) } else { resp_new <- NULL resp_fix <- NULL } resp_all <- purrr::map2(.x=data.frame(data_all), .y=x_all$cats, .f=function(k, m) factor(k, levels=(seq_len(m) - 1))) std.id <- 1:nstd if(!is.null(x_new)) { freq_new.cat <- purrr::map(.x=resp_new, .f=function(k) stats::xtabs(~ std.id + k, na.action=stats::na.pass, addNA = FALSE)) freq_fix.cat <- purrr::map(.x=resp_fix, .f=function(k) stats::xtabs(~ std.id + k, na.action=stats::na.pass, addNA = FALSE)) } else { freq_new.cat <- NULL freq_fix.cat <- NULL } freq_all.cat <- purrr::map(.x=resp_all, .f=function(k) stats::xtabs(~ std.id + k, na.action=stats::na.pass, addNA = FALSE)) if(!is.null(x_new)) { freq_new.cat <- purrr::map(.x=freq_new.cat, .f=function(k) data.matrix(k) %>% unname()) freq_fix.cat <- purrr::map(.x=freq_fix.cat, .f=function(k) data.matrix(k) %>% unname()) } else { freq_new.cat <- NULL freq_fix.cat <- NULL } freq_all.cat <- purrr::map(.x=freq_all.cat, .f=function(k) data.matrix(k) %>% unname()) if(!is.null(x_new)) { rm(resp_new, envir=environment(), inherits = FALSE) rm(resp_fix, envir=environment(), inherits = FALSE) } rm(resp_all, envir=environment(), inherits = FALSE) if(!is.null(x_new)) { datlist_new <- divide_data(data=data_new, cats=cats, freq.cat=freq_new.cat) datlist_fix <- divide_data(data=data_fix, cats=x_fix$cats, freq.cat=freq_fix.cat) } else { datlist_new <- NULL datlist_fix <- NULL } datlist_all <- divide_data(data=data_all, cats=x_all$cats, freq.cat=freq_all.cat) if(is.null(x_new)) {mmt_dist_old <- c(group.mean, group.var)} if(verbose) { cat("Estimating item parameters...", '\n') } if(fipc.method=="OEM") MaxE <- 1 time1 <- Sys.time() par.history <- list() for(r in 1:MaxE) { if(!is.null(x_new)) { if(r == 1L) { estep <- Estep_fipc(x1=x_new, x2=x_fix, data1_drm1=datlist_new$data1_drm, data2_drm1=datlist_new$data2_drm, data_plm1=datlist_new$data_plm, data1_drm2=datlist_fix$data1_drm, data2_drm2=datlist_fix$data2_drm, data_plm2=datlist_fix$data_plm, freq.cat=freq_new.cat, weights=weights, D=D) } else { estep <- Estep_fipc(x1=x_new, x2=x_all, data1_drm1=datlist_new$data1_drm, data2_drm1=datlist_new$data2_drm, data_plm1=datlist_new$data_plm, data1_drm2=datlist_all$data1_drm, data2_drm2=datlist_all$data2_drm, data_plm2=datlist_all$data_plm, freq.cat=freq_new.cat, weights=weights, D=D) } } else { estep <- Estep_fipc(x1=x_all, x2=x_all, data1_drm1=datlist_all$data1_drm, data2_drm1=datlist_all$data2_drm, data_plm1=datlist_all$data_plm, data1_drm2=datlist_all$data1_drm, data2_drm2=datlist_all$data2_drm, data_plm2=datlist_all$data_plm, freq.cat=freq_all.cat, weights=weights, D=D) estep$meta <- NULL } mstep <- Mstep(estep=estep, id=id, cats=cats, model=model, quadpt=quadpt, D=D, loc_1p_const=loc_1p_const, loc_else=loc_else, EmpHist=EmpHist, weights=weights, fix.a.1pl=fix.a.1pl, fix.a.gpcm=fix.a.gpcm, fix.g=fix.g, a.val.1pl=a.val.1pl, a.val.gpcm=a.val.gpcm, g.val=g.val, use.aprior=use.aprior, use.bprior=use.bprior, use.gprior=use.gprior, aprior=aprior, bprior=bprior, gprior=gprior, group.mean=group.mean, group.var=group.var, nstd=nstd, Quadrature=Quadrature, use.startval=TRUE, control=control, iter=r, fipc=TRUE, reloc.par=param_loc$reloc.par, info.mstep=FALSE) if(!is.null(x_new)) { diff_par <- mstep$par_df[, -c(1, 2, 3)] - x_new[, -c(1, 2, 3)] max.diff <- abs(max(diff_par, na.rm=TRUE)) } else { mmt_dist_new <- cal_moment(node=mstep$weights$theta, weight=mstep$weights$weight) diff_par <- mmt_dist_new - mmt_dist_old max.diff <- abs(max(diff_par, na.rm=TRUE)) } llike <- mstep$loglike if(verbose) { cat("\r", paste0("EM iteration: ", r, ", Loglike: ", format(round(mstep$loglike, 4), nsmall=4), ", Max-Change: ", format(round(max.diff, 5), nsmall=4))) } converge <- max.diff <= Etol if(converge | r == MaxE) { if(!is.null(x_new)) { par_df <- mstep$par_df x_all[nofix.loc, 1:ncol(par_df)] <- par_df par.history[[r]] <- mstep$par_vec } weights <- mstep$weights break } else { if(!is.null(x_new)) { x_new <- mstep$par_df x_all[nofix.loc, 1:ncol(x_new)] <- x_new par.history[[r]] <- mstep$par_vec } else { mmt_dist_old <- mmt_dist_new } weights <- mstep$weights } } if(verbose) { cat("", "\n") } time2 <- Sys.time() est_time1 <- round(as.numeric(difftime(time2, time1, units = "secs")), 2) test_1st <- all(c(all(mstep$convergence == 0L), r < MaxE)) if(test_1st) { memo3 <- "Convergence criteria are satisfied." } else { memo3 <- "Convergence criteria are not satisfied." warning(paste0(memo3, " \n"), call.=FALSE) } if(!is.null(x_new)) { estep <- Estep_fipc(x1=par_df, x2=x_all, data1_drm1=datlist_new$data1_drm, data2_drm1=datlist_new$data2_drm, data_plm1=datlist_new$data_plm, data1_drm2=datlist_all$data1_drm, data2_drm2=datlist_all$data2_drm, data_plm2=datlist_all$data_plm, freq.cat=freq_new.cat, weights=weights, D=D) } else { estep <- Estep_fipc(x1=x_all, x2=x_all, data1_drm1=datlist_all$data1_drm, data2_drm1=datlist_all$data2_drm, data_plm1=datlist_all$data_plm, data1_drm2=datlist_all$data1_drm, data2_drm2=datlist_all$data2_drm, data_plm2=datlist_all$data_plm, freq.cat=freq_all.cat, weights=weights, D=D) } llike <- sum(log(estep$likehd %*% matrix(weights[, 2]))) pop_moments <- cal_moment(node=quadpt, weight=weights[, 2]) if(!is.null(x_new)) { meta <- metalist2(par_df) post_dist <- estep$post_dist if(verbose) { cat("Computing item parameter var-covariance matrix...", '\n') } time1 <- Sys.time() info.data <- info_xpd(meta=meta, freq.cat=freq_new.cat, post_dist=post_dist, cats=cats, model=model, quadpt=quadpt, D=D, loc_1p_const=loc_1p_const, loc_else=loc_else, nstd=nstd, fix.a.1pl=fix.a.1pl, fix.a.gpcm=fix.a.gpcm, fix.g=fix.g, a.val.1pl=a.val.1pl, a.val.gpcm=a.val.gpcm, g.val=g.val, reloc.par=param_loc$reloc.par) info.prior <- info_prior(meta=meta, cats=cats, model=model, D=D, loc_1p_const=loc_1p_const, loc_else=loc_else, nstd=nstd, fix.a.1pl=fix.a.1pl, fix.a.gpcm=fix.a.gpcm, fix.g=fix.g, a.val.1pl=a.val.1pl, a.val.gpcm=a.val.gpcm, g.val=g.val, aprior=aprior, bprior=bprior, gprior=gprior, use.aprior=use.aprior, use.bprior=use.bprior, use.gprior=use.gprior, reloc.par=param_loc$reloc.par) info.mat <- info.data + info.prior test_2nd <- all(eigen(info.mat, only.values=TRUE)$values > 1e-8) if(test_2nd) { if(test_1st) { memo4 <- "Solution is a possible local maximum." } else { memo4 <- "Information matrix of item parameter estimates is positive definite." } } else { memo4 <- "Information matrix of item parameter estimates is not positive definite; unstable solution." warning(paste0(memo4, " \n"), call.=FALSE) } cov_mat <- suppressWarnings(tryCatch({solve(info.mat, tol=1e-200)}, error = function(e) {NULL})) if(is.null(cov_mat)) { se_par <- rep(99999, length(diag(info.mat))) memo5 <- "Variance-covariance matrix of item parameter estimates is not obtainable; unstable solution." warning(paste0(memo5, " \n"), call.=FALSE) } else { se_par <- suppressWarnings(sqrt(diag(cov_mat))) memo5 <- "Variance-covariance matrix of item parameter estimates is obtainable." } if(any(is.nan(se_par))) { se_par[is.nan(se_par)] <- 99999 } se_par <- ifelse(se_par > 99999, 99999, se_par) time2 <- Sys.time() est_time2 <- round(as.numeric(difftime(time2, time1, units = "secs")), 2) se_df <- loc.par <- param_loc$loc.par for(i in 1:nrow(loc.par)) { num.loc <- which(!is.na(loc.par[i, ])) se.loc <- loc.par[i, ][num.loc] se_df[i, num.loc] <- se_par[se.loc] } all.col <- max(x_all$cats) all.col <- ifelse(all.col == 2, 3, all.col) se_all_df <- loc_all.par <- matrix(NA, nrow=nitem, ncol=all.col) if(ncol(se_df) < ncol(se_all_df)) { n2add <- ncol(se_all_df) - ncol(se_df) se_df <- cbind(se_df, matrix(NA, nrow=nrow(se_df), ncol=n2add)) } se_all_df[nofix.loc, 1:ncol(se_df)] <- se_df loc_all.par[nofix.loc, 1:ncol(loc.par)] <- loc.par se_all_df <- data.frame(x_all[, 1:3], se_all_df) colnames(se_all_df) <- c("id", "cats", "model", paste0("se.", 1:ncol(loc_all.par))) loc_all_df <- data.frame(x_all[, 1:3], loc_all.par) colnames(loc_all_df) <- c("id", "cats", "model", paste0("par.", 1:ncol(loc_all.par))) } else { post_dist <- estep$post_dist if(test_1st) { memo4 <- "Solution is a possible local maximum." } else { memo4 <- "Solution is not a possible local maximum because convergence criteria are not satisfied." } cov_mat <- NULL memo5 <- "Variance-covariance matrix of item parameter estimates was not estimated." est_time2 <- NULL se_df <- loc_all.par <- param_loc$loc.par se_all_df <- data.frame(x_all[, 1:3], se_df) colnames(se_all_df) <- c("id", "cats", "model", paste0("se.", 1:ncol(se_df))) loc_all_df <- NULL } all_df <- data.frame(matrix(NA, nrow=nrow(loc_all.par), ncol=2*ncol(loc_all.par))) all_df[, seq(1, 2*ncol(loc_all.par), 2)] <- x_all[, -c(1:3)] all_df[, seq(2, 2*ncol(loc_all.par), 2)] <- se_all_df[, -c(1:3)] col.names <- rep(NA, 2*ncol(loc_all.par)) col.names[seq(1, 2*ncol(loc_all.par), 2)] <- paste0("par.", 1:ncol(loc_all.par)) col.names[seq(2, 2*ncol(loc_all.par), 2)] <- paste0("se.", 1:ncol(loc_all.par)) colnames(all_df) <- col.names full_all_df <- data.frame(x_all[, 1:3], all_df) mu <- pop_moments[1] sigma2 <- pop_moments[2] sigma <- sqrt(pop_moments[2]) moments.est <- c(mu, sigma2, sigma) se.mu <- sigma / sqrt(nstd) se.sigma2 <- sigma2 * sqrt(2 / (nstd - 1)) se.sigma <- (1 / (2 * sigma)) * se.sigma2 moments.se <- c(se.mu, se.sigma2, se.sigma) group.par <- data.frame(rbind(moments.est, moments.se)) colnames(group.par) <- c("mu", "sigma2", "sigma") rownames(group.par) <- c("estimates", "se") if(use.aprior) aprior.dist <- aprior else aprior.dist <- NULL if(use.bprior) bprior.dist <- bprior else bprior.dist <- NULL if(use.gprior) gprior.dist <- gprior else gprior.dist <- NULL if(!is.null(x_new)) { npar.est <- length(param_loc$reloc.par) + 2 } else { npar.est <- 2 } neg2llke <- - 2 * llike aic <- 2 * npar.est + neg2llke bic <- npar.est * log(nstd) + neg2llke end.time <- Sys.time() est_time3 <- round(as.numeric(difftime(end.time, start.time, units = "secs")), 2) rst <- list(estimates=full_all_df, par.est=x_all, se.est=se_all_df, pos.par=loc_all_df, covariance=cov_mat, loglikelihood=llike, aic=aic, bic=bic, group.par=group.par, weights=weights, posterior.dist=post_dist, data=data_all, scale.D=D, ncase=nstd, nitem=nitem, Etol=Etol, MaxE=MaxE, aprior=aprior.dist, bprior=bprior.dist, gprior=gprior.dist, npar.est=npar.est, niter=r, maxpar.diff=max.diff, EMtime=est_time1, SEtime=est_time2, TotalTime=est_time3, test.1=memo3, test.2=memo4, var.note=memo5, fipc=TRUE, fipc.method=fipc.method, fix.loc=fix.loc) if(verbose) { cat("Estimation is finished in", est_time3, "seconds.",'\n') } return(rst) }
interactive_threshold <- function(image, type = c("black", "white"), channel = NULL, resolution = 0.1, return_param = FALSE, scale) { image_original <- image image <- image_convert(as.list(image)[[1]], format = "png") if (!missing(scale)) { image <- image_scale(image, scale) } iniv <- "0" initial <- image_threshold(image, type = type, threshold = paste(iniv, "%", sep = ""), channel = channel) iminfo <- image_info(image) range_thr <- c(0,100) length_slider <- as.integer(iminfo$width * 0.6) if (length_slider < 200) { length_slider <- 200 } text_label <- "Threshold: " quit_waiting <- !is.null(getOption("unit_test_magickGUI")) temp <- tempfile(fileext = ".jpg") on.exit(unlink(temp), add = TRUE) image_write(initial, temp) image_tcl <- tkimage.create("photo", "image_tcl", file = temp) iminfo <- image_info(image) win1 <- tktoplevel() on.exit(tkdestroy(win1), add = TRUE) win1.frame1 <- tkframe(win1) win1.im <- tklabel(win1, image = image_tcl) win1.frame1.label <- tklabel(win1.frame1, text = sprintf("%s%s %%", text_label, iniv)) slider_value <- tclVar(iniv) command_slider <- function(...) { assign("slider_value", slider_value, inherits = TRUE) } win1.frame1.slider <- tkscale(win1.frame1, from = range_thr[1], to = range_thr[2], variable = slider_value, orient = "horizontal", length = length_slider, command = command_slider, resolution = resolution, showvalue = 0) command_button <- function(...) { assign("quit_waiting", TRUE, inherits = TRUE) } temp_val <- iniv update_image <- function() { temp_image <- image_threshold(image, type = type, threshold = paste(temp_val, "%", sep = ""), channel = channel) image_write(temp_image, temp) image_tcl <- tkimage.create("photo", "image_tcl", file = temp) tkconfigure(win1.im, image = image_tcl) } win1.button <- tkbutton(win1, text = "OK", command = command_button) tkpack(win1.im) tkpack(win1.frame1.label, side = "left", anchor = "c") tkpack(win1.frame1.slider, side = "left", anchor = "c") tkpack(win1.frame1, side = "top", anchor = "c") tkpack(win1.button, side = "top", anchor = "c", pady = 20) pre_slider_value <- as.numeric(tclvalue(slider_value)) if (quit_waiting) { wait_test <- TRUE while (wait_test) { wait_test <- FALSE tryCatch({ tkwm.state(win1) }, error = function(e) assign("wait_test", TRUE, inherits = TRUE) ) } wait_time() } tkwm.state(win1, "normal") while (TRUE) { tryCatch({ tkwm.state(win1) }, error = function(e) assign("quit_waiting", TRUE, inherits = TRUE) ) if (quit_waiting) break temp_val <- as.numeric(tclvalue(slider_value)) if (temp_val != pre_slider_value) { temp_label <- sprintf("%s%s %%", text_label, formatC(temp_val)) tkconfigure(win1.frame1.label, text = temp_label) update_image() pre_slider_value <- temp_val } } val_res <- paste(formatC(pre_slider_value), "%", sep = "") names(val_res) <- "threshold" if (return_param) { return(val_res) } return(image_threshold(image_original, type = type, threshold = val_res, channel = channel)) }
EDpeff<-function(weight,dose,P,EDp,LB,UB,r=30,epsilon=.001,grid=.01, N_dose=FALSE) { change<-ifelse(N_dose==F,0,1) k1<-length(P) p<-EDp e1<-10^-7 e2<-epsilon n<-1 p1<-1 it<-1 nit<-r gr<-grid I5<-10^-10*diag(5) lb<-LB LB<-ifelse(change==0,log(LB),log(-UB)) UB<-ifelse(change==0,log(UB),log(-lb)) P[3]<-ifelse(change==0,log(P[3]),log(-P[3])) T<-P X<-c(LB,LB+(UB-LB)/4,LB+2*(UB-LB)/4,LB+3*(UB-LB)/4,UB) W<-rep(1/length(X),length(X)-1) M<-upinfor(W,T,X,k1) while(n<nit){ x<-seq(LB,UB,gr) ds<-rep(0,length(x)) if(exp(UB)<999) { inv<-ginv(M) } else { inv<-Inv(M,I5) } for (i in 1:length(x)) { ds[i]<-DS1(T,x[i],inv,p,k1) } newX<-x[which.max(ds)] newds<-max(ds) an<-1/(n+1) newM<-(1-an)*M+an*f(T,newX,k1)%*%t(f(T,newX,k1)) M<-newM X<-c(X,newX) n<-n+1 } r<-length(X) X<-unique(X[(r-k1):r]) X<-sort(X,decreasing=F) while(p1>e2) { x<-seq(LB,UB,gr) ds<-rep(0,length(x)) D<-S_weight(X,T,e1,c_weight,p,k1,UB,I5) X<-D[1,] k<-length(X) W<-D[2,1:k-1] if(exp(UB)<999) { inv<-ginv(upinfor(W,T,X,k1)) } else { inv<-Inv(upinfor(W,T,X,k1),I5) } for (i in 1:length(x)) { ds[i]<-DS1(T,x[i],inv,p,k1) } newX<-x[which.max(ds)] newds<-max(ds) X<-c(X,newX) X<-unique(sort(X,decreasing=F)) newp<-abs(newds-1) if(abs(newp-p1)<.0000001) newp<-10^-20 if(it>20) newp<-10^-20 p1<-newp it<-it+1 } Cpoints<-D[1,] Cweight<-D[2,1:(length(Cpoints)-1)] if (change==0) { Dose<-round(exp(D[1,]),2) } else { Dose<--round(exp(D[1,]),2) } Weight<-round(D[2,],3) Copt<-rbind(Dose,Weight) k<-length(dose) for (i in 1:k) if(dose[i]==0) dose[i]<-.0001 if(change==1) dose<--dose dose<-log(dose) if(exp(UB)<999) { inv<-ginv(upinfor(weight,T,dose,k1)) inv_min<-ginv(upinfor(Cweight,T,Cpoints,k1)) } else { inv<-Inv(upinfor(weight,T,dose,k1),I5) inv_min<-Inv(upinfor(Cweight,T,Cpoints,k1),I5) } eff<-(t(g(T,p))%*%inv_min%*%g(T,p))/(t(g(T,p))%*%inv%*%g(T,p)) size<-100*(1/eff-1) eff<-round(eff,2) size<-round(size,2) cat(format("c-optimal design", width=50),"\n") print(Copt) cat(format("c-efficiency", width=50),"\n") print(eff) cat(format("%More Samples Needed", width=50),"\n") print(size) }
tidy.confusionMatrix <- function(x, by_class = TRUE, ...) { cm <- as.list(x$overall) nms_cm <- stringr::str_to_lower(c(names(cm)[1:2], "McNemar")) if (by_class) { if (!inherits(x$byClass, "matrix")) { classes <- x$byClass %>% as.data.frame() %>% rename_at(1, ~"value") %>% tibble::rownames_to_column("var") %>% mutate(var = stringr::str_to_lower(gsub(" ", "_", var))) terms <- c(nms_cm, classes$var) class <- c(rep(NA_character_, 3), rep(x$positive, length(terms) - 3)) estimates <- c(cm$Accuracy, cm$Kappa, NA, classes$value) conf.low <- c(cm$AccuracyLower, rep(NA, length(terms) - 1)) conf.high <- c(cm$AccuracyUpper, rep(NA, length(terms) - 1)) p.value <- c( cm$AccuracyPValue, NA, cm$McnemarPValue, rep(NA, length(terms) - 3) ) } else { classes <- x$byClass %>% as.data.frame() %>% tibble::rownames_to_column("class") %>% pivot_longer( cols = c(dplyr::everything(), -class), names_to = "var", values_to = "value" ) %>% mutate( var = stringr::str_to_lower(gsub(" ", "_", var)), class = gsub("Class: ", "", class) ) terms <- c(nms_cm, classes$var) class <- c(rep(NA_character_, 3), classes$class) estimates <- c(cm$Accuracy, cm$Kappa, NA, classes$value) conf.low <- c(cm$AccuracyLower, rep(NA, length(terms) - 1)) conf.high <- c(cm$AccuracyUpper, rep(NA, length(terms) - 1)) p.value <- c( cm$AccuracyPValue, NA, cm$McnemarPValue, rep(NA, length(terms) - 3) ) } df <- tibble( term = terms, class = class, estimate = estimates, conf.low = conf.low, conf.high = conf.high, p.value = p.value ) } else { terms <- c(nms_cm) estimates <- c(cm$Accuracy, cm$Kappa, NA) conf.low <- c(cm$AccuracyLower, NA, NA) conf.high <- c(cm$AccuracyUpper, NA, NA) p.value <- c(cm$AccuracyPValue, NA, cm$McnemarPValue) df <- tibble( term = terms, estimate = estimates, conf.low = conf.low, conf.high = conf.high, p.value = p.value ) } as_tidy_tibble(df) }
context('GetMonthlyPayments') test_that("'getURL' errors are handled gracefully", { set_zillow_web_service_id('ZWSID') with_mock( getURL = function(...) {stop('Cryptic getURL error')}, expect_error(GetMonthlyPayments(price = 300000L), "Zillow API call with request '.+' failed with Error in RCurl::getURL\\(request\\): Cryptic getURL error"), .env = 'RCurl' ) })
approxTime <- function(x, xout, ...) { if (is.data.frame(x)) {x <- as.matrix(x); wasdf <- TRUE} else wasdf <- FALSE if (!is.matrix(x)) stop("x must be a matrix or data frame") m <- ncol(x) y <- matrix(0, nrow=length(xout), ncol=m) y[,1] <- xout for (i in 2:m) { y[,i] <- as.vector(approx(x[,1], x[,i], xout, ...)$y) } if (wasdf) y <- as.data.frame(y) names(y) <- dimnames(x)[[2]] y }
as.wcmd <- function(x) { if(!is.list(x)) stop("'x' must be a list") varcheck(x, c("data", "item1", "ni", "name1")) if(is.na(pmatch("namel", names(x)))) { x$namelen <- as.numeric(x$item1) - as.numeric(x$name1) warning("Missing argument 'namelen' set to item1 - name1 = ", x$namelen) } class(x) <- "wcmd" return(x) }
NUCKpartComposition_RNA<- function(seqs,k=5,ORF=FALSE,reverseORF=TRUE,normalized=TRUE,label=c()) { if(length(seqs)==1&&file.exists(seqs)){ seqs<-fa.read(seqs,alphabet="rna") seqs_Lab<-alphabetCheck(seqs,alphabet = "rna",label) seqs<-seqs_Lab[[1]] label<-seqs_Lab[[2]] } else if(is.vector(seqs)){ seqs<-sapply(seqs,toupper) seqs_Lab<-alphabetCheck(seqs,alphabet = "rna",label) seqs<-seqs_Lab[[1]] label<-seqs_Lab[[2]] } else { stop("ERROR: Input sequence is not in the correct format. It should be a FASTA file or a string vector.") } if(ORF==TRUE){ seqs=maxORF_RNA(seqs,reverse=reverseORF) } lenSeqs<-sapply(seqs,nchar) if(k<=0) { stop("k should be greater than zero") } if(!all(lenSeqs>k)) { stop("ERROR: k should be smaller than length of sequences") } dict<-list("A"=1,"C"=2,"G"=3,"U"=4) numSeqs<-length(seqs) featureMatrix<-matrix(0,ncol = (4*k),nrow = numSeqs) tname<-nameKmer(k=1,type = "rna") tname<-rep(tname,k) wname<-rep(1:k,each =4) coln<-paste(tname,"p",wname,sep = "") colnames(featureMatrix)<-coln winSize<-ceiling(lenSeqs/k) for(n in 1:numSeqs){ seq<-seqs[n] charSeq<-unlist(strsplit(seq,split = "")) for(i in 1:k) { winSeq<-charSeq[(((i-1)*winSize[n])+1):(i*winSize[n])] twinSeq<-table(winSeq) ntwinseq<-names(twinSeq) for(j in 1:length(twinSeq)) { colindex<-(i-1)*4+as.numeric(dict[ntwinseq[j]]) featureMatrix[n,colindex]<-twinSeq[j] } } } if(normalized==TRUE){ featureMatrix[,]<-apply(featureMatrix, 2, function(i) i/winSize) } if(length(label)==numSeqs){ featureMatrix<-as.data.frame(featureMatrix) featureMatrix<-cbind(featureMatrix,label) } row.names(featureMatrix)<-names(seqs) return(featureMatrix) }
get_var_info <- function(var_names = NULL, categories = NULL, related_to = NULL, exact = FALSE){ codebook <- csppData::codebook if(!is.null(var_names) & !is.character(var_names)){ stop("var_names must be a string or character vector.") } if(!is.null(categories) & !is.character(categories)){ stop("categories must be a string or character vector.") } if(!is.null(related_to) & !is.character(related_to)){ stop("related_to must be a string or character vector.") } if(exact == FALSE){ vars <- paste0(var_names, collapse = "|") cats <- paste0(categories, collapse = "|") rels <- paste0(related_to, collapse = "|") data <- codebook %>% dplyr::filter(stringr::str_detect(.data$variable, vars)) %>% dplyr::filter(stringr::str_detect(.data$category, cats)) %>% dplyr::filter_at(.vars = vars(.data$variable, .data$short_desc, .data$long_desc, .data$category, .data$sources), .vars_predicate = dplyr::any_vars(stringr::str_detect(., rels))) if(nrow(data) == 0){ stop("Your request returned no results.") } if(nrow(data) > 0){ return(data) } } if(exact == TRUE & !is.null(related_to) & is.null(var_names) & is.null(categories)){ rels <- paste0("\\b",related_to,"\\b", collapse = "|") data <- data %>% dplyr::filter_at(.vars = vars(.data$variable, .data$short_desc, .data$long_desc, .data$category, .data$sources), .vars_predicate = dplyr::any_vars(grepl(rels, ., ignore.case = T))) if(nrow(data) == 0){ stop("Your request returned no results.") } if(nrow(data) > 0){ return(data) } } if(exact == TRUE & !is.null(var_names) & is.null(categories)){ data <- codebook[codebook$variable %in% var_names, ] if(!is.null(related_to)){ rels <- paste0("\\b",related_to,"\\b", collapse = "|") data <- data %>% dplyr::filter_at(.vars = vars(.data$variable, .data$short_desc, .data$long_desc, .data$category, .data$sources), .vars_predicate = dplyr::any_vars(grepl(rels, ., ignore.case = T))) if(nrow(data) == 0){ stop("Your request returned no results.") } if(nrow(data) > 0){ return(data) } } if(nrow(data) == 0){ stop("Your request returned no results.") } if(nrow(data) > 0){ return(data) } } if(exact == TRUE & is.null(var_names) & !is.null(categories)){ data <- codebook[codebook$category %in% categories, ] if(!is.null(related_to)){ rels <- paste0("\\b",related_to,"\\b", collapse = "|") data <- data %>% dplyr::filter_at(.vars = vars(.data$variable, .data$short_desc, .data$long_desc, .data$category, .data$sources), .vars_predicate = dplyr::any_vars(grepl(rels, ., ignore.case = T))) if(nrow(data) == 0){ stop("Your request returned no results.") } if(nrow(data) > 0){ return(data) } } if(nrow(data) == 0){ stop("Your request returned no results.") } if(nrow(data) > 0){ return(data) } } if(exact == TRUE & !is.null(var_names) & !is.null(categories)){ data <- codebook[c(codebook$variable %in% var_names & codebook$category %in% categories), ] if(!is.null(related_to)){ rels <- paste0("\\b",related_to,"\\b", collapse = "|") data <- data %>% dplyr::filter_at(.vars = vars(.data$variable, .data$short_desc, .data$long_desc, .data$category, .data$sources), .vars_predicate = dplyr::any_vars(grepl(rels, ., ignore.case = T))) if(nrow(data) == 0){ stop("Your request returned no results.") } if(nrow(data) > 0){ return(data) } } if(nrow(data) == 0){ stop("Your request returned no results.") } if(nrow(data) > 0){ return(data) } } }
ss.aipe.c.ancova <- function(error.var.ancova=NULL, error.var.anova=NULL, rho=NULL, c.weights, width, conf.level=.95, assurance=NULL, certainty=NULL) { if (is.null(error.var.ancova)&is.null(error.var.anova)) stop("Please specify either the ANCOVA error variance, or both the ANOVA error variance and the correlation coefficient") if(!is.null(assurance)& !is.null(certainty)) {if(assurance!=certainty) stop("'assurance' and 'certainty' must have the same value")} if(!is.null(certainty)) assurance<- certainty if(is.null(error.var.ancova)) {if(is.null(error.var.anova)|is.null(rho)) stop("Please specify either the ANCOVA error variance, or both the ANOVA error variance and the correlation coefficient") error.var<- error.var.anova*(1-rho^2) } if(!is.null(error.var.ancova)) {if(!is.null(error.var.anova)|!is.null(rho)) stop("Since you input the ANCOVA error variance, do not input the ANOVA error variance and the correlation coefficient") error.var<- error.var.ancova } if(sum(c.weights)!=0) stop("The sum of the coefficients must be zero") if(sum(c.weights[c.weights>0])>1) stop("Please use fractions to specify the contrast weights") alpha <- 1-conf.level J <- length(c.weights) sigma <- sqrt(error.var) n <- (sigma^2 * 4* (qnorm(1-alpha/2))^2* sum(c.weights^2) ) / width^2 tol<- 1e-6 dif<- tol+1 if(is.null(assurance)) { while (dif > tol) {n.p <- n n<- (sigma^2 *4* (qt(1-alpha/2, n*J-J-1))^2 * sum(c.weights^2) ) / width^2 dif <- abs(n-n.p) } n<- ceiling(n) return(n) } if(!is.null(assurance)) { while(dif > tol) {n.p<-n n<- ((sigma^2 *4* (qt(1-alpha/2, n*J-J-1))^2 * sum(c.weights^2) ) / width^2) * ( qchisq(assurance, n*J-J-1) / (n*J-J-1) ) dif <- abs(n-n.p) } n<- ceiling(n) return(n) } }
wrapr::apply_left wrapr::apply_right wrapr::mk_tmp_name_source wrapr::map_to_char wrapr::`%.>%` wrapr::let wrapr::qc wrapr::qe wrapr::qae wrapr::build_frame wrapr::draw_frame wrapr::qchar_frame wrapr::`%:=%`
power.scABEL <- function(alpha=0.05, theta1, theta2, theta0, CV, n, design=c("2x3x3", "2x2x4", "2x2x3"), regulator, nsims, details=FALSE, setseed=TRUE) { desi <- match.arg(design) if (missing(regulator)) regulator <- "EMA" reg <- reg_check(regulator) if (reg$est_method!="ISC"){ r <- power.scABEL1(alpha, theta1, theta2, theta0, CV, n, design=desi, reg, nsims, details, setseed) } else { r <- power.scABEL2(alpha, theta1, theta2, theta0, CV, n, design=desi, reg, nsims, details, setseed) } r }
rRCMT <- function(n, p, p.delta, p.eps, lambda, gamma, mu, sigma, RCMTobj) { if (missing(n)) { p <- RCMTobj$p p.delta <- RCMTobj$p.delta p.eps <- RCMTobj$p.eps lambda <- RCMTobj$lambda gamma <- RCMTobj$gamma mu <- RCMTobj$mu sigma <- RCMTobj$sigma } x <- 0 y <- as.numeric(n) if (x==0) { y[1] <- rET(1, p.delta, gamma) } else { z <- rET(1, p.eps, lambda) alpha <- rlnorm(1, meanlog=mu, sdlog=sigma) k <- 1+1/alpha y[1] <- min(z, alpha*x)*k } for (i in 2:n) { if (y[i-1]==0) { y[i] <- rET(1, p.delta, gamma) } else { z <- rET(1, p.eps, lambda) alpha <- rlnorm(1, meanlog=mu, sdlog=sigma) k <- 1+1/alpha y[i] <- min(z, alpha*y[i-1])*k } } y^p }
text2color <- function(words, recode.words, colors) { nc <- length(colors) if ((nc -1) != length(recode.words)) { warning("length of colors should be 1 more than length of recode.words") } nomatch <- colors[nc] colors <- colors[-nc] nulls <- sapply(recode.words, function(x) identical(x, character(0))) recode.words[nulls] <- "" lookup <- lapply(seq_along(recode.words), function(n) cbind(recode.words[[n]], colors[n])) lookup <- do.call("rbind.data.frame", lookup) lookup <- apply(lookup, 2, as.character) recode <- lookup[match(words, lookup[, 1]), 2] recode[is.na(recode)] <- nomatch return(recode) }
md_rule <- function(char = c("*", "-", "_"), n = 3, space = FALSE) { if (n < 3) { stop("At least 3 characters must be used") } char <- match.arg(char) spaces <- glue::glue_collapse(rep(" ", as.numeric(space))) if (length(spaces) == 0) { sep <- "" } else { sep <- spaces } glue::glue_collapse(rep(char, n), sep = sep) }
test_that("modelling works", { model <- Algorithm.SDM("GLM") model@name <- paste0("test", "GLM", ".SDM") model@parameters$data <- "presence-only data set" model@parameters$metric <- "SES" data("Occurrences") data <- data.frame(X = Occurrences$LONGITUDE, Y = Occurrences$LATITUDE) data$Presence <- 1 model@data <- data data(Env) model = PA.select(model, Env, NULL, verbose = FALSE) model@parameters["PA"] = TRUE expect_equal(length(which(model@data$Presence == 0)), 1000) model = data.values(model, Env) expect_equal(dim(model@data), c(1057, 6)) model = evaluate(model, cv = "holdout", cv.param = c(0.7, 2), thresh = 1001, metric = "SES", Env) expect_equal(dim(model@evaluation), c(1, 7)) model = project(model, Env) expect_equal(all(is.na(values(model@projection))), FALSE) model = evaluate.axes(model, cv.param = c(0.7, 2), thresh = 1001, metric = "SES", axes.metric = "Pearson", Env) expect_equal(dim([email protected]), c(1, 3)) })
test_that("plot_partialAPCeffects and plot_marginalAPCeffects", { testthat::skip_if_not_installed("mgcv") library(mgcv) data(drug_deaths) model <- gam(mortality_rate ~ te(period, age), data = drug_deaths) drug_deaths$mortality_rate <- drug_deaths$mortality_rate + 1 model_logLink <- bam(mortality_rate ~ te(period, age), family = Gamma(link = "log"), data = drug_deaths) gg1 <- plot_partialAPCeffects(model, dat = drug_deaths, variable = "age", vlines_vec = c(20,70)) gg2 <- plot_partialAPCeffects(model, dat = drug_deaths, variable = "period", vlines_vec = c(1990,2010)) gg3 <- plot_partialAPCeffects(model, dat = drug_deaths, variable = "cohort", vlines_vec = c(1950,1970)) gg4 <- plot_partialAPCeffects(model_logLink, dat = drug_deaths, variable = "age") gg5 <- plot_partialAPCeffects(model_logLink, dat = drug_deaths, variable = "period") gg6 <- plot_partialAPCeffects(model_logLink, dat = drug_deaths, variable = "cohort") expect_s3_class(gg1, class = c("gg","ggplot")) expect_s3_class(gg2, class = c("gg","ggplot")) expect_s3_class(gg3, class = c("gg","ggplot")) expect_s3_class(gg4, class = c("gg","ggplot")) expect_s3_class(gg5, class = c("gg","ggplot")) expect_s3_class(gg6, class = c("gg","ggplot")) dat_list <- plot_partialAPCeffects(model, dat = drug_deaths, variable = "cohort", return_plotData = TRUE) expect_length(dat_list, 4) expect_s3_class(dat_list[[2]], "data.frame") expect_identical(names(dat_list), c("dat_overallEffect","dat_age","dat_period", "dat_cohort")) gg7 <- plot_marginalAPCeffects(model, dat = drug_deaths, variable = "age") gg8 <- plot_marginalAPCeffects(model, dat = drug_deaths, variable = "period") gg9 <- plot_marginalAPCeffects(model, dat = drug_deaths, variable = "cohort") expect_s3_class(gg7, class = c("gg","ggplot")) expect_s3_class(gg8, class = c("gg","ggplot")) expect_s3_class(gg9, class = c("gg","ggplot")) dat_list2 <- plot_marginalAPCeffects(model, dat = drug_deaths, variable = "period", return_plotData = TRUE) expect_length(dat_list2, 4) expect_s3_class(dat_list2[[2]], "data.frame") expect_identical(names(dat_list2), c("dat_overallEffect","dat_age","dat_period", "dat_cohort")) }) test_that("plot_jointMarginalAPCeffects", { testthat::skip_if_not_installed("mgcv") library(mgcv) data(drug_deaths) model1 <- gam(mortality_rate ~ te(period, age), data = drug_deaths) model2 <- gam(mortality_rate ~ te(period, age) + population, data = drug_deaths) model_list <- list("Model A" = model1, "Model B" = model2) gg <- plot_jointMarginalAPCeffects(model_list, dat = drug_deaths, vlines_list = list("age" = c(20,50), "cohort" = c(1950,1980))) expect_s3_class(gg, class = c("gg","ggplot")) })
wilcoxon_rank_sum_test <- function( data = NULL, iv_name = NULL, dv_name = NULL, sigfigs = 3) { iv <- dv <- wilcoxon_rank_sum_p_value <- effect_size_r <- NULL number_of_lvls_in_iv <- length(unique(data[[iv_name]])) if (number_of_lvls_in_iv < 2) { stop(paste0( "There are fewer than 2 levels in the IV: ", sort(unique(data[[iv_name]])))) } dt01 <- setDT(copy(data))[, c(iv_name, dv_name), with = FALSE] names(dt01) <- c("iv", "dv") dt01[, iv := factor(iv)] dt01 <- stats::na.omit(dt01) group <- sort(unique(dt01$iv)) dt02 <- data.table(t(utils::combn(group, 2))) names(dt02) <- c("group_1", "group_2") group_1_median <- vapply(dt02[["group_1"]], function(i) { stats::median(dt01[iv == i]$dv, na.rm = TRUE)}, FUN.VALUE = numeric(1L)) group_2_median <- vapply(dt02[["group_2"]], function(i) { stats::median(dt01[iv == i]$dv, na.rm = TRUE)}, FUN.VALUE = numeric(1L)) wilcoxon_results <- lapply(seq_len(nrow(dt02)), function(i) { results_for_1_pair <- stats::wilcox.test( formula = dv ~ iv, data = dt01[iv %in% dt02[i, ]], paired = FALSE) wilcoxon_rank_sum_p_value <- results_for_1_pair[["p.value"]] w_stat <- results_for_1_pair[["statistic"]] z_for_effect_size_r <- stats::qnorm(wilcoxon_rank_sum_p_value / 2) n_for_pairwise_comparison <- nrow(dt01[iv %in% dt02[i, ]]) effect_size_r <- z_for_effect_size_r / sqrt(n_for_pairwise_comparison) output <- c(wilcoxon_rank_sum_p_value, w_stat, effect_size_r) names(output) <- c( "wilcoxon_rank_sum_p_value", "w_stat", "effect_size_r") return(output)}) wilcoxon_results_dt <- as.data.table( do.call(rbind, wilcoxon_results)) bonferroni_signif_for_wilcoxon_test <- ifelse( wilcoxon_results_dt[, wilcoxon_rank_sum_p_value] < (.05 / nrow(dt02)), "Yes", "No") output <- data.table( dt02, group_1_median, group_2_median, wilcoxon_results_dt) output[, wilcoxon_rank_sum_p_value := kim::pretty_round_p_value(wilcoxon_rank_sum_p_value)] output[, effect_size_r := kim::round_flexibly(effect_size_r, sigfigs)] return(output) }
context("Compile") test_that("Categorical versus Numerical generates a table", { test_table <- tangram(drug ~ bili, pbc, "test") expect_true(inherits(test_table, "tangram")) }) test_that("Categorical versus a function of Numerical generates a table", { test_table <- tangram(drug ~ log(bili), pbc, "test") expect_true(inherits(test_table, "tangram")) }) test_that("Categorical versus a Categorical generates a table", { test_table <- tangram(drug ~ sex, pbc, "test") expect_true(inherits(test_table, "tangram")) }) test_that("Categorical versus a Categorical of coerced type generates a table", { test_table <- tangram(drug ~ stage::Categorical, pbc, "test") expect_true(inherits(test_table, "tangram")) }) test_that("A multiterm expression generates a table", { test_table <- tangram(drug ~ bili + albumin + stage::Categorical + protime + sex + age + spiders, pbc, "test") expect_true(inherits(test_table, "tangram")) }) test_that("A Numerical versus a Numerical generates a table", { test_table <- tangram(age ~ albumin, pbc, "test") expect_true(inherits(test_table, "tangram")) }) test_that("Intercept handling works", { d1 <- iris d1$A <- d1$Sepal.Length > 5.1 attr(d1$A,"label") <- "Sepal Length > 5.1" tbl1 <- tangram(Species + 1 ~ A + Sepal.Width,data = d1, "test") expect_true(inherits(tbl1, "tangram")) }) test_that("trailing spaces in a formula work", { tbl1 <- tangram("drug ~ bili ", pbc, "test") expect_true(inherits(tbl1, "tangram")) }) test_that("data.frame with names having spaces renders", { df <- data.frame("Given Name" = c("John", "Jacob"), "Sur Name" = c("Jingleheimer", "Smith"), check.names=FALSE) tbl1 <- tangram(df, as.character=TRUE, id="tbl1") expect_true(nchar(summary(tbl1)) > 0) }) test_that("2 contingency table is correctly rendered", { x <- with(warpbreaks, table(wool)) %>% tangram(id="tbl1") expect_true(length(x) == 2) expect_true(length(x[[1]]) == 2) }) test_that("2x3 contingency table is correctly rendered", { x <- with(warpbreaks, table(wool, tension)) %>% tangram(id="tbl1") expect_true(length(x) == 3) expect_true(length(x[[1]]) == 4) }) test_that("2x2X6 contingency table is correctly rendered", { x <- tangram(UCBAdmissions, id="tbl1", style="nejm") expect_true(length(x) == 5) expect_true(length(x[[1]]) == 8) }) test_that("handles columns with spaces", { df <- data.frame(z=1:3, x=4:6) names(df) <- c("foo bar", "x") tbl1 <- tangram(x ~ `foo bar`, df) expect_true(inherits(tbl1, "tangram")) })
tokens_ngrams <- function(x, n = 2L, skip = 0L, concatenator = "_") { UseMethod("tokens_ngrams") } tokens_ngrams.default <- function(x, n = 2L, skip = 0L, concatenator = "_") { check_class(class(x), "tokens_ngrams") } tokens_ngrams.character <- function(x, n = 2L, skip = 0L, concatenator = "_") { if (is.na(x[1]) && length(x) == 1) return(NULL) if (any(stringi::stri_detect_charclass(x, "\\p{Z}")) & concatenator != " ") warning("whitespace detected: you may need to run tokens() first") if (length(x) < min(n)) return(NULL) if (identical(as.integer(n), 1L)) { if (!identical(as.integer(skip), 0L)) warning("skip argument ignored for n = 1") return(x) } tokens_ngrams(as.tokens(list(x)), n = n, skip = skip, concatenator = concatenator)[[1]] } char_ngrams <- function(x, n = 2L, skip = 0L, concatenator = "_") { UseMethod("char_ngrams") } char_ngrams.default <- function(x, n = 2L, skip = 0L, concatenator = "_") { check_class(class(x), "char_ngrams") } char_ngrams.character <- function(x, n = 2L, skip = 0L, concatenator = "_") { as.character(tokens_ngrams(x, n, skip, concatenator)) } tokens_ngrams.tokens <- function(x, n = 2L, skip = 0L, concatenator = "_") { x <- as.tokens(x) n <- check_integer(n, min = 1, max_len = Inf) skip <- check_integer(skip, min_len = 1, max_len = Inf, min = 0) concatenator <- check_character(concatenator) attrs <- attributes(x) if (identical(n, 1L) && identical(skip, 0L)) return(x) result <- qatd_cpp_tokens_ngrams(x, types(x), concatenator, n, skip) field_object(attrs, "ngram") <- n field_object(attrs, "skip") <- skip field_object(attrs, "concatenator") <- concatenator rebuild_tokens(result, attrs) } tokens_skipgrams <- function(x, n, skip, concatenator = "_") { UseMethod("tokens_skipgrams") } tokens_skipgrams.default <- function(x, n, skip, concatenator = "_") { check_class(class(x), "tokens_skipgrams") } tokens_skipgrams.tokens <- function(x, n, skip, concatenator = "_") { tokens_ngrams(x, n = n, skip = skip, concatenator = concatenator) }
library(dplyr) df <- head(ggplot2::diamonds, 20) df df <- df %>% mutate_if(is.character, as.factor) df classes <- map_chr(df, ~ class(.x)[[1]]) df <- df %>% mutate_if(is.factor, as.numeric) dfl <- df %>% purrr::transpose() %>% purrr::map(unname) %>% purrr::map(unlist) %>% purrr::map(~ list(data = .x)) dfl highchart() %>% hc_chart( type = "line", parallelCoordinates = TRUE, parallelAxes = list(lineWidth = 2) ) %>% hc_plotOptions( series = list( animation = FALSE, marker= list( enabled = FALSE, states = list( hover = list( enabled = FALSE ) ) ), states= list( hover= list( halo= list( size = 0 ) ) ), events= list(mouseOver = JS("function () { this.group.toFront(); }")) ) ) %>% hc_add_series_list(dfl)
poissonize <- function(data, interval.width = 365.25/4, factors = NULL, compress = TRUE) { person.breaks <- Vectorize(function(stopT) unique(c(seq(0, stopT, by = interval.width), stopT))) the.breaks <- person.breaks(data$time) startT <- lapply(the.breaks, function(x) x[-length(x)]) stopT <- lapply(the.breaks, function(x) x[-1]) count.per.id <- sapply(startT, length) index <- tapply(data$id, data$id, length) index <- cumsum(index) event <- rep(0, sum(count.per.id)) event[cumsum(count.per.id)] <- data$status[index] expData <- cbind( data.frame(id = rep(data$id[index], count.per.id), startT = unlist(startT), stopT = unlist(stopT), event = event), data[sapply(rep(data$id[index], count.per.id), function(x) which(data$id==x)), factors, drop=FALSE]) expData$time <- expData$stopT - expData$startT expData$interval <- factor(expData$start) expData <- subset(expData, select=-c(startT, stopT)) expData$time <- expData$time if (compress) { m <- aggregate(x = expData$event, by = expData[, c('interval', factors), drop=FALSE], sum) colnames(m)[ncol(m)] <- 'm' Rt <- aggregate(x = expData$time, by = expData[, c('interval', factors), drop=FALSE], sum) colnames(Rt)[ncol(Rt)] <- 'Rt' N <- aggregate(x = expData$event, by = expData[, c('interval', factors), drop=FALSE], function(x) sum(!is.na(x))) colnames(N)[ncol(N)] <- 'N' expData <- base::merge(m, base::merge(Rt, N)) } attr(expData, 'interval.width') <- interval.width return(expData) }
split.ped <- function(ped, mem = new.env()) { key <- digest(list("split.ped",ped)) if(exists(key, envir = mem)) return(list(result= get(key, envir = mem), mem = mem)) n.vec <- which(nb.enfants(ped) > 0 & ped$st[,"pere"] != 0); ped$st <- ped$st[, c('id', 'pere', 'mere', 'sexe') ] id.pivots <- matrix(ncol=length(n.vec), nrow=2) n.pivots <- matrix(ncol=length(n.vec), nrow=2) new.id <- max(ped$st[,"id"]) new.n <- dim(ped$st)[1] for(i in seq_along(n.vec)) { n <- n.vec[i] new.n <- new.n + 1; new.id <- new.id + 1 id.pivots[1,i] <- ped$st[n,"id"] id.pivots[2,i] <- new.id n.pivots[1,i] <- n; n.pivots[2,i] <- new.n; ped$st <- rbind(ped$st, ped$st[n,]); ped$st[new.n,"id"] <- new.id ped$st[new.n,"pere"] <- ped$st[n,"pere"] ped$st[new.n,"mere"] <- ped$st[n,"mere"] ped$st[n,"pere"] <- ped$st[n,"mere"] <- 0 ped$geno <- c(ped$geno, ped$geno[n]) ped$pheno <- c(ped$pheno, ped$pheno[n]) } w <- rep(TRUE, new.n) f2G <- list(); while(any(w)) { b <- min( ped$st[ w , "id"] ) L <- 0; while(length(b) != L) { L <- length(b); w.b <- is.element(ped$st[,"id"],b) b <- union(b, ped$st[w.b,"pere"]) b <- union(b, ped$st[w.b,"mere"]) b <- setdiff(b, 0) b <- union(b, ped$st[ is.element(ped$st[,"pere"], b) | is.element(ped$st[,"mere"], b) , "id"]); } f2G <- c(f2G, list(w.b)) w <- w & (!w.b); } x <- as.vector(id.pivots) f2G.pivots <- vector('list', length(f2G)) for(i in seq_along(f2G)) f2G.pivots[[i]] <- x[is.element(x, ped$st[f2G[[i]],"id"])] r <- list(ped = ped, id.pivots = id.pivots, n.pivots = n.pivots, f2G = f2G, f2G.pivots=f2G.pivots) mem.sv(key, r, mem) return( list(result=r, mem=mem)); } Elston.on.splitted <- function(splitted, modele, theta, mem=new.env()) { key <- digest(list("bidouille",splitted, modele, theta)) if(exists(key, envir = mem)) return(list(result= get(key, envir = mem), mem = mem)) if(dim(splitted$n.pivots)[2] == 0) { P <- 1; for(i in seq_along(splitted$f2G)) { w <- splitted$f2G[[i]] ped <- list( st = splitted$ped$st[w,,drop=FALSE], geno=splitted$ped$geno[w], pheno=splitted$ped$pheno[w] ) lik.2g <- Likelihood.2g(ped,modele,theta,mem) P <- P*lik.2g$result; mem <- lik.2g$mem; } mem.sv(key, P, mem); return( list(result=P, mem=mem) ); } Re <- extract.pivot(splitted, mem); extract <- Re$result; mem <- Re$mem; S <- 0; for(a in extract$geno.piv) { numerateur <- modele$proba.g(a,theta)*modele$p.pheno(extract$pheno.piv,a,theta) if(all(numerateur == 0)) next; numerateur[ numerateur == 0 ] <- 1; extract$splitted$ped$geno[extract$n.piv] <- a Re <- Recall(extract$splitted, modele, theta, mem) P <- Re$result mem <- Re$mem for(i in seq_along(extract$F2G)) { f2g <- extract$F2G[[i]]$ped n.piv.f2g <- extract$F2G[[i]]$n.piv f2g$geno[n.piv.f2g] <- a lik.2g <- Likelihood.2g(f2g,modele,theta,mem) P <- P*lik.2g$result; mem <- lik.2g$mem; } S <- S + P/numerateur } mem.sv(key, S, mem); return( list(result=S, mem=mem) ); } extract.pivot <- function(splitted, mem = new.env()) { key <- digest(list("extract.pivot",splitted)) if(exists(key, envir = mem)) return(list(result= get(key, envir = mem), mem = mem)) k <- 1 n.piv.1 <- splitted$n.pivots[1,k] n.piv.2 <- splitted$n.pivots[2,k] id.piv.1 <- splitted$id.pivots[1,k] id.piv.2 <- splitted$id.pivots[2,k] ph <- splitted$ped$pheno[[n.piv.1]]; g <- splitted$ped$geno[[ n.piv.1 ]] splitted$n.pivots <- splitted$n.pivots[,-k,drop=FALSE] splitted$id.pivots <- splitted$id.pivots[,-k,drop=FALSE] F2G <- list() w.fix <- rep(FALSE, length(splitted$f2G)) w <- rep(FALSE, dim(splitted$ped$st)[1]) for(i in seq_along(splitted$f2G)) { a <- splitted$f2G.pivots[[i]] splitted$f2G.pivots[[i]] <- a[ a != id.piv.1 & a != id.piv.2 ]; if( length( splitted$f2G.pivots[[i]] ) == 0 ) { w.fix[i] <- TRUE w <- w | splitted$f2G[[i]]; ped <- list(st = splitted$ped$st[splitted$f2G[[i]],,drop=FALSE], pheno = splitted$ped$pheno[splitted$f2G[[i]]], geno=splitted$ped$geno[splitted$f2G[[i]]] ) n.piv <- which( ped$st[,"id"] == id.piv.1 | ped$st[,"id"] == id.piv.2 ) F2G <- c( F2G, list(list(ped=ped, n.piv=n.piv) )) } } if(any(w)) { splitted$ped <- list( st = splitted$ped$st[!w,,drop=FALSE] , geno = splitted$ped$geno[!w], pheno = splitted$ped$pheno[!w] ) splitted$f2G <- splitted$f2G[!w.fix]; for(i in seq_along(splitted$f2G)) splitted$f2G[[i]] <- splitted$f2G[[i]][!w] splitted$f2G.pivots <- splitted$f2G.pivots[!w.fix]; splitted$n.pivots <- matrix(sapply( splitted$id.pivots, function(i) which(splitted$ped$st[,"id"]==i) ), nrow=2) } n.piv = which( is.element(splitted$ped$st[,"id"], c(id.piv.1, id.piv.2))) r <- list(n.piv = n.piv , pheno.piv = ph, geno.piv = g, splitted = splitted, F2G = F2G) mem.sv(key, r, mem); return(list(result=r, mem=mem)) } Elston <- function(ped, modele, theta, mem = new.env()) { if(class(ped) != "es.pedigree") stop("Argument ped is not of class es.pedigree") Re <- split.ped(ped, mem) Elston.on.splitted( Re$result, modele, theta, Re$mem) }
cdm_attach_exported_function <- function(pack, fun) { CDM_require_namespace(pkg=pack) fn <- paste0(pack, paste0(rep(":",2), collapse=""), fun) fn <- eval(parse(text=fn)) return(fn) }
library(dbscan) cl <- dbscan(iris[,-5], eps = .5, minPts = 5) plot(iris[,-5], col = cl$cluster)
context('plm0') test_that("plm0 can handle different inputs", { expect_error(plm0(Q~W,c(1,2,3))) expect_error(plm0('Q~W',krokfors)) expect_error(plm0(V~W,krokfors)) expect_error(plm0(Q~W+X,krokfors)) expect_error(plm0(Q~W,krokfors,c_param=min(krokfors$W)+0.5)) expect_error(plm0(Q~W,krokfors,c_param=1L)) expect_error(plm0(Q~W,krokfors,h_max=max(krokfors$W)-0.5)) skip_on_cran() krokfors_new_names <- krokfors names(krokfors_new_names) <- c('t1','t2') set.seed(1) plm0.fit_new_names <- plm0(t2~t1,krokfors_new_names,num_cores=2) expect_equal(plm0.fit_new_names$rating_curve,plm0.fit$rating_curve) }) test_that("the plm0 object with unknown c is in tact", { expect_is(plm0.fit,"plm0") test_stage_indep_param(plm0.fit,'a') test_stage_indep_param(plm0.fit,'b') test_stage_indep_param(plm0.fit,'c') test_stage_indep_param(plm0.fit,'sigma_eps') expect_true(is.double(plm0.fit$Deviance_posterior)) expect_equal(length(plm0.fit$Deviance_posterior),plm0.fit$run_info$num_chains*((plm0.fit$run_info$nr_iter-plm0.fit$run_info$burnin)/plm0.fit$run_info$thin + 1)) expect_equal(unname(unlist(plm0.fit$Deviance_summary[1,])),unname(quantile(plm0.fit$Deviance_posterior,probs=c(0.025,0.5,0.975)))) test_stage_dep_component(plm0.fit,'rating_curve') test_stage_dep_component(plm0.fit,'rating_curve_mean') expect_equal(plm0.fit$formula,Q~W) expect_equal(plm0.fit$data,krokfors[order(krokfors$W),c('Q','W')]) }) test_that("the plm0 object with known c with a maximum stage value is in tact", { skip_on_cran() set.seed(1) plm0.fit_known_c <- plm0(Q~W,krokfors,c_param=known_c,h_max=h_extrap,num_cores=2) expect_is(plm0.fit_known_c,"plm0") test_stage_indep_param(plm0.fit_known_c,'a') test_stage_indep_param(plm0.fit_known_c,'b') expect_true(is.null(plm0.fit_known_c[['c_posterior']])) expect_false('c' %in% row.names(plm0.fit_known_c)) test_stage_indep_param(plm0.fit_known_c,'sigma_eps') expect_true(is.double(plm0.fit_known_c$Deviance_posterior)) expect_equal(length(plm0.fit_known_c$Deviance_posterior),plm0.fit_known_c$run_info$num_chains*((plm0.fit_known_c$run_info$nr_iter-plm0.fit_known_c$run_info$burnin)/plm0.fit_known_c$run_info$thin + 1)) expect_equal(unname(unlist(plm0.fit_known_c$Deviance_summary[1,])),unname(quantile(plm0.fit_known_c$Deviance_posterior,probs=c(0.025,0.5,0.975)))) test_stage_dep_component(plm0.fit_known_c,'rating_curve') test_stage_dep_component(plm0.fit_known_c,'rating_curve_mean') expect_equal(max(plm0.fit_known_c$rating_curve$h),h_extrap) expect_true(max(diff(plm0.fit_known_c$rating_curve$h))<=(0.05+1e-9)) }) test_that("plm0 output remains unchanged", { skip_on_cran() skip_on_ci() skip_on_covr() expect_equal_to_reference(plm0.fit,file='../cached_results/plm0.fit.rds',update=TRUE) })
CreateInitializeMatrix <- function(InitialData,WhichCat,empty=FALSE){ N=names(InitialData) InitMat=matrix(rep(0,length(N)*length(N)),nrow=length(N)) InitDatF=data.frame(InitMat) names(InitDatF)=N row.names(InitDatF)=N if(empty==TRUE){ return(InitDatF) }else{ InitMat[upper.tri(InitMat)]=1 InitMat[WhichCat!=1,]=0 InitDatF=data.frame(InitMat) names(InitDatF)=N row.names(InitDatF)=N return(InitDatF) } }
data(iris) data(audit) test_that("ClusteringModel/stats kmeans pmml() output contains MiningSchema, Output, ClusteringField, and Cluster nodes", { library(clue) fit <- kmeans(iris[, 1:4], 3) pmml_fit <- pmml(fit) expect_named(names(pmml_fit[[3]]), c("MiningSchema", "Output", "ComparisonMeasure", "ClusteringField", "ClusteringField", "ClusteringField", "ClusteringField", "Cluster", "Cluster", "Cluster")) }) test_that("GeneralRegressionModel/glmnet pmml() output contains Extension, MiningSchema, Output, ParameterList, CovariateList, PPMatrix, and ParamMatrix nodes", { library(glmnet) x <- data.matrix(iris[1:4]) y <- data.matrix(iris[5]) fit <- cv.glmnet(x, y) pmml_fit <- pmml(fit) expect_named(names(pmml_fit[[3]]), c("Extension", "MiningSchema", "Output", "ParameterList", "CovariateList", "PPMatrix", "ParamMatrix")) }) test_that("GeneralRegressionModel/stats pmml() output contains MiningSchema, Output, ParameterList, FactorList, CovariateList, PPMatrix, and ParamMatrix nodes", { suppressWarnings(fit <- glm(as.factor(Adjusted) ~ Age + Employment + Education + Marital + Occupation + Income + Sex + Deductions + Hours, family = binomial(link = logit), audit )) pmml_fit <- pmml(fit) expect_named(names(pmml_fit[[3]]), c("MiningSchema", "Output", "ParameterList", "FactorList", "CovariateList", "PPMatrix", "ParamMatrix")) }) test_that("MiningModel/randomForest pmml() output contains MiningSchema, Output, and Segmentation nodes", { library(randomForest) fit <- randomForest(Species ~ ., data = iris, ntree = 3) a <- capture.output(pmml_fit <- pmml(fit)) expect_named(names(pmml_fit[[3]]), c("MiningSchema", "Output", "Segmentation")) }) test_that("NaiveBayesModel/e1071 pmml() output contains MiningSchema, Output, BayesInputs, and BayesOutput nodes", { library(e1071) fit <- naiveBayes(as.factor(Adjusted) ~ Employment + Education + Marital + Occupation + Sex, data = audit) pmml_fit <- pmml(fit, predicted_field = "Adjusted") expect_named(names(pmml_fit[[3]]), c("MiningSchema", "Output", "BayesInputs", "BayesOutput")) }) test_that("NeuralNetwork/nnet pmml() output contains MiningSchema, Output, NeuralInputs, NeuralLayer, and NeuralOutputs nodes", { library(nnet) fit <- nnet(Species ~ ., data = iris, size = 4, trace = F) pmml_fit <- pmml(fit) expect_named(names(pmml_fit[[3]]), c("MiningSchema", "Output", "NeuralInputs", "NeuralLayer", "NeuralLayer", "NeuralOutputs")) }) test_that("RegressionModel/stats pmml() output contains MiningSchema, Output, and RegressionTable nodes", { fit <- lm(Sepal.Length ~ ., data = iris) pmml_fit <- pmml(fit) expect_named(names(pmml_fit[[3]]), c("MiningSchema", "Output", "RegressionTable")) }) test_that("RegressionModel/nnet pmml() output contains MiningSchema, Output, and RegressionTable nodes", { library(nnet) fit <- multinom(Species ~ ., data = iris, trace = F) pmml_fit <- pmml(fit) expect_named(names(pmml_fit[[3]]), c("MiningSchema", "Output", "RegressionTable", "RegressionTable", "RegressionTable")) }) test_that("SupportVectorMachineModel/e1071 pmml() output contains MiningSchema, Output, LocalTransformations, RadialBasisKernelType, VectorDictionary, and SupportVectorMachine nodes", { library(e1071) fit <- svm(Species ~ ., data = iris) pmml_fit <- pmml(fit) expect_named(names(pmml_fit[[3]]), c("MiningSchema", "Output", "LocalTransformations", "RadialBasisKernelType", "VectorDictionary", "SupportVectorMachine", "SupportVectorMachine", "SupportVectorMachine")) }) test_that("SupportVectorMachineModel/kernlab pmml() output contains MiningSchema, Output, LocalTransformations, RadialBasisKernelType, VectorDictionary, and SupportVectorMachine nodes", { library(kernlab) a <- capture.output(fit <- ksvm(Species ~ ., data = iris, kernel = "rbfdot")) pmml_fit <- pmml(fit, data = iris) expect_named(names(pmml_fit[[3]]), c("MiningSchema", "Output", "LocalTransformations", "RadialBasisKernelType", "VectorDictionary", "SupportVectorMachine", "SupportVectorMachine", "SupportVectorMachine")) }) test_that("Transformations pmml() output contains MiningSchema, Output, LocalTransformations, and RegressionTable nodes", { dataBox <- xform_wrap(iris) dataBox <- xform_min_max(dataBox, "1") dataBox <- xform_z_score(dataBox, "1", map_missing_to = 999) dataBox <- xform_norm_discrete(dataBox, input_var = "Species") dataBox <- xform_function(dataBox, orig_field_name = "Sepal.Width", new_field_name = "a_derived_field", expression = "sqrt(Sepal.Width^2 - 3)") fit <- lm(Petal.Width ~ ., data = dataBox$data) pmml_fit <- pmml(fit, transform = dataBox) expect_named(names(pmml_fit[[3]]), c("MiningSchema", "Output", "LocalTransformations", "RegressionTable")) }) test_that("Rpart pmml() output contains MiningSchema, Output, and Node nodes", { library(rpart) fit <- rpart(Species ~ ., data = iris) pmml_fit <- pmml(fit) expect_named(names(pmml_fit[[3]]), c("MiningSchema", "Output", "Node")) })
library(hamcrest) Conj.foo <- function(...) 41 Complex.bar <- function(...) 45 test.Conj.1 <- function() assertThat(Conj(NULL), throwsError()) test.Conj.2 <- function() assertThat(Conj(logical(0)), identicalTo(numeric(0))) test.Conj.3 <- function() assertThat(Conj(c(TRUE, TRUE, FALSE, FALSE, TRUE)), identicalTo(c(1, 1, 0, 0, 1))) test.Conj.4 <- function() assertThat(Conj(structure(c(TRUE, FALSE), .Names = c("a", ""))), identicalTo(structure(c(1, 0), .Names = c("a", "")))) test.Conj.5 <- function() assertThat(Conj(c(TRUE, FALSE, NA)), identicalTo(c(1, 0, NA))) test.Conj.6 <- function() assertThat(Conj(integer(0)), identicalTo(numeric(0))) test.Conj.7 <- function() assertThat(Conj(structure(integer(0), .Names = character(0))), identicalTo(structure(numeric(0), .Names = character(0)))) test.Conj.8 <- function() assertThat(Conj(1:3), identicalTo(c(1, 2, 3))) test.Conj.9 <- function() assertThat(Conj(c(1L, NA, 4L, NA, 999L)), identicalTo(c(1, NA, 4, NA, 999))) test.Conj.10 <- function() assertThat(Conj(c(1L, 2L, 1073741824L, 1073741824L)), identicalTo(c(1, 2, 1073741824, 1073741824), tol = 0.000100)) test.Conj.11 <- function() assertThat(Conj(numeric(0)), identicalTo(numeric(0))) test.Conj.12 <- function() assertThat(Conj(NaN), identicalTo(NaN)) test.Conj.13 <- function() assertThat(Conj(NA_real_), identicalTo(NA_real_)) test.Conj.14 <- function() assertThat(Conj(1), identicalTo(1)) test.Conj.15 <- function() assertThat(Conj(1.5), identicalTo(1.5, tol = 0.000100)) test.Conj.16 <- function() assertThat(Conj(-1.5), identicalTo(-1.5, tol = 0.000100)) test.Conj.17 <- function() assertThat(Conj(3.14), identicalTo(3.14, tol = 0.000100)) test.Conj.18 <- function() assertThat(Conj(Inf), identicalTo(Inf)) test.Conj.19 <- function() assertThat(Conj(-Inf), identicalTo(-Inf)) test.Conj.20 <- function() assertThat(Conj(complex(0)), identicalTo(complex(0))) test.Conj.21 <- function() assertThat(Conj(structure(complex(0), .Names = character(0))), identicalTo(structure(complex(0), .Names = character(0)))) test.Conj.22 <- function() assertThat(Conj(complex(real=NaN, imaginary=3)), identicalTo(complex(real=NaN, imaginary=-3))) test.Conj.23 <- function() assertThat(Conj(NA_complex_), identicalTo(NA_complex_)) test.Conj.24 <- function() assertThat(Conj(1.5+3i), identicalTo(1.5-3i)) test.Conj.25 <- function() assertThat(Conj(1.5-3i), identicalTo(1.5+3i)) test.Conj.26 <- function() assertThat(Conj(-1.5+3i), identicalTo(-1.5-3i)) test.Conj.27 <- function() assertThat(Conj(1.5-3i), identicalTo(1.5+3i)) test.Conj.28 <- function() assertThat(Conj(structure(c(3+4i, 9+2i), .Names = c("a", "b"))), identicalTo(structure(c(3-4i, 9-2i), .Names = c("a", "b")))) test.Conj.29 <- function() assertThat(Conj(structure(5+9i, rando.attr = "bazinga", class = "zarg")), identicalTo(structure(5-9i, rando.attr = "bazinga", class = "zarg"))) test.Conj.30 <- function() assertThat(Conj(character(0)), throwsError()) test.Conj.31 <- function() assertThat(Conj(c("4.1", "blahh", "99.9", "-413", NA)), throwsError()) test.Conj.32 <- function() assertThat(Conj(list(1)), throwsError()) test.Conj.33 <- function() assertThat(Conj(structure(1:12, .Dim = 3:4)), identicalTo(structure(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), .Dim = 3:4))) test.Conj.34 <- function() assertThat(Conj(structure(1:12, .Dim = 3:4, .Dimnames = structure(list(x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y")))), identicalTo(structure(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y"))))) test.Conj.35 <- function() assertThat(Conj(structure(1:3, rando.attrib = 941L)), identicalTo(structure(c(1, 2, 3), rando.attrib = 941L))) test.Conj.36 <- function() assertThat(Conj(structure(c(1+4.5i, 2+4.5i, 3+4.5i), .Dim = 3L, .Dimnames = list( c("a", "b", "c")))), identicalTo(structure(c(1-4.5i, 2-4.5i, 3-4.5i), .Dim = 3L, .Dimnames = list( c("a", "b", "c"))))) test.Conj.37 <- function() assertThat(Conj(structure(list("foo"), class = "foo")), identicalTo(41)) test.Conj.38 <- function() assertThat(Conj(structure(list("bar"), class = "foo")), identicalTo(41)) test.Conj.39 <- function() assertThat(Conj(structure("foo", class = "foo")), identicalTo(41)) test.Conj.40 <- function() assertThat(Conj(structure(list(1L, "bar"), class = "bar")), identicalTo(45))
paletteIFC <- function(x = c("","palette","palette_R","to_light","to_dark")[1], col = "White") { assert(x, len = 1, alw = c("","palette","palette_R","to_light","to_dark")) Software_Colors=data.frame(matrix(c("White","LightSkyBlue","CornflowerBlue","MediumSlateBlue","Blue","Aquamarine","MediumSpringGreen","Cyan","DarkTurquoise", "Teal","Yellow","Gold","DarkKhaki","Lime","Green","Lime","Wheat","SandyBrown","Orange", "Tomato","Red","Pink","HotPink","Plum","Magenta","DarkOrchid","LightCoral","IndianRed", "LightGray","Control","Gray","Black", "Black","CornflowerBlue","CornflowerBlue","MediumSlateBlue","Blue","Aquamarine","MediumSpringGreen","Teal","DarkTurquoise", "Teal","Gold","Gold","IndianRed","Green","Green", "Lime","DarkOrange","Tomato","DarkOrange", "Tomato","Red","DeepPink","DeepPink","DarkOrchid","Magenta","DarkOrchid","IndianRed","IndianRed", "Black","Control","Gray","White"), ncol=2, byrow = FALSE), stringsAsFactors = FALSE) names(Software_Colors) = c("color", "lightModeColor") Software_Colors$color_R = gsub("^Teal$","Cyan4", Software_Colors$color) Software_Colors$color_R = gsub("^Green$","Green4", Software_Colors$color_R) Software_Colors$color_R = gsub("^Control$","Gray81", Software_Colors$color_R) Software_Colors$color_R = gsub("^Lime$","Chartreuse", Software_Colors$color_R) Software_Colors$lightModeColor_R = gsub("^Teal$","Cyan4", Software_Colors$lightModeColor) Software_Colors$lightModeColor_R = gsub("^Green$","Green4", Software_Colors$lightModeColor_R) Software_Colors$lightModeColor_R = gsub("^Control$","Gray81", Software_Colors$lightModeColor_R) Software_Colors$lightModeColor_R = gsub("^Lime$","Chartreuse", Software_Colors$lightModeColor_R) if(x == "palette") return(as.character(unique(c(Software_Colors[,1], Software_Colors[,2])))) if(x == "palette_R") return(tolower(as.character(unique(c(Software_Colors[,3], Software_Colors[,4]))))) columns = c(0,0) M = FALSE if(x == "to_light") { columns = c(1,3,2,4) } if(x == "to_dark") { columns = c(2,4,1,3) } if(!identical(columns,c(0,0))) M = Software_Colors[,columns[1]]==col | Software_Colors[,columns[2]]==col if(any(M)) return(Software_Colors[which(M), columns[3:4]]) return(Software_Colors) }
"hspider" <- structure(list(WaterCon = c(2.3321, 3.0493, 2.5572, 2.6741, 3.0155, 3.381, 3.1781, 2.6247, 2.4849, 2.1972, 2.2192, 2.2925, 3.5175, 3.0865, 3.2696, 3.0301, 3.3322, 3.1224, 2.9232, 3.1091, 2.9755, 1.2528, 1.1939, 1.6487, 1.8245, 0.9933, 0.9555, 0.9555), BareSand = c(0, 0, 0, 0, 0, 2.3979, 0, 0, 0, 3.9318, 0, 0, 1.7918, 0, 0, 0, 0, 0, 0, 0, 0, 3.2581, 3.0445, 3.2581, 3.5835, 4.5109, 2.3979, 3.434 ), FallTwig = c(0, 1.7918, 0, 0, 0, 3.434, 0, 4.2627, 0, 0, 0, 0, 1.7918, 0, 4.3944, 4.6052, 4.4543, 4.3944, 4.5109, 4.5951, 4.5643, 0, 0, 0, 0, 0, 0, 0), CoveMoss = c(3.0445, 1.0986, 2.3979, 2.3979, 0, 2.3979, 0.6931, 1.0986, 4.3307, 3.434, 4.1109, 3.8286, 0.6931, 1.7918, 0.6931, 0.6931, 0.6931, 0, 1.6094, 0.6931, 0.6931, 4.3307, 4.0254, 4.0254, 1.0986, 1.7918, 3.8286, 3.7136), CoveHerb = c(4.4543, 4.5643, 4.6052, 4.6151, 4.6151, 3.434, 4.6151, 3.434, 3.2581, 3.0445, 3.7136, 4.0254, 4.5109, 4.5643, 3.0445, 0.6931, 3.0445, 3.0445, 1.6094, 0.6931, 1.7918, 0.6931, 3.2581, 3.0445, 4.1109, 1.7918, 3.434, 3.434), ReflLux = c(3.912, 1.6094, 3.6889, 2.9957, 2.3026, 0.6931, 2.3026, 0.6931, 3.4012, 3.6889, 3.6889, 3.6889, 3.4012, 1.0986, 0.6931, 0, 1.0986, 1.0986, 0, 0, 0, 3.912, 4.0943, 4.0073, 2.3026, 4.382, 3.6889, 3.6889), Alopacce = c(25, 0, 15, 2, 1, 0, 2, 0, 1, 3, 15, 16, 3, 0, 0, 0, 0, 0, 0, 0, 0, 7, 17, 11, 9, 3, 29, 15), Alopcune = c(10, 2, 20, 6, 20, 6, 7, 11, 1, 0, 1, 13, 43, 2, 0, 3, 0, 1, 1, 2, 1, 0, 0, 0, 1, 0, 0, 0), Alopfabr = c(0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 16, 15, 20, 9, 6, 11, 14), Arctlute = c(0, 0, 2, 1, 2, 6, 12, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Arctperi = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 5, 0, 18, 4, 1), Auloalbi = c(4, 30, 9, 24, 9, 6, 16, 7, 0, 0, 1, 0, 18, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0), Pardlugu = c(0, 1, 1, 1, 1, 0, 1, 55, 0, 0, 0, 0, 1, 3, 6, 6, 2, 5, 12, 13, 16, 0, 2, 0, 1, 0, 0, 0), Pardmont = c(60, 1, 29, 7, 2, 11, 30, 2, 26, 22, 95, 96, 24, 14, 0, 0, 0, 0, 0, 0, 1, 2, 6, 3, 11, 0, 1, 6), Pardnigr = c(12, 15, 18, 29, 135, 27, 89, 2, 1, 0, 0, 1, 53, 15, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 6, 0, 0, 0), Pardpull = c(45, 37, 45, 94, 76, 24, 105, 1, 1, 0, 1, 8, 72, 72, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0), Trocterr = c(57, 65, 66, 86, 91, 63, 118, 30, 2, 1, 4, 13, 97, 94, 25, 28, 23, 25, 22, 22, 18, 1, 1, 0, 16, 1, 0, 2), Zoraspin = c(4, 9, 1, 25, 17, 34, 16, 3, 0, 0, 0, 0, 22, 32, 3, 4, 2, 0, 3, 2, 2, 0, 0, 0, 6, 0, 0, 0)), .Names = c("WaterCon", "BareSand", "FallTwig", "CoveMoss", "CoveHerb", "ReflLux", "Alopacce", "Alopcune", "Alopfabr", "Arctlute", "Arctperi", "Auloalbi", "Pardlugu", "Pardmont", "Pardnigr", "Pardpull", "Trocterr", "Zoraspin"), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28"), class = "data.frame")
set_lockfile_metadata <- function(repos = NULL, r_version = NULL, project = NULL) { project <- getProjectDir(project) lf_filepath <- lockFilePath(project) if (!file.exists(lf_filepath)) { stop(paste(lockFilePath, " is missing. Run packrat::init('", project, "') to generate it.", sep = "")) } lf <- as.data.frame(readDcf(lf_filepath), stringsAsFactors = FALSE) if (!is.null(repos)) { separator <- ",\n" reposString <- paste(names(repos), unname(repos), sep = "=", collapse = separator) lf[1, "Repos"] <- reposString } if (!is.null(r_version)) { if (length(r_version) > 1) { stop("RVersion metadata must contains one element only", call. = FALSE) } lf[1, "RVersion"] <- as.character(package_version(r_version)) } write_dcf(lf, lf_filepath) invisible() } get_lockfile_metadata <- function(metadata = NULL, simplify = TRUE, project = NULL) { project <- getProjectDir(project) lockFilePath <- lockFilePath(project) if (!file.exists(lockFilePath)) { stop(paste(lockFilePath, " is missing. Run packrat::init('", project, "') to generate it.", sep = "")) } lf_metadata <- readLockFile(lockFilePath)[names(available_metadata)] if (is.null(metadata)) { lf_metadata } else { result <- lf_metadata[names(lf_metadata) %in% metadata] if (simplify) unlist(unname(result)) else result } } available_metadata <- c( r_version = "RVersion", repos = "Repos" )
as.data.frame.CodeSet <- function(x, row.names = NULL, optional = FALSE, ...) { codes = x$codes len = 0; if(is.null(x$excerpts)) { excerpts = x$codes[[1]]$excerpts; } else{ excerpts = x$excerpts } len = length(excerpts) args = list(...) if(is.null(len) && !is.null(args$len)) len = args$len; if(is.null(args$codes)) codes = x$codes; if(!is.null(len) && len > 0) { coded_cols <- sapply(codes, function(x){ df = data.frame( x$computerSet[1:len] ) df }) names(coded_cols) <- as.character(lapply(codes, `[[`, "name")) data.frame(ID = 1:len, excerpt = excerpts[1:len], coded_cols) } else { data.frame() } }
dFNCHypergeo <- function(x, m1, m2, n, odds, precision=1E-7) { stopifnot(is.numeric(x), is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds), is.numeric(precision)); .Call("dFNCHypergeo", as.integer(x), as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), as.double(precision), PACKAGE = "BiasedUrn"); } dWNCHypergeo <- function(x, m1, m2, n, odds, precision=1E-7 ) { stopifnot(is.numeric(x), is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds), is.numeric(precision)); .Call("dWNCHypergeo", as.integer(x), as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), as.double(precision), PACKAGE = "BiasedUrn"); } pFNCHypergeo <- function(x, m1, m2, n, odds, precision=1E-7, lower.tail=TRUE) { stopifnot(is.numeric(x), is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds), is.numeric(precision), is.vector(lower.tail)); .Call("pFNCHypergeo", as.integer(x), as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), as.double(precision), as.logical(lower.tail), PACKAGE = "BiasedUrn"); } pWNCHypergeo <- function(x, m1, m2, n, odds, precision=1E-7, lower.tail=TRUE) { stopifnot(is.numeric(x), is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds), is.numeric(precision), is.vector(lower.tail)); .Call("pWNCHypergeo", as.integer(x), as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), as.double(precision), as.logical(lower.tail), PACKAGE = "BiasedUrn"); } qFNCHypergeo <- function(p, m1, m2, n, odds, precision=1E-7, lower.tail=TRUE) { stopifnot(is.numeric(p), is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds), is.numeric(precision), is.vector(lower.tail)); .Call("qFNCHypergeo", as.double(p), as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), as.double(precision), as.logical(lower.tail), PACKAGE = "BiasedUrn"); } qWNCHypergeo <- function(p, m1, m2, n, odds, precision=1E-7, lower.tail=TRUE) { stopifnot(is.numeric(p), is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds), is.numeric(precision), is.vector(lower.tail)); .Call("qWNCHypergeo", as.double(p), as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), as.double(precision), as.logical(lower.tail), PACKAGE = "BiasedUrn"); } rFNCHypergeo <- function(nran, m1, m2, n, odds, precision=1E-7) { stopifnot(is.numeric(nran), is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds), is.numeric(precision)); .Call("rFNCHypergeo", as.integer(nran), as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), as.double(precision), PACKAGE = "BiasedUrn"); } rWNCHypergeo <- function(nran, m1, m2, n, odds, precision=1E-7) { stopifnot(is.numeric(nran), is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds), is.numeric(precision)); .Call("rWNCHypergeo", as.integer(nran), as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), as.double(precision), PACKAGE = "BiasedUrn"); } meanFNCHypergeo <- function( m1, m2, n, odds, precision=1E-7) { stopifnot(is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds), is.numeric(precision)); .Call("momentsFNCHypergeo", as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), as.double(precision), as.integer(1), PACKAGE = "BiasedUrn"); } meanWNCHypergeo <- function( m1, m2, n, odds, precision=1E-7) { stopifnot(is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds), is.numeric(precision)); .Call("momentsWNCHypergeo", as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), as.double(precision), as.integer(1), PACKAGE = "BiasedUrn"); } varFNCHypergeo <- function( m1, m2, n, odds, precision=1E-7) { stopifnot(is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds), is.numeric(precision)); .Call("momentsFNCHypergeo", as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), as.double(precision), as.integer(2), PACKAGE = "BiasedUrn"); } varWNCHypergeo <- function( m1, m2, n, odds, precision=1E-7) { stopifnot(is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds), is.numeric(precision)); .Call("momentsWNCHypergeo", as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), as.double(precision), as.integer(2), PACKAGE = "BiasedUrn"); } modeFNCHypergeo <- function( m1, m2, n, odds, precision=0) { stopifnot(is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds)); .Call("modeFNCHypergeo", as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), PACKAGE = "BiasedUrn"); } modeWNCHypergeo <- function( m1, m2, n, odds, precision=1E-7) { stopifnot(is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(odds), is.numeric(precision)); .Call("modeWNCHypergeo", as.integer(m1), as.integer(m2), as.integer(n), as.double(odds), as.double(precision), PACKAGE = "BiasedUrn"); } oddsFNCHypergeo <- function(mu, m1, m2, n, precision=0.1) { stopifnot(is.numeric(mu), is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(precision)); .Call("oddsFNCHypergeo", as.double(mu), as.integer(m1), as.integer(m2), as.integer(n), as.double(precision), PACKAGE = "BiasedUrn"); } oddsWNCHypergeo <- function(mu, m1, m2, n, precision=0.1) { stopifnot(is.numeric(mu), is.numeric(m1), is.numeric(m2), is.numeric(n), is.numeric(precision)); .Call("oddsWNCHypergeo", as.double(mu), as.integer(m1), as.integer(m2), as.integer(n), as.double(precision), PACKAGE = "BiasedUrn"); } numFNCHypergeo <- function(mu, n, N, odds, precision=0.1) { stopifnot(is.numeric(mu), is.numeric(n), is.numeric(N), is.numeric(odds), is.numeric(precision)); .Call("numFNCHypergeo", as.double(mu), as.integer(n), as.integer(N), as.double(odds), as.double(precision), PACKAGE = "BiasedUrn"); } numWNCHypergeo <- function(mu, n, N, odds, precision=0.1) { stopifnot(is.numeric(mu), is.numeric(n), is.numeric(N), is.numeric(odds), is.numeric(precision)); .Call("numWNCHypergeo", as.double(mu), as.integer(n), as.integer(N), as.double(odds), as.double(precision), PACKAGE = "BiasedUrn"); } minHypergeo <- function(m1, m2, n) { stopifnot(m1>=0, m2>=0, n>=0, n<=m1+m2); max(n-m2, 0); } maxHypergeo <- function(m1, m2, n) { stopifnot(m1>=0, m2>=0, n>=0, n<=m1+m2); min(m1, n); }
context("cmdscale and sammon") library(cops) initsam <- sammon(dis^3) expect_that(initsam,is_a("sammon")) expect_that(initsam,is_a("cmdscale"))
cat_control <- function ( center = FALSE, standardize = FALSE, accuracy = 2, digits = 4, g = 0.5, epsilon = 10^(-5), maxi = 250, c = 10^(-5), gama = 20, steps = 25, nu = 1, tuning.criterion = "GCV", K = 5, cv.refit = FALSE, lambda.upper=50, lambda.lower=0, lambda.accuracy=.01, scaled.lik=FALSE, adapted.weights=FALSE, adapted.weights.adj = FALSE, adapted.weights.ridge=FALSE, assured.intercept=TRUE, level.control = FALSE, case.control = FALSE, pairwise = TRUE, grouped.cat.diffs = FALSE, bootstrap = 0, start.ml = FALSE, L0.log = TRUE, subjspec.gr = FALSE, high = NULL, ...) { if (!is.logical(center)) stop ("center must be logical. \n") if (!is.logical(standardize)) stop ("standardize must be logical. \n") if (!is.numeric(accuracy) || accuracy < 0) stop("'accuracy' must be >= 0") accuracy <- as.integer(accuracy) if (!is.numeric(digits) || digits < 0) stop("'digits' must be >= 0") digits <- as.integer(digits) if (!is.numeric(g) || length(as.vector(g))!=1 || g>1 || g<0) stop ("g must be a single, numeric value out of ]0;1[. \n") if (!is.numeric(epsilon) || epsilon <= 0 || epsilon>1 || length(epsilon)!=1) stop ("epsilon is ment to be a single, small, positive and numeric value. \n") if (!is.numeric(maxi) || length(maxi)!=1 || maxi < 1) stop ("maxi must be a sinlge integer > 0 \n") maxi <- as.integer(maxi) if (!is.numeric(steps) || length(steps)!=1 || steps < 1) stop ("steps must be a sinlge integer > 0 \n") steps <- as.integer(steps) if (!is.numeric(c) || c<0 || length(c)!=1) stop ("c is ment to be a single, small, positive and numeric value. \n") if (!is.numeric(gama) || length(as.vector(gama))!=1 || gama<0) stop ("gama must be a singl, positive and numeric value. \n") if (!(tuning.criterion %in% c("GCV", "UBRE", "deviance", "1SE"))) stop ("tuning.criterion must be one out of 'GCV', 'UBRE', 'deviance'. \n") if (!is.vector(K)) stop ("K must be a single integer > 1. \n") if (!is.list(K)) { if (!is.numeric(K) || K<2) stop ("K must be a single integer > 1. \n") } if (!is.logical(cv.refit)) stop ("cv.refit must be logical. \n") if (!is.numeric(lambda.upper) || length(lambda.upper)!=1) stop ("lambda.upper must be numeric and positive \n") if (!is.numeric(lambda.lower) || length(lambda.lower)!=1) stop ("lambda.lower must be numeric and positive \n") if (!is.numeric(lambda.accuracy) || lambda.accuracy <= 0 || length(lambda.accuracy)!=1) stop ("lambda.accuracy is ment to be a single, positive and numeric value. \n") if (!is.logical(scaled.lik)) stop ("scaled.lik must be logical. \n") if (!is.logical(adapted.weights.ridge)) stop ("adapted.weights.ridge must be logical. \n") if (!is.logical(adapted.weights.adj)) stop ("adapted.weights.adj must be logical. \n") if (!is.logical(adapted.weights)) stop ("adapted.weights must be logical. \n") if (!is.logical(assured.intercept)) stop ("assured.intercept must be logical. \n") if (!is.logical(pairwise)) stop ("pairwise must be logical. \n") if (!is.logical(grouped.cat.diffs)) stop ("grouped.cat.diffs must be logical. \n") if (!is.numeric(bootstrap) || bootstrap<0 || length(bootstrap)!=1) stop ("bootstrap must be positive and numeric; value zero or >10. \n") if (bootstrap!=0 && bootstrap<10) bootstrap <- 10 if (!is.logical(level.control)) stop ("level.control must be logical. \n") if (!is.logical(case.control)) stop ("case.control must be logical. \n") if (!is.logical(start.ml)) stop ("start.ml must be logical. \n") if (!is.logical(L0.log)) stop ("L0.log must be logical. \n") if (!is.logical(subjspec.gr)) stop ("subjspec.gr must be logical. \n") if (pairwise == FALSE) {high <- NULL} if (!is.null(high) && !is.numeric(high) ) stop ("high must be NULL or a positive integer. \n") if (is.numeric(high) && high < 1) stop ("high must be NULL or a positive integer. \n") if (is.numeric(high)) high <- as.integer(high) list( center = center, standardize = standardize, accuracy = accuracy, digits = digits, g = g, epsilon = epsilon, maxi = maxi, c = c, gama = gama, steps = steps, nu = nu, tuning.criterion = tuning.criterion, K = K, cv.refit = cv.refit, lambda.upper = lambda.upper, lambda.lower = lambda.lower, lambda.accuracy = lambda.accuracy, scaled.lik = scaled.lik, adapted.weights = adapted.weights, adapted.weights.adj = adapted.weights.adj, adapted.weights.ridge=adapted.weights.ridge, assured.intercept = assured.intercept, level.control = level.control, case.control = case.control, pairwise = pairwise, grouped.cat.diffs = grouped.cat.diffs, bootstrap = bootstrap, start.ml = start.ml, L0.log = L0.log, subjspec.gr = subjspec.gr, high = high ) }
context("compare with glmnet") test_that("training loss is similar to the fit by glmnet when E=0", { grid_size = 10 grid = 10^seq(-4, log10(1), length.out=grid_size) grid = rev(grid) tols = c(1e-4) max_iterations = 2000 for (family in c("gaussian", "binomial")){ for (seed in 1:5) { for (tol in tols) { file_name = paste0("testdata/compare_with_glmnet/", seed, "_", family, "_data.rds") data = readRDS(file_name) file_name = paste0("testdata/compare_with_glmnet/", seed, "_", family, "_glmnet_results.rds") glmnet_fit = readRDS(file_name) sample_size = length(data$Y_train) fit = gesso.fit(G=data$G_train, E=rep(0, sample_size), Y=data$Y_train, C=data$C_train, tolerance=tol, grid=grid, family=family, normalize=FALSE, max_iterations=max_iterations) expect_equal(sum(fit$has_converged != 1), 0) expect_lt(max(fit$objective_value - rep(glmnet_fit$objective_value, rep(grid_size, grid_size))), tol) } } } })
BridgeRHalfLifeCalc3models <- function(inputFile, group = c("Control","Knockdown"), hour = c(0, 1, 2, 4, 8, 12), inforColumn = 4, CutoffTimePointNumber = 4, save = T, outputPrefix = "BridgeR_5"){ stopifnot(is.character(group) && is.vector(group)) stopifnot(is.numeric(hour) && is.vector(hour)) stopifnot(is.numeric(CutoffTimePointNumber)) stopifnot(is.numeric(inforColumn)) stopifnot(is.logical(save)) stopifnot(is.character(outputPrefix)) time_points <- length(hour) group_number <- length(group) input_matrix <- inputFile halflife_infor_header <- c("Model", "R2", "half_life") half_calc_3model <- function(time_exp_table){ data_point <- length(time_exp_table$exp) if(!is.null(time_exp_table)){ if(data_point >= CutoffTimePointNumber){ if(as.numeric(as.vector(as.matrix(time_exp_table$exp[1]))) > 0){ optim1 <- function(x){ mRNA_exp <- exp(-x * time_exp_table$hour) sum((time_exp_table$exp - mRNA_exp)^2) } model1_pred <- function(x){ mRNA_exp <- exp(-x * time_exp_table$hour) (cor(mRNA_exp, time_exp_table$exp, method="pearson"))^2 } model1_half <- function(x){ mRNA_half <- exp(-a_1 * x) (mRNA_half - 0.5)^2 } optim2 <- function(x){ mRNA_exp <- (1.0 - x[2]) * exp(-x[1] * time_exp_table$hour) + x[2] sum((time_exp_table$exp - mRNA_exp)^2) } model2_pred <- function(a,b){ mRNA_exp <- (1.0 - b) * exp(-a * time_exp_table$hour) + b (cor(mRNA_exp, time_exp_table$exp, method="pearson"))^2 } model2_half <- function(x){ mRNA_half <- (1.0 - b_2) * exp(-a_2 * x) + b_2 (mRNA_half - 0.5)^2 } optim3 <- function(x){ mRNA_exp <- x[3] * exp(-x[1] * time_exp_table$hour) + (1.0 - x[3]) * exp(-x[2] * time_exp_table$hour) sum((time_exp_table$exp - mRNA_exp)^2) } model3_pred <- function(a,b,c){ mRNA_exp <- c * exp(-a * time_exp_table$hour) + (1.0 - c) * exp(- b * time_exp_table$hour) (cor(mRNA_exp, time_exp_table$exp, method="pearson"))^2 } model3_half <- function(x){ mRNA_half <- c_3 * exp(-a_3 * x) + (1.0 - c_3) * exp(-b_3 * x) (mRNA_half - 0.5)^2 } out1 <- suppressWarnings(optim(1,optim1)) min1 <- out1$value a_1 <- out1$par[1] half1_1 <- log(2) / a_1 cor1 <- model1_pred(a_1) out1 <- suppressWarnings(optim(1,model1_half)) half1_2 <- out1$par mRNA_pred <- exp(-a_1 * time_exp_table$hour) s2 <- sum((time_exp_table$exp - mRNA_pred)^2) / data_point AIC1 <- data_point * log(s2) + (2 * 0) out2 <- suppressWarnings(optim(c(1,0),optim2)) min2 <- out2$value a_2 <- out2$par[1] b_2 <- out2$par[2] cor2 <- model2_pred(a_2, b_2) out2 <- suppressWarnings(optim(1,model2_half)) half2 <- out2$par if(b_2 >= 0.5){ half2 <- Inf } mRNA_pred <- (1.0 - b_2) * exp(-a_2 * time_exp_table$hour) + b_2 s2 <- sum((time_exp_table$exp - mRNA_pred)^2) / data_point AIC2 <- data_point * log(s2) + (2 * 1) out3 <- suppressWarnings(optim(c(1,1,0.1),optim3)) min3 <- out3$value a_3 <- out3$par[1] b_3 <- out3$par[2] c_3 <- out3$par[3] cor3 <- model3_pred(a_3,b_3,c_3) out3 <- suppressWarnings(optim(1,model3_half)) half3 <- out3$par mRNA_pred <- c_3 * exp(-a_3 * time_exp_table$hour) + (1.0 - c_3) * exp(-b_3 * time_exp_table$hour) s2 <- sum((time_exp_table$exp - mRNA_pred)^2) / data_point AIC3 <- data_point * log(s2) + (2 * 2) half_table <- data.frame(half=c(as.numeric(half1_2), as.numeric(half2), as.numeric(half3)), AIC=c(as.numeric(AIC1), as.numeric(AIC2), as.numeric(AIC3))) AIC_list <- order(half_table$AIC) AIC_flg <- 0 model <- NULL R2 <- NULL halflife <- NULL for(min_AIC_index in AIC_list){ if(min_AIC_index == 1){ selected_half <- half1_2 if(selected_half > 24){ selected_half <- 24 } if(a_1 > 0){ model <- "model1" R2 <- cor1 halflife <- selected_half AIC_flg <- 1 break } } if(min_AIC_index == 2){ selected_half <- half2 if(selected_half == "Inf"){ selected_half <- 24 }else if(selected_half > 24){ selected_half <- 24 } if(a_2 > 0 && b_2 > 0 && b_2 < 1){ model <- "model2" R2 <- cor2 halflife <- selected_half AIC_flg <- 1 break } } if(min_AIC_index == 3){ selected_half <- half3 if(selected_half > 24){ selected_half <- 24 } if(a_3 > 0 && b_3 > 0 && c_3 > 0 && c_3 < 1){ model <- "model3" R2 <- cor3 halflife <- selected_half AIC_flg <- 1 break } } } if(AIC_flg == 0){ if(a_1 < 0){ model <- "model1" R2 <- cor1 halflife <- 24 }else{ model <- "no_good_model" R2 <- "NA" halflife <- 24 } } return(c(model, R2, halflife)) }else{ return(rep("NA", 3)) } }else{ return(rep("NA", 3)) } }else{ return(rep("NA", 3)) } } halflife_calc_3model <- function(data){ data_vector <- NULL gene_infor <- data[infor_st:infor_ed] exp <- data[exp_st:exp_ed] data_vector <- c(gene_infor, exp) if (all(is.nan(exp)) || all(exp == "NaN")) { result_list <- rep("NA", 3) data_vector <- c(data_vector, result_list) return(data_vector) } exp <- as.numeric(exp) time_point_exp_raw <- data.frame(hour,exp) time_point_exp_base <- time_point_exp_raw[time_point_exp_raw$exp > 0, ] model3_result <- half_calc_3model(time_point_exp_base) data_vector <- c(data_vector, model3_result) return(data_vector) } output_matrix <- NULL for (group_index in 1:group_number) { colname_st <- 1 + (group_index - 1) * (inforColumn + time_points) colname_ed <- group_index * (inforColumn + time_points) header_label <- colnames(input_matrix)[colname_st:colname_ed] infor_st_ed <- generate_infor_st_ed(group_index, time_points, inforColumn) infor_st <- infor_st_ed[1] infor_ed <- infor_st_ed[2] exp_st <- infor_ed + 1 exp_ed <- infor_ed + time_points result_matrix <- t(apply((input_matrix), 1, halflife_calc_3model)) colnames(result_matrix) <- c(header_label, halflife_infor_header) output_matrix <- cbind(output_matrix, result_matrix) } output_matrix <- data.table(output_matrix) if (save == T) { write.table(output_matrix, quote = F, sep = "\t", row.names = F, file = paste(outputPrefix, "_halflife_calc_3models.txt", sep="")) } return(output_matrix) }
guided_tour <- function(index_f, d = 2, alpha = 0.5, cooling = 0.99, max.tries = 25, max.i = Inf, search_f = search_geodesic, n_sample = 5, ...) { generator <- function(current, data, tries, ...) { index <- function(proj) { index_f(as.matrix(data) %*% proj) } valid_fun <- c( "search_geodesic", "search_better", "search_better_random", "search_polish", "search_posse" ) method <- valid_fun[vapply(valid_fun, function(x) { identical(get(x), search_f) }, logical(1))] if (is.null(current)) { current <- basis_random(ncol(data), d) cur_index <- index(current) rcd_env <- parent.frame(n = 3) rcd_env[["record"]] <- dplyr::add_row( rcd_env[["record"]], basis = list(current), index_val = cur_index, info = "new_basis", method = method, alpha = formals(guided_tour)$alpha, tries = 1, loop = 1 ) return(current) } cur_index <- index(current) if (cur_index > max.i) { cat("Found index ", cur_index, ", larger than selected maximum ", max.i, ". Stopping search.\n", sep = "" ) cat("Final projection: \n") if (ncol(current) == 1) { for (i in 1:length(current)) { cat(sprintf("%.3f", current[i]), " ") } cat("\n") } else { for (i in 1:nrow(current)) { for (j in 1:ncol(current)) { cat(sprintf("%.3f", current[i, j]), " ") } cat("\n") } } return(NULL) } basis <- search_f(current, alpha, index, tries, max.tries, cur_index = cur_index, frozen = frozen, n_sample = n_sample, ...) if (method == "search_posse") { if (!is.null(basis$h)) { if (basis$h > 30) { alpha <<- alpha * cooling } } } else { alpha <<- alpha * cooling } list(target = basis$target, index = index) } new_geodesic_path("guided", generator) }
xgb.unserialize <- function(buffer, handle = NULL) { cachelist <- list() if (is.null(handle)) { handle <- .Call(XGBoosterCreate_R, cachelist) } else { if (!is.null.handle(handle)) stop("'handle' is not null/empty. Cannot overwrite existing handle.") .Call(XGBoosterCreateInEmptyObj_R, cachelist, handle) } tryCatch( .Call(XGBoosterUnserializeFromBuffer_R, handle, buffer), error = function(e) { error_msg <- conditionMessage(e) m <- regexec("(src[\\\\/]learner.cc:[0-9]+): Check failed: (header == serialisation_header_)", error_msg, perl = TRUE) groups <- regmatches(error_msg, m)[[1]] if (length(groups) == 3) { warning(paste("The model had been generated by XGBoost version 1.0.0 or earlier and was ", "loaded from a RDS file. We strongly ADVISE AGAINST using saveRDS() ", "function, to ensure that your model can be read in current and upcoming ", "XGBoost releases. Please use xgb.save() instead to preserve models for the ", "long term. For more details and explanation, see ", "https://xgboost.readthedocs.io/en/latest/tutorials/saving_model.html", sep = "")) .Call(XGBoosterLoadModelFromRaw_R, handle, buffer) } else { stop(e) } }) class(handle) <- "xgb.Booster.handle" return (handle) }
if (Sys.getenv("RunAllRcppTests") != "yes") exit_file("Set 'RunAllRcppTests' to 'yes' to run.") Rcpp::sourceCpp("cpp/language.cpp") expect_equal( runit_language( call("rnorm") ), call("rnorm" ), info = "Language( LANGSXP )" ) expect_error( runit_language(test.Language), info = "Language not compatible with function" ) expect_error( runit_language(new.env()), info = "Language not compatible with environment" ) expect_error( runit_language(1:10), info = "Language not compatible with integer" ) expect_error( runit_language(TRUE), info = "Language not compatible with logical" ) expect_error( runit_language(1.3), info = "Language not compatible with numeric" ) expect_error( runit_language(as.raw(1) ), info = "Language not compatible with raw" ) expect_equal( runit_lang_variadic_1(), call("rnorm", 10L, 0.0, 2.0 ), info = "variadic templates" ) expect_equal( runit_lang_variadic_2(), call("rnorm", 10L, mean = 0.0, 2.0 ), info = "variadic templates (with names)" ) expect_equal( runit_lang_push_back(), call("rnorm", 10L, mean = 0.0, 2.0 ), info = "Language::push_back" ) expect_equal( runit_lang_square_rv(), 10.0, info = "Language::operator[] used as rvalue" ) expect_equal( runit_lang_square_lv(), call("rnorm", "foobar", 20.0, 20.0) , info = "Pairlist::operator[] used as lvalue" ) expect_equal( runit_lang_fun(sort, sample(1:10)), 1:10, info = "Language( Function ) " ) expect_equal( runit_lang_inputop(), call("rnorm", 10L, sd = 10L ) , info = "Language<<" ) expect_equal( runit_lang_unarycall( 1:10 ), lapply( 1:10, function(n) seq(from=n, to = 0 ) ), info = "c++ lapply using calls" ) expect_equal( runit_lang_unarycallindex( 1:10 ), lapply( 1:10, function(n) seq(from=10, to = n ) ), info = "c++ lapply using calls" ) expect_equal( runit_lang_binarycall( 1:10, 11:20 ), lapply( 1:10, function(n) seq(n, n+10) ), info = "c++ lapply using calls" ) set.seed(123) res <- runit_lang_fixedcall() set.seed(123) exp <- lapply( 1:10, function(n) rnorm(10) ) expect_equal( res, exp, info = "std::generate" ) e <- new.env() e[["y"]] <- 1:10 expect_equal( runit_lang_inenv(e), sum(1:10), info = "Language::eval( SEXP )" ) expect_equal( runit_pairlist( pairlist("rnorm") ), pairlist("rnorm" ), info = "Pairlist( LISTSXP )" ) expect_equal( runit_pairlist( call("rnorm") ), pairlist(as.name("rnorm")), info = "Pairlist( LANGSXP )" ) expect_equal( runit_pairlist(1:10), as.pairlist(1:10) , info = "Pairlist( INTSXP) " ) expect_equal( runit_pairlist(TRUE), as.pairlist( TRUE) , info = "Pairlist( LGLSXP )" ) expect_equal( runit_pairlist(1.3), as.pairlist(1.3), info = "Pairlist( REALSXP) " ) expect_equal( runit_pairlist(as.raw(1) ), as.pairlist(as.raw(1)), info = "Pairlist( RAWSXP)" ) expect_error( runit_pairlist(runit_pairlist), info = "Pairlist not compatible with function" ) expect_error( runit_pairlist(new.env()), info = "Pairlist not compatible with environment" ) expect_equal( runit_pl_variadic_1(), pairlist("rnorm", 10L, 0.0, 2.0 ), info = "variadic templates" ) expect_equal( runit_pl_variadic_2(), pairlist("rnorm", 10L, mean = 0.0, 2.0 ), info = "variadic templates (with names)" ) expect_equal( runit_pl_push_front(), pairlist( foobar = 10, "foo", 10.0, 1L), info = "Pairlist::push_front" ) expect_equal( runit_pl_push_back(), pairlist( 1L, 10.0, "foo", foobar = 10), info = "Pairlist::push_back" ) expect_equal( runit_pl_insert(), pairlist( 30.0, 1L, bla = "bla", 10.0, 20.0, "foobar" ), info = "Pairlist::replace" ) expect_equal( runit_pl_replace(), pairlist( first = 1, 20.0 , FALSE), info = "Pairlist::replace" ) expect_equal( runit_pl_size(), 3L, info = "Pairlist::size()" ) expect_equal( runit_pl_remove_1(), pairlist(10.0, 20.0), info = "Pairlist::remove(0)" ) expect_equal( runit_pl_remove_2(), pairlist(1L, 10.0), info = "Pairlist::remove(0)" ) expect_equal( runit_pl_remove_3(), pairlist(1L, 20.0), info = "Pairlist::remove(0)" ) expect_equal( runit_pl_square_1(), 10.0, info = "Pairlist::operator[] used as rvalue" ) expect_equal( runit_pl_square_2(), pairlist(1L, "foobar", 1L) , info = "Pairlist::operator[] used as lvalue" ) expect_equal( runit_formula_(), x ~ y + z, info = "Formula( string )" ) expect_equal( runit_formula_SEXP( x ~ y + z), x ~ y + z, info = "Formula( SEXP = formula )" ) expect_equal( runit_formula_SEXP( "x ~ y + z" ), x ~ y + z, info = "Formula( SEXP = STRSXP )" ) expect_equal( runit_formula_SEXP( parse( text = "x ~ y + z") ), x ~ y + z, info = "Formula( SEXP = EXPRSXP )" ) expect_equal( runit_formula_SEXP( list( "x ~ y + z") ), x ~ y + z, info = "Formula( SEXP = VECSXP(1 = STRSXP) )" ) expect_equal( runit_formula_SEXP( list( x ~ y + z) ), x ~ y + z, info = "Formula( SEXP = VECSXP(1 = formula) )" )
context("dam_first_last_lines") test_that("Start and stop dates work as expected when reading whole file with error 51 at the begining and end", { FILE <- damr_example("M064.txt") EXPECTED_FIRST_READ <- damr:::parse_datetime("2017-06-30 14:43:08", tz="UTC") EXPECTED_LAST_READ <- damr:::parse_datetime("2017-07-03 00:05:00", tz="UTC") expect_warning(d <- damr:::find_dam_first_last_lines(FILE, start_datetime = -Inf, stop_datetime = +Inf, tz="UTC"), regexp = "The sampling period is not always regular") expect_equal(damr:::parse_datetime(d$datetime[1]), EXPECTED_FIRST_READ) expect_equal(damr:::parse_datetime(d$datetime[2]), EXPECTED_LAST_READ) EXPECTED_FIRST_READ <- damr:::parse_datetime("2017-06-30 14:44:08", tz="UTC") expect_silent(damr:::find_dam_first_last_lines( FILE, start_datetime = EXPECTED_FIRST_READ, stop_datetime = +Inf, tz="UTC")) }) test_that("Start and stop dates work as expected when setting a start", { FILE <- damr_example("M064.txt") EXPECTED_FIRST_READ <- damr:::parse_datetime("2017-06-30 14:55:00", tz="UTC") d <- damr:::find_dam_first_last_lines(FILE, start_datetime = "2017-06-30 14:55:00", stop_datetime = +Inf, tz="UTC") expect_equal(damr:::parse_datetime(d$datetime[1]), EXPECTED_FIRST_READ) }) test_that("Start and stop dates work as expected when setting a stop", { FILE <- damr_example("M064.txt") EXPECTED_FIRST_READ <- damr:::parse_datetime("2017-06-30 14:55:00", tz="UTC") EXPECTED_LAST_READ <- damr:::parse_datetime("2017-07-01 13:51:00", tz="UTC") d <- damr:::find_dam_first_last_lines(FILE, start_datetime = "2017-06-30 14:55:00", stop_datetime = "2017-07-01 13:51:00", tz="UTC") expect_equal(damr:::parse_datetime(d$datetime[1]), EXPECTED_FIRST_READ) expect_equal(damr:::parse_datetime(d$datetime[2]), EXPECTED_LAST_READ) }) test_that("Start date is inclusive when time not specified", { FILE <- damr_example("M064.txt") EXPECTED_FIRST_READ <- damr:::parse_datetime("2017-07-01", tz="UTC") EXPECTED_LAST_READ <- damr:::parse_datetime("2017-07-01 23:59:00", tz="UTC") d <- damr:::find_dam_first_last_lines(FILE, start_datetime = "2017-07-01", stop_datetime = "2017-07-01", tz="UTC") expect_equal(damr:::parse_datetime(d$datetime[1]), EXPECTED_FIRST_READ) expect_equal(damr:::parse_datetime(d$datetime[2]), EXPECTED_LAST_READ) }) test_that("Stop date is inclusive when time not specified", { FILE <- damr_example("M064.txt") EXPECTED_FIRST_READ <- damr:::parse_datetime("2017-06-30 14:55:00", tz="UTC") EXPECTED_LAST_READ <- damr:::parse_datetime("2017-07-02 00:00:00", tz="UTC") d <- damr:::find_dam_first_last_lines(FILE, start_datetime = "2017-06-30 14:55:00", stop_datetime = "2017-07-01", tz="UTC") expect_equal(damr:::parse_datetime(d$datetime[1]), EXPECTED_FIRST_READ) }) test_that("Error when dates are inconsistent", { FILE <- damr_example("M064.txt") expect_error(damr:::find_dam_first_last_lines(FILE, "2017-07-30 14:55:00", "2017-07-01 13:51:00", tz="UTC"), regex="start_datetime is greater than stop_datetime") expect_error(damr:::find_dam_first_last_lines(FILE, "2017-01-30 14:55:00", "2017-02-01 13:51:00", tz="UTC"), regex="No data") expect_error(damr:::find_dam_first_last_lines(FILE, "2017-07-03 00:06:00", +Inf, tz="UTC"), regex="No data") expect_error(damr:::find_dam_first_last_lines(FILE, -Inf, "2017-06-30 14:42:00", tz="UTC"), regex="No data") }) test_that("Error for daylight saving bug", { FILE <- damr_example("M064_DLS_bug1.txt") expect_error(damr:::find_dam_first_last_lines(FILE), regex="computer changing time") FILE <- damr_example("M064_DLS_bug2.txt") expect_error(damr:::find_dam_first_last_lines(FILE), regex="[Tt]ime has jumped") FILE <- damr_example("M064_disconnected.txt") expect_error(damr:::find_dam_first_last_lines(FILE), regexp = "[Tt]ime has jumped") }) test_that("ZIP wiles can be processed", { FILE <- damr_example("M014.txt.zip") EXPECTED_FIRST_READ <- damr:::parse_datetime("2017-06-30 14:55:00", tz="UTC") d <- damr:::find_dam_first_last_lines(FILE, start_datetime = "2017-06-30 14:55:00", stop_datetime = +Inf, tz="UTC") expect_equal(damr:::parse_datetime(d$datetime[1]), EXPECTED_FIRST_READ) }) test_that("https://github.com/rethomics/damr/issues/11", { FILE <- damr_example("issue_11.txt.zip") d <- damr:::find_dam_first_last_lines(FILE, start_datetime = "2017-07-11 07:59:00", stop_datetime = +Inf, tz="UTC") expect_equal(d[,paste(date, time, sep= " ")], c("11 Jul 17 07:59:00", "11 Jul 17 09:27:00")) })
set.seed(123) xu <- stats::rnorm(50) xm <- matrix(stats::rnorm(100), ncol = 2) index <- seq(Sys.Date(), Sys.Date() + 49, "day") lambda <- 0.01 xu_vec <- xu xu_mat <- as.matrix(xu) xu_ts <- stats::as.ts(xu) xu_xts <- xts::xts(xu, index) xu_df <- as.data.frame(xu) xu_tbl <- tibble::tibble(index = index, x = xu) xm_vec <- xm xm_mat <- as.matrix(xm) xm_ts <- stats::as.ts(xm) xm_xts <- xts::xts(xm, index) xm_df <- as.data.frame(xm) xm_tbl <- tibble::tibble(index = index, x = xm) test_that("lambda must specified", { expect_error(exp_decay(xu)) }) test_that("error if lambda is not a number of length 1", { expect_error(exp_decay(xu, c(lambda, lambda))) expect_error(exp_decay(xu, as.matrix(lambda))) }) smooth_numeric <- exp_decay(xu, lambda) test_that("works on doubles", { expect_type(smooth_numeric, "double") expect_s3_class(smooth_numeric, "ffp") expect_equal(vctrs::vec_size(smooth_numeric), vctrs::vec_size(xu)) }) smooth_matu <- exp_decay(xu_mat, lambda) test_that("works on univariate matrices", { expect_type(smooth_matu, "double") expect_s3_class(smooth_numeric, "ffp") expect_equal(vctrs::vec_size(smooth_matu), vctrs::vec_size(xu)) }) smooth_matm <- exp_decay(xm_mat, lambda) test_that("works on multivariate matrices", { expect_type(smooth_matm, "double") expect_s3_class(smooth_matm, "ffp") expect_equal(vctrs::vec_size(smooth_matm), vctrs::vec_size(xu)) }) smooth_tsu <- exp_decay(xu_ts, lambda) test_that("works on univariate ts", { expect_type(smooth_tsu, "double") expect_s3_class(smooth_tsu, "ffp") expect_equal(vctrs::vec_size(smooth_tsu), vctrs::vec_size(xu)) }) smooth_tsm <- exp_decay(xm_ts, lambda) test_that("works on multivariate ts", { expect_type(smooth_tsm, "double") expect_s3_class(smooth_tsm, "ffp") expect_equal(vctrs::vec_size(smooth_tsm), vctrs::vec_size(xu)) }) smooth_xtsu <- exp_decay(xu_xts, lambda) test_that("works on univariate xts", { expect_type(smooth_xtsu, "double") expect_s3_class(smooth_xtsu, "ffp") expect_equal(vctrs::vec_size(smooth_xtsu), vctrs::vec_size(xu)) }) smooth_xtsm <- exp_decay(xm_xts, lambda) test_that("works on multivariate xts", { expect_type(smooth_xtsm, "double") expect_s3_class(smooth_xtsm, "ffp") expect_equal(vctrs::vec_size(smooth_xtsm), vctrs::vec_size(xu)) }) smooth_dfu <- exp_decay(xu_df, lambda) test_that("works on univariate data.frames", { expect_type(smooth_dfu, "double") expect_s3_class(smooth_dfu, "ffp") expect_equal(vctrs::vec_size(smooth_dfu), vctrs::vec_size(xu)) }) smooth_dfm <- exp_decay(xm_df, lambda) test_that("works on multivariate data.frames", { expect_type(smooth_dfm, "double") expect_s3_class(smooth_dfm, "ffp") expect_equal(vctrs::vec_size(smooth_dfm), vctrs::vec_size(xu)) }) smooth_tblu <- exp_decay(xu_tbl, lambda) test_that("works on univariate tibbles", { expect_type(smooth_tblu, "double") expect_s3_class(smooth_tblu, "ffp") expect_equal(vctrs::vec_size(smooth_tblu), vctrs::vec_size(xu)) }) smooth_tblm <- exp_decay(xm_tbl, lambda) test_that("works on multivariate tibbles", { expect_type(smooth_tblm, "double") expect_s3_class(smooth_tblm, "ffp") expect_equal(vctrs::vec_size(smooth_tblm), vctrs::vec_size(xu)) }) test_that("results are identical and don't depend on the class", { expect_equal(smooth_numeric, smooth_matu) expect_equal(smooth_tsu, smooth_tblu) expect_equal(smooth_matm, smooth_xtsm) expect_equal(smooth_tsm, smooth_tblm) })
logml <- function (x, ...) { UseMethod("logml", x) } logml.bridge <- function (x, ...) { x$logml } logml.bridge_list <- function (x, fun = median, ...) { out <- fun(x$logml, ...) if (length(out) != 1) { warning("fun returns results of length != 1, only first used.") out <- out[1] } out }
library(rstan) d <- read.csv('../input/data-ss2.txt') T <- nrow(d) data <- list(T=T, T_pred=8, Y=d$Y) stanmodel <- stan_model(file='ex2.stan') fit <- sampling(stanmodel, data=data, iter=4000, thin=5, seed=1234)
source("R/DynCommMainR.R") source("R/ALGORITHM.R") source("R/CRITERION.R") ALGORITHM <- list( LOUVAIN=1L ) CRITERION <- list( MODULARITY=1L ) DynCommMain <- function(Algorithm,Criterion,Parameters) { thisEnv <- environment() alg <- Algorithm qlt <- Criterion prm <- Parameters if(alg>=1 & alg<=10000){ dc <- new(DynCommRcpp,alg,qlt,prm) } else if(alg>=20001 & alg<=30000){ dc <- DynCommMainR(alg,qlt,prm) } else{ dc<-NULL print("Unknown algorithm :(") } me <- list( thisEnv = thisEnv, results = function(differential=TRUE) { if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$results(differential)) } else{ return(matrix(nrow=0,ncol=2,byrow=TRUE,dimnames = list(c(),c("name","value")))) } }, addRemoveEdgesFile = function(graphAddRemoveFile){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$addRemoveEdgesFile(graphAddRemoveFile)) } else{ return(FALSE) } }, addRemoveEdgesMatrix = function(graphAddRemoveMatrix){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$addRemoveEdgesMatrix(graphAddRemoveMatrix)) } else{ return(FALSE) } }, quality=function(){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$quality()) } else{ return(NA) } }, communityCount=function(){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$communityCount()) } else{ return(NA) } }, communities=function(){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$communities()) } else{ return(list()) } }, communitiesEdgeCount=function() { if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$communitiesEdgeCount()) } else{ return(NA) } }, communityNeighbours=function(community){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$communityNeighbours(community)) } else{ return(matrix(nrow=0,ncol=2,byrow=TRUE,dimnames = list(c(),c("neighbour","weight")))) } }, communityInnerEdgesWeight=function(community){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$communityInnerEdgesWeight(community)) } else{ return(NA) } }, communityTotalWeight=function(community){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$communityTotalWeight(community)) } else{ return(NA) } }, communityEdgeWeight=function(source,destination){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$communityEdgeWeight(source,destination)) } else{ return(NA) } }, communityVertexCount=function(community){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$communityVertexCount(community)) } else{ return(NA) } }, community=function(vertex){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$community(vertex)) } else{ return(NA) } }, vertexCount=function(){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$vertexCount()) } else{ return(NA) } }, verticesAll=function(){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$verticesAll()) } else{ return(list()) } }, neighbours=function(vertex){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$neighbours(vertex)) } else{ return(matrix(nrow=0,ncol=2,byrow=TRUE,dimnames = list(c(),c("neighbour","weight")))) } }, edgeWeight=function(source,destination){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$edgeWeight(source,destination)) } else{ return(NA) } }, vertices=function(community){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$vertices(community)) } else{ return(list()) } }, edgeCount=function() { if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$edgeCount()) } else{ return(NA) } }, communityMappingMatrix = function(differential=TRUE){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$communityMappingMatrix(differential)) } else{ return(matrix(nrow=0,ncol=2,byrow=TRUE,dimnames = list(c(),c("vertex","community")))) } }, communityMappingFile = function(differential=TRUE,file=""){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$communityMappingFile(prm[which(prm=="cv"),2], differential,file)) } else{ return(matrix(nrow=0,ncol=1,byrow=TRUE,dimnames = list(c(),c("reply")))) } }, time=function(differential=FALSE){ if((alg>=1 & alg<=10000) | (alg>=20001 & alg<=30000)){ return(dc$time(differential)) } else{ return(NA) } } ) assign('this',me,envir=thisEnv) class(me) <- append(class(me),"DynCommMain") return(me) }
engine_write = function(x, path, drivers) { dir <- dirname(path) if (!dir.exists(dir)) dir.create(dir, recursive = TRUE) if (class(x)[1] %in% names(drivers)) driver <- drivers[[class(x)[1]]] else if (inherits(x, "LAS")) driver <- drivers$LAS else if (inherits(x, "stars")) driver <- drivers$stars else if (inherits(x, "Raster")) driver <- drivers$Raster else if (inherits(x, "Spatial")) driver <- drivers$Spatial else if (inherits(x, "sf")) driver <- drivers$sf else if (inherits(x, "data.frame")) driver <- drivers$data.frame else if (is(x, "lidr_internal_skip_write")) return(x) else stop(glue::glue("Trying to write an object of class {class(x)} but this type is not supported.")) path <- paste0(path, driver$extension) if (is_raster(x)) { attr(path, "rasterpkg") <- raster_pkg(x) attr(path, "layernames") <- raster_names(x) } driver$param[[driver$object]] <- x driver$param[[driver$path]] <- path do.call(driver$write, driver$param) return(path) } writeSpatial = function(x, filename, overwrite = FALSE, ...) { filename <- normalizePath(filename, winslash = "/", mustWork = FALSE) x <- sf::st_as_sf(x) if (isTRUE(overwrite)) append = FALSE else append = NA sf::st_write(x, filename, append = append, quiet = TRUE) }
context("weighted.ksvm") test_that("weighted.ksvm fitting", { library(kernlab) set.seed(123) n <- 40 x <- matrix(rnorm(n * 2), ncol = 2) y <- 2 * (sin(x[,2]) ^ 2 * exp(-x[,2]) > rnorm(n, sd = 0.1) + 0.225) - 1 weights <- runif(n, max = 1.5, min = 0.5) wk <- weighted.ksvm(x = x[1:n/2,], y = y[1:n/2], C = c(0.1, 0.5, 1), weights = weights[1:n/2]) expect_is(wk, "wksvm") pr <- predict(wk, newx = x[1:n/2,]) if (Sys.info()[[1]] != "windows") { wk <- weighted.ksvm(x = x[1:n/2,], y = y[1:n/2], C = 1, weights = weights[1:n/2]) expect_is(wk, "wksvm") } expect_error(weighted.ksvm(x = x[1:(n/2+1),], y = y[1:n/2], C = c(10), weights = weights[1:n/2])) expect_error(weighted.ksvm(x = x[1:n/2,], y = y[1:n/2], C = c(0.1), weights = weights[1:(n/2 + 1)])) foldid <- sample(rep(seq(3), length = n/2)) if (Sys.info()[[1]] != "windows") { wk <- weighted.ksvm(x = x[1:n/2,], y = y[1:n/2], C = c(1, 3), foldid = foldid, weights = weights[1:n/2]) expect_is(wk, "wksvm") expect_error(weighted.ksvm(x = x[1:(n/2),], y = y[1:(n/2)], C = c(0.1), nfolds = 150, weights = weights[1:(n/2)])) wk <- weighted.ksvm(x = x[1:(n/2),], y = as.factor(y[1:(n/2)]), C = c(1, 3), foldid = foldid, weights = weights[1:(n/2)]) expect_is(wk, "wksvm") expect_error(weighted.ksvm(x = x[1:(n/2),], y = c(1:5, y[5:(n/2)]), C = c(0.1), weights = weights[1:(n/2)])) wk <- weighted.ksvm(x = x[1:(n/2),], y = as.character(y[1:(n/2)]), C = c(1, 3), foldid = foldid, weights = weights[1:(n/2)]) expect_is(wk, "wksvm") wk <- weighted.ksvm(x = x[1:(n/2),], y = as.factor(y[1:(n/2)]), C = c(1, 3), foldid = foldid, weights = weights[1:(n/2)]) expect_is(wk, "wksvm") expect_warning(weighted.ksvm(x = x[1:(n/2),], y = as.character(y[1:(n/2)]), C = c(1, 3), nfolds = -5, weights = weights[1:(n/2)])) expect_error(weighted.ksvm(x = x[1:(n/2),], y = y[1:(n/2)]/2 + 0.5, C = c(0.1), weights = weights[1:(n/2)])) wk <- weighted.ksvm(x = x[1:(n/2),], y = as.character(y[1:(n/2)]), C = c(1, 10), foldid = foldid, kernel = "polydot", weights = weights[1:(n/2)]) expect_is(wk, "wksvm") wk <- weighted.ksvm(x = x[1:(n/2),], y = as.factor(y[1:(n/2)]), C = c(1, 3), foldid = foldid, weights = weights[1:(n/2)]) expect_is(wk, "wksvm") wk <- weighted.ksvm(x = x[1:(n/2),], y = as.character(y[1:(n/2)]), C = c(10), foldid = foldid, kernel = "tanhdot", weights = rep(1, (n/2)), margin = 0.5, bound = 10, maxiter = 200) expect_is(wk, "wksvm") wk <- weighted.ksvm(x = x[1:(n/2),], y = as.character(y[1:(n/2)]), C = c(1, 10), foldid = foldid, kernel = "vanilladot", weights = weights[1:(n/2)]) expect_is(wk, "wksvm") wk <- weighted.ksvm(x = x[1:(n/2),], y = as.character(y[1:(n/2)]), C = c(1, 10), foldid = foldid, kernel = "laplacedot", weights = weights[1:(n/2)]) expect_is(wk, "wksvm") wk <- weighted.ksvm(x = x[1:(n/2),], y = as.character(y[1:(n/2)]), C = c(1, 10), foldid = foldid, kernel = "besseldot", weights = weights[1:(n/2)]) expect_is(wk, "wksvm") wk <- weighted.ksvm(x = x[1:25,], y = as.character(y[1:25]), C = c(1, 10), kernel = "tanhdot", maxiter = 500, bound = 10, weights = weights[1:25]) expect_is(wk, "wksvm") summary(wk) wk <- weighted.ksvm(x = x[1:(n/2),], y = as.character(y[1:(n/2)]), C = c(1, 10), foldid = foldid, kernel = "anovadot", weights = weights[1:(n/2)]) expect_is(wk, "wksvm") } })
setClass( Class = "Bargaining", contains="Bertrand", representation=representation( bargpowerPre = "numeric", bargpowerPost = "numeric", prices = "numeric", margins = "numeric", priceStart = "numeric" ), prototype=prototype( bargpowerPre = numeric(), priceStart = numeric() ), validity=function(object){ nprods <- length(object@prices) if(length(object@margins) != nprods){stop("'margins' and 'prices' must have the same length")} if( !(all(object@margins >0,na.rm=TRUE) && all(object@margins <=1,na.rm=TRUE)) ){ stop("elements of vector 'margins' must be between 0 and 1") } if( !(all(object@bargpowerPre >=0,na.rm=TRUE) && all(object@bargpowerPre <=1,na.rm=TRUE)) ){ stop("elements of vector 'bargpowerPre' must be between 0 and 1") } if( !(all(object@bargpowerPost >=0,na.rm=TRUE) && all(object@bargpowerPost <=1,na.rm=TRUE)) ){ stop("elements of vector 'bargpowerPost' must be between 0 and 1") } if(nprods != length(object@priceStart)){ stop("'priceStart' must have the same length as 'prices'")} } ) setClass( Class = "BargainingLogit", contains="Logit", representation=representation( bargpowerPre = "numeric", bargpowerPost = "numeric" ), prototype=prototype( bargpowerPre = numeric() ), validity=function(object){ if( !(all(object@bargpowerPre >=0,na.rm = TRUE) && all(object@bargpowerPre <=1,na.rm=TRUE)) ){ stop("elements of vector 'bargpowerPre' must be between 0 and 1") } if( !(all(object@bargpowerPost >=0,na.rm=TRUE) && all(object@bargpowerPost <=1,na.rm=TRUE)) ){ stop("elements of vector 'bargpowerPost' must be between 0 and 1") } } )
.update_everything <- function() { old_opt <- .set_opt( offline = FALSE, verbose = TRUE ) on.exit(options(old_opt), add = TRUE) .parse_icd9cm_leaf_year( year = "2014", save_pkg_data = TRUE ) .print_options() .set_icd_data_dir() .print_options() .icd10cm_extract_sub_chapters(save_pkg_data = TRUE) .generate_sysdata() load(file.path("R", "sysdata.rda")) .generate_spelling() message("Parsing comorbidity mappings from SAS and text sources. (Make sure lookup files are updated first.) Depends on icd9cm_hierarchy being updated.") icd9_parse_ahrq_sas(save_pkg_data = TRUE) icd9_parse_quan_deyo_sas(save_pkg_data = TRUE) .parse_icd9cm_cc(save_pkg_data = TRUE) icd9_parse_ahrq_ccs(single = TRUE, save_pkg_data = TRUE) icd9_parse_ahrq_ccs(single = FALSE, save_pkg_data = TRUE) icd10_parse_ahrq_ccs(version = "2018.1", save_pkg_data = TRUE) icd9_generate_map_quan_elix(save_pkg_data = TRUE) icd9_generate_map_elix(save_pkg_data = TRUE) .parse_icd10cm_all(save_pkg_data = TRUE) icd10_parse_ahrq_sas(save_pkg_data = TRUE) .parse_icd10cm_cc(save_pkg_data = TRUE) icd10_generate_map_quan_elix(save_pkg_data = TRUE) icd10_generate_map_quan_deyo(save_pkg_data = TRUE) icd10_generate_map_elix(save_pkg_data = TRUE) generate_maps_pccc(save_pkg_data = TRUE) icd10_parse_map_ahrq_pc(save_pkg_data = TRUE) .parse_cc_hierarchy(save_pkg_data = TRUE) icd9cm2014_leaf <- get_icd9cm2014_leaf() .save_in_data_dir(icd9cm2014_leaf) icd10cm2019 <- .parse_icd10cm_year(2019) .save_in_data_dir(icd10cm2019) icd9cm_hierarchy <- get_icd9cm2014() names(icd9cm_hierarchy)[names(icd9cm_hierarchy) == "leaf"] <- "billable" .save_in_data_dir(icd9cm_hierarchy) } .generate_sysdata <- function(save_pkg_data = TRUE) { path <- file.path("R", "sysdata.rda") icd9_short_n <- icd9_generate_all_n() icd9_short_v <- icd9_generate_all_v() icd9_short_e <- icd9_generate_all_e() codes <- icd9cm_hierarchy[["code"]] icd9_short_n_defined <- vec_to_lookup_pair(grep("^[^VE]+", codes, perl = TRUE, value = TRUE)) icd9_short_v_defined <- vec_to_lookup_pair(grep("^V", codes, perl = TRUE, value = TRUE)) icd9_short_e_defined <- vec_to_lookup_pair(grep("^E", codes, perl = TRUE, value = TRUE)) icd9_short_n_leaf <- vec_to_lookup_pair(get_billable.icd10cm( icd9_short_n_defined$vec, short_code = TRUE, icd9cm_edition = "32" )) icd9_short_v_leaf <- vec_to_lookup_pair(get_billable.icd10cm( icd9_short_v_defined$vec, short_code = TRUE, icd9cm_edition = "32" )) icd9_short_e_leaf <- vec_to_lookup_pair(get_billable.icd10cm( icd9_short_e_defined$vec, short_code = TRUE, icd9cm_edition = "32" )) stopifnot(length(icd9_short_n$vec) == length(icd9_short_n$env)) stopifnot(length(icd9_short_v$vec) == length(icd9_short_v$env)) stopifnot(length(icd9_short_e$vec) == length(icd9_short_e$env)) stopifnot(length(icd9_short_n_leaf$vec) == length(icd9_short_n_leaf$env)) stopifnot(length(icd9_short_v_leaf$vec) == length(icd9_short_v_leaf$env)) stopifnot(length(icd9_short_e_leaf$vec) == length(icd9_short_e_leaf$env)) icd9_short_e icd9_short_n_leaf icd9_short_v_leaf icd9_short_e_leaf sysdata_names <- c( "icd9_short_n", "icd9_short_v", "icd9_short_e", "icd9_short_n_defined", "icd9_short_v_defined", "icd9_short_e_defined", "icd9_short_n_leaf", "icd9_short_v_leaf", "icd9_short_e_leaf" ) if (save_pkg_data) { save( list = sysdata_names, file = path, compress = "xz", version = 2 ) } invisible(mget(sysdata_names)) } icd9_generate_all_major_n <- function() { sprintf("%03d", 1:999) } icd9_generate_all_major_v <- function() { sprintf("V%02d", 1:99) } icd9_generate_all_major_e <- function() { sprintf("E%03d", 0:999) } icd9_generate_all_n <- function(...) { icd9_generate_all_(major_fun = icd9_generate_all_major_n, ...) } icd9_generate_all_v <- function(...) { icd9_generate_all_(major_fun = icd9_generate_all_major_v, ...) } icd9_generate_all_e <- function(...) { icd9_generate_all_(major_fun = icd9_generate_all_major_e, ...) } icd9_generate_all_ <- function(major_fun, short_code = TRUE, env = new.env(hash = TRUE, baseenv())) { vec <- character() for (i in major_fun()) { kids <- children.icd9(i, short_code = short_code, defined = FALSE) vec <- c(vec, kids) } vec_to_env_count(vec, env = env) invisible(list(env = env, vec = env_to_vec_flip(env))) }
context("test-left_join") setup({ setup_disk.frame(2) a = data.frame(a = 1:100, b = 1:100) b = data.frame(a = 51:150, b = 1:100) d = data.frame(a = 1:50, b = 1:50) as.disk.frame(a, file.path(tempdir(), "tmp_a_lj.df"), nchunks = 4, overwrite = T) as.disk.frame(b, file.path(tempdir(), "tmp_b_lj.df"), nchunks = 5, overwrite = T) as.disk.frame(d, file.path(tempdir(), "tmp_d_lj.df"), overwrite = T) as.disk.frame(a, file.path(tempdir(), "tmp_a_lj2.df"), nchunks = 4, overwrite = T) as.disk.frame(b, file.path(tempdir(), "tmp_b_lj2.df"), nchunks = 5, overwrite = T) as.disk.frame(d, file.path(tempdir(), "tmp_d_lj2.df"), overwrite = T) }) test_that("testing left_join where right is data.frame", { a = disk.frame(file.path(tempdir(), "tmp_a_lj.df")) b = disk.frame(file.path(tempdir(), "tmp_b_lj.df")) d = disk.frame(file.path(tempdir(), "tmp_d_lj.df")) bc = collect(b) dc = collect(d) abc = left_join(a, bc, by = "a") %>% collect expect_equal(nrow(abc), 100) abc0 = left_join(a, bc, by = c("a","b")) %>% collect expect_equal(nrow(abc0), 100) by_cols = c("a","b") abc0 = left_join(a, bc, by = by_cols) %>% collect expect_equal(nrow(abc0), 100) abc100 = left_join(a, bc, by = "b") %>% collect expect_equal(nrow(abc100), 100) abd50 = left_join(a, dc, by = "b") %>% collect expect_equal(nrow(abd50), 100) }) test_that("testing left_join where right is disk.frame", { a = disk.frame(file.path(tempdir(), "tmp_a_lj2.df")) b = disk.frame(file.path(tempdir(), "tmp_b_lj2.df")) d = disk.frame(file.path(tempdir(), "tmp_d_lj2.df")) expect_warning({ ab = left_join(a, b, by = "a", merge_by_chunk_id = F) %>% collect }) expect_equal(nrow(ab), 100) expect_warning({ ab0 = left_join(a, b, by = c("a","b"), merge_by_chunk_id = F) %>% collect }) expect_equal(nrow(ab0), 100) expect_warning({ ab100 = left_join(a, b, by = "b", merge_by_chunk_id = F) %>% collect }) expect_equal(nrow(ab100), 100) expect_warning({ ad50 = left_join(a, d, by = "b", merge_by_chunk_id = F) %>% collect }) expect_equal(nrow(ad50), 100) }) teardown({ fs::dir_delete(file.path(tempdir(), "tmp_a_lj.df")) fs::dir_delete(file.path(tempdir(), "tmp_b_lj.df")) fs::dir_delete(file.path(tempdir(), "tmp_d_lj.df")) fs::dir_delete(file.path(tempdir(), "tmp_a_lj2.df")) fs::dir_delete(file.path(tempdir(), "tmp_b_lj2.df")) fs::dir_delete(file.path(tempdir(), "tmp_d_lj2.df")) })
library(shiny) ui = fluidPage( titlePanel("Example Shiny App"), sidebarLayout( sidebarPanel( selectInput( inputId = "dataset", label = "Choose a dataset", choices = c("rock", "pressure", "cars", "iris")), numericInput( inputId = "obs", label = "Number of observations to view:", value = 10) ), mainPanel( tags$div(sprintf("Global Variable Value: %s", GLOBAL_VAR)), verbatimTextOutput("commandArgs"), verbatimTextOutput("dataSummary"), tableOutput("dataView") ) ) )
`dixon2002` <- function (datos, nsim = 99) { datos <- as.matrix(datos) info = mNNinfo(xy = datos[, 1:2], label = datos[, 3]) datos.test = mNNtest(info) Ni = rowSums(info$ON) S = log10((info$ON/(Ni - info$ON))/(info$EN/(Ni - info$EN))) ON = info$ON EN = info$EN Z = datos.test$Z Z.obs = Z pZas = 2 * (ifelse(Z >= 0, 1 - pnorm(Z), pnorm(Z))) C = datos.test$C[1] C.obs = C Ci = datos.test$Ci[, 1] Ci.obs = Ci pCas = datos.test$C[2] pCias = datos.test$Ci[, 2] pZr = NULL pCr = NULL pCir = NULL SN = as.vector(t(ON)) if (nsim > 0) { for (i in 1:nsim) { print(i) datos[, 3] = sample(datos[, 3]) info = mNNinfo(xy = datos[, 1:2], label = datos[, 3]) datos.test = mNNtest(info) Z = cbind(Z, datos.test$Z) C = c(C, datos.test$C[1]) Ci = cbind(Ci, datos.test$Ci[, 1]) SN <-cbind(SN, as.vector(t(info$ON))) } pNr = apply(SN, 1, p2colasr) pCr = 1 - rank(C)[1]/(length(C)) pCir = apply(Ci, 1, function(x) 1 - rank(x)[1]/(length(x))) } St = as.data.frame(as.table(round(S, 2))) ONt = as.data.frame(as.table(ON)) ENt = as.data.frame(as.table(round(EN, 2))) Zt = round(datos.test$Z, 2) round(pZas, 4) tableZ = cbind(ONt[order(ONt[, 1]), ], ENt[order(ENt[, 1]), 3], St[order(St[, 1]), 3], round(Z.obs, 2), round(pZas, 4)) names(tableZ) = c("From", "To", " Obs.Count", " Exp. Count", "S ", "Z ", " p-val.as") if (length(pNr) != 0) { tableZ = cbind(tableZ, round(pNr, 4)) names(tableZ) = c(names(tableZ)[-8], " p-val.Nobs") } rownames(tableZ) = NULL k = length(unique(datos[, 3])) df = c(k * (k - 1), rep(k - 1, k)) nombres.test = c("Overall segregation", paste("From ", dimnames(EN)[[1]], " ")) tablaC = data.frame(cbind(df, round(c(C.obs, Ci.obs), 2), round(c(pCas, pCias), 4))) row.names(tablaC) = nombres.test names(tablaC) = c(" df ", "Chi-sq", "P.asymp") if (length(pCir) != 0) { tablaC = cbind(tablaC, round(c(pCr, pCir), 4)) names(tablaC) = c(names(tablaC)[-4], " P.rand") } return(list(ON = ON, EN = EN, Z = Z.obs, S = S, pZas = pZas, pNr = pNr, C = C.obs, Ci = Ci.obs, pCas = pCas, pCias = pCias, pCr = pCr, pCir = pCir, tablaZ = tableZ, tablaC = tablaC)) }
NULL "eight_schools"
opt.landgen <- function(landscape, nlocations, mindist=0, fixed = NULL, method, NN=8, iter =100, retry=10, mask=NULL, plot=TRUE) { scenario <- list() opt <- data.frame(sd.cost=NA, sd.detour=NA) if (!is.null(fixed)) { specified <- nrow(fixed) } else specified = 0 nadd <- nlocations - specified if (is.na(crs(landscape))) crs(landscape) <-"+proj=merc +units=m" for (it in 1:iter) { r1 <-landscape values(r1) <- NA if (!is.null(mask)) { r1 <- mask values(r1)<- ifelse(is.na(values(r1)),1,NA) } retryc <- retry if (mindist==0) { r1inv <- r1 values(r1inv) <- ifelse(is.na(values(r1inv)),1,NA) rp<-coordinates(as(r1inv,"SpatialPointsDataFrame") ) choosep <- sample(1:nrow(rp),nadd) xs <- rp[choosep,1] ys <- rp[choosep,2] } if (mindist>0) { if (!is.null(fixed)) { rd <- rasterize(fixed, r1,1) rd <- buffer(rd, mindist) r1 <- sum(r1,rd, na.rm=T) values(r1) <- ifelse(values(r1)>0,1,NA) } left <- sum(is.na(values(r1))) if (left==0) {cat("There is no area left to place the required number of locations after placing the fixed locations. Reduce mindist or the amount of fixed locations.\n"); stop()} xc <- NA yc <- NA i <- 1 rback <- r1 while (i<=nadd) { r1inv <- r1 values(r1inv) <- ifelse(is.na(values(r1inv)),1,NA) rp<-coordinates(as(r1inv,"SpatialPointsDataFrame") ) choosep <- sample(1:nrow(rp),1) xs <- rp[choosep,1] ys <- rp[choosep,2] xc[i] <- xs yc[i] <- ys i <- i+1 rd <- rasterize(cbind(xs,ys), r1,1) rd <- buffer(rd, mindist) r1 <- sum(r1,rd, na.rm=T) values(r1) <- ifelse(values(r1)>0,1,NA) left <- sum(is.na(values(r1))) if (left==0 & i<=nadd) { retryc <- retryc - 1 cat(paste("No area left after ",i,"points at iteration",it,". I go back and try again.", retryc, "retries left...\n")) i <- 1 r1 <- rback if (retryc<1) {stop("Could not find any good combination, reduce mindist or increase retry or reduce number of fixed locations.\n")} } } xs <- xc ys <- yc } locs <- cbind(xs,ys) rownames(locs) <- LETTERS[1:nadd] locs <- rbind(fixed, locs) cost.mat <- costdistances(landscape, locs, method, NN) eucl.mat <- as.matrix(dist(locs)) sd.cost <- sd(as.dist(cost.mat)) sd.detour = sd(resid(lm(as.dist(cost.mat)~as.dist( eucl.mat)))) opt[it,] <-c(sd.cost, sd.detour) scenario[[it]] <- locs } if (plot) { op <- par(mfrow=c(2,2), mai=c(0.5,0.5,0.2,0.2)) opt.val <- which.max(opt$sd.detour) locs.opt <- scenario[[opt.val]] locs <- locs.opt cost.mat <- costdistances(landscape, locs, method, NN) eucl.mat <- as.matrix(dist(locs)) detour = resid(lm(as.dist(cost.mat)~as.dist( eucl.mat))) hist(detour, main="Distrubtion of detour", col="darkgreen") plot(ecdf(opt$sd.detour), main="Cummulative Density of sd.detour") abline(v=opt[opt.val,"sd.detour"] ,col="blue") opt.val <- which.max(opt$sd.detour) locs.opt <- scenario[[opt.val]] locs <- locs.opt plot(landscape, main=paste("best:",round(opt[opt.val,"sd.detour"],2) )) points(locs[,1], locs[,2], pch=16, cex=1.2, col=c(rep("blue", specified), rep("black", nadd))) text(locs[,1],locs[,2], row.names(locs), cex=1) opt.val <- which.min(opt$sd.detour) locs.opt <- scenario[[opt.val]] locs <- locs.opt plot(landscape, main=paste("worst:",round(opt[opt.val,"sd.detour"],2) )) points(locs[,1], locs[,2], pch=16, cex=1.2, col=c(rep("blue", specified), rep("black", nadd))) text(locs[,1],locs[,2], row.names(locs), cex=1) par(op) } ord <- order(opt$sd.detour, decreasing = TRUE) return(list(opt=opt[ord,], scenario = scenario[ord])) }
expand_list = function(x, max = 5) { max = max - 1 N = names(x) ans = lapply(x, FUN=function(n) { foo = attributes(n) bar = (names(foo) == "names") if((length(n) == 0) | (max < 0)) return(foo) c(foo[!bar], expand_list(n[bar], max = max)) }) names(ans) <- N return(ans) } escape_entities = function(text) { text = gsub("&", "&amp;", text) text = gsub(">", "&gt;", text) text = gsub("<", "&lt;", text) text = gsub("'", "&apos;", text) gsub('"', '&quot;', text) } to_list_node = function(x, max = 5) { expand_list(xml2::as_list(x), max = max) } to_xml_list = function(x, name, kids, indent = " ", escape = "\n") { name = as.character(name); assert(name, len = 1, typ = "character") N = names(x) if(length(N)==0 & missing(kids)) { return(sprintf("<%s>%s</%s>", name, x, name)) } node = do.call(paste0, args = c(list(collapse = " ", lapply(1:length(x), FUN=function(i) sprintf('%s="%s"',N[i],x[[i]]))))) if(missing(kids)) { return(sprintf("<%s %s />", name, node)) } else { K = lapply(kids, FUN =function(k) paste0(indent, k, escape)) return(sprintf("<%s %s>%s%s</%s>", name, node, escape, paste0(K, collapse=""), name)) } } xml_new_node <- function(name, attrs, .children, text, ...) { tmp <- xml_new_root("foo") if(!missing(text) & !missing(attrs)) stop("should be either a 'text' node or a 'attr' node") tmp %>% xml_add_child(.value = name) node <- xml_find_first(tmp, xpath = name) if(!missing(text)) { node %>% xml_set_text(value = text) } if(!missing(attrs)) { node %>% xml_set_attrs(value = attrs) } if(!missing(.children)) { if(any(class(.children) == "xml_node")) { node %>% xml_add_child(.value = .children) } else { L = length(.children) first <- node %>% xml_add_child(.value = "") for(i in 1:L) { first %>% xml_add_sibling(.value = .children[[i]], .where = "before") } xml_remove(first) } } return(node) }
calc_si = function(TMAX,TMIN,lat,missingcalc="mean"){ if(is.matrix(TMAX)==FALSE | is.matrix(TMIN)==FALSE){ stop("TMAX or TMIN are not matrices",.call=TRUE) } if(is.numeric(TMAX)==FALSE | is.numeric(TMIN)==FALSE | is.numeric(lat)==FALSE){ stop("TMAX, TMIN, or lat are not numeric",.call=TRUE) } if(all(TMAX[which(is.na(TMAX)==FALSE)]>200)==TRUE & all(TMIN[which(is.na(TMIN)==FALSE)]>200)==TRUE){ warning("TMAX and TMIN appear to be in degrees K, so I converted them to degrees F") TMAX = (TMAX-273.15)*9/5+32 TMIN = (TMIN-273.15)*9/5+32 } baset = 31 frzval = 28 FLImat = FBImat = DMGmat = matrix(NA,nrow=ncol(TMAX),ncol=4) FSmat = matrix(NA,nrow=ncol(TMAX),ncol=2) lastfreeze = c() for(i in 1:ncol(TMAX)){ tasmax = as.vector(TMAX[,i]) tasmin = as.vector(TMIN[,i]) if(missingcalc=="mean"){ message("using monthly mean to impute missing values") for(x in seq(1,211,by=30)){ start = x end = x+29 flagm = 0 tmaxNAidx = which(is.na(tasmax[start:end])==TRUE) tminNAidx = which(is.na(tasmin[start:end])==TRUE) cntmax = length(tasmax[start:end])-length(tmaxNAidx) cntmin = length(tasmin[start:end])-length(tminNAidx) tmax = tasmax[start:end] tmin = tasmin[start:end] idx = start:end if(length(tmaxNAidx)>0){ avgmax = mean(tmax[-tmaxNAidx]) tasmax[idx[tmaxNAidx]]=avgmax } if(length(tminNAidx)>0){ avgmin = mean(tmin[-tminNAidx]) tasmin[idx[tminNAidx]]=avgmin } if(cntmax < 20 | cntmin <20) flagm = 1 if(flagm == 1){ warning(paste("There is a lot of missing data in TMAX and TMIN for column ",i,sep="")) } } } if(missingcalc=="loess"){ message("using loess to impute missing values") tstart = -(nrow(TMAX)/2):0 tstartuse = 1:184 t=1:nrow(TMAX) tend = seq(367,by=1,length.out=184) tenduse = seq(366,by=-1,length.out=184) tenduse = tenduse[order(tenduse)] tstring = c(tstart,t,tend) if(i==1){ tmaxseries = c(TMAX[tenduse,i],tasmax,TMAX[tstartuse,(i+1)]) tminseries = c(TMIN[tenduse,i],tasmin,TMIN[tstartuse,(i+1)]) } if(i>1 & i<ncol(TMAX)){ tmaxseries = c(TMAX[tenduse,(i-1)],tasmax,TMAX[tstartuse,(i+1)]) tminseries = c(TMIN[tenduse,(i-1)],tasmin,TMIN[tstartuse,(i+1)]) } if(i==ncol(TMAX)){ tmaxseries = c(TMAX[tenduse,(i-1)],tasmax,TMAX[tstartuse,(i-1)]) tminseries = c(TMIN[tenduse,(i-1)],tasmin,TMIN[tstartuse,(i-1)]) } notNAidx = which(is.na(tmaxseries)==FALSE) isNAidx = which(is.na(tmaxseries)==TRUE) loessfit = loess(tmaxseries[notNAidx]~tstring[notNAidx],span=0.03) tmaxseries[isNAidx] = predict(loessfit,newdata=tstring[isNAidx]) tasmax = tmaxseries[which(tstring>=1 & tstring<=366)] notNAidx = which(is.na(tminseries)==FALSE) isNAidx = which(is.na(tminseries)==TRUE) loessfit = loess(tminseries[notNAidx]~tstring[notNAidx],span=0.03) tminseries[isNAidx] = predict(loessfit,newdata=tstring[isNAidx]) tasmin = tminseries[which(tstring>=1 & tstring<=366)] check1idx = which(is.na(tasmax[1:31])==TRUE) if(length(check1idx)>0){ tasmax[check1idx] = mean(tasmax[1:31],na.rm=TRUE) } check1idx = which(is.na(tasmin[1:31])==TRUE) if(length(check1idx)>0){ tasmin[check1idx] = mean(tasmin[1:31],na.rm=TRUE) } if(is.na(tasmax[length(tasmax)])==TRUE){ tasmax[length(tasmax)] = tasmax[(length(tasmax)-1)] } if(is.na(tasmin[length(tasmin)])==TRUE){ tasmin[length(tasmin)] = tasmin[(length(tasmin)-1)] } if(any(is.na(tasmax)==TRUE)==TRUE){ message("Still has missing values in tasmax") print(tasmax) } if(any(is.na(tasmin)==TRUE)==TRUE){ message("Still has missing values in tasmin") print(tasmin) } } DOY = 1:length(tasmax) daystop = max(DOY) dlen = daylength(daystop,lat=lat) FLImat[i,2] = leafindex(tasmax=tasmax,tasmin=tasmin,daylen=dlen,baset=baset,refdate=1,type="leaf",plant=1) FLImat[i,3] = leafindex(tasmax=tasmax,tasmin=tasmin,daylen=dlen,baset=baset,refdate=1,type="leaf",plant=2) FLImat[i,4] = leafindex(tasmax=tasmax,tasmin=tasmin,daylen=dlen,baset=baset,refdate=1,type="leaf",plant=3) FLImat[i,1] = round(mean(FLImat[i,2:4],na.rm=TRUE)) if(is.na(FLImat[i,2])==FALSE){FBImat[i,2] = leafindex(tasmax=tasmax,tasmin=tasmin,daylen=dlen,baset=baset,refdate=FLImat[i,2],type="bloom",plant=1)} if(is.na(FLImat[i,3])==FALSE){FBImat[i,3] = leafindex(tasmax=tasmax,tasmin=tasmin,daylen=dlen,baset=baset,refdate=FLImat[i,3],type="bloom",plant=2)} if(is.na(FLImat[i,4])==FALSE){FBImat[i,4] = leafindex(tasmax=tasmax,tasmin=tasmin,daylen=dlen,baset=baset,refdate=FLImat[i,4],type="bloom",plant=3)} FBImat[i,1] = round(mean(FBImat[i,2:4],na.rm=TRUE)) freezeinfo = freezedates(tasmin=tasmin,frzval=frzval,DOY=DOY) lastfreeze[i] = freezeinfo$lastfreeze freezedata = subset(freezeinfo[[4]],DOY>=1 & DOY<=180) if(is.na(lastfreeze[i])==FALSE){ if(is.na(FLImat[i,2])==FALSE){DMGmat[i,2] = damageindex(leafidx=FLImat[i,2],lastfreeze=freezeinfo$lastfreeze)} if(is.na(FLImat[i,3])==FALSE){DMGmat[i,3] = damageindex(leafidx=FLImat[i,3],lastfreeze=freezeinfo$lastfreeze)} if(is.na(FLImat[i,4])==FALSE){DMGmat[i,4] = damageindex(leafidx=FLImat[i,4],lastfreeze=freezeinfo$lastfreeze)} DMGmat[i,1] = round(mean(DMGmat[i,2:4],na.rm=TRUE)) fs = falsesprings(SI=c(FLImat[i,1],FBImat[i,1]),freezedata = freezedata) FSmat[i,1] = fs$EFS FSmat[i,2] = fs$LFS } else { message("Freeze didn't happen this year, so no damage or false springs") DMGmat[i,1:4] = 0 FSmat[i,1:2] = 0 } } FSEImat = apply(FSmat,2,FSEI) list(FLImat=FLImat,FBImat=FBImat,DMGmat=DMGmat,lastfreeze=lastfreeze,FSmat=FSmat,FSEImat=FSEImat) } soldec = function(DOY){ decvals=c(-23.16,-23.08,-23,-22.92,-22.83,-22.73,-22.62,-22.5,-22.38,-22.24,-22.11,-21.96,-21.81,-21.65,-21.48,-21.31,-21.13,-20.94, -20.75,-20.55,-20.34,-20.13,-19.91,-19.68,-19.45,-19.21,-18.97,-18.72,-18.46,-18.2,-17.94,-17.68,-17.39,-17.11,-16.83,-16.53,-16.23, -15.93,-15.62,-15.31,-15,-14.68,-14.36,-14.03,-13.7,-13.36,-13.03,-12.68,-12.34,-11.99,-11.64,-11.28,-10.93,-10.57,-10.2,-9.84,-9.47, -9.1,-8.73,-8.35,-7.98,-7.6,-7.22,-6.83,-6.45,-6.06,-5.68,-5.29,-4.9,-4.51,-4.12,-3.72,-3.33,-2.93,-2.54,-2.15,-1.75,-1.36,-0.97,-0.57, -0.17,0.22,0.62,1.01,1.41,1.8,2.19,2.58,2.98,3.37,3.76,4.14,4.53,4.92,5.3,5.68,6.06,6.44,6.82,7.19,7.57,7.94,8.31,8.67,9.04,9.4,9.76, 10.11,10.47,10.82,11.16,11.51,11.85,12.19,12.52,12.85,13.18,13.5,13.83,14.14,14.45,14.76,15.07,15.37,15.67,15.95,16.24,16.53,16.81,17.08, 17.35,17.61,17.87,18.13,18.38,18.62,18.87,19.09,19.32,19.54,19.76,19.97,20.18,20.38,20.57,20.76,20.94,21.12,21.29,21.46,21.61,21.77,21.91, 22.05,22.18,22.31,22.43,22.54,22.65,22.75,22.84,22.93,23.01,23.08,23.15,23.21,23.26,23.31,23.35,23.38,23.41,23.43,23.44,23.44,23.43,23.41, 23.38,23.35,23.31,23.26,23.21,23.15,23.08,23.01,22.93,22.84,22.75,22.65,22.54,22.43,22.31,22.18,22.05,21.91,21.77,21.61,21.46,21.29,21.12, 20.94,20.76,20.57,20.38,20.18,19.97,19.76,19.54,19.32,19.09,18.87,18.62,18.38,18.13,17.87,17.61,17.35,17.08,16.81,16.53,16.24,15.95,15.67, 15.37,15.07,14.76,14.45,14.14,13.83,13.5,13.18,12.85,12.52,12.19,11.85,11.51,11.16,10.82,10.47,10.11,9.76,9.4,9.04,8.67,8.31,7.94,7.57,7.19, 6.82,6.44,6.06,5.68,5.3,4.92,4.53,4.14,3.76,3.37,2.98,2.58,2.19,1.8,1.41,1.01,0.62,0.22,-0.17,-0.57,-0.97,-1.36,-1.75,-2.15,-2.54,-2.93,-3.33, -3.72,-4.12,-4.51,-4.9,-5.29,-5.68,-6.06,-6.45,-6.83,-7.22,-7.6,-7.98,-8.35,-8.73,-9.1,-9.47,-9.84,-10.2,-10.57,-10.93,-11.28,-11.64,-11.99,-12.34, -12.68,-13.03,-13.36,-13.7,-14.03,-14.36,-14.68,-15,-15.31,-15.62,-15.93,-16.23,-16.53,-16.83,-17.11,-17.39,-17.68,-17.94,-18.2,-18.46,-18.72,-18.97, -19.21,-19.45,-19.68,-19.91,-20.13,-20.34,-20.55,-20.75,-20.94,-21.13,-21.31,-21.48,-21.65,-21.81,-21.96,-22.11,-22.24,-22.38,-22.5,-22.62,-22.73, -22.83,-22.92,-23,-23.08,-23.16,-23.23,-23.29,-23.34,-23.38,-23.42,-23.45,-23.47,-23.48,-23.49,-23.5,-23.5,-23.49,-23.48,-23.47,-23.45,-23.42, -23.38,-23.34,-23.29,-23.23) dayvals = c(307:366,1:306) dayvals[DOY] } daylength = function(daystop,lat){ DAYLEN = c() for(i in 1:daystop){ if(lat < 40){ DLL = 12.14+3.34*tan(lat*pi/180)*cos(0.0172*soldec(i)-1.95) } else { DLL = 12.25 + (1.6164+1.7643*(tan(lat*pi/180))^2)*cos(0.0172*soldec(i)-1.95) } if(DLL < 1) DLL=1 if(DLL> 23) DLL = 23 DAYLEN[i]=DLL } DAYLEN } chillh = function(tmax,tmin,daylen,baset){ DTR = tmax-tmin IDL = floor(daylen) Thr = c() Thr[1] = tmin Thr[2:(IDL+1)]=DTR*sin(pi/(daylen+4)*(1:IDL))+tmin TS1 = DTR*sin(pi/(daylen+4)*daylen)+tmin if(TS1 <=0) TS1 = 0.01 Thr[(IDL+2):24] = TS1-(TS1-tmin)/(log(24-daylen))*log((1:(23-IDL))) CHRS = baset-Thr CHRSflag = ifelse(CHRS<0,0,1) CHOUR = sum(CHRSflag) CHOUR } chilldate = function(tasmax,tasmin,DOY,daylen,baset,plant=1){ chillframe = data.frame(tasmax,tasmin,daylen,DOY) if(nrow(chillframe)==365){ chillframe$DOYadj = ifelse(DOY<=180,DOY+185,DOY-180) } else { chillframe$DOYadj = ifelse(DOY<=180,DOY+186,DOY-180) } chillframe = chillframe[order(chillframe$DOYadj),] chillframe$CH = NA chillframe$ACH = NA for(i in 1:nrow(chillframe)){ chillframe$CH[i] = chillh(chillframe$tasmax[i],chillframe$tasmin[i],chillframe$daylen[i],baset=baset) if(i==1) chillframe$ACH[i]=chillframe$CH[i] if(i>1) chillframe$ACH[i]=chillframe$ACH[(i-1)]+chillframe$CH[i] } if(plant==1) chillidx = which(chillframe$ACH >= 1375) if(plant==2 | plant==3) chillidx = which(chillframe$ACH >= 1250) chillDOY = chillframe$DOY[chillidx[1]] chillDOY } growdh = function(tmax,tmin,daylen,baset){ if(tmin==0) tmin=0.01 if(tmax==tmin) tmax=tmax+0.01 DTR = tmax-tmin IDL = floor(daylen) Thr = c() Thr[1] = tmin Thr[2:(IDL+1)]=DTR*sin(pi/(daylen+4)*(1:IDL))+tmin TS1 = DTR*sin(pi/(daylen+4)*daylen)+tmin if(TS1 <=0) TS1 = 0.01 Thr[(IDL+2):24] = TS1-(TS1-tmin)/(log(24-daylen))*log((1:(23-IDL))) GHRS = Thr-baset GHRS = ifelse(GHRS<0,0,GHRS) GDHOUR = sum(GHRS) GDHOUR } synval = function(GDH,lagGDH,type="leaf"){ SYNFLAG=0 if(type == "leaf") LIMIT=637 if(type == "bloom") LIMIT=2001 if(type != "leaf" & type !="bloom") stop("Improper event type",.call=TRUE) VALUE=GDH+lagGDH[1]+lagGDH[2] if(VALUE >= LIMIT){ SYNFLAG=1 } else { SNYFLAG=0 } DDE2=GDH+lagGDH[1]+lagGDH[2] DD57=sum(lagGDH[5:7]) output = list(synflag = SYNFLAG,ddE2=DDE2,dd57=DD57) output } leafindex = function(tasmax,tasmin,daylen,baset,refdate,type="leaf",plant=1, verbose=FALSE){ ID2 = refdate daymax = 240 Eflag = 0 AGDH = 0 SYNOP = 0 CNT = refdate-1 lagGDH = rep(0,7) Alf=list(c(3.306,13.878,0.201,0.153),c(4.266,20.899,0.000,0.248),c(2.802,21.433,0.266,0.000)) Alb=list(c(-23.934,0.116),c(-24.825,0.127),c(-11.368,0.096)) parametersout = matrix(NA,nrow=366,ncol=6) lagGDHvals = matrix(NA,nrow=366,ncol=7) while(CNT<daymax & Eflag==0){ CNT = CNT+1 GDH = growdh(tasmax[CNT],tasmin[CNT],daylen[CNT],baset) if(CNT==1 & type=="leaf"){ lagGDH[1] = GDH lagGDH[2] = GDH } lagGDHvals[CNT,] = lagGDH synlist = synval(GDH,lagGDH,type=type) if(CNT>=refdate){ AGDH = GDH+AGDH if(synlist[[1]]==1) SYNOP=SYNOP+1 } if(CNT>=refdate){ MDS0 = CNT-refdate parametersout[CNT,1] = MDS0 parametersout[CNT,2] = SYNOP parametersout[CNT,3] = synlist[[2]] parametersout[CNT,4] = synlist[[3]] parametersout[CNT,5] = AGDH parametersout[CNT,6] = GDH if(type=="leaf"){ if(plant==1) MDSUM1=(Alf[[1]][1]*MDS0)+(Alf[[1]][2]*SYNOP)+(Alf[[1]][3]*synlist[[2]])+(Alf[[1]][4]*synlist[[3]]) if(plant==2) MDSUM1=(Alf[[2]][1]*MDS0)+(Alf[[2]][2]*SYNOP)+(Alf[[2]][3]*synlist[[2]])+(Alf[[2]][4]*synlist[[3]]) if(plant==3) MDSUM1=(Alf[[3]][1]*MDS0)+(Alf[[3]][2]*SYNOP)+(Alf[[3]][3]*synlist[[2]])+(Alf[[3]][4]*synlist[[3]]) } if(type=="bloom"){ if(plant==1) MDSUM1=(Alb[[1]][1]*MDS0)+(Alb[[1]][2]*AGDH) if(plant==2) MDSUM1=(Alb[[2]][1]*MDS0)+(Alb[[2]][2]*AGDH) if(plant==3) MDSUM1=(Alb[[3]][1]*MDS0)+(Alb[[3]][2]*AGDH) } } else { MDSUM1 = 1 } if(MDSUM1>=999.5 & Eflag==0){ if(type=="leaf"){ if(plant==1 | plant==3) OUTDOY = CNT if(plant==2) OUTDOY = CNT+1 } if(type=="bloom"){ OUTDOY = CNT } Eflag=1 } lagGDH[2:7]=lagGDH[1:6] lagGDH[1] = GDH } if(CNT>=daymax){ OUTDOY=NA } if(verbose==TRUE){ list(OUTDOY=round(OUTDOY),parameters=parametersout,lagGDHvals = lagGDHvals) } else { round(OUTDOY) } } freezedates = function(tasmin,frzval,DOY){ frzframe = data.frame(tasmin,DOY) if(nrow(frzframe)==365){ frzframe$DOYadj = ifelse(DOY<=180,DOY+185,DOY-180) } else { frzframe$DOYadj = ifelse(DOY<=180,DOY+186,DOY-180) } frzframe = frzframe[order(frzframe$DOYadj),] idx = which(frzframe$tasmin<=frzval) lastfreeze = frzframe[idx[length(idx)],2] firstfreeze = frzframe[idx[1],2] freezeperiod = frzframe[idx[length(idx)],3]- frzframe[idx[1],3] if(length(lastfreeze)==0) lastfreeze=NA freezelist = list(firstfreeze=firstfreeze,lastfreeze=lastfreeze,freezeperiod=freezeperiod,freezedata=frzframe[idx,]) freezelist } damageindex = function(leafidx,lastfreeze){ idx = lastfreeze - leafidx DMG = ifelse(idx<0 | idx>=180,0,idx) DMG } falsesprings = function(SI=c(60,65),freezedata){ EFSidx = which(freezedata$DOY>=(SI[1]+7) & freezedata$DOY<=SI[2]) LFSidx = which(freezedata$DOY>SI[2]) EFS = ifelse(length(EFSidx)>0,1,0) LFS = ifelse(length(LFSidx)>0,1,0) FSlist= list(EFS=EFS,LFS=LFS) FSlist } FSEI = function(falsespringvector){ FSEI = (sum(falsespringvector,na.rm=TRUE)/length(falsespringvector))*100 FSEI }
renv_report_user_cancel <- function() { message("* Operation canceled.") renv_snapshot_auto_suppress_next() }
import_nl <- function(tarfile, targetdir, new_session = FALSE) { system(paste0("tar -zxvf \"", tarfile, "\" -C \"", targetdir, "\"")) if (length(list.files(tarfile, pattern = "Rproj")) == 1 && isTRUE(new_session)) { rstudioapi::openProject(list.files(tarfile, pattern = "Rproj", full.names = TRUE )) } }
saveAllMatchesBetween2WBBTeams <- function(dir=".",odir="."){ teams <-c("Adelaide Strikers", "Brisbane Heat", "Hobart Hurricanes", "Melbourne Renegades", "Melbourne Stars", "Perth Scorchers", "Sydney Sixers", "Sydney Thunder") matches <- NULL for(i in seq_along(teams)){ for(j in seq_along(teams)){ if(teams[i] != teams[j]){ cat("Team1=",teams[i],"Team2=",teams[j],"\n") tryCatch(matches <- getAllMatchesBetweenTeams(teams[i],teams[j],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) } } matches <- NULL } }
Psi.varshrinkest <- function (x, nstep = 10, ...) { if (!(inherits(x, "varest"))) { stop("\nPlease provide an object inheriting class 'varest'.\n") } nstep <- abs(as.integer(nstep)) Phi <- Phi(x, nstep = nstep) Psi <- array(0, dim = dim(Phi)) dfr <- df.residual(x$varresult[[1]]) sigma.u <- crossprod(resid(x)) / dfr P <- t(chol(sigma.u)) dim3 <- dim(Phi)[3] for (i in 1:dim3) { Psi[, , i] <- Phi[, , i] %*% P } return(Psi) }
hclust_method='ward.D2' num_rand_iters = 100 MAX_PVAL=0.05 suppressPackageStartupMessages(library("argparse")) parser = ArgumentParser() parser$add_argument("--infercnv_obj", help="infercnv_obj file", required=TRUE, nargs=1) args = parser$parse_args() library(infercnv) library(ggplot2) library(futile.logger) library(pheatmap) infercnv_obj = readRDS(args$infercnv_obj) pdf("test.recursive_trees.pdf") adj.obj = infercnv:::define_signif_tumor_subclusters(infercnv_obj, p_val=0.05, hclust_method='ward.D2', partition_method='random_trees')
compute.laplacian.NJW <- function(W, verbose= FALSE){ if(verbose){message("CALCULATION OF THE DEGREE MATRIX")} degrees <- rowSums(W) Ds <- diag(1/sqrt(degrees)) if(verbose){message("CALCULATION OF THE LAPLACIAN MATRIX")} Lsym <- Ds %*% W %*% Ds if(verbose){message("CALCULATION OF THE EIGEN VECTORS AND VALUES")} U <- eigen(Lsym, symmetric=TRUE) if(verbose){ message("EIGEN VALUES = ") print(U$values) message("EIGEN VECTOR = ") print(U$vector) } out <- list(Lsym = Lsym, eigen = U, diag = Ds) }
absolute_map_builder <- function(variable, temp_dir, infile, mask_file_final, country_code, lon_min, lon_max, lat_min, lat_max, start_date, end_date, nc = NULL) { outfile <- add_ncdf_ext(construct_filename(variable, format(end_date, "%Y"), country_code, "mask")) outfile <- file.path(temp_dir, outfile) tmpfile <- add_ncdf_ext(construct_filename(variable, format(end_date, "%Y"), country_code)) tmpfile <- file.path(temp_dir, tmpfile) tmpfile2 <- add_ncdf_ext(construct_filename("TMP", variable, format(end_date, "%Y"), country_code)) tmpfile2 <- file.path(temp_dir, tmpfile2) tryCatch({ cmsafops::sellonlatbox( var = variable, infile = infile, outfile = tmpfile, lon1 = lon_min, lon2 = lon_max, lat1 = lat_min, lat2 = lat_max, overwrite = TRUE, nc = nc )}, error = function(cond) { stop(paste0("An error occured while selecting the given spatial range.")) }) tryCatch({ cmsafops::selperiod( var = variable, start = start_date, end = end_date, infile = tmpfile, outfile = tmpfile2, overwrite = TRUE ) }, error = function(cond) { stop(paste0("An error occured while selecting the given period (", start_date, "-", end_date, "). Please make sure that your file contains data for this range.")) }) variable_mask <- get_country_name(country_code) adjust_location( variable = variable, variable_mask = variable_mask, is_country = is_country(country_code), mask_file = mask_file_final, var_file = tmpfile2, outfile = outfile) if (file.exists(tmpfile)) { file.remove(tmpfile) } if (file.exists(tmpfile2)) { file.remove(tmpfile2) } return(outfile) }
context("vault: auth") test_that("auth", { srv <- vault_test_server() cl <- srv$client() expect_is(cl$auth, "vault_client_auth") d <- cl$auth$list() expect_equal(d$path, "token/") expect_equal(d$type, "token") expect_error(cl$auth$list(TRUE), "Detailed auth information not supported") }) test_that("introspect methods", { srv <- vault_test_server() cl <- srv$client() expect_setequal(cl$auth$backends(), c("token", "github", "userpass", "approle")) })
clonalOverlap <- function(df, cloneCall = "gene+nt", method = c("overlap", "morisita", "jaccard", "raw"), chain = "both", split.by = NULL, exportTable = FALSE){ df <- list.input.return(df, split.by) cloneCall <- theCall(cloneCall) df <- checkBlanks(df, cloneCall) df <- df[order(names(df))] values <- str_sort(as.character(unique(names(df))), numeric = TRUE) df <- df[quiet(dput(values))] num_samples <- length(df[]) names_samples <- names(df) coef_matrix <- data.frame(matrix(NA, num_samples, num_samples)) colnames(coef_matrix) <- names_samples rownames(coef_matrix) <- names_samples length <- seq_len(num_samples) if (chain != "both") { for (i in seq_along(df)) { df[[i]] <- off.the.chain(df[[i]], chain, cloneCall) } } if (method == "overlap") { coef_matrix <- overlapIndex(df, length, cloneCall, coef_matrix) } else if (method == "morisita") { coef_matrix <- morisitaIndex(df, length, cloneCall, coef_matrix) } else if (method == "jaccard") { coef_matrix <- jaccardIndex(df, length, cloneCall, coef_matrix) } else if (method == "raw") { coef_matrix <- rawIndex(df, length, cloneCall, coef_matrix) } coef_matrix$names <- rownames(coef_matrix) if (exportTable == TRUE) { return(coef_matrix) } coef_matrix <- suppressMessages(melt(coef_matrix))[,-1] col <- colorblind_vector(7) coef_matrix$variable <- factor(coef_matrix$variable, levels = values) coef_matrix$names <- factor(coef_matrix$names, levels = values) plot <- ggplot(coef_matrix, aes(x=names, y=variable, fill=value)) + geom_tile() + labs(fill = method) + geom_text(aes(label = round(value, digits = 3))) + scale_fill_gradientn(colors = rev(colorblind_vector(5)), na.value = "white") + theme_classic() + theme(axis.title = element_blank()) return(plot) }
srt_to_df <- function(file_name) { con <- file(file_name, encoding = uchardet::detect_file_enc(file_name)) srt <- readLines(con) close(con) result <- lapply(split(seq_along(srt), cumsum(grepl("^\\s*$", srt))), function(i) { block <- srt[i] block <- block[!grepl("^\\s*$", block)] if (length(block) == 0) { return(NULL) } if (length(block) < 3) { warning(paste0( "There are some non-standard blocks in ", file_name, " file" )) } return(data.frame( id = block[1], times = block[2], content = paste0(block[3:length(block)], collapse = "\n") )) }) result <- do.call(rbind, result) result <- cbind(result, do.call(rbind, strsplit(result[, "times"], " --> "))) result <- result[, -2] names(result)[3:4] <- c("time_start", "time_end") l <- lapply(c("time_start", "time_end"), function(i) { do.call(rbind, lapply( strsplit(result[, i], ":|,"), as.double )) %*% c(60 * 60, 60, 1, 1 / 1000) }) result <- cbind(result, as.data.frame(l)) result <- result[, -which(names(result) %in% c("time_start", "time_end"))] names(result)[3:4] <- c("time_start", "time_end") result$source <- basename(file_name) return(result) }
NULL evppi_plot_base <- function(evppi_obj, pos_legend, col = NULL, annot = FALSE) { legend_params <- evppi_legend_base(evppi_obj, pos_legend, col) plot(evppi_obj$k, evppi_obj$evi, type = "l", col = legend_params$col[1], lty = legend_params$lty[1], xlab = "Willingness to pay", ylab = "", main = "Expected Value of Perfect Partial Information", lwd = 2, ylim = range(range(evppi_obj$evi), range(evppi_obj$evppi))) if (!is.list(evppi_obj$evppi)) evppi_obj$evppi <- list(evppi_obj$evppi) evppi_dat <- do.call(cbind, evppi_obj$evppi) txt_coord_y <- evppi_dat[length(evppi_obj$k), ] matplot(evppi_obj$k, evppi_dat, type = "l", col = legend_params$col[-1], lty = legend_params$lty[-1], add = TRUE) if (annot) { text(x = par("usr")[2], y = txt_coord_y, labels = paste0("(", evppi_obj$index, ")", collapse = " "), cex = 0.7, pos = 2) } do.call(legend, legend_params) return(invisible(NULL)) }
madapply <- function(...){ .Defunct("future.apply::future_apply") }
"als" <- function(CList, PsiList, S=matrix(), WList=list(), thresh = .001, maxiter = 100, forcemaxiter=FALSE, optS1st=TRUE, x=1:nrow(CList[[1]]), x2 = 1:nrow(S), baseline=FALSE, fixed=vector("list", length(PsiList)), uniC=FALSE, uniS=FALSE, nonnegC = TRUE, nonnegS = TRUE, normS=0, closureC=list()) { RD <- 10^20 PsiAll <- do.call("rbind", PsiList) resid <- vector("list", length(PsiList)) if(length(WList) == 0){ WList <- vector("list", length(PsiList)) for(i in 1:length(PsiList)) WList[[i]] <- matrix(1, nrow(PsiList[[1]]), ncol(PsiList[[1]])) } W <- do.call("rbind",WList) for(i in 1:length(PsiList)) resid[[i]] <- matrix(0, nrow(PsiList[[i]]), ncol(PsiList[[i]])) for(j in 1:length(PsiList)) { for(i in 1:nrow(PsiList[[j]])) { resid[[j]][i,] <- PsiList[[j]][i,] - CList[[j]][i,] %*% t(S * WList[[j]][i,]) } } initialrss <- oldrss <- sum(unlist(resid)^2) cat("Initial RSS", initialrss, "\n") iter <- 1 b <- if(optS1st) 1 else 0 oneMore <- FALSE while( ((RD > thresh || forcemaxiter ) && maxiter >= iter) || oneMore) { if(iter %% 2 == b) S <- getS(CList, PsiAll, S, W, baseline, uniS, nonnegS, normS, x2) else CList <- getCList(S, PsiList, CList, WList, resid, x, baseline, fixed, uniC, nonnegC, closureC) for(j in 1:length(PsiList)) { for(i in 1:nrow(PsiList[[j]])) { resid[[j]][i,] <- PsiList[[j]][i,] - CList[[j]][i,] %*% t(S * WList[[j]][i,]) } } rss <- sum(unlist(resid)^2) RD <- ((oldrss - rss) / oldrss) oldrss <- rss typ <- if(iter %% 2 == b) "S" else "C" cat("Iteration (opt. ", typ, "): ", iter, ", RSS: ", rss, ", RD: ", RD, "\n", sep = "") iter <- iter + 1 oneMore <- (normS > S && (iter %% 2 != b) && maxiter != 1) || (length(closureC) > 0 && (iter %% 2 == b) ) } cat("Initial RSS / Final RSS =", initialrss, "/", rss, "=", initialrss/rss,"\n") return(list(CList = CList, S = S, rss = rss, resid = resid, iter = iter)) }
theEndClasses <- c('One', 'Two', 'Three', 'Four', 'Five', 'Six') .quiet <- function(x) { sink(tempfile()) on.exit(sink()) invisible(force(x)) } for (thisClass in theEndClasses) { test_that( sprintf('%s class can be sucessfully intialized', thisClass) , expect_true({ .quiet({myObj <- get(thisClass)$new()}) R6::is.R6(myObj) }) ) }
print.threg <- function(x, digits=max(options()$digits - 4, 3), ...) { if (!is.null(cl<- x$call)) { cat("Call:\n") dput(cl) cat("\n") } coef <- x$coefficients se <- sqrt(diag(x$var)) tmp <- cbind(coef, se, coef/se, signif(1 - pchisq((coef/ se)^2, 1), digits -1)) dimnames(tmp) <- list(names(coef), c("coef", "se(coef)", "z", "p")) prmatrix(tmp) cat("\n") cat("Log likelihood =", format(round(x$loglik, 2)), ",", " AIC =", format(round(x$AIC, 2)), sep="") cat("\n") invisible(x) }
tb2.norm <- function(alpha,theta) { m0=length(alpha) N=10000 quan=matrix((0:(N-1)+0.5)/N,ncol=1) x=as.numeric(apply(quan,1,qmixnorm,alpha=alpha,theta=theta)) pdf=0 delta=c() y=c() z=c() for(i in 1:m0) { delta=cbind(delta,dnorm(x,theta[i],1)-dnorm(x,theta[m0],1)) y=cbind(y,(x-theta[i])*dnorm(x,theta[i],1)) z=cbind(z,((x-theta[i])^2-1)*dnorm(x,theta[i],1)/2 ) pdf=pdf+alpha[i]*dnorm(x,theta[i],1) } bi=cbind(delta[,1:(m0-1)],y,z)/pdf B=t(bi)%*%bi B11=B[1:(2*m0-1),1:(2*m0-1)] B12=B[1:(2*m0-1),(2*m0):(3*m0-1)] B22=B[(2*m0):(3*m0-1),(2*m0):(3*m0-1)] tB22=B22-t(B12)%*%solve(B11)%*%B12 diagB22=diag(diag(tB22)^(-1/2),m0,m0) corr=diagB22%*%tB22%*%diagB22 round(corr,3) }
plot(seq(-3, 3, 0.1), dnorm(seq(-3, 3, 0.1)), type = "l", xlab = "$x$", ylab = "$\\phi(x)$") text(-3, 0.37, adj = c(0, 1), "$\\phi(x) = \\frac{1}{\\sqrt{2 \\pi}} \\exp(-\\frac{x^2}{2})$", cex = 1.2) arrows(-2, 0.27, -1.3, dnorm(-1.3) + 0.02) abline(v = qnorm(0.95), lty = 2) text(0, dnorm(qnorm(0.95)), "$\\int_{-\\infty}^{1.65} \\phi(x) dx \\approx 0.95$")
metamodel <- function(analysis = c("oneway", "twoway", "multiway"), psa, params = NULL, strategies = NULL, outcome = c("eff", "cost", "nhb", "nmb", "nhb_loss", "nmb_loss", "nhb_loss_voi", "nmb_loss_voi"), wtp = NULL, type = c("linear", "gam", "poly"), poly.order = 2, k = -1) { pnames <- psa$parnames analysis <- match.arg(analysis) type <- match.arg(type) if (is.null(params)) { params <- pnames } else if (!all(params %in% pnames)) { wrong_p <- setdiff(p, pnames) stop(paste0("the following parameters are not valid: ", paste(wrong_p, collapse = ","))) } else if (length(params) != 2 & analysis == "twoway") { stop("If analysis == twoway, exactly 2 params must be provided.") } outcome <- match.arg(outcome) y <- calculate_outcome(outcome, psa$cost, psa$effectiveness, wtp) strat <- psa$strategies if (is.null(strategies)) { strategies <- strat } else if (!all(strategies %in% strat)) { wrong_strats <- setdiff(strategies, strat) errmsg <- paste0("the following are not in psa$strategies: ", paste(wrong_strats, collapse = ",")) stop(errmsg) } dat <- data.frame(y, psa$parameters) if (nrow(dat) < length(params)) { errmsg <- paste0("The number of parameters to be estimated by the metamodel cannot be greater than the number of PSA samples") stop(errmsg) } lms <- NULL if (analysis == "oneway") { for (p in params) { for (s in strategies) { mod <- mm_run_reg(analysis, s, p, dat, type, poly.order, k) mod$param_of_int <- p mod$strat <- s lms[[p]][[s]] <- mod } } } if (analysis == "twoway" | analysis == "multiway") { for (s in strategies) { mod <- mm_run_reg(analysis, s, params, dat, type, poly.order, k) mod$param_of_int <- params mod$strat <- s lms[[s]] <- mod } } metamodel <- list(outcome = outcome, mods = lms, wtp = wtp, params = params, strategies = strategies, psa = psa, analysis = analysis, type = type, poly.order = poly.order, k = k) class(metamodel) <- "metamodel" return(metamodel) } mm_run_reg <- function(analysis, dep, params, dat, type, poly.order, k) { n_params <- length(params) if (type == "gam" && k < 3 && n_params != 1) { k <- 3 warning("k has been set to its minimum value of 3") } if (type == "gam" && ((k - 1) ^ n_params > 500)) { stop(paste0("\nIn your proposed metamodel, k-1 to the power of the number of parameters must not be greater than 500 (i.e. (k-1)^n_params < 500). This proposed model has ", n_params, " parameters, and a k value of ", k, ". Models that exceed this approximate threshold will fail to execute due to memory constraints and/or take an excessively long time to fit.")) } if (type == "linear") { fbeg <- paste0(dep, " ~ ") if (n_params > 1) { fparam <- paste(params, collapse = " + ") } else { fparam <- params } f <- as.formula(paste0(fbeg, fparam)) metamod <- lm(f, data = dat) metamod$call <- call("lm", formula = f, data = quote(dat)) } if (type == "poly") { fbeg <- paste0(dep, " ~ ") fparam <- "" list_of_ps <- lapply(params, function(p) paste("poly(", p, ",", poly.order, ", raw=TRUE)")) if (analysis == "twoway") { list_of_ps <- append(list_of_ps, paste0("poly(", params[1], ",", poly.order, ", raw=TRUE):", "poly(", params[2], ",", poly.order, ", raw=TRUE)")) } fparam <- paste(list_of_ps, collapse = " + ") f <- as.formula(paste0(fbeg, fparam)) metamod <- lm(f, data = dat) metamod$call <- call("lm", formula = f, data = quote(dat)) } if (type == "gam") { fbeg <- paste0(dep, " ~ ") fparam <- "" if (n_params == 1) { fparam <- paste0(fparam, "s(", params, ", k=", k, ")") } else { params_k <- paste0("s(", params, ", k=", k, ")") f_s <- paste(params_k, collapse = " + ") k_ti <- ifelse(k == -1, NA, k) fparam <- paste0(f_s, " + ti(", paste(params, collapse = ", "), ", k = ", k_ti, ")") } f <- as.formula(paste0(fbeg, fparam)) metamod <- gam(f, data = dat) } return(metamod) } print.metamodel <- function(x, ...) { wtp <- x$wtp cat("metamodel object", "\n", "-------------------------", "\n", "a list of the following objects: ", paste(names(x), collapse = ", "), "\n", "\n", "some details: ", "\n", "-------------------------", "\n", "analysis: this is a ", substr(x$analysis, 1, 3), "-way metamodel \n", "mods: a nested list of ", x$type, " metamodels \n", "outcome: ", x$outcome, "\n", "WTP: ", ifelse(!is.null(wtp), wtp, "NA"), "\n", "strategies: ", paste(x$strategies, collapse = ", "), "\n", "parameters modeled: ", paste(x$params, collapse = ", "), "\n", sep = "") } summary.metamodel <- function(object, ...) { analysis <- object$analysis type <- object$type summary_df <- NULL if (analysis == "multiway") { stop("metamodel summary not available for multiway analyses") } if (analysis == "oneway") { for (p in object$params) { for (s in object$strategies) { lm_summary <- summary(object$mods[[p]][[s]]) if (type == "gam") { r2 <- lm_summary$r.sq } else { r2 <- lm_summary$r.squared } df_new_row <- data.frame("param" = p, "strat" = s, "rsquared" = r2) summary_df <- rbind(summary_df, df_new_row) } } } if (analysis == "twoway") { params <- object$params for (s in object$strategies) { lm_summary <- summary(object$mods[[s]]) if (type == "gam") { r2 <- lm_summary$r.sq } else { r2 <- lm_summary$r.squared } df_new_row <- data.frame("param1" = params[1], "param2" = params[2], "strat" = s, "rsquared" = r2) summary_df <- rbind(summary_df, df_new_row) } } return(summary_df) } predict.metamodel <- function(object, ranges = NULL, nsamp = 100, ...) { analysis <- object$analysis if (analysis == "multiway") { stop("metamodel predictions not available for multiway analyses") } if (!is.null(ranges)) { if (!inherits(ranges, "list")) { stop("ranges must be a named list of vectors") } for (i in ranges) { if (!is.null(i) & length(i) != 2) { stop("all entries in ranges must have length 2 or be NULL") } } } psa_params <- object$params psa_paramvals <- object$psa$parameters mods <- object$mods strats <- object$strategies if (analysis == "oneway") { pred_data_nrow <- nsamp } if (analysis == "twoway") { pred_data_nrow <- nsamp ^ 2 } pdata <- data.frame(matrix(colMeans(psa_paramvals), nrow = pred_data_nrow, ncol = ncol(psa_paramvals), byrow = TRUE)) colnames(pdata) <- colnames(psa_paramvals) if (is.null(ranges)) { q_params <- psa_params } else { q_params <- names(ranges) if (!all(q_params %in% psa_params)) { wrong_params <- setdiff(q_params, psa_params) stop(paste0("The following range names were not found in psa$parameters:\n", paste(wrong_params, collapse = ", "))) } } if (analysis == "oneway") { outcome_dfs <- vector(mode = "list", length = length(strats) * length(q_params)) counter <- 1 for (p in q_params) { param_val <- make_param_seq(p, ranges, nsamp, psa_paramvals) newdata <- data.frame(param_val) this_p_data <- pdata this_p_data[, p] <- newdata for (s in strats) { mod <- mods[[p]][[s]] outcome_dfs[[counter]] <- data.frame("parameter" = p, "strategy" = s, "param_val" = newdata, "outcome_val" = predict(mod, newdata = this_p_data, type = "response"), stringsAsFactors = FALSE) counter <- counter + 1 } } } if (analysis == "twoway") { outcome_dfs <- vector(mode = "list", length = length(strats)) counter <- 1 p1 <- psa_params[1] p2 <- psa_params[2] p1_samp <- make_param_seq(p1, ranges, nsamp, psa_paramvals) p2_samp <- make_param_seq(p2, ranges, nsamp, psa_paramvals) p1p2_data <- data.frame(expand.grid(p1_samp, p2_samp)) pdata[, c(p1, p2)] <- p1p2_data for (s in strats) { mod <- mods[[s]] outcome <- predict(mod, newdata = pdata) outcome_df <- data.frame("p1" = pdata[, p1], "p2" = pdata[, p2], "strategy" = s, "outcome_val" = outcome, stringsAsFactors = FALSE) names(outcome_df)[1:2] <- c(p1, p2) outcome_dfs[[counter]] <- outcome_df counter <- counter + 1 } } combined_df <- bind_rows(outcome_dfs) return(combined_df) } make_param_seq <- function(p, ranges, nsamp, psa_paramvals) { p_range <- ranges[[p]] p_psa_vals <- psa_paramvals[, p] if (is.null(p_range)) { p_range <- quantile(p_psa_vals, c(0.025, 0.975)) } else { psa_range <- range(p_psa_vals) if (p_range[1] < psa_range[1] | p_range[2] > psa_range[2]) { warning(paste0("The requested range for ", p, " is outside of the PSA range.\n", "requested range: [", paste(p_range, collapse = ","), "]\n", "PSA range: [", paste(psa_range, collapse = ", "), "]\n.", "Please interpret results with caution.")) } } seq(p_range[1], p_range[2], length.out = nsamp) }
zhr.plot<-function(zhrdata,xlim1,xlim2,xinc,ylim1,ylim2,yinc,dlim1=NULL,dlim2=NULL,dinc=NULL,dunit=NULL) { if(!is.data.frame(zhrdata)) stop("Invalid input parameter specification: check data") if(!("sollong"%in%names(zhrdata))|| !("ZHR"%in%names(zhrdata)) || !("st.error"%in%names(zhrdata))) stop("Error: zhrdata does not contain columns named sollong, ZHR and st.error") year<-year(zhrdata$date[1]) if(is.null(dlim1) || is.null(dlim2) || is.null(dinc) || is.null(dunit)){ solvals<-seq(xlim1,xlim2,by=xinc) dates<-solar.long_date(solvals,year) }else{ date1<-tryCatch(as.POSIXct(dlim1,tz="UTC"),error=function(e){return(NA)}) date2<-tryCatch(as.POSIXct(dlim2,tz="UTC"),error=function(e){return(NA)}) if(is.na(date1) || is.na(date2)) stop("Invalid input parameter specification: check dlim1/dlim2 format") if(date1>date2) stop("Error:dlim2 must be greater than dlim1") if(any(c(year(date1),year(date2))!=year)) stop("Year in start and end dates have to match data year") if(!is.numeric(dinc)) stop("Invalid input parameter specification: check dinc format") if(!dunit%in%c("min","h","day")) stop("Invalid input parameter specification: check dunit format") dstep<-function(dinc,dunit) {switch(dunit,min=60*dinc,h=3600*dinc,day=86400*dinc) } dates<-seq(date1,date2,by=dstep(dinc,dunit)) solvals<-solar.long(dates) } if(!is.null(dunit) && dunit=="day") {xlab2<-paste(day(dates),month.abb[month(dates)],sep="") }else{ xlab2<-paste(day(dates),month.abb[month(dates)]," ",strftime(dates,format="%H:%M",tz="UTC"),sep="")} ind<-!is.na(zhrdata$ZHR) par(mar=c(5,4,6,3)) graph.data(zhrdata$sollong[ind],zhrdata$ZHR[ind],zhrdata$st.error[ind],"ZHR(Corrected hourly meteor rate)",xlim1,xlim2,xinc,ylim1,ylim2,yinc) axis(3,solvals,labels=F,tcl=0.4) text(solvals,par("usr")[4]+0.1*yinc,srt=45,xpd=TRUE,pos=4,offset=-0.1,labels=xlab2) mtext(paste("Time (UT,",year,")",sep=""),side=3,line=4,cex=1.2) }
context("test-ls_packages") test_that("listing packages from list of calls works", { pkgs <- ls_packages(list( quote(library(tidycode)), quote(library(chicken)), quote(foo::bar), quote(lm(mpg ~ cyl, mtcars))) ) expect_equal(pkgs, c("tidycode", "chicken", "foo")) }) test_that("listing packages from data frame works", { d <- read_rfiles(tidycode_example("example_plot.R")) pkgs <- ls_packages(d$expr) expect_equal(pkgs, "tidyverse") }) test_that("can list packages from an individual call", { expect_equal(ls_packages(quote(library(tidycode))), "tidycode") })
plot.survFitTT <- function(x, xlab = "Concentration", ylab = "Survival probability", main = NULL, fitcol = "orange", fitlty = 1, fitlwd = 1, spaghetti = FALSE, cicol = "orange", cilty = 2, cilwd = 1, ribcol = "grey70", adddata = FALSE, addlegend = FALSE, log.scale = FALSE, style = "ggplot", ...) { sel <- if(log.scale) x$dataTT$conc > 0 else TRUE dataTT <- x$dataTT[sel, ] dataTT$resp <- dataTT$Nsurv / dataTT$Ninit dataTT <- aggregate(resp ~ conc, dataTT, mean) transf_data_conc <- optLogTransform(log.scale, dataTT$conc) display.conc <- (function() { x <- optLogTransform(log.scale, dataTT$conc) s <- seq(min(x),max(x), length = 100) if(log.scale) exp(s) else s })() curv_conc <- optLogTransform(log.scale, display.conc) conf.int <- survLlbinomConfInt(x, log.scale) cred.int <- survMeanCredInt(x, display.conc) spaghetti.CI <- if (spaghetti) { survSpaghetti(x, display.conc) } else NULL dataCIm <- if (spaghetti) {melt(cbind(curv_conc, spaghetti.CI), id.vars = c("curv_conc", "conc"))} else NULL curv_resp <- data.frame(conc = curv_conc, resp = cred.int[["q50"]], Line = "loglogistic") if (style == "generic") { survFitPlotGenericCredInt(x, dataTT$conc, transf_data_conc, dataTT$resp, curv_conc, curv_resp, conf.int, cred.int, spaghetti.CI, dataCIm, xlab, ylab, fitcol, fitlty, fitlwd, main, addlegend, adddata, cicol, cilty, cilwd, ribcol, log.scale) } else if (style == "ggplot") { survFitPlotGG(x, dataTT$conc, transf_data_conc, dataTT$resp, curv_conc, curv_resp, conf.int, cred.int, spaghetti.CI, dataCIm, xlab, ylab, fitcol, fitlty, fitlwd, main, addlegend, adddata, cicol, cilty, cilwd / 2, ribcol) } else stop("Unknown style") } survLlbinomConfInt <- function(x, log.scale) { x <- cbind(aggregate(Nsurv ~ time + conc, x$dataTT, sum), Ninit = aggregate(Ninit ~ time + conc, x$dataTT, sum)$Ninit) ci <- apply(x, 1, function(x) { binom.test(x["Nsurv"], x["Ninit"])$conf.int }) rownames(ci) <- c("qinf95", "qsup95") colnames(ci) <- x$conc if (log.scale) ci <- ci[ ,colnames(ci) != 0] return(ci) } survMeanCredInt <- function(fit, x) { mctot <- do.call("rbind", fit$mcmc) k <- nrow(mctot) if (fit$det.part == "loglogisticbinom_3") { d2 <- mctot[, "d"] } log10b2 <- mctot[, "log10b"] b2 <- 10^log10b2 log10e2 <- mctot[, "log10e"] e2 <- 10^log10e2 qinf95 = NULL q50 = NULL qsup95 = NULL for (i in 1:length(x)) { if (fit$det.part == "loglogisticbinom_2") { theomean <- 1 / (1 + (x[i] / e2)^(b2)) } else if (fit$det.part == "loglogisticbinom_3") { theomean <- d2 / (1 + (x[i] / e2)^(b2)) } qinf95[i] <- quantile(theomean, probs = 0.025, na.rm = TRUE) q50[i] <- quantile(theomean, probs = 0.5, na.rm = TRUE) qsup95[i] <- quantile(theomean, probs = 0.975, na.rm = TRUE) } ci <- data.frame(qinf95 = qinf95, q50 = q50, qsup95 = qsup95) return(ci) } survSpaghetti <- function(fit, x) { mctot <- do.call("rbind", fit$mcmc) sel <- sample(nrow(mctot))[1:ceiling(nrow(mctot) / 10)] if (fit$det.part == "loglogisticbinom_3") { d2 <- mctot[, "d"][sel] } log10b2 <- mctot[, "log10b"][sel] b2 <- 10^log10b2 log10e2 <- mctot[, "log10e"][sel] e2 <- 10^log10e2 dtheo <- array(data = NA, dim = c(length(x), length(e2))) for (i in 1:length(e2)) { if (fit$det.part == "loglogisticbinom_2") { dtheo[, i] <- 1 / (1 + (x / e2[i])^(b2[i])) } else if (fit$det.part == "loglogisticbinom_3") { dtheo[, i] <- d2[i] / (1 + (x / e2[i])^(b2[i])) } } dtheof <- as.data.frame(cbind(x, dtheo)) names(dtheof) <- c("conc", paste0("X", 1:length(sel))) return(dtheof) } survFitPlotGenericCredInt <- function(x, data_conc, transf_data_conc, data_resp, curv_conc, curv_resp, conf.int, cred.int, spaghetti.CI, dataCIm, xlab, ylab, fitcol, fitlty, fitlwd, main, addlegend, adddata, cicol, cilty, cilwd, ribcol, log.scale) { plot(transf_data_conc, data_resp, xlab = xlab, ylab = ylab, main = main, xaxt = "n", yaxt = "n", ylim = c(0, 1.01), type = "n") axis(side = 2, at = pretty(c(0, max(c(conf.int["qsup95",], cred.int[["qsup95"]]))))) axis(side = 1, at = transf_data_conc, labels = data_conc) if (!is.null(spaghetti.CI)) { color <- "gray" color_transparent <- adjustcolor(color, alpha.f = 0.05) by(dataCIm, dataCIm$variable, function(x) { lines(x$curv_conc, x$value, col = color_transparent) }) } else if(!is.null(ribcol)) { polygon(c(curv_conc, rev(curv_conc)), c(cred.int[["qinf95"]], rev(cred.int[["qsup95"]])), col = ribcol, border = NA) } lines(curv_conc, cred.int[["qsup95"]], type = "l", col = cicol, lty = cilty, lwd = cilwd) lines(curv_conc, cred.int[["qinf95"]], type = "l", col = cicol, lty = cilty, lwd = cilwd) if (adddata) { segments(transf_data_conc, data_resp, transf_data_conc, conf.int["qsup95", ]) segments(transf_data_conc, data_resp, transf_data_conc, conf.int["qinf95", ]) points(transf_data_conc, data_resp, pch = 16) } lines(curv_conc, curv_resp[, "resp"], type = "l", col = fitcol, lty = fitlty, lwd = fitlwd) if (addlegend) { legend("bottomleft", pch = c(ifelse(adddata, 16, NA), NA, NA, NA), lty = c(NA, ifelse(adddata, 1, NA), cilty, fitlty), lwd = c(NA, ifelse(adddata,1, NA), cilwd, fitlwd), col = c(ifelse(adddata, 1, NA), 1, cicol, fitcol), legend = c(ifelse(adddata, "Observed values", NA), ifelse(adddata, "Confidence interval", NA), "Credible limits", x$det.part), bty = "n") } } survFitPlotGGCredInt <- function(x, data, curv_resp, conf.int, cred.int, spaghetti.CI, dataCIm, cilty, cilwd, valCols, fitlty, fitlwd, ribcol, xlab, ylab, main, adddata) { data.three <- data.frame(conc = data$transf_conc, qinf95 = conf.int["qinf95",], qsup95 = conf.int["qsup95",], Conf.Int = "Confidence interval") data.four <- data.frame(conc = curv_resp$conc, qinf95 = cred.int[["qinf95"]], qsup95 = cred.int[["qsup95"]], Cred.Lim = "Credible limits") if (adddata) { plt_3 <- ggplot(data) + geom_segment(aes(x = conc, xend = conc, y = qinf95, yend = qsup95, linetype = Conf.Int), data.three, color = valCols$cols3) + scale_linetype(name = "") + theme_minimal() } plt_302 <- if (!is.null(spaghetti.CI)) { ggplot(data) + geom_line(data = dataCIm, aes(x = curv_conc, y = value, group = variable), col = "gray", alpha = 0.05) } else { ggplot(data) + geom_ribbon(data = data.four, aes(x = conc, ymin = qinf95, ymax = qsup95), fill = ribcol, col = NA, alpha = 0.4) } plt_32 <- plt_302 + geom_line(data = data.four, aes(conc, qinf95, color = Cred.Lim), linetype = cilty, size = cilwd) + geom_line(data = data.four, aes(conc, qsup95, color = Cred.Lim), linetype = cilty, size = cilwd) + scale_color_manual("", values = valCols$cols4) + theme_minimal() if (!is.null(spaghetti.CI)) { plt_40 <- ggplot(data) + geom_line(data = dataCIm, aes(x = curv_conc, y = value, group = variable), col = "gray", alpha = 0.05) } else { plt_40 <- ggplot(data) + geom_ribbon(data = data.four, aes(x = conc, ymin = qinf95, ymax = qsup95), fill = ribcol, col = NA, alpha = 0.4) } plt_401 <- plt_40 + geom_line(data = data.four, aes(conc, qinf95), linetype = cilty, size = cilwd, color = valCols$cols4) + geom_line(data = data.four, aes(conc, qsup95), linetype = cilty, size = cilwd, color = valCols$cols4) + geom_line(data = curv_resp, aes(conc, resp), linetype = fitlty, size = fitlwd, color = valCols$cols2) + scale_color_discrete(guide = "none") + ylim(0, 1) + labs(x = xlab, y = ylab) + ggtitle(main) + theme_minimal() if (adddata) { plt_4 <- plt_401 + geom_point(data = data, aes(transf_conc, resp)) + geom_segment(aes(x = conc, xend = conc, y = qinf95, yend = qsup95), data.three, col = valCols$cols3) } else { plt_4 <- plt_401 } return(list(plt_3 = if (adddata) plt_3 else NULL, plt_32 = plt_32, plt_4 = plt_4)) } survFitPlotGG <- function(x, data_conc, transf_data_conc, data_resp, curv_conc, curv_resp, conf.int, cred.int, spaghetti.CI, dataCIm, xlab, ylab, fitcol, fitlty, fitlwd, main, addlegend, adddata, cicol, cilty, cilwd, ribcol) { if (Sys.getenv("RSTUDIO") == "") { dev.new() } data <- data.frame(conc = data_conc, transf_conc = transf_data_conc, resp = data_resp, Points = "Observed values") valCols <- fCols(data, fitcol, cicol) if (adddata) { plt_1 <- ggplot(data) + geom_point(data = data, aes(transf_conc, resp, fill = Points), col = valCols$cols1) + scale_fill_hue("") + theme_minimal() } plt_2 <- ggplot(data) + geom_line(data = curv_resp, aes(conc, resp, colour = Line), linetype = fitlty, size = fitlwd) + scale_colour_manual("", values = valCols$cols2) + theme_minimal() plt_4 <- survFitPlotGGCredInt(x, data, curv_resp, conf.int, cred.int, spaghetti.CI, dataCIm, cilty, cilwd, valCols, fitlty, fitlwd, ribcol, xlab, ylab, main, adddata)$plt_4 if (addlegend) { mylegend_1 <- if (adddata) { legendGgplotFit(plt_1) } else NULL mylegend_2 <- legendGgplotFit(plt_2) plt_5 <- plt_4 + scale_x_continuous(breaks = data$transf_conc, labels = data$conc) plt_3 <- survFitPlotGGCredInt(x, data, curv_resp, conf.int, cred.int, spaghetti.CI, dataCIm, cilty, cilwd, valCols, fitlty, fitlwd, ribcol, xlab, ylab, main, adddata)$plt_3 plt_32 <- survFitPlotGGCredInt(x, data, curv_resp, conf.int, cred.int, spaghetti.CI, dataCIm, cilty, cilwd, valCols, fitlty, fitlwd, ribcol, xlab, ylab, main, adddata)$plt_32 mylegend_3 <- if (adddata) { legendGgplotFit(plt_3) } else NULL mylegend_32 <- legendGgplotFit(plt_32) if (adddata) { grid.arrange(plt_5, arrangeGrob(mylegend_1, mylegend_3, mylegend_32, mylegend_2, nrow = 6), ncol = 2, widths = c(6, 2)) } else { grid.arrange(plt_5, arrangeGrob(mylegend_32, mylegend_2, nrow = 6), ncol = 2, widths = c(6, 2)) } } else { plt_5 <- plt_4 + scale_x_continuous(breaks = data$transf_conc, labels = data$conc) return(plt_5) } }
library(testthat) library(tsbox) test_that("works with df with improper col classes", { library(dplyr) x.chr <- ts_tbl(mdeaths) %>% mutate(time = as.character(time)) expect_s3_class(ts_ts(x.chr), "ts") x.fct <- ts_tbl(mdeaths) %>% mutate(time = as.factor(as.character(time))) expect_s3_class(ts_ts(x.fct), "ts") }) test_that("time column of daily data is treated as Date ( x <- tibble( time = seq.Date(as.Date("2000-01-01"), length.out = 10, by = "day"), value = rnorm(10) ) z <- ts_dts(ts_ts(x)) expect_s3_class(z$time, "Date") }) test_that("time column of daily data is survives two way conversion ( x <- structure(list(time = structure(c( 16030, 16031, 16034, 16035, 16036 ), class = "Date"), value = c( 18680.35, 18766.53, 18741.95, 18759.68, 18812.33 )), class = "data.frame", row.names = c( NA, -5L )) z <- ts_na_omit(ts_tbl(ts_ts(x))) expect_equal(z$time, x$time) })
NULL setMethod("nrow", "VTableTree", function(x) length(collect_leaves(x, TRUE ,TRUE))) setMethod("nrow", "TableRow", function(x) 1L) setMethod("ncol", "VTableNodeInfo", function(x) { ncol(col_info(x)) }) setMethod("ncol", "TableRow", function(x) { if(!no_colinfo(x)) ncol(col_info(x)) else length(spanned_values(x)) }) setMethod("ncol", "LabelRow", function(x) { ncol(col_info(x)) }) setMethod("ncol", "InstantiatedColumnInfo", function(x) { length(col_exprs(x)) }) setMethod("dim", "VTableNodeInfo", function(x) c(nrow(x), ncol(x))) setGeneric("tree_children", function(x) standardGeneric("tree_children")) setMethod("tree_children", c(x = "VTree"), function(x) x@children) setMethod("tree_children", c(x = "VTableTree"), function(x) x@children) setMethod("tree_children", c(x = "VLeaf"), function(x) list()) setGeneric("tree_children<-", function(x, value) standardGeneric("tree_children<-")) setMethod("tree_children<-", c(x = "VTree"), function(x, value){ x@children = value x }) setMethod("tree_children<-", c(x = "VTableTree"), function(x, value){ x@children = value x }) setGeneric("content_table", function(obj) standardGeneric("content_table")) setMethod("content_table", "TableTree", function(obj) obj@content) setMethod("content_table", "ANY", function(obj) NULL) setGeneric("content_table<-", function(obj, value) standardGeneric("content_table<-")) setMethod("content_table<-", c("TableTree", "ElementaryTable"), function(obj, value) { obj@content = value obj }) setGeneric("next_rpos", function(obj, nested = TRUE, for_analyze = FALSE) standardGeneric("next_rpos")) setMethod("next_rpos", "PreDataTableLayouts", function(obj, nested, for_analyze = FALSE) next_rpos(rlayout(obj), nested, for_analyze = for_analyze)) .check_if_nest <- function(obj, nested, for_analyze) { if(!nested) FALSE else for_analyze || !(is(last_rowsplit(obj), "VAnalyzeSplit") || is(last_rowsplit(obj), "AnalyzeMultiVars")) } setMethod("next_rpos", "PreDataRowLayout", function(obj, nested, for_analyze) { l = length(obj) if(length(obj[[l]]) > 0L && !.check_if_nest(obj, nested, for_analyze)) { l = l + 1L } l }) setMethod("next_rpos", "ANY", function(obj, nested) 1L) setGeneric("next_cpos", function(obj, nested = TRUE) standardGeneric("next_cpos")) setMethod("next_cpos", "PreDataTableLayouts", function(obj, nested) next_cpos(clayout(obj), nested)) setMethod("next_cpos", "PreDataColLayout", function(obj, nested) { if(nested || length(obj[[length(obj)]]) == 0) length(obj) else length(obj) + 1L }) setMethod("next_cpos", "ANY", function(obj, nested) 1L) setGeneric("last_rowsplit", function(obj) standardGeneric("last_rowsplit")) setMethod("last_rowsplit", "NULL", function(obj) NULL) setMethod("last_rowsplit", "SplitVector", function(obj) { if(length(obj) == 0) NULL else obj[[length(obj)]] }) setMethod("last_rowsplit", "PreDataRowLayout", function(obj) { if(length(obj) == 0) NULL else last_rowsplit(obj[[ length( obj ) ]]) }) setMethod("last_rowsplit", "PreDataTableLayouts", function(obj) last_rowsplit(rlayout(obj))) setGeneric("rlayout", function(obj) standardGeneric("rlayout")) setMethod("rlayout", "PreDataTableLayouts", function(obj) obj@row_layout) setMethod("rlayout", "ANY", function(obj) PreDataRowLayout()) setGeneric("rlayout<-", function(object, value) standardGeneric("rlayout<-")) setMethod("rlayout<-", "PreDataTableLayouts", function(object, value) { object@row_layout = value object }) setGeneric("tree_pos", function(obj) standardGeneric("tree_pos")) setMethod("tree_pos", "VLayoutNode", function(obj) obj@pos_in_tree) setGeneric("pos_subset", function(obj) standardGeneric("pos_subset")) setMethod("pos_subset", "TreePos", function(obj) obj@subset) setMethod("pos_subset", "VLayoutNode", function(obj) pos_subset(tree_pos(obj))) setGeneric("pos_splits", function(obj) standardGeneric("pos_splits")) setMethod("pos_splits", "TreePos", function(obj) obj@splits) setMethod("pos_splits", "VLayoutNode", function(obj) pos_splits(tree_pos(obj))) setGeneric("pos_splvals", function(obj) standardGeneric("pos_splvals")) setMethod("pos_splvals", "TreePos", function(obj) obj@s_values) setMethod("pos_splvals", "VLayoutNode", function(obj) pos_splvals(tree_pos(obj))) setGeneric("pos_split_labels", function(obj) standardGeneric("pos_split_labels")) setMethod("pos_split_labels", "TreePos", function(obj) { spls = pos_splits(obj) sapply(spls, function(x) x@split_label) }) setMethod("pos_split_labels", "VLayoutNode", function(obj) pos_split_labels(tree_pos(obj))) setGeneric("split_texttype", function(obj) standardGeneric("split_texttype")) setMethod("split_texttype", "VarLevelSplit", function(obj) "varlevels") setMethod("split_texttype", "MultiVarSplit", function(obj) "multivar") setMethod("split_texttype", "AllSplit", function(obj) "allobs") setMethod("split_texttype", "RootSplit", function(obj) "root") setMethod("split_texttype", "NULLSplit", function(obj) "null") setMethod("split_texttype", "VarStaticCutSplit", function(obj) "scut") setMethod("split_texttype", "VarDynCutSplit", function(obj) "dyncut") setMethod("split_texttype", "ManualSplit", function(obj) "manual") setMethod("split_texttype", "ANY", function(obj) stop("unknown split type")) setGeneric("pos_spltypes", function(obj) standardGeneric("pos_spltypes")) setMethod("pos_spltypes", "TreePos", function(obj) { spls = pos_splits(obj) sapply(spls, split_texttype) }) setMethod("pos_spltypes", "VLayoutNode", function(obj) pos_spltypes(tree_pos(obj))) setGeneric("pos_splval_labels", function(obj) standardGeneric("pos_splval_labels")) setMethod("pos_splval_labels", "TreePos", function(obj) obj@sval_labels) setMethod("pos_splval_labels", "VLayoutNode", function(obj) pos_splval_labels(tree_pos(obj))) setGeneric("spl_payload", function(obj) standardGeneric("spl_payload")) setMethod("spl_payload", "Split", function(obj) obj@payload) setGeneric("spl_payload<-", function(obj, value) standardGeneric("spl_payload<-")) setMethod("spl_payload<-", "Split", function(obj, value) { obj@payload <- value obj }) setGeneric("spl_label_var", function(obj) standardGeneric("spl_label_var")) setMethod("spl_label_var", "VarLevelSplit", function(obj) obj@value_label_var) setMethod("spl_label_var", "Split", function(obj) NULL) setGeneric("obj_name", function(obj) standardGeneric("obj_name")) setMethod("obj_name", "VNodeInfo", function(obj) obj@name) setMethod("obj_name", "Split", function(obj) obj@name) setGeneric("obj_name<-", function(obj, value) standardGeneric("obj_name<-")) setMethod("obj_name<-", "VNodeInfo", function(obj, value) { obj@name = value obj }) setMethod("obj_name<-", "Split", function(obj, value) { obj@name = value obj }) setGeneric("obj_label", function(obj) standardGeneric("obj_label")) setMethod("obj_label", "Split", function(obj) obj@split_label) setMethod("obj_label", "ANY", function(obj) attr(obj, "label")) setMethod("obj_label", "TableRow", function(obj) obj@label) setMethod("obj_label", "VTableTree", function(obj) obj_label(tt_labelrow(obj))) setMethod("obj_label", "ValueWrapper", function(obj) obj@label) setGeneric("obj_label<-", function(obj, value) standardGeneric("obj_label<-")) setMethod("obj_label<-", "Split", function(obj, value) { obj@split_label <- value obj }) setMethod("obj_label<-", "TableRow", function(obj, value){ obj@label = value obj }) setMethod("obj_label<-", "ValueWrapper", function(obj, value){ obj@label = value obj }) setMethod("obj_label<-", "ANY", function(obj, value){ attr(obj, "label") = value obj }) setMethod("obj_label<-", "VTableTree", function(obj, value) { lr = tt_labelrow(obj) obj_label(lr) = value if( !is.na(value) && nzchar(value)) labelrow_visible(lr) = TRUE else if(is.na(value)) labelrow_visible(lr) = FALSE tt_labelrow(obj) = lr obj }) setGeneric("tt_labelrow", function(obj) standardGeneric("tt_labelrow")) setMethod("tt_labelrow", "VTableTree", function(obj) obj@labelrow) setGeneric("tt_labelrow<-", function(obj, value) standardGeneric("tt_labelrow<-")) setMethod("tt_labelrow<-", "VTableTree", function(obj, value) { obj@labelrow = value obj }) setGeneric("labelrow_visible", function(obj) standardGeneric("labelrow_visible")) setMethod("labelrow_visible", "VTableTree", function(obj) { labelrow_visible(tt_labelrow(obj)) }) setMethod("labelrow_visible", "LabelRow", function(obj) obj@visible) setMethod("labelrow_visible", "VAnalyzeSplit", function(obj) .labelkids_helper(obj@var_label_position)) setGeneric("labelrow_visible<-", function(obj, value) standardGeneric("labelrow_visible<-")) setMethod("labelrow_visible<-", "VTableTree", function(obj, value) { lr = tt_labelrow(obj) labelrow_visible(lr) = value tt_labelrow(obj) = lr obj }) setMethod("labelrow_visible<-", "LabelRow", function(obj, value) { obj@visible = value obj }) setMethod("labelrow_visible<-", "VAnalyzeSplit", function(obj, value) { obj@var_label_position = value obj }) setGeneric("label_kids", function(spl) standardGeneric("label_kids")) setMethod("label_kids", "Split", function(spl) spl@label_children) setGeneric("label_kids<-", function(spl, value) standardGeneric("label_kids<-")) setMethod("label_kids<-", c("Split", "character"), function(spl, value) { label_kids(spl) <- .labelkids_helper(value) spl }) setMethod("label_kids<-", c("Split", "logical"), function(spl, value) { spl@label_children <- value spl }) setGeneric("vis_label", function(spl) standardGeneric("vis_label")) setMethod("vis_label", "Split", function(spl) { .labelkids_helper(label_position(spl)) }) setGeneric("vis_label<-", function(spl, value) standardGeneric("vis_label<-")) setGeneric("label_position", function(spl) standardGeneric("label_position")) setMethod("label_position", "Split", function(spl) spl@split_label_position) setMethod("label_position", "VAnalyzeSplit", function(spl) spl@var_label_position) setGeneric("label_position<-", function(spl, value) standardGeneric("label_position<-")) setMethod("label_position<-", "Split", function(spl, value) { value <- match.arg(value, valid_lbl_pos) spl@split_label_position <- value spl }) setGeneric("content_fun", function(obj) standardGeneric("content_fun")) setMethod("content_fun", "Split", function(obj) obj@content_fun) setGeneric("content_fun<-", function(object, value) standardGeneric("content_fun<-")) setMethod("content_fun<-", "Split", function(object, value) { object@content_fun = value object }) setGeneric("analysis_fun", function(obj) standardGeneric("analysis_fun")) setMethod("analysis_fun", "AnalyzeVarSplit", function(obj) obj@analysis_fun) setMethod("analysis_fun", "AnalyzeColVarSplit", function(obj) obj@analysis_fun) setGeneric("analysis_fun<-", function(object, value) standardGeneric("analysis_fun<-")) setMethod("analysis_fun<-", "AnalyzeVarSplit", function(object, value) { object@analysis_fun <- value object }) setMethod("analysis_fun<-", "AnalyzeColVarSplit", function(object, value) { if(is(value, "function")) value <- list(value) object@analysis_fun <- value object }) setGeneric("split_fun", function(obj) standardGeneric("split_fun")) setMethod("split_fun", "CustomizableSplit", function(obj) obj@split_fun) setMethod("split_fun", "Split", function(obj) NULL) setGeneric("content_extra_args", function(obj) standardGeneric("content_extra_args")) setMethod("content_extra_args", "Split", function(obj) obj@content_extra_args) setGeneric("content_extra_args<-", function(object, value) standardGeneric("content_extra_args<-")) setMethod("content_extra_args<-", "Split", function(object, value) { object@content_extra_args = value object }) setGeneric("content_var", function(obj) standardGeneric("content_var")) setMethod("content_var", "Split", function(obj) obj@content_var) setGeneric("content_var<-", function(object, value) standardGeneric("content_var<-")) setMethod("content_var<-", "Split", function(object, value) { object@content_var = value object }) setGeneric("avar_inclNAs", function(obj) standardGeneric("avar_inclNAs")) setMethod("avar_inclNAs", "VAnalyzeSplit", function(obj) obj@include_NAs) setGeneric("avar_inclNAs<-", function(obj, value) standardGeneric("avar_inclNAs<-")) setMethod("avar_inclNAs<-", "VAnalyzeSplit", function(obj, value) { obj@include_NAs = value }) setGeneric("spl_labelvar", function(obj) standardGeneric("spl_labelvar")) setMethod("spl_labelvar", "VarLevelSplit", function(obj) obj@value_label_var) setGeneric("spl_child_order", function(obj) standardGeneric("spl_child_order")) setMethod("spl_child_order", "VarLevelSplit", function(obj) obj@value_order) setGeneric("spl_child_order<-", function(obj, value) standardGeneric("spl_child_order<-")) setMethod("spl_child_order<-", "VarLevelSplit", function(obj, value) { obj@value_order = value obj }) setMethod("spl_child_order", "ManualSplit", function(obj) obj@levels) setMethod("spl_child_order", "MultiVarSplit", function(obj) spl_varnames(obj)) setMethod("spl_child_order", "AllSplit", function(obj) character()) setMethod("spl_child_order", "VarStaticCutSplit", function(obj) spl_cutlabels(obj)) setGeneric("root_spl", function(obj) standardGeneric("root_spl")) setMethod("root_spl", "PreDataAxisLayout", function(obj) obj@root_split) setGeneric("root_spl<-", function(obj, value) standardGeneric("root_spl<-")) setMethod("root_spl<-", "PreDataAxisLayout", function(obj, value) { obj@root_split <- value obj }) setGeneric("obj_avar", function(obj) standardGeneric("obj_avar")) setMethod("obj_avar", "TableRow", function(obj) obj@var_analyzed) setMethod("obj_avar", "ElementaryTable", function(obj) obj@var_analyzed) setGeneric("row_cells", function(obj) standardGeneric("row_cells")) setMethod("row_cells", "TableRow", function(obj) obj@leaf_value) setGeneric("row_cells<-", function(obj, value) standardGeneric("row_cells<-")) setMethod("row_cells<-", "TableRow", function(obj, value) { obj@leaf_value <- value obj }) setGeneric("row_values", function(obj) standardGeneric("row_values")) setMethod("row_values", "TableRow", function(obj) rawvalues(obj@leaf_value)) setGeneric("row_values<-", function(obj, value) standardGeneric("row_values<-")) setMethod("row_values<-", "TableRow", function(obj, value) { obj@leaf_value = lapply(value, rcell) obj }) setMethod("row_values<-", "LabelRow", function(obj, value) { stop("LabelRows cannot have row values.") }) setGeneric("spanned_values", function(obj) standardGeneric("spanned_values")) setMethod("spanned_values", "TableRow", function(obj) { sp = row_cspans(obj) rvals = row_values(obj) unlist(mapply(function(v, s) rep(list(v), times = s), v = rvals, s = sp), recursive = FALSE) }) setMethod("spanned_values", "LabelRow", function(obj) { rep(list(NULL), ncol(obj)) }) setGeneric("spanned_cells", function(obj) standardGeneric("spanned_cells")) setMethod("spanned_cells", "TableRow", function(obj) { sp = row_cspans(obj) rvals = row_cells(obj) unlist(mapply(function(v, s) rep(list(v), times = s)), recursive = FALSE) }) setMethod("spanned_cells", "LabelRow", function(obj) { rep(list(NULL), ncol(obj)) }) setGeneric("spanned_values<-", function(obj, value) standardGeneric("spanned_values<-")) setMethod("spanned_values<-", "TableRow", function(obj, value) { sp = row_cspans(obj) splvec = cumsum(unlist(lapply(sp, function(x) c(1, rep(0, x - 1))))) rvals = lapply(split(value, splvec), function(v) { if(length(v) == 1) return(v) stopifnot(length(unique(v)) == 1L) rcell(unique(v), colspan= length(v)) }) row_values(obj) = rvals obj }) setMethod("spanned_values<-", "LabelRow", function(obj, value) { if(!is.null(value)) stop("Label rows can't have non-null cell values, got", value) obj }) setGeneric("obj_format", function(obj) standardGeneric("obj_format")) setMethod("obj_format", "ANY", function(obj) attr(obj, "format")) setMethod("obj_format", "VTableNodeInfo", function(obj) obj@format) setMethod("obj_format", "Split", function(obj) obj@split_format) setGeneric("obj_format<-", function(obj, value) standardGeneric("obj_format<-")) setMethod("obj_format<-", "ANY", function(obj, value) { attr(obj, "format") = value obj }) setMethod("obj_format<-", "VTableNodeInfo", function(obj, value) { obj@format = value obj }) setMethod("obj_format<-", "Split", function(obj, value) { obj@split_format = value obj }) setGeneric("set_format_recursive", function(obj, format, override = FALSE) standardGeneric("set_format_recursive")) setMethod("set_format_recursive", "TableRow", function(obj, format, override = FALSE) { if(is.null(format)) return(obj) if(is.null(obj_format(obj)) || override) obj_format(obj) = format lcells = row_cells(obj) lvals = lapply(lcells, function(x) { if(!is.null(x) && is.null(obj_format(x))) obj_format(x) = obj_format(obj) x }) row_values(obj) = lvals obj }) setMethod("set_format_recursive", "LabelRow", function(obj, format, override = FALSE) obj) setMethod("set_format_recursive", "VTableTree", function(obj, format, override = FALSE) { force(format) if(is.null(format)) return(obj) if(is.null(obj_format(obj)) || override) obj_format(obj) = format kids = tree_children(obj) kids = lapply(kids, function(x, format2, oride) set_format_recursive(x, format = format2, override = oride), format2 = obj_format(obj), oride = override) tree_children(obj) = kids obj }) setGeneric("content_format", function(obj) standardGeneric("content_format")) setMethod("content_format", "Split", function(obj) obj@content_format) setGeneric("content_format<-", function(obj, value) standardGeneric("content_format<-")) setMethod("content_format<-", "Split", function(obj, value) { obj@content_format = value obj }) `%||%` = function(L, R) if(length(L) == 0) R else L setGeneric("value_formats", function(obj, default = obj_format(obj)) standardGeneric("value_formats")) setMethod("value_formats", "ANY", function(obj, default) { attr(obj, "format") %||% default }) setMethod("value_formats", "TableRow", function(obj, default) { if(!is.null(obj_format(obj))) default <- obj_format(obj) formats = lapply(row_cells(obj), function(x) value_formats(x) %||% default) formats }) setMethod("value_formats", "LabelRow", function(obj, default) { rep(list(NULL), ncol(obj)) }) setMethod("value_formats", "VTableTree", function(obj, default) { if(!is.null(obj_format(obj))) default <- obj_format(obj) rws = collect_leaves(obj, TRUE, TRUE) formatrws = lapply(rws, value_formats, default = default) mat = do.call(rbind, formatrws) row.names(mat) = row.names(obj) mat }) setGeneric("collect_leaves", function(tt, incl.cont = TRUE, add.labrows = FALSE) standardGeneric("collect_leaves"), signature = "tt") setMethod("collect_leaves", "TableTree", function(tt, incl.cont = TRUE, add.labrows = FALSE) { ret = c( if(add.labrows && labelrow_visible(tt)) { tt_labelrow(tt) }, if(incl.cont) {tree_children(content_table(tt))}, lapply(tree_children(tt), collect_leaves, incl.cont = incl.cont, add.labrows = add.labrows)) unlist(ret, recursive = TRUE) }) setMethod("collect_leaves", "ElementaryTable", function(tt, incl.cont = TRUE, add.labrows = FALSE) { ret = tree_children(tt) if(add.labrows && labelrow_visible(tt)) { ret = c(tt_labelrow(tt), ret) } ret }) setMethod("collect_leaves", "VTree", function(tt, incl.cont, add.labrows) { ret = lapply(tree_children(tt), collect_leaves) unlist(ret, recursive = TRUE) }) setMethod("collect_leaves", "VLeaf", function(tt, incl.cont, add.labrows) { list(tt) }) setMethod("collect_leaves", "NULL", function(tt, incl.cont, add.labrows) { list() }) setMethod("collect_leaves", "ANY", function(tt, incl.cont, add.labrows) stop("class ", class(tt), " does not inherit from VTree or VLeaf")) n_leaves <- function(tt, ...) { length(collect_leaves(tt, ...)) } setGeneric("row_cspans", function(obj) standardGeneric("row_cspans")) setMethod("row_cspans", "TableRow", function(obj) obj@colspans) setMethod("row_cspans", "LabelRow", function(obj) rep(1L, ncol(obj))) setGeneric("row_cspans<-", function(obj, value) standardGeneric("row_cspans<-")) setMethod("row_cspans<-", "TableRow", function(obj, value) { obj@colspans = value obj }) setMethod("row_cspans<-", "LabelRow", function(obj, value) { stop("attempted to set colspans for LabelRow") }) setGeneric("cell_cspan", function(obj) standardGeneric("cell_cspan")) setMethod("cell_cspan", "CellValue", function(obj) attr(obj, "colspan")) setGeneric("cell_cspan<-", function(obj, value) standardGeneric("cell_cspan<-")) setMethod("cell_cspan<-", "CellValue", function(obj, value) { attr(obj, "colspan") <- value obj }) setGeneric("tt_level", function(obj) standardGeneric("tt_level")) setMethod("tt_level", "VNodeInfo", function(obj) obj@level) setGeneric("tt_level<-", function(obj, value) standardGeneric("tt_level<-")) setMethod("tt_level<-", "VNodeInfo", function(obj, value) { obj@level = as.integer(value) obj }) setMethod("tt_level<-", "VTableTree", function(obj, value) { obj@level = as.integer(value) tree_children(obj) = lapply(tree_children(obj), `tt_level<-`, value = as.integer(value) + 1L) obj }) setGeneric("indent_mod", function(obj) standardGeneric("indent_mod")) setMethod("indent_mod", "Split", function(obj) obj@indent_modifier) setMethod("indent_mod", "VTableNodeInfo", function(obj) obj@indent_modifier) setMethod("indent_mod", "ANY", function(obj) attr(obj, "indent_mod") %||% 0L) setMethod("indent_mod", "RowsVerticalSection", function(obj) { val <- attr(obj, "indent_mods") %||% rep(0L, length(obj)) setNames(val, names(obj)) }) setGeneric("indent_mod<-", function(obj, value) standardGeneric("indent_mod<-")) setMethod("indent_mod<-", "Split", function(obj, value) { obj@indent_modifier = as.integer(value) obj }) setMethod("indent_mod<-", "VTableNodeInfo", function(obj, value) { obj@indent_modifier = as.integer(value) obj }) setMethod("indent_mod<-", "CellValue", function(obj, value) { attr(obj, "indent_mod") <- as.integer(value) obj }) setMethod("indent_mod<-", "RowsVerticalSection", function(obj, value) { if(length(value) != 1 && length(value) != length(obj)) stop("When setting indent mods on a RowsVerticalSection the value must have length 1 or the number of rows") attr(obj, "indent_mods") <- as.integer(value) obj }) setGeneric("content_indent_mod", function(obj) standardGeneric("content_indent_mod")) setMethod("content_indent_mod", "Split", function(obj) obj@content_indent_modifier) setMethod("content_indent_mod", "VTableNodeInfo", function(obj) obj@content_indent_modifier) setGeneric("content_indent_mod<-", function(obj, value) standardGeneric("content_indent_mod<-")) setMethod("content_indent_mod<-", "Split", function(obj, value) { obj@content_indent_modifier = as.integer(value) obj }) setMethod("content_indent_mod<-", "VTableNodeInfo", function(obj, value) { obj@content_indent_modifier = as.integer(value) obj }) setGeneric("rawvalues", function(obj) standardGeneric("rawvalues")) setMethod("rawvalues", "ValueWrapper", function(obj) obj@value) setMethod("rawvalues", "LevelComboSplitValue", function(obj) obj@combolevels) setMethod("rawvalues", "list", function(obj) lapply(obj, rawvalues)) setMethod("rawvalues", "ANY", function(obj) obj) setMethod("rawvalues", "CellValue", function(obj) obj[[1]]) setMethod("rawvalues", "TreePos", function(obj) rawvalues(pos_splvals(obj))) setMethod("rawvalues", "RowsVerticalSection", function(obj) unlist(obj, recursive = FALSE)) setGeneric("value_names", function(obj) standardGeneric("value_names")) setMethod("value_names", "ANY", function(obj) as.character(rawvalues(obj))) setMethod("value_names", "TreePos", function(obj) value_names(pos_splvals(obj))) setMethod("value_names", "list", function(obj) lapply(obj, value_names)) setMethod("value_names", "ValueWrapper", function(obj) rawvalues(obj)) setMethod("value_names", "LevelComboSplitValue", function(obj) obj@value) setMethod("value_names", "RowsVerticalSection", function(obj) attr(obj, "row_names")) setGeneric("value_labels", function(obj) standardGeneric("value_labels")) setMethod("value_labels", "ANY", function(obj) as.character(obj_label(obj))) setMethod("value_labels", "TreePos", function(obj) sapply(pos_splvals(obj), obj_label)) setMethod("value_labels", "list", function(obj) { ret <- lapply(obj, obj_label) if(!is.null(names(obj))) { inds <- vapply(ret, function(x) length(x) == 0, NA) ret[inds] = names(obj)[inds] } ret }) setMethod("value_labels", "RowsVerticalSection", function(obj) setNames(attr(obj, "row_labels"), value_names(obj))) setMethod("value_labels", "ValueWrapper", function(obj) obj_label(obj)) setMethod("value_labels", "LevelComboSplitValue", function(obj) obj_label(obj)) setMethod("value_labels", "MultiVarSplit", function(obj) obj@var_labels) setGeneric("spl_varlabels", function(obj) standardGeneric("spl_varlabels")) setMethod("spl_varlabels", "MultiVarSplit", function(obj) obj@var_labels) setGeneric("spl_varlabels<-", function(object, value) standardGeneric("spl_varlabels<-")) setMethod("spl_varlabels<-", "MultiVarSplit", function(object, value) { object@var_labels <- value object }) setGeneric("splv_extra", function(obj) standardGeneric("splv_extra")) setMethod("splv_extra", "SplitValue", function(obj) obj@extra) setGeneric("splv_extra<-", function(obj, value) standardGeneric("splv_extra<-")) setMethod("splv_extra<-", "SplitValue", function(obj, value) { obj@extra <- value obj }) setGeneric("split_exargs", function(obj) standardGeneric("split_exargs")) setMethod("split_exargs", "Split", function(obj) obj@extra_args) setGeneric("split_exargs<-", function(obj, value) standardGeneric("split_exargs<-")) setMethod("split_exargs<-", "Split", function(obj, value ) { obj@extra_args <- value obj }) is_labrow = function(obj) is(obj, "LabelRow") spl_ref_group = function(obj) { stopifnot(is(obj, "VarLevWBaselineSplit")) obj@ref_group_value } setGeneric("clayout_splits", function(obj) standardGeneric("clayout_splits")) setMethod("clayout_splits", "LayoutColTree", function(obj) { clayout_splits(tree_children(obj)[[1]]) }) setMethod("clayout_splits", "LayoutColLeaf", function(obj) { pos_splits(tree_pos(obj)) }) setMethod("clayout_splits", "VTableNodeInfo", function(obj) clayout_splits(clayout(obj))) setGeneric("clayout", function(obj) standardGeneric("clayout")) setMethod("clayout", "VTableNodeInfo", function(obj) obj@col_info@tree_layout) setMethod("clayout", "PreDataTableLayouts", function(obj) obj@col_layout) setMethod("clayout", "ANY", function(obj) PreDataColLayout()) setGeneric("clayout<-", function(object, value) standardGeneric("clayout<-")) setMethod("clayout<-", "PreDataTableLayouts", function(object, value) { object@col_layout = value object }) setGeneric("col_info", function(obj) standardGeneric("col_info")) setMethod("col_info", "VTableNodeInfo", function(obj) obj@col_info) setGeneric("col_info<-", function(obj, value) standardGeneric("col_info<-")) setMethod("col_info<-", "TableRow", function(obj, value) { obj@col_info = value obj }) .set_cinfo_kids = function(obj) { kids = lapply(tree_children(obj), function(x) { col_info(x) = col_info(obj) x }) tree_children(obj) = kids obj } setMethod("col_info<-", "ElementaryTable", function(obj, value) { obj@col_info = value .set_cinfo_kids(obj) }) setMethod("col_info<-", "TableTree", function(obj, value) { obj@col_info = value if(nrow(content_table(obj))) { ct = content_table(obj) col_info(ct) = value content_table(obj) = ct } .set_cinfo_kids(obj) }) setGeneric("coltree", function(obj, df = NULL, rtpos = TreePos()) standardGeneric("coltree")) setMethod("coltree", "InstantiatedColumnInfo", function(obj, df = NULL, rtpos = TreePos()) { if(!is.null(df)) warning("Ignoring df argument and retrieving already-computed LayoutColTree") obj@tree_layout }) setMethod("coltree", "PreDataTableLayouts", function(obj, df, rtpos) coltree(clayout(obj), df, rtpos)) setMethod("coltree", "PreDataColLayout", function(obj, df, rtpos) { kids = lapply(obj, function(x) splitvec_to_coltree(df = df, splvec = x, pos = rtpos)) if(length(kids) == 1) res = kids[[1]] else res = LayoutColTree(lev = 0L, kids = kids, tpos = rtpos, spl = RootSplit()) disp_ccounts(res) = disp_ccounts(obj) res }) setMethod("coltree", "LayoutColTree", function(obj, df, rtpos) obj) setMethod("coltree", "VTableTree", function(obj, df, rtpos) coltree(col_info(obj))) setMethod("coltree", "TableRow", function(obj, df, rtpos) coltree(col_info(obj))) setGeneric("coltree<-", function(obj, value) standardGeneric("coltree<-")) setMethod("coltree<-", c("InstantiatedColumnInfo", "LayoutColTree"), function(obj, value) { obj@tree_layout <- value obj }) setMethod("coltree<-", c("VTableTree", "LayoutColTree"), function(obj, value) { cinfo <- col_info(obj) coltree(cinfo) <- value col_info(obj) <- cinfo obj }) setGeneric("col_exprs", function(obj, df = NULL) standardGeneric("col_exprs")) setMethod("col_exprs", "PreDataTableLayouts", function(obj, df = NULL) col_exprs(clayout(obj), df)) setMethod("col_exprs", "PreDataColLayout", function(obj, df = NULL) { if(is.null(df)) stop("can't determine col_exprs without data") ct <- coltree(obj, df = df) make_col_subsets(ct, df = df) }) setMethod("col_exprs", "InstantiatedColumnInfo", function(obj, df = NULL) { if(!is.null(df)) warning("Ignoring df method when extracted precomputed column subsetting expressions.") obj@subset_exprs }) setGeneric("col_extra_args", function(obj, df = NULL) standardGeneric("col_extra_args")) setMethod("col_extra_args", "InstantiatedColumnInfo", function(obj, df) { if(!is.null(df)) warning("Ignorning df when retrieving already-computed column extra arguments.") obj@cextra_args }) setMethod("col_extra_args", "PreDataTableLayouts", function(obj, df) col_extra_args(clayout(obj), df)) setMethod("col_extra_args", "PreDataColLayout", function(obj, df) { col_extra_args(coltree(obj, df), NULL) }) setMethod("col_extra_args", "LayoutColTree", function(obj, df) { if(!is.null(df)) warning("Ignoring df argument and returning already calculated extra arguments") get_col_extras(obj) }) setMethod("col_extra_args", "LayoutColLeaf", function(obj, df) { if(!is.null(df)) warning("Ignoring df argument and returning already calculated extra arguments") get_pos_extra(pos = tree_pos(obj)) }) setGeneric("col_counts", function(obj) standardGeneric("col_counts")) setMethod("col_counts", "InstantiatedColumnInfo", function(obj) obj@counts) setMethod("col_counts", "VTableNodeInfo", function(obj) col_counts(col_info(obj))) setGeneric("col_counts<-", function(obj, value) standardGeneric("col_counts<-")) setMethod("col_counts<-", "InstantiatedColumnInfo", function(obj, value) { obj@counts = value obj }) setMethod("col_counts<-", "VTableNodeInfo", function(obj, value) { cinfo = col_info(obj) col_counts(cinfo) = value col_info(obj) = cinfo obj }) setGeneric("col_total", function(obj) standardGeneric("col_total")) setMethod("col_total", "InstantiatedColumnInfo", function(obj) obj@total_count) setMethod("col_total", "VTableNodeInfo", function(obj) col_total(col_info(obj))) setGeneric("col_total<-", function(obj, value) standardGeneric("col_total<-")) setMethod("col_total<-", "InstantiatedColumnInfo", function(obj, value) { obj@total_count = value obj }) setMethod("col_total<-", "VTableNodeInfo", function(obj, value) { cinfo = col_info(obj) col_total(cinfo) = value col_info(obj) = cinfo obj }) setGeneric("disp_ccounts", function(obj) standardGeneric("disp_ccounts")) setMethod("disp_ccounts", "VTableTree", function(obj) disp_ccounts(col_info(obj))) setMethod("disp_ccounts", "InstantiatedColumnInfo", function(obj) obj@display_columncounts) setMethod("disp_ccounts", "PreDataTableLayouts", function(obj) disp_ccounts(clayout(obj))) setMethod("disp_ccounts", "PreDataColLayout", function(obj) obj@display_columncounts) setGeneric("disp_ccounts<-", function(obj, value) standardGeneric("disp_ccounts<-")) setMethod("disp_ccounts<-", "VTableTree", function(obj, value) { cinfo = col_info(obj) disp_ccounts(cinfo) = value col_info(obj) = cinfo obj }) setMethod("disp_ccounts<-", "InstantiatedColumnInfo", function(obj, value) { obj@display_columncounts = value obj }) setMethod("disp_ccounts<-", "PreDataColLayout", function(obj, value) { obj@display_columncounts = value obj }) setMethod("disp_ccounts<-", "LayoutColTree", function(obj, value) { obj@display_columncounts = value obj }) setMethod("disp_ccounts<-", "PreDataTableLayouts", function(obj, value) { clyt = clayout(obj) disp_ccounts(clyt) = value clayout(obj) = clyt obj }) setGeneric("colcount_format", function(obj) standardGeneric("colcount_format")) setMethod("colcount_format", "InstantiatedColumnInfo", function(obj) obj@columncount_format) setMethod("colcount_format", "VTableNodeInfo", function(obj) colcount_format(col_info(obj))) setMethod("colcount_format", "PreDataColLayout", function(obj) obj@columncount_format) setMethod("colcount_format", "PreDataTableLayouts", function(obj) colcount_format(clayout(obj))) setGeneric("colcount_format<-", function(obj,value) standardGeneric("colcount_format<-")) setMethod("colcount_format<-", "InstantiatedColumnInfo", function(obj, value) { obj@columncount_format = value obj }) setMethod("colcount_format<-", "VTableNodeInfo", function(obj, value) { cinfo = col_info(obj) colcount_format(cinfo) = value col_info(obj) = cinfo obj }) setMethod("colcount_format<-", "PreDataColLayout", function(obj, value) { obj@columncount_format = value obj }) setMethod("colcount_format<-", "PreDataTableLayouts", function(obj, value) { clyt = clayout(obj) colcount_format(clyt) = value clayout(obj) = clyt obj }) setGeneric("no_colinfo", function(obj) standardGeneric("no_colinfo")) setMethod("no_colinfo", "VTableNodeInfo", function(obj) no_colinfo(col_info(obj))) setMethod("no_colinfo", "InstantiatedColumnInfo", function(obj) length(obj@subset_exprs) == 0) setMethod("names", "VTableNodeInfo", function(x) names(col_info(x))) setMethod("names", "InstantiatedColumnInfo", function(x) names(coltree(x))) setMethod("names", "LayoutColTree", function(x) { unname(unlist(lapply(tree_children(x), function(obj) { nm <- obj_name(obj) rep(nm, n_leaves(obj)) }))) }) setMethod("row.names", "VTableTree", function(x) { unname(sapply(collect_leaves(x, add.labrows = TRUE), obj_label, USE.NAMES = FALSE)) }) setMethod("as.vector", "TableRow", function(x, mode) as.vector(unlist(row_values(x)), mode = mode)) setMethod("as.vector", "ElementaryTable", function(x, mode) { stopifnot(nrow(x) == 1L) as.vector(tree_children(x)[[1]], mode = mode) }) setMethod("as.vector", "VTableTree", function(x, mode) { stopifnot(nrow(x) == 1L) if(nrow(content_table(x)) == 1L) tab = content_table(x) else tab = x as.vector(tree_children(tab)[[1]], mode = mode) }) setGeneric("spl_cuts", function(obj) standardGeneric("spl_cuts")) setMethod("spl_cuts", "VarStaticCutSplit", function(obj) obj@cuts) setGeneric("spl_cutlabels", function(obj) standardGeneric("spl_cutlabels")) setMethod("spl_cutlabels", "VarStaticCutSplit", function(obj) obj@cut_labels) setGeneric("spl_cutfun", function(obj) standardGeneric("spl_cutfun")) setMethod("spl_cutfun", "VarDynCutSplit", function(obj) obj@cut_fun) setGeneric("spl_cutlabelfun", function(obj) standardGeneric("spl_cutlabelfun")) setMethod("spl_cutlabelfun", "VarDynCutSplit", function(obj) obj@cut_label_fun) setGeneric("spl_is_cmlcuts", function(obj) standardGeneric("spl_is_cmlcuts")) setMethod("spl_is_cmlcuts", "VarDynCutSplit", function(obj) obj@cumulative_cuts) setGeneric("spl_varnames", function(obj) standardGeneric("spl_varnames")) setMethod("spl_varnames", "MultiVarSplit", function(obj) obj@var_names) setGeneric("spl_varnames<-", function(object, value) standardGeneric("spl_varnames<-")) setMethod("spl_varnames<-", "MultiVarSplit", function(object, value) { object@var_names <- value object }) setGeneric("top_left", function(obj) standardGeneric("top_left")) setMethod("top_left", "VTableTree", function(obj) top_left(col_info(obj))) setMethod("top_left", "InstantiatedColumnInfo", function(obj) obj@top_left) setMethod("top_left", "PreDataTableLayouts", function(obj) obj@top_left) setGeneric("top_left<-", function(obj, value) standardGeneric("top_left<-")) setMethod("top_left<-", "VTableTree", function(obj, value) { cinfo <- col_info(obj) top_left(cinfo) <- value col_info(obj) <- cinfo obj }) setMethod("top_left<-", "InstantiatedColumnInfo", function(obj, value) { obj@top_left <- value obj }) setMethod("top_left<-", "PreDataTableLayouts", function(obj, value) { obj@top_left <- value obj }) vil_collapse <- function(x) { x <- unlist(x) x <- x[!is.na(x)] x <- unique(x) x[nzchar(x)] } setGeneric("vars_in_layout", function(lyt) standardGeneric("vars_in_layout")) setMethod("vars_in_layout", "PreDataTableLayouts", function(lyt) { vil_collapse(c(vars_in_layout(clayout(lyt)), vars_in_layout(rlayout(lyt)))) }) setMethod("vars_in_layout", "PreDataAxisLayout", function(lyt) { vil_collapse(lapply(lyt, vars_in_layout)) }) setMethod("vars_in_layout", "SplitVector", function(lyt) { vil_collapse(lapply(lyt, vars_in_layout)) }) setMethod("vars_in_layout", "Split", function(lyt) vil_collapse(c(spl_payload(lyt), content_var(lyt), spl_label_var(lyt)))) setMethod("vars_in_layout", "CompoundSplit", function(lyt) vil_collapse(lapply(spl_payload(lyt), vars_in_layout))) setMethod("vars_in_layout", "ManualSplit", function(lyt) character()) setGeneric("main_title", function(obj) standardGeneric("main_title")) setMethod("main_title", "VTitleFooter", function(obj) obj@main_title) setGeneric("main_title<-", function(obj, value) standardGeneric("main_title<-")) setMethod("main_title<-", "VTitleFooter", function(obj, value) { stopifnot(length(value) == 1) obj@main_title <- value obj }) setGeneric("subtitles", function(obj) standardGeneric("subtitles")) setMethod("subtitles", "VTitleFooter", function(obj) obj@subtitles) setGeneric("subtitles<-", function(obj, value) standardGeneric("subtitles<-")) setMethod("subtitles<-", "VTitleFooter", function(obj, value) { obj@subtitles <- value obj }) all_titles <- function(obj) c(main_title(obj), subtitles(obj)) setGeneric("main_footer", function(obj) standardGeneric("main_footer")) setMethod("main_footer", "VTitleFooter", function(obj) obj@main_footer) setGeneric("main_footer<-", function(obj, value) standardGeneric("main_footer<-")) setMethod("main_footer<-", "VTitleFooter", function(obj, value) { obj@main_footer <- value obj }) setGeneric("prov_footer", function(obj) standardGeneric("prov_footer")) setMethod("prov_footer", "VTitleFooter", function(obj) obj@provenance_footer) setGeneric("prov_footer<-", function(obj, value) standardGeneric("prov_footer<-")) setMethod("prov_footer<-", "VTitleFooter", function(obj, value) { obj@provenance_footer <- value obj }) all_footers <- function(obj) c(main_footer(obj), prov_footer(obj)) make_ref_value <- function(value) { if(is(value, "RefFootnote")) value <- list(value) else if (!is.list(value) || any(!sapply(value, is, "RefFootnote"))) value <- lapply(value, RefFootnote) value } setGeneric("row_footnotes", function(obj) standardGeneric("row_footnotes")) setMethod("row_footnotes", "TableRow", function(obj) obj@row_footnotes) setMethod("row_footnotes", "RowsVerticalSection", function(obj) attr(obj, "row_footnotes") %||% list()) setGeneric("row_footnotes<-", function(obj, value) standardGeneric("row_footnotes<-")) setMethod("row_footnotes<-", "TableRow", function(obj, value) { obj@row_footnotes <- make_ref_value(value) obj }) setMethod("row_footnotes", "ElementaryTable", function(obj) { rws <- collect_leaves(obj, TRUE, TRUE) cells <- lapply(rws, row_footnotes) cells }) setGeneric("cell_footnotes", function(obj) standardGeneric("cell_footnotes")) setMethod("cell_footnotes", "CellValue", function(obj) attr(obj, "footnotes") %||% list()) setMethod("cell_footnotes", "TableRow", function(obj) { ret <- lapply(row_cells(obj), cell_footnotes) if(length(ret) != ncol(obj)) { ret <- rep(ret, row_cspans(obj)) } ret }) setMethod("cell_footnotes", "LabelRow", function(obj) { rep(list(list()), ncol(obj)) }) setMethod("cell_footnotes", "ElementaryTable", function(obj) { rws <- collect_leaves(obj, TRUE, TRUE) cells <- lapply(rws, cell_footnotes) do.call(rbind, cells) }) setGeneric("cell_footnotes<-", function(obj, value) standardGeneric("cell_footnotes<-")) setMethod("cell_footnotes<-", "CellValue", function(obj, value) { attr(obj, "footnotes") <- make_ref_value(value) obj }) .cfn_set_helper <- function(obj, value) { if(length(value) != ncol(obj)) stop("Did not get the right number of footnote ref values for cell_footnotes<- on a full row.") row_cells(obj) <- mapply(function(cell, fns) { if(is.list(fns)) cell_footnotes(cell) <- lapply(fns, RefFootnote) else cell_footnotes(cell) <- list(RefFootnote(fns)) cell }, cell = row_cells(obj), fns = value, SIMPLIFY=FALSE) obj } setMethod("cell_footnotes<-", "DataRow", definition = .cfn_set_helper) setMethod("cell_footnotes<-", "ContentRow", definition = .cfn_set_helper) setGeneric("col_fnotes_here", function(obj) standardGeneric("col_fnotes_here")) setMethod("col_fnotes_here", c("LayoutColTree"), function(obj) obj@col_footnotes) setMethod("col_fnotes_here", c("LayoutColLeaf"), function(obj) obj@col_footnotes) setGeneric("col_fnotes_here<-", function(obj, value) standardGeneric("col_fnotes_here<-")) setMethod("col_fnotes_here<-", "LayoutColTree", function(obj, value) { obj@col_footnotes <- make_ref_value(value) obj }) setMethod("col_fnotes_here<-", "LayoutColLeaf", function(obj, value) { obj@col_footnotes <- make_ref_value(value) obj }) setGeneric("ref_index", function(obj) standardGeneric("ref_index")) setMethod("ref_index", "RefFootnote", function(obj) obj@index) setGeneric("ref_index<-", function(obj, value) standardGeneric("ref_index<-")) setMethod("ref_index<-", "RefFootnote", function(obj, value) { obj@index <- value obj }) setGeneric(".fnote_set_inner<-", function(ttrp, colpath, value) standardGeneric(".fnote_set_inner<-")) setMethod(".fnote_set_inner<-", c("TableRow", "NULL"), function(ttrp, colpath, value) { row_footnotes(ttrp) <- value ttrp }) setMethod(".fnote_set_inner<-", c("TableRow", "character"), function(ttrp, colpath, value) { ind <- .path_to_pos(path = colpath, tt = ttrp, cols = TRUE) cfns <- cell_footnotes(ttrp) cfns[[ind]] <- value cell_footnotes(ttrp) <- cfns ttrp }) setMethod(".fnote_set_inner<-", c("InstantiatedColumnInfo", "character"), function(ttrp, colpath, value) { ctree <- col_fnotes_at_path(coltree(ttrp), colpath, fnotes = value) coltree(ttrp) <- ctree ttrp }) setMethod(".fnote_set_inner<-", c("VTableTree", "ANY"), function(ttrp, colpath, value) { if(labelrow_visible(ttrp) && !is.null(value)) { lblrw <- tt_labelrow(ttrp) row_footnotes(lblrw) <- value tt_labelrow(ttrp) <- lblrw } else if(NROW(content_table(ttrp)) == 1L) { ctbl <- content_table(ttrp) pth <- make_row_df(ctbl)$path[[1]] fnotes_at_path(ctbl, pth, colpath) <- value content_table(ttrp) <- ctbl } else { stop("an error occured. this shouldn't happen. please contact the maintainer") } ttrp }) setGeneric("fnotes_at_path<-", function(obj, rowpath = NULL, colpath = NULL, reset_idx = TRUE, value) standardGeneric("fnotes_at_path<-")) setMethod("fnotes_at_path<-", c("VTableTree", "character"), function(obj, rowpath = NULL, colpath = NULL, reset_idx = TRUE, value) { rw <- tt_at_path(obj, rowpath) .fnote_set_inner(rw, colpath) <- value tt_at_path(obj, rowpath) <- rw if(reset_idx) obj <- update_ref_indexing(obj) obj }) setMethod("fnotes_at_path<-", c("VTableTree", "NULL"), function(obj, rowpath = NULL, colpath = NULL, reset_idx = TRUE, value) { cinfo <- col_info(obj) .fnote_set_inner(cinfo, colpath) <- value col_info(obj) <- cinfo if(reset_idx) obj <- update_ref_indexing(obj) obj }) `col_footnotes_here<-` <- function(obj, value) { obj@col_footnotes <- make_ref_value(value) obj }
dateTaxonTreePBDB <- function( taxaTree, taxaDataPBDB = taxaTree$taxaDataPBDB, minBranchLen = 0, tipTaxonDateUsed = "shallowestAge", dropZeroOccurrenceTaxa = TRUE, plotTree = FALSE){ if(!any(colnames(taxaDataPBDB)!="lastapp_min_ma")){ stop(paste0( "a data table of PBDB variables, generated with show=app", " must be provided either directly", "or as a taxaDataPBDB element of taxaTrees")) } lastAppTimes <- c("lastapp_min_ma","lastapp_max_ma") firstAppTimes <- c("firstapp_min_ma","firstapp_max_ma") taxaDataPBDB_orig <- taxaDataPBDB if(is.null(taxaTree$node.label)){ message("No node labels found - is this a taxon tree from the PBDB?") combData <- taxaDataPBDB }else{ nodeNames <- taxaTree$node.label nodeNames <- sapply( strsplit( nodeNames, split=".", fixed=TRUE ), function(x) x[[1]] ) nodeNamesNoMatch <- sapply( nodeNames, function(x) all(x != taxaDataPBDB$taxon_name) ) if(any(nodeNamesNoMatch)){ nodeNames <- nodeNames[nodeNamesNoMatch] nodeNames <- paste0(nodeNames, collapse=",") apiAddressNodes <- paste0( "http://paleobiodb.org/data1.2/taxa/list.txt?name=", nodeNames,"&show=app,parent" ) nodeData <- read.csv(apiAddressNodes, stringsAsFactors = FALSE) sharedColNames <- intersect(colnames(nodeData), colnames(taxaDataPBDB)) taxaDataReduced <- taxaDataPBDB[,sharedColNames] nodeDataReduced <- nodeData[,sharedColNames] combData <- rbind(taxaDataReduced, nodeDataReduced) } } appData <- processTaxonAppData(dataPBDB = combData, dropZeroOccurrenceTaxa = dropZeroOccurrenceTaxa) dropTips <- sapply(taxaTree$tip.label, function(x) all(x != appData$taxon_name) ) if(any(dropTips)){ message(paste0("The following tips did not have resolvable", " appearance times and were dropped:")) message(paste0(taxaTree$tip.label[dropTips], collapse = ", ")) taxaTree <- drop.tip(taxaTree, tip = which(dropTips) ) } if(is.null(taxaTree$node.label)){ nodeChildren <- lapply(prop.part(taxaTree), function(x) taxaTree$tip.label[x] ) nodeMaxAges <- numeric() for(i in 1:Nnode(taxaTree)){ matchedChildren <- match(nodeChildren[[i]], appData$taxon_name) maxChildAges <- appData$firstapp_max_ma[matchedChildren] nodeMaxAges[i] <- max(maxChildAges) } }else{ nodeMaxAges <- appData$firstapp_max_ma[ match(taxaTree$node.label, appData$taxon_name) ] } tipMatches <- match(taxaTree$tip.label, appData$taxon_name) fourDateRanges <- appData[tipMatches, c(firstAppTimes,lastAppTimes )] if(tipTaxonDateUsed == "deepestAge"){ tipAges <- fourDateRanges$firstapp_max_ma } if(tipTaxonDateUsed == "shallowestAge"){ tipAges <- fourDateRanges$lastapp_min_ma } allAges <- as.numeric(c(tipAges, nodeMaxAges)) taxaNAapps <- is.na(allAges) if(any(taxaNAapps)){ namesAllAges <- c(taxaTree$tip.label, taxaTree$node.label) noappNames <- namesAllAges[taxaNAapps] noappNames <- paste0(noappNames, collapse = ",\n") stop(paste0("Some ages contain NAs: \n", noappNames)) } datedTree <- nodeDates2branchLengths( nodeDates = allAges, tree = taxaTree, allTipsModern = FALSE ) if(minBranchLen>0){ datedTree <- minBranchLength( tree = datedTree, mbl = minBranchLen) datedTree <- ladderize(datedTree) plotName <- paste0( "Dated Phylogeny (", minBranchLen, " Minimum Branch Length)" ) }else{ plotName <- "Dated Phylogeny" } checkRootTimeRes <- checkRootTime(datedTree, stopIfFail = TRUE) if(plotTree){ plot(datedTree, main = plotName, show.node.label = FALSE, cex = 0.5) axisPhylo() } rownames(fourDateRanges) <- taxaTree$tip.label datedTree$tipTaxonFourDateRanges <- fourDateRanges datedTree$ranges.used <- fourDateRanges[, c("firstapp_max_ma","lastapp_min_ma") ] colnames(datedTree$ranges.used) <- c("FAD", "LAD") datedTree$taxaDataPBDB <- taxaDataPBDB_orig return(datedTree) } processTaxonAppData <- function(dataPBDB, dropZeroOccurrenceTaxa){ lastAppTimes <- c("lastapp_min_ma","lastapp_max_ma") firstAppTimes <- c("firstapp_min_ma","firstapp_max_ma") isExtant <- dataPBDB$is_extant == "extant" isExtinct <- dataPBDB$is_extant == "extinct" hasZeroOcc <- (dataPBDB$n_occs == 0) isExtinctAndZeroOcc <- hasZeroOcc & isExtinct hasNAFirstApps <- apply( dataPBDB[,firstAppTimes], 1,function(x) is.na(x[1]) & is.na(x[2]) ) if(any(isExtant)){ dataPBDB[isExtant, lastAppTimes] <- 0 dataPBDB[isExtant & hasNAFirstApps, firstAppTimes] <- 0 } if(any(isExtinctAndZeroOcc) & dropZeroOccurrenceTaxa){ dataPBDB <- dataPBDB[-which(isExtinctAndZeroOcc),] } return(dataPBDB) }
get_nominees_by_state <- function(congress, state, page = 1, myAPI_Key){ API = 'congress' control <- 107:cMaxCongress if(!congress %in% 107:cMaxCongress){ stop("Incorrect congress, posible options are: ", control[1], ", ", control[2], ", ", control[3], " through ", control[9] ) } if(!validate_state(state)) stop("Incorrect state") query <- sprintf("%s/nominees/state/%s.json", congress, state) pp_query(query, API, page = page, myAPI_Key = myAPI_Key) }
calculateFeatures = function(feat.object, control, ...) { assertClass(feat.object, "FeatureObject") possible = as.character(unlist(listAllFeatureSets())) if (missing(control)) control = list() assertList(control) prog = control_parameter(control, "show_progress", TRUE) subset = control_parameter(control, "subset", possible) assertSubset(subset, choices = possible) allow.costs = control_parameter(control, "allow_costs", !is.null(feat.object$fun)) allow.cellmapping = control_parameter(control, "allow_cellmapping", TRUE) assertLogical(allow.costs) blacklist = control_parameter(control, "blacklist", NULL) if (any(feat.object$blocks <= 2)) { if (!("cm_conv" %in% blacklist)) { blacklist = unique(c(blacklist, "cm_conv")) warning("The 'cm_conv' features were not computed, because not all blocks were greater than 2.") } } assertSubset(blacklist, choices = possible) expensive = setdiff(listAvailableFeatureSets(allow.additional_costs = TRUE), listAvailableFeatureSets(allow.additional_costs = FALSE)) if (allow.costs & is.null(feat.object$fun) & any(expensive %in% setdiff(subset, blacklist))) stop("The local search features require the exact function!") sets = listAvailableFeatureSets(subset, allow.cellmapping, allow.costs, blacklist) if (prog) { bar = makeProgressBar(min = 0, max = length(sets), label = "") no_chars = max(nchar(sets)) features = lapply(sets, function(set) { txt = paste0(set, paste(rep(" ", no_chars - nchar(set)), collapse = "")) bar$inc(1L, txt) calculateFeatureSet(feat.object, set, control, ...) }) } else { features = lapply(sets, function(set) calculateFeatureSet(feat.object, set, control, ...)) } do.call(c, features) }