code
stringlengths
1
13.8M
summary.rmas <- function (object, stage = NULL, harvest=FALSE, ...) { cosa <- object if(length(names(cosa))>0){ if(harvest==FALSE) cosa<- cosa$vn else cosa <-cosa$harvest } nl <- length(cosa) time <- dim(cosa[[1]])[2] if (nl > 1) { abundances <- sapply(cosa, function(x) apply(x, 2, sum)) if (!is.null(stage)) abundances <- sapply(cosa, function(x) x[stage, ]) summary <- apply(abundances, 1, function(x) c(min(x), mean(x) - sd(x), mean(x), mean(x) + sd(x), max(x))) summary <- t(summary) summary <- data.frame(cbind(0:(time - 1), round(summary, 2)), row.names = 0:(time - 1)) names(summary) <- c("Time", "Minimum", "-1 S.D.", "Average", "+1 S.D.", "Maximum") } if (nl == 1) { abundances <- apply(cosa[[1]], 2, sum) if (!is.null(stage)) abundances <- apply(cosa, function(x) x[stage, ]) summary <- cbind(0:(time - 1), abundances) colnames(summary) <- c("Time", "Abundance") } summary <- data.frame(summary, row.names = NULL, check.names = FALSE) class(summary) <- c("summary.rmas", class(summary)) warnold <- options("warn") options(warn=-1) plot(summary) options(warn=warnold$warn) return(summary) }
smartAlign2 = function(start, end, range, plot = FALSE) { if(missing(end)) { end = start[, 2] start = start[, 1] } if(missing(range)) { range = range(c(start, end)) } if(0) { qqcat("start <- c(@{toString(start)})\n") qqcat("end <- c(@{toString(end)})\n") } if(sum(end - start) > range[2] - range[1]) { mid = (start + end)/2 od = order(mid) rk = rank(mid, ties.method = "random") h = end[od] - start[od] n = length(start) mid_diff = numeric(n); mid_diff[1] = 0 mid_diff[2:n] = h[2:n]/2 + h[1:(n-1)]/2 mid_radius = sum(h) - h[n]/2 - h[1]/2 a_1 = range[1] + h[1]/2 a_n = range[2] - h[n]/2 a = a_1 + cumsum(mid_diff)/mid_radius * (a_n - a_1) new_start = a - h/2 new_end = a + h/2 df = data.frame(start = new_start, end = new_end) return(df[rk, , drop = FALSE]) } ba = BoxArrange(start, end, range) if(plot) ba$plot() ba$box_pos() } box_overlap = function(x1, x2) { start1 = x1$start end1 = x1$end start2 = x2$start end2 = x2$end if(end1 < start2) { FALSE } else if(end2 < start1) { FALSE } else { TRUE } } Box = setRefClass("Box", fields = list( start = "numeric", end = "numeric", new_start = "numeric", new_end = "numeric", height = "numeric", mid = "numeric" ) ) Box$methods(initialize = function(start, end) { start <<- start end <<- end new_start <<- start new_end <<- end height <<- end - start mid <<- (start + end)/2 }) BoxCluster = setRefClass("BoxCluster", fields = list( start = "numeric", end = "numeric", height = "numeric", mid = "numeric", boxes = "list" ) ) BoxCluster$methods(add_box = function(box) { if(inherits(box, "Box")) { boxes <<- c(.self$boxes, list(box)) } else { boxes <<- c(.self$boxes, box$boxes) } s = min(sapply(.self$boxes, function(b) b$start)) e = max(sapply(.self$boxes, function(b) b$end)) mid <<- (s + e)/2 height <<- e - s start <<- s end <<- e invisible(NULL) }) BoxCluster$methods(flatten = function(range) { s = min(sapply(.self$boxes, function(b) b$start)) e = max(sapply(.self$boxes, function(b) b$end)) mid <<- (s + e)/2 height <<- sum(sapply(.self$boxes, function(b) b$height)) s2 = .self$mid - .self$height/2 e2 = .self$mid + .self$height/2 if(s2 < range[1]) { s2 = range[1] e2 = s2 + height } else if(e2 > range[2]) { e2 = range[2] s2 = e2 - height } start <<- s2 end <<- e2 .self$update_box_new_pos() }) BoxCluster$methods(update_box_new_pos = function() { h = sapply(.self$boxes, function(b) b$height) new_s = .self$start + cumsum(c(0, h[-length(h)])) new_e = .self$start + cumsum(h) bb = .self$boxes for(i in seq_along(bb)) { bb[[i]]$new_start = new_s[i] bb[[i]]$new_end = new_e[i] } boxes <<- bb }) BoxCluster$methods(move = function(x) { start <<- .self$start + x end <<- .self$end + x mid <<- .self$mid + x .self$update_box_new_pos() invisible(NULL) }) BoxCluster$methods(middle = function(original = TRUE) { if(original) { s = min(sapply(.self$boxes, function(b) b$start)) e = max(sapply(.self$boxes, function(b) b$end)) (s + e)/2 } else { .self$mid } }) BoxCluster$methods(show = function(x) { n = length(.self$boxes) qqcat("@{n} box@{ifelse(n > 1, 'es', '')}\n") qqcat("start: @{.self$start}\n") qqcat("end: @{.self$end}\n") qqcat("height: @{.self$height}\n") }) BoxArrange = setRefClass("BoxArrange", fields = list( box_clusters = "list", range = "numeric", rank = "integer", debug = "logical" ) ) BoxArrange$methods(initialize = function(start, end, range = range(c(start, end)), debug = FALSE) { if(sum(end - start) > range[2] - range[1]) { stop() } boxes = list() for(i in seq_along(start)) { boxes[[i]] = Box(start = start[i], end = end[i]) } mid = sapply(boxes, function(b) (b$start + b$end)/2) boxes = boxes[order(mid)] cl = list() cl[[1]] = BoxCluster() cl[[1]]$add_box(boxes[[1]]) i_cluster = 1 for(i in seq_along(boxes)[-1]) { if(box_overlap(cl[[i_cluster]], boxes[[i]])) { cl[[i_cluster]]$add_box(boxes[[i]]) } else { i_cluster = i_cluster + 1 cl[[i_cluster]] = BoxCluster() cl[[i_cluster]]$add_box(boxes[[i]]) } } for(i in seq_along(cl)) { cl[[i]]$flatten(range) } box_clusters <<- cl range <<- range rank <<- rank(mid, ties.method = "random") debug <<- debug if(debug) { .self$plot(main = "initialize") } .self$merge() if(debug) { .self$plot(main = "merge after initialization") } .self$adjust_to_range() if(debug) { .self$plot(main = "adjust to ranges") } .self$merge() if(debug) { .self$plot(main = "merge after adjusting to ranges") } }) BoxArrange$methods(merge = function() { cl = .self$box_clusters while(1) { merged = FALSE n_cluster = length(cl) for(i in seq_len(n_cluster)[-1]) { if(box_overlap(cl[[i]], cl[[i-1]])) { cl[[i-1]]$add_box(cl[[i]]) cl[[i]] = cl[[i-1]] cl[[i-1]] = NA merged = TRUE if(.self$debug) qqcat("cluster @{i-1} and @{i} are merged\n") } } if(!merged) { break } cl = cl[!sapply(cl, identical, NA)] for(i in seq_along(cl)) { cl[[i]]$flatten(.self$range) } } box_clusters <<- cl invisible(NULL) }) BoxArrange$methods(adjust_to_range = function() { cl = .self$box_clusters for(i in seq_along(cl)) { if(cl[[i]]$start < range[1]) { cl[[i]]$move(range[1] - cl[[i]]$start) } if(cl[[i]]$end > range[2]) { cl[[i]]$move(range[2] - cl[[i]]$end) } } box_clusters <<- cl .self$merge() invisible(NULL) }) BoxArrange$methods(n_cluster = function() { length(.self$box_clusters) }) BoxArrange$methods(box_pos = function(new = TRUE) { if(new) { pos_lt = lapply(.self$box_clusters, function(x) { do.call(rbind, lapply(x$boxes, function(b) { c(b$new_start, b$new_end) })) }) } else { pos_lt = lapply(.self$box_clusters, function(x) { do.call(rbind, lapply(x$boxes, function(b) { c(b$start, b$end) })) }) } pos = do.call(rbind, pos_lt) pos[.self$rank, , drop = FALSE] }) BoxArrange$methods(plot = function(main = "") { pos1_lt = lapply(.self$box_clusters, function(x) { do.call(rbind, lapply(x$boxes, function(b) { c(b$start, b$end) })) }) pos2_lt = lapply(.self$box_clusters, function(x) { do.call(rbind, lapply(x$boxes, function(b) { c(b$new_start, b$new_end) })) }) n = length(pos1_lt) oxpd = par("xpd") par(xpd = NA) graphics::plot(NULL, xlim = c(0, 4), ylim = range(c(.self$range, unlist(pos1_lt), unlist(pos2_lt))), ann = FALSE, axes = FALSE) for(i in seq_len(n)) { pos1 = pos1_lt[[i]] pos2 = pos2_lt[[i]] col = add_transparency(i, 0.5) rect(0.5, pos1[, 1], 1.5, pos1[, 2], col = col) rect(2.5, pos2[, 1], 3.5, pos2[, 2], col = col) segments(1.5, rowMeans(pos1), 2.5, rowMeans(pos2), col = i) start = .self$box_clusters[[i]]$start end = .self$box_clusters[[i]]$end rect(2.5, start, 3.5, end, border = i, col = NA, lwd = 2) } text(1, -0.02, "original", adj = c(0.5, 1)) text(3, -0.02, "adjusted", adj = c(0.5, 1)) rect(0, .self$range[1], 4, .self$range[2], col = NA, border = "black") title(qq("@{main}, @{n} clusters")) par(xpd = oxpd) readline(prompt = "enter to continue") })
test_that("str_alphord_nums works", { strings <- paste0("abc", 1:12) expect_equal( str_alphord_nums(strings), str_c("abc", c(paste0(0, 1:9), 10:12)) ) expect_equal( str_alphord_nums(c("01abc9def55", "5abc10def777", "99abc4def4")), c("01abc09def055", "05abc10def777", "99abc04def004") ) expect_equal( str_alphord_nums(c("abc9def55", "abc10def7")), c("abc09def55", "abc10def07") ) expect_equal( str_alphord_nums(c("abc9def55", "abc10def777", "abc4def4")), c("abc09def055", "abc10def777", "abc04def004") ) expect_error( str_alphord_nums(c("abc9def55", "abc9def5", "abc10xyz7")), paste( "The non-number bits of every string must be the", "same.\n * The first pair of strings with", "different non-number bits are strings 1 and", "3.\n * They are \"abc9def55\" and \"abc10xyz7\"" ), fixed = TRUE ) expect_error( str_alphord_nums(c("abc9def55", "9abc10def7")), "The strings must all have the same number of numbers." ) expect_error( str_alphord_nums(c("0abc9def55g", "abc10def7g0")), paste0( "It should either be the case that all strings start\\s?", "with.+numbers or that none of them do.+String number 1\\s?", "\"0abc9def55g\" does\\s?", "start with a number.+whereas string number 2\\s?", "\"abc10def7g0\" does\\s?", "not, start.+with a number." ) ) expect_error( str_alphord_nums("abc"), "Some of the input strings have no numbers in them." ) expect_equal(str_alphord_nums(1:10), c(paste0(0, 1:9), 10)) expect_equal(str_alphord_nums(character()), character()) })
context("Testing create_version_number()") date <- Sys.Date() datetime <- Sys.time() date_1 <- "01/01/2020" date_2 <- "01-01-2020" date_3 <- "01012020" date_4 <- "20200101" date_5 <- "01.01.2020" date_6 <- "2020.01.01" version_1 <- "0.1.0" version_2 <- "0.2.0" version_3 <- "1.1.1" version_4 <- "Inf" version_5 <- "NaN" version_6 <- "100000.100000.100000" output <- "0.20200101.0" output_1 <- "100000.20200101.100000" test_that("Sys.Date and Sys.time produce correct results", { testthat::expect_equal(create_version_number(date, "0.1.0"), create_version_number(date, "0.1.0")) testthat::expect_equal(create_version_number(datetime, "0.1.0"), create_version_number(datetime, "0.1.0")) testthat::expect_equal(create_version_number(datetime, "0.1.0"), create_version_number(date, "0.1.0")) }) test_that("create_version_number output is as expected", { testthat::expect_equal(create_version_number(date_1, version_1), create_version_number(date_2, version_1)) testthat::expect_equal(create_version_number(date_5, version_1), create_version_number(date_6, version_1)) testthat::expect_warning( testthat::expect_equal(create_version_number(date_3, version_1), create_version_number(date_4, version_1))) testthat::expect_equal(create_version_number(date_1, version_1), output) testthat::expect_equal(create_version_number(date_2, version_1), output) testthat::expect_equal(create_version_number(date_4, version_1), output) testthat::expect_equal(create_version_number(date_5, version_1), output) testthat::expect_equal(create_version_number(date_6, version_1), output) testthat::expect_equal(create_version_number(), version_1) testthat::expect_equal(create_version_number(date_4, "0"), output) testthat::expect_equal(create_version_number(date_4, "0.0"), output) testthat::expect_equal(create_version_number(date_4, major = "0", minor = "0"), output) }) test_that("create_version_number validation works as expected", { testthat::expect_error(create_version_number("01-01-20", version_1)) testthat::expect_error(create_version_number("20-01-01", version_1)) testthat::expect_error(create_version_number(date, version_4)) testthat::expect_error(create_version_number(date, version_5)) testthat::expect_error(create_version_number("200101", version_1)) testthat::expect_error(create_version_number("18150101", version_1)) testthat::expect_warning(create_version_number("01022020", version_1)) })
KernSec <- function( x, xgridsize=100, xbandwidth, range.x ) { deadspace <- 1.5 flag.type.II <- 0 flag.range <- 0 if(missing(xbandwidth)) { xbandwidths <- bandwidthselect(as.vector(na.omit(x)), bandwidths=FALSE) if(missing(range.x)) { xords <- rangeselect(x, rnge=FALSE, as.integer(xgridsize), xbandwidths, deadspace) if(any(is.na(x)) == TRUE){warning("NAs in x - removing: "); x <- as.vector(na.omit(x))} flag.range <- 1 } if((! flag.range) && (! missing(range.x)) && (length(range.x) == 2)) { xords <- rangeselect(x, rnge=range.x, as.integer(xgridsize), xbandwidths, deadspace) if(any(is.na(x)) == TRUE){warning("NAs in x - removing: "); x <- as.vector(na.omit(x))} flag.range <- 1 } if((! flag.range) && (! missing(range.x)) && (length(range.x) > 5)) { xords <- range.x if(any(is.na(xords)) == TRUE){warning("NAs in range.x - removing: "); x <- as.vector(na.omit(xords))} if(any(is.na(x)) == TRUE){warning("NAs in x - removing: "); x <- as.vector(na.omit(x))} flag.range <- 1 } } if((! missing(xbandwidth)) && (length(xbandwidth) == 1)) { xbandwidths <- bandwidthselect(as.vector(na.omit(x)), bandwidths=xbandwidth) if(missing(range.x)) { xords <- rangeselect(x, rnge=FALSE, as.integer(xgridsize), xbandwidths, deadspace) if(any(is.na(x)) == TRUE){warning("NAs in x - removing: "); x <- as.vector(na.omit(x))} flag.range <- 1 } if((! flag.range) && (! missing(range.x)) && (length(range.x) == 2)) { xords <- rangeselect(x, rnge=range.x, as.integer(xgridsize), xbandwidths, deadspace) if(any(is.na(x)) == TRUE){warning("NAs in x - removing: "); x <- as.vector(na.omit(x))} flag.range <- 1 } if((! flag.range) && (! missing(range.x)) && (length(range.x) > 5)) { xords <- range.x if(any(is.na(xords)) == TRUE){warning("NAs in range.x - removing: "); x <- as.vector(na.omit(xords))} if(any(is.na(x)) == TRUE){warning("NAs in x - removing: "); x <- as.vector(na.omit(x))} flag.range <- 1 } } if((! missing(xbandwidth)) && (length(xbandwidth) == length(x))) { xbandwidths <- xbandwidth z <- data.frame(x, xbandwidth) if(any(is.na(z)) == TRUE){warning("NAs in bandwidths or/and data - removing: "); z <- na.omit(z)} x <- z$x; xbandwidths <- z$xbandwidth if(missing(range.x)) { xords <- rangeselect(x, rnge=FALSE, as.integer(xgridsize), xbandwidths, deadspace) flag.range <- 1 } if((! flag.range) && (! missing(range.x)) && (length(range.x) == 2)) { xords <- rangeselect(x, rnge=range.x, as.integer(xgridsize), xbandwidths, deadspace) flag.range <- 1 } if((! flag.range) && (! missing(range.x)) && (length(range.x) > 5)) { xords <- range.x if(any(is.na(xords)) == TRUE){warning("NAs in range.x - removing: "); x <- as.vector(na.omit(xords))} flag.range <- 1 } } if((! missing(xbandwidth)) && (! missing(range.x)) && (length(xbandwidth) == length(range.x))) { flag.type.II <- 1 z <- data.frame(range.x, xbandwidth) if(any(is.na(z)) == TRUE){warning("NAs in bandwidths or/and ordinates - removing: "); z <- na.omit(z)} xords <- z$range.x; xbandwidths <- z$xbandwidth if(any(is.na(x)) == TRUE){warning("NAs in x - removing: "); x <- as.vector(na.omit(x))} flag.range <- 1 } if((! missing(xbandwidth)) && (length(xbandwidth) == xgridsize)) { flag.type.II <- 1 if(any(is.na(x)) == TRUE){warning("NAs in x - removing: "); x <- as.vector(na.omit(x))} xbandwidths <- xbandwidth if(any(is.na(xbandwidths)) == TRUE){warning("NAs in bandwidths - removing: "); xbandwidths <- as.vector(na.omit(xbandwidth))} if(missing(range.x)) { xords <- rangeselect(x, rnge=FALSE, as.integer(xgridsize), xbandwidths, deadspace) flag.range <- 1 } if((! flag.range) && (! missing(range.x)) && (length(range.x) == 2)) { xords <- rangeselect(x, rnge=range.x, as.integer(xgridsize), xbandwidths, deadspace) flag.range <- 1 } } if((! missing(xbandwidth)) && (! missing(range.x))) {if((length(x) == length(range.x)) && (length(x) == length(xbandwidth))){stop("too many inputs of same length")}} if(! flag.range){stop("undefined problem with input")} xordslen <- length(xords) est <- rep(0, xordslen) out <- .C( "GenKernSec", as.double(x), as.integer(length(x)), as.double(xords), as.double(xbandwidths), as.double(est), as.integer(xordslen), as.integer(flag.type.II), PACKAGE="GenKern" ) yden <- out[[5]] op <- list(xords, yden); names(op) <- c("xords", "yden") return(op) }
reord <- function(...) corReorder(...)
possible_observed_comparisons <- function(drug_names, obs_comp) { if (length(drug_names) < 3) { stop("This function is *not* relevant for a pairwise meta-analysis", call. = FALSE) } nt <- length(drug_names) poss_pair_comp <- data.frame(t(combn(1:nt, 2))[, 2], t(combn(1:nt, 2))[, 1]) poss_pair_comp$comp <- paste0(poss_pair_comp[, 1], "vs", poss_pair_comp[, 2]) colnames(poss_pair_comp) <- c("treat1", "treat2", "comp") observed_comp <- poss_pair_comp[is.element(poss_pair_comp$comp, obs_comp), ] for (i in sort(unique(unlist(poss_pair_comp[, 1])))) { poss_pair_comp[poss_pair_comp$treat1 == i, 1] <- drug_names[i] } for (i in sort(unique(unlist(poss_pair_comp[, 2])))) { poss_pair_comp[poss_pair_comp$treat2 == i, 2] <- drug_names[i] } poss_pair_comp$comp_name <- paste(poss_pair_comp[, 1], "vs", poss_pair_comp[, 2]) for (i in sort(unique(unlist(observed_comp[, 1])))) { observed_comp[observed_comp$treat1 == i, 1] <- drug_names[i] } for (i in sort(unique(unlist(observed_comp[, 2])))) { observed_comp[observed_comp$treat2 == i, 2] <- drug_names[i] } observed_comp$comp_name <- paste(observed_comp[, 1], "vs", observed_comp[, 2]) return(list(poss_comp = data.frame(ID = seq_len(length(poss_pair_comp$comp)), poss_pair_comp), obs_comp = observed_comp)) }
lrMix = function(profiles, Freqs){ N = length(profiles) nLoci = length(Freqs$loci) results = matrix(0, nrow = N, ncol = nLoci) for(i in 1:N){ results[i,] = .LRmix(profiles[[i]][[1]], profiles[[i]][[2]], Freqs$freqs) } colnames(results) = Freqs$loci return(results) }
library(survival) fit <- survfit(Surv(futime, fustat) ~rx, data=ovarian) temp1 <- summary(fit) temp2 <- summary(fit, scale=365.25) all.equal(temp1$time/365.25, temp2$time) all.equal(temp1$rmean.endtime/365.25, temp2$rmean.endtime) all.equal(temp1$table[,5:6]/365.25, temp2$table[,5:6]) temp <- names(fit) temp <- temp[!temp %in% c("time", "table", "rmean.endtime")] all.equal(temp1[temp], temp2[temp]) temp1 <- summary(fit, rmean=300) temp2 <- summary(fit, rmean=300, scale=365.25) all.equal(temp1$time/365.25, temp2$time) all.equal(temp1$rmean.endtime/365.25, temp2$rmean.endtime) all.equal(temp1$table[,5:6]/365.25, temp2$table[,5:6]) all.equal(temp1[temp], temp2[temp]) etime <- with(mgus2, ifelse(pstat==0, futime, ptime)) event <- with(mgus2, ifelse(pstat==0, 2*death, 1)) event <- factor(event, 0:2, labels=c("censor", "pcm", "death")) mfit <- survfit(Surv(etime, event) ~ sex, mgus2) temp1 <- summary(mfit) temp2 <- summary(mfit, scale=12) all.equal(temp1$time/12, temp2$time) all.equal(temp1$rmean.endtime/12, temp2$rmean.endtime) all.equal(temp1$table[,3]/12, temp2$table[,3]) temp <- names(temp1) temp <- temp[!temp %in% c("time", "table", "rmean.endtime")] all.equal(temp1[temp], temp2[temp]) temp1 <- summary(mfit, rmean=240) temp2 <- summary(mfit, rmean=240, scale=12) all.equal(temp1$time/12, temp2$time) all.equal(temp1$rmean.endtime/12, temp2$rmean.endtime) all.equal(temp1$table[,3]/12, temp2$table[,3]) all.equal(temp1[temp], temp2[temp]) m1 <- mfit[1,] m2 <- mfit[2,] s1 <- summary(m1, times=c(0,100, 200, 300)) s2 <- summary(m2, times=c(0,100, 200, 300)) s3 <- summary(mfit, times=c(0,100, 200, 300)) tfun <- function(what) { if (is.matrix(s3[[what]])) all.equal(rbind(s1[[what]], s2[[what]]), s3[[what]]) else all.equal(c(s1[[what]], s2[[what]]), s3[[what]]) } tfun('n') tfun("time") tfun("n.risk") tfun("n.event") tfun("n.censor") tfun("pstate") all.equal(rbind(s1$p0, s2$p0), s3$p0, check.attributes=FALSE) tfun("std.err") tfun("lower") tfun("upper") temp <- rbind(0, 0, colSums(m1$n.event[m1$time <= 100,]), colSums(m1$n.event[m1$time <= 200, ]), colSums(m1$n.event[m1$time <= 300, ])) all.equal(s1$n.event, apply(temp,2, diff)) temp <- rbind(0, 0, colSums(m2$n.event[m2$time <= 100,]), colSums(m2$n.event[m2$time <= 200, ]), colSums(m2$n.event[m2$time <= 300, ])) all.equal(s2$n.event, apply(temp,2, diff)) temp <- c(0, 0,sum(m1$n.censor[m1$time <= 100]), sum(m1$n.censor[m1$time <= 200]), sum(m1$n.censor[m1$time <= 300])) all.equal(s1$n.censor, diff(temp)) s1 <- summary(fit[1], times=c(0, 200, 400, 600)) s2 <- summary(fit[2], times=c(0, 200, 400, 600)) s3 <- summary(fit, times=c(0, 200, 400, 600)) tfun('n') tfun("time") tfun("n.risk") tfun("n.event") tfun("n.censor") tfun("surv") tfun("std.err") tfun("lower") tfun("upper") f2 <- fit[2] temp <- c(0, 0, sum(f2$n.event[f2$time <= 200]), sum(f2$n.event[f2$time <= 400]), sum(f2$n.event[f2$time <= 600])) all.equal(s2$n.event, diff(temp)) f1 <- fit[1] temp <- c(0, 0,sum(f1$n.censor[f1$time <= 200]), sum(f1$n.censor[f1$time <= 400]), sum(f1$n.censor[f1$time <= 600])) all.equal(s1$n.censor, diff(temp)) s1 <- summary(fit[1]) s2 <- summary(fit[2]) s3 <- summary(fit) tfun('n') tfun("time") tfun("n.risk") tfun("n.event") tfun("n.censor") tfun("surv") tfun("std.err") tfun("lower") tfun("upper") s1 <- summary(mfit[1,]) s2 <- summary(mfit[2,]) s3 <- summary(mfit) tfun('n') tfun("time") tfun("n.risk") tfun("n.event") tfun("n.censor") tfun("surv") tfun("std.err") tfun("lower") tfun("upper")
get_type <- function(x, strict = FALSE) { if (!is.phone(x)) stop("`x` must be a vector of class `phone`.", call. = FALSE) phone_util <- .get_phoneNumberUtil() out <- phone_apply(x, function(pn) { .jstrVal(.jcall(phone_util, "Lcom/google/i18n/phonenumbers/PhoneNumberUtil$PhoneNumberType;", "getNumberType", pn)) }, character(1)) if (strict) out[!is_valid(x)] <- NA_character_ out } get_supported_types <- function() { .get_phoneNumberType() } get_types_for_region <- function(x) { validate_phone_region(x) lapply(x, .getSupportedTypesForRegion) }
volume_calculation <- function(point_counts_raw, point_density, quantile, verbose=TRUE) { if (verbose==TRUE) {cat('Beginning volume calculation... ')} tabulated_counts <- cbind((1:max(point_counts_raw)), (tabulate(point_counts_raw))) if (verbose==TRUE) {cat('done. \n')} weighted_count = tabulated_counts[,2] / tabulated_counts[,1] cumulatesum = cumsum(weighted_count)/sum(weighted_count) qindex = head(which(cumulatesum >= quantile),n=1) qval = c(0,cumulatesum)[qindex] final_volume = sum(weighted_count[qindex:length(weighted_count)]) / point_density return(list(final_volume = final_volume, index_out = qindex, quantile_obtained = qval)) }
utils::globalVariables(c("k","jaccard","min.agreement","community_coexist","community_membership","community_membership_boot", "boost.community","scheme2.module","agreement","scheme2.exp","network.stability")) threshold.select <- function(data.input,threshold.seq, B=20, cor.method,large.size, no_cores=8,PermuNo = 10, scheme_2 = FALSE){ myFuncCmp <- cmpfun(network.stability) result<-c() for (i in 1:length(threshold.seq)) { k=threshold.seq[i] result[[i]]<-myFuncCmp(data.input=data.input,threshold=k, B=B, PermuNo = PermuNo, cor.method=cor.method,large.size=large.size, scheme_2 = scheme_2) } if(length(result)==0)print('Something wrong') gc() clst.ref<-list() obs_wise<-list() overall<-c() mscore<-list() mscore.exp<-list() minvalue<-c() obsvalue<-list() expvalue<-c() ref<-c() data<-list() graph<-list() adjacency<-list() if(scheme_2==TRUE){ data2<-list() graph2<-list() adjacency2<-list() } for(i in 1:length(result)){ clst.ref[[i]]<-result[[i]]$stabilityresult$membership obs_wise[[i]]<-result[[i]]$stabilityresult$obs_wise overall[i]<-result[[i]]$stabilityresult$overall ref[i]<-result[[i]]$stabilityresult$ref mscore[[i]]<-result[[i]]$modularityresult$mscore mscore.exp[[i]]<-result[[i]]$modularityresult$mscore.exp minvalue[i]<-result[[i]]$jaccardresult$min obsvalue[[i]]<-result[[i]]$jaccardresult$obsvalue expvalue[i]<-result[[i]]$jaccardresult$expvalue data[[i]]<-result[[i]]$originalinformation$data graph[[i]]<-result[[i]]$originalinformation$graph adjacency[[i]]<-result[[i]]$originalinformation$adjacency if(scheme_2==TRUE){ data2[[i]]<-result[[i]]$originalinformation$data2 graph2[[i]]<-result[[i]]$originalinformation$graph2 adjacency2[[i]]<-result[[i]]$originalinformation$adjacency2 } } stabilityresult<-list() stabilityresult$membership <- clst.ref stabilityresult$obs_wise <- obs_wise stabilityresult$overall <- overall stabilityresult$ref<- ref modularityresult<-list() modularityresult$mscore=mscore modularityresult$mscore.exp=mscore.exp jaccardresult<-list() jaccardresult$min=minvalue jaccardresult$obsvalue=obsvalue jaccardresult$expvalue=expvalue originalinformation<-list() originalinformation$data=data originalinformation$graph=graph originalinformation$adjacency=adjacency if(scheme_2==TRUE){ originalinformation$data2=data2 originalinformation$graph2=graph2 originalinformation$adjacency2=adjacency2 } result<-list(jaccardresult=jaccardresult, stabilityresult=stabilityresult, modularityresult=modularityresult, originalinformation=originalinformation, threshold=threshold.seq) return(result) }
svgviewr.circles <- function(x, file=NULL, y=NULL, col=NULL, col.fill="black", col.stroke="black", z.index=0, layer="", label="", r=1, lwd=2, opacity.stroke=1, opacity.fill=1, append=TRUE, tag.name="point"){ return_val <- svgviewr.points(x, file, y, type='p', col, col.fill, col.stroke, z.index, layer, label, cex=r, lwd, opacity.stroke, opacity.fill, append, tag.name="circle") return_val }
NULL if(getRversion() >= "2.15.1") { utils::globalVariables(c("id", "subject_impute_futility", "subject_impute_success", "treatment")) }
PTaxes <- function( strike,dip,rake) { Vnorm <-function(X){ return( sqrt(sum(X^2)) ) } N = length(strike) n.1 =matrix(ncol=3, nrow=N) u.1 =matrix(ncol=3, nrow=N) P.osa=matrix(ncol=3, nrow=N) T.osa=matrix(ncol=3, nrow=N) P.azimuth= rep(NA, N) T.azimuth= rep(NA, N) T.theta= rep(NA, N) P.theta= rep(NA, N) P.x= rep(NA, N) P.y= rep(NA, N) T.x= rep(NA, N) T.y= rep(NA, N) n.1[,1] = -sin(dip*pi/180)*sin(strike*pi/180) n.1[,2] = sin(dip*pi/180)*cos(strike*pi/180) n.1[,3] = -cos(dip*pi/180) u.1[,1] = cos(rake*pi/180)*cos(strike*pi/180) + cos(dip*pi/180)*sin(rake*pi/180)*sin(strike*pi/180) u.1[,2] = cos(rake*pi/180)*sin(strike*pi/180) - cos(dip*pi/180)*sin(rake*pi/180)*cos(strike*pi/180) u.1[,3] = -sin(rake*pi/180)*sin(dip*pi/180) projekce = -1 for ( i in 1 : N ) { P.osa[i,] = (n.1[i,]-u.1[i,])/Vnorm(n.1[i,]-u.1[i,]) T.osa[i,] = (n.1[i,]+u.1[i,])/Vnorm(n.1[i,]+u.1[i,]) if (P.osa[i,3]>0) { P.osa[i,1]=-P.osa[i,1]; P.osa[i,2]=-P.osa[i,2]; P.osa[i,3]=-P.osa[i,3] } if (T.osa[i,3]>0) { T.osa[i,1]=-T.osa[i,1]; T.osa[i,2]=-T.osa[i,2]; T.osa[i,3]=-T.osa[i,3] } fi = atan(abs(P.osa[i,1]/P.osa[i,2]))*180/pi if (P.osa[i,1]>0 & P.osa[i,2]>0) { P.azimuth[i] = fi } if (P.osa[i,1]>0 & P.osa[i,2]<0) { P.azimuth[i] = 180-fi } if (P.osa[i,1]<0 & P.osa[i,2]<0) { P.azimuth[i] = fi+180 } if (P.osa[i,1]<0 & P.osa[i,2]>0) { P.azimuth[i] = 360-fi } P.theta[i] = acos(abs(P.osa[i,3]))*180/pi fi = atan(abs(T.osa[i,1]/T.osa[i,2]))*180/pi if (T.osa[i,1]>0 & T.osa[i,2]>0){ T.azimuth[i] = fi } if (T.osa[i,1]>0 & T.osa[i,2]<0){ T.azimuth[i] = 180-fi } if (T.osa[i,1]<0 & T.osa[i,2]<0){ T.azimuth[i] = fi+180 } if (T.osa[i,1]<0 & T.osa[i,2]>0){ T.azimuth[i] = 360-fi } T.theta[i] = acos(abs(T.osa[i,3]))*180/pi P.x[i] = sqrt(2.)*projekce*sin(P.theta[i]*pi/360)*sin(P.azimuth[i]*pi/180) P.y[i] = sqrt(2.)*projekce*sin(P.theta[i]*pi/360)*cos(P.azimuth[i]*pi/180) T.x[i] = sqrt(2.)*projekce*sin(T.theta[i]*pi/360)*sin(T.azimuth[i]*pi/180) T.y[i] = sqrt(2.)*projekce*sin(T.theta[i]*pi/360)*cos(T.azimuth[i]*pi/180) } points(P.y,P.x,col='green') text(P.y,P.x,labels='P', pos=3) points(T.y,T.x,col='green', pch=3) text(T.y,T.x,labels='T', pos=4) return(NULL) }
corr_dist <- function(method) { function(x) as.dist(1 - cor(t(x), method = method)) } pearson <- corr_dist("pearson") spearman <- corr_dist("spearman") kendall <- corr_dist("kendall")
blockSim = function(N, Freqs, rel = "UN", ibsthresh = NULL, kithresh = NULL, code = 1, falseNeg = TRUE, BlockSize = N/10, showProgress = FALSE){ rel = toupper(rel) if(!grepl("(UN|FS|PC)", rel)){ stop("rel must be one of 'UN', 'FS' or 'PC'") } nBlocks = N / BlockSize if(is.null(ibsthresh) & is.null(kithresh)) stop("You must specify one or both of ibsthresh or kithresh") nResults = 0 if(is.null(ibsthresh) & !is.null(kithresh)){ nResults = length(kithresh) ibsthresh = rep(0, nResults) }else if(is.null(kithresh) & !is.null(ibsthresh)){ nResults = length(ibsthresh) kithresh = rep(0, nResults) }else{ if(length(ibsthresh) != length(kithresh)){ stop("ibsthresh and kithresh must be the same length") }else{ nResults = length(ibsthresh) } } if(nResults == 0) stop("Nothing to count") nTotal = rep(0, nResults) if(showProgress){ pb = txtProgressBar(min = 0, max = nBlocks, style = 3) } if(rel == "UN"){ for(block in 1:nBlocks){ Prof1 = randomProfiles(Freqs$freqs, BlockSize) Prof2 = randomProfiles(Freqs$freqs, BlockSize) count = blockStatCounts(Prof1, Prof2, BlockSize, Freqs$freqs, code, falseNeg, ibsthresh, kithresh, nResults) nTotal = nTotal + count if(showProgress){ setTxtProgressBar(pb, block) } } }else if(rel == "FS"){ for(block in 1:nBlocks){ Prof1 = randomProfiles(Freqs$freqs, BlockSize) Prof2 = randomSibs(Prof1, Freqs$freqs, BlockSize) count = blockStatCounts(Prof1, Prof2, BlockSize, Freqs$freqs, code, falseNeg, ibsthresh, kithresh, nResults) nTotal = nTotal + count if(showProgress){ setTxtProgressBar(pb, block) } } }else if(rel == "PC"){ for(block in 1:nBlocks){ Prof1 = randomProfiles(Freqs$freqs, BlockSize) Prof2 = randomChildren(Prof1, Freqs$freqs, BlockSize) count = blockStatCounts(Prof1, Prof2, BlockSize, Freqs$freqs, code, falseNeg, ibsthresh, kithresh, nResults) nTotal = nTotal + count if(showProgress){ setTxtProgressBar(pb, block) } } } if(showProgress){ close(pb) } return(list(nTotal = nTotal, N = N, p = nTotal / N)) }
rand_forest <- function(mode = "unknown", engine = "ranger", mtry = NULL, trees = NULL, min_n = NULL) { args <- list( mtry = enquo(mtry), trees = enquo(trees), min_n = enquo(min_n) ) new_model_spec( "rand_forest", args = args, eng_args = NULL, mode = mode, method = NULL, engine = engine ) } print.rand_forest <- function(x, ...) { cat("Random Forest Model Specification (", x$mode, ")\n\n", sep = "") model_printer(x, ...) if(!is.null(x$method$fit$args)) { cat("Model fit template:\n") print(show_call(x)) } invisible(x) } update.rand_forest <- function(object, parameters = NULL, mtry = NULL, trees = NULL, min_n = NULL, fresh = FALSE, ...) { eng_args <- update_engine_parameters(object$eng_args, ...) if (!is.null(parameters)) { parameters <- check_final_param(parameters) } args <- list( mtry = enquo(mtry), trees = enquo(trees), min_n = enquo(min_n) ) args <- update_main_parameters(args, parameters) if (fresh) { object$args <- args object$eng_args <- eng_args } else { null_args <- map_lgl(args, null_value) if (any(null_args)) args <- args[!null_args] if (length(args) > 0) object$args[names(args)] <- args if (length(eng_args) > 0) object$eng_args[names(eng_args)] <- eng_args } new_model_spec( "rand_forest", args = object$args, eng_args = object$eng_args, mode = object$mode, method = NULL, engine = object$engine ) } translate.rand_forest <- function(x, engine = x$engine, ...) { if (is.null(engine)) { message("Used `engine = 'ranger'` for translation.") engine <- "ranger" } x <- translate.default(x, engine, ...) arg_vals <- x$method$fit$args if (x$engine == "spark") { if (x$mode == "unknown") { rlang::abort( glue::glue("For spark random forests models, the mode cannot ", "be 'unknown' if the specification is to be translated.") ) } else { arg_vals$type <- x$mode } if (any(names(arg_vals) == "feature_subset_strategy") && isTRUE(is.numeric(quo_get_expr(arg_vals$feature_subset_strategy)))) { arg_vals$feature_subset_strategy <- paste(quo_get_expr(arg_vals$feature_subset_strategy)) } } if (engine == "ranger") { if (any(names(arg_vals) == "importance")) { if (isTRUE(is.logical(quo_get_expr(arg_vals$importance)))) { rlang::abort("`importance` should be a character value. See ?ranger::ranger.") } } if (x$mode == "classification" && !any(names(arg_vals) == "probability")) { arg_vals$probability <- TRUE } } if (any(names(arg_vals) == "mtry") & engine != "cforest") { arg_vals$mtry <- rlang::call2("min_cols", arg_vals$mtry, expr(x)) } if (any(names(arg_vals) == "mtry") & engine == "cforest") { arg_vals$mtry <- rlang::call2("min_cols", arg_vals$mtry, expr(data)) } if (any(names(arg_vals) == "min.node.size")) { arg_vals$min.node.size <- rlang::call2("min_rows", arg_vals$min.node.size, expr(x)) } if (any(names(arg_vals) == "minsplit" & engine == "cforest")) { arg_vals$minsplit <- rlang::call2("min_rows", arg_vals$minsplit, expr(data)) } if (any(names(arg_vals) == "nodesize")) { arg_vals$nodesize <- rlang::call2("min_rows", arg_vals$nodesize, expr(x)) } if (any(names(arg_vals) == "min_instances_per_node")) { arg_vals$min_instances_per_node <- rlang::call2("min_rows", arg_vals$min_instances_per_node, expr(x)) } x$method$fit$args <- arg_vals x } check_args.rand_forest <- function(object) { invisible(object) }
card_pieces <- function(title, text, image, link, footer, header, layout, border, corners) { title <- make_title(title, text) text <- make_text(text, title) image <- make_image(image, layout, corners, border) footer <- make_footer(footer, corners, border) header <- make_header(header, corners, border) if(!is_na(link)) { title <- htmltools::a(title, href = link) image <- htmltools::a(image, href = link, style = image_link_style()) } return(list(title = title, text = text, image = image, footer = footer, header = header)) } make_title <- function(title, text) { if(is_na(title)) return(NULL) return(htmltools::h5( title, class = title_class(!is_na(text)) )) } make_text <- function(text, title) { if(is_na(text)) return(NULL) return(htmltools::p( text, class = text_class(!is_na(title)) )) } make_image <- function(image, layout, corners, border) { if(is_na(image)) return(NULL) return(htmltools::img( src = image, class = image_class(layout), style = image_style(corners, border, layout) )) } make_footer <- function(footer, corners, border) { if(is_na(footer)) return(NULL) return(htmltools::div( footer, class = footer_class(), style = footer_style(corners, border) )) } make_header <- function(header, corners, border) { if(is_na(header)) return(NULL) return(htmltools::div( header, class = header_class(), style = header_style(corners, border) )) }
`colwheel` <- function(v=1, BACK="black") { if(missing(v)) { v=1 } if(missing(BACK)) { BACK="white" } opar = par(no.readonly=TRUE) require(RPMG) labs = c("DONE", "REFRESH", "SHOW", "CLEAR", "BACK.BW", "BACK", "CHANGEV") changev<-function(g, TE="Click in Bar for change of v") { pct1 = .25 pct2 = .35 u = par("usr") x = c(u[1] , u[2]) y = c(u[3] , u[4]) curx = x = c(x[1]+pct1*diff(x), x[2]-pct1*diff(x)) y = c(y[1]+pct2*diff(y), y[2]-pct2*diff(y)) rect(x[1], y[1], x[2], y[2], col=rgb(1,.7, .7), border="blue", lwd=2) text(x[1], mean(y), labels=0, pos=4) text(x[2], mean(y), labels=1, pos=2) curx = x[1] + diff(x)*g$v text(mean(x), mean(y), TE) segments(curx, y[1] , curx, y[2] , col='red', lwd=2) L = locator(1, type="p" ) new = (L$x-x[1])/diff(x) if(new>1) new = 1 if(new<0) new = 0 invisible(new) } NLABS = length(labs) NOLAB = NLABS +1000 pchlabs = c(rep(1,length(labs))) if(identical(BACK, "black")) { cmain = rgb(.7,.7,.7) par(bg=rgb(0.1,0.1,0.1), fg=rgb(1,1,1), col.axis=rgb(1,1,1), col.lab=rgb(1,1,1), col.main=cmain , col.sub=rgb(1,1,1) ) colabs = c(rep('white',length(labs))) } else { cmain = rgb(1-.7, 1-.7, 1-.7) par(bg=rgb(1,1,1), fg=rgb(0,0,0),col.axis=rgb(0,0,0),col.lab=rgb(0,0,0), col.main=cmain ,col.sub=rgb(0,0,0) ) colabs = c(rep('black',length(labs))) } BIGMESH = VVwheel( v=v) RY = BIGMESH$RY rye = range(c(BIGMESH$RX , BIGMESH$RX+diff(BIGMESH$RY))) littley = .2*abs(diff(BIGMESH$RY)) gv = list(BIGMESH=BIGMESH, RY=RY ,v=v, labs=labs, colabs=colabs, pchlabs=pchlabs) CWreplot<-function(gv) { VVwheel(BIGMESH=gv$BIGMESH, v=gv$v) buttons = rowBUTTONS(gv$labs, col=gv$colabs, pch=gv$pchlabs) return(buttons) } buttons = CWreplot(gv) zloc = list(x=NULL, y=NULL) sloc = zloc DF = NULL MAINdev = dev.cur() PALdev = NULL while(TRUE) { iloc = locator(1,type='p') zloc = list(x=c(zloc$x,iloc$x), y=c(zloc$y, iloc$y)) Nclick = length(iloc$x) if(is.null(iloc$x)) { par(opar); return(zloc) } K = whichbutt(iloc ,buttons) if(iloc$x>=BIGMESH$RX[1] & iloc$x<=BIGMESH$RX[2] & iloc$y>=rye[1] & iloc$y<=rye[2]) { Wcols = wheelrgb(iloc, gv$v, gv$RY) rect(BIGMESH$RX[1],rye[1]-littley/2, BIGMESH$RX[1]+littley, rye[1]-littley, col=Wcols, border=NA, xpd=TRUE) } if(K[Nclick] == match("DONE", labs, nomatch = NOLAB)) { nloc=length(zloc$x)-1 zloc = list(x=zloc$x[1:nloc], y=zloc$y[1:nloc]) thecols = wheelrgb(zloc, gv$v, gv$RY) cprint(thecols) DF = thecols zloc = list(x=NULL, y=NULL) break; } if(K[Nclick] == match("REFRESH", labs, nomatch = NOLAB)) { buttons =CWreplot(gv) next } if(K[Nclick] == match("CHANGEV", labs, nomatch = NOLAB)) { newv = changev(gv, TE="Click in Bar for change of v") gv$v = newv BIGMESH = VVwheel( v=v) RY = BIGMESH$RY rye = range(c(BIGMESH$RX , BIGMESH$RX+diff(BIGMESH$RY))) littley = .2*abs(diff(BIGMESH$RY)) gv$BIGMESH=BIGMESH gv$RY=RY buttons =CWreplot(gv) next } if(K[Nclick] == match("BACK.BW", labs, nomatch = NOLAB)) { if( identical(BACK, "black") ) { BACK="white" } else{ BACK="black" } if(identical(BACK, "black")) { cmain = rgb(.7,.7,.7) par(bg=rgb(0.1,0.1,0.1), fg=rgb(1,1,1),col.axis=rgb(1,1,1),col.lab=rgb(1,1,1),col.main=cmain ,col.sub=rgb(1,1,1) ) gv$colabs = c(rep('white',length(labs))) gv$pchlabs = c(rep(1,length(labs))) } else { cmain = rgb(1-.7, 1-.7, 1-.7) par(bg=rgb(1,1,1), fg=rgb(0,0,0),col.axis=rgb(0,0,0),col.lab=rgb(0,0,0),col.main=cmain ,col.sub=rgb(0,0,0) ) gv$colabs = c(rep('black',length(labs))) gv$pchlabs = c(rep(1,length(labs))) } buttons = CWreplot(gv) next } if(K[Nclick] == match("BACK", labs, nomatch = NOLAB)) { nloc=length(zloc$x)-1 if(nloc<1) next zloc = list(x=zloc$x[nloc], y=zloc$y[nloc]) thecols = wheelrgb(zloc, gv$v, gv$RY) aa = col2rgb(thecols) print(paste(sep=" ", thecols, paste(aa, collapse=" ") )) aa = col2rgb(thecols) bb = c(255-aa[1], 255-aa[2], 255-aa[3]) aacomp = rgb(bb[1], bb[2], bb[3], maxColorValue=255) print(paste(sep=" ", aacomp, paste( bb, collapse=" "))) cmain = rgb(.7,.7,.7) BACK = thecols par(bg=thecols, fg=aacomp ,col.axis=rgb(1,1,1),col.lab=rgb(1,1,1),col.main=cmain ,col.sub=rgb(1,1,1) ) gv$colabs = c(rep(aacomp,length(labs))) gv$pchlabs = c(rep(1,length(labs))) buttons = CWreplot(gv) zloc = list(x=NULL, y=NULL) next } if(K[Nclick]==match("SHOW", labs, nomatch = NOLAB) ) { nloc=length(zloc$x)-1 zloc = list(x=zloc$x[1:nloc], y=zloc$y[1:nloc]) thecols = wheelrgb(zloc, gv$v, gv$RY) print(thecols) cprint(thecols) DF = thecols print(PALdev) if( is.null(PALdev) ) { dev.new(); PALdev=dev.cur(); print(PALdev) } else { dev.set(PALdev) } SHOWPAL(thecols, BACK=BACK, NAME=TRUE) dev.set( MAINdev) next } if(K[Nclick]==match("CLEAR", labs, nomatch = NOLAB) ) { DF = NULL buttons = CWreplot(gv) zloc = list(x=NULL, y=NULL) next } } par(opar) if(!is.null(DF)) invisible(DF) }
NULL nse_preopen_nifty <- function(clean_names = TRUE) { url <- "https://www1.nseindia.com/live_market/dynaContent/live_analysis/pre_open/nifty.json" nse_preopen_base(url, clean_names) } nse_preopen_nifty_bank <- function(clean_names = TRUE) { url <- "https://www1.nseindia.com/live_market/dynaContent/live_analysis/pre_open/niftybank.json" nse_preopen_base(url, clean_names) }
remote_sha <- function(...){ getFromNamespace('remote_sha', 'remotes')(...) } github_remote <- function(...){ getFromNamespace('github_remote', 'remotes')(...) } parse_git_repo <- function(...){ getFromNamespace('parse_git_repo', 'remotes')(...) } github_pat <- function(...){ getFromNamespace('github_pat', 'remotes')(...) }
NULL na_lgl <- NA na_int <- NA_integer_ na_dbl <- NA_real_ na_chr <- NA_character_ na_cpl <- NA_complex_ are_na <- function(x) { if (!is_atomic(x)) { stop_input_type(x, "an atomic vector") } is.na(x) } is_na <- function(x) { is_scalar_vector(x) && is.na(x) } detect_na <- are_na is_lgl_na <- function(x) { identical(x, na_lgl) } is_int_na <- function(x) { identical(x, na_int) } is_dbl_na <- function(x) { identical(x, na_dbl) } is_chr_na <- function(x) { identical(x, na_chr) } is_cpl_na <- function(x) { identical(x, na_cpl) }
pole <- function(sys) { if (class(sys) == 'tf') { res <- pracma::roots(c(sys[[2]])) return(as.matrix(res)) } if (class(sys) == 'ss') { res <- eigen(sys[[1]])$values return(as.matrix(res)) } if (class(sys) == 'zpk') { res <- sys[[2]] return(as.matrix(res)) } if(is.vector(sys)){ res <- pracma::roots(sys) return(as.matrix(res)) } }
unique_by <- function(text.var, grouping.var) { if (is.list(grouping.var)) { m <- unlist(as.character(substitute(grouping.var))[-1]) m <- sapply(strsplit(m, "$", fixed=TRUE), function(x) { x[length(x)] } ) G <- paste(m, collapse="&") } else { G <- as.character(substitute(grouping.var)) G <- G[length(G)] } if (is.list(grouping.var) & length(grouping.var)>1) { grouping <- paste2(grouping.var) } else { grouping <- unlist(grouping.var) } DF <- stats::na.omit(data.frame(grouping, text.var, check.names = FALSE, stringsAsFactors = FALSE)) DF[, "grouping"] <- factor(DF[, "grouping"]) LIST <- split(DF[, "text.var"], DF[, "grouping"]) LIST <- lapply(LIST, function(x) unique(bag_o_words(x))) stats::setNames(lapply(seq_along(LIST), function(i) { inds <- seq_along(LIST)[!seq_along(LIST) %in% i] sort(LIST[[i]][!LIST[[i]] %in% unique(unlist(LIST[inds]))]) }), names(LIST)) }
coef.lm.beta <- function(object, standardized=TRUE, ...) { if(standardized) { res <- object$standardized.coefficients } else { res <- object$coefficients } res }
PCsaveWPX<-function(twpx, destdir="." ) { if( identical(legitWPX(twpx),0) ) { cat("No legitimate picks", sep="\n") } else { RDATES = Qrangedatetime(twpx) if(RDATES$max$yr == 0 & RDATES$min$yr == 0) { return() } fout1 = PCfiledatetime(RDATES$min, 0) fout2 = paste(fout1,"RDATA", sep="." ) if( !identical(destdir, ".") ) { fout3 = paste(destdir, fout2, sep="/") } else { fout3 = fout2 } save(file=fout3, twpx) invisible(fout2) } invisible(NULL) }
test_that("backticks are converted to \\code & \\verb", { out1 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] out2 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] expect_equivalent_rd(out1, out2) }) test_that("code blocks work", { out1 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] out2 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] expect_equivalent_rd(out1, out2) }) test_that("code block with language creates HTML tag", { out1 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] out2 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] expect_equivalent_rd(out1, out2) }) test_that("inline code escapes %", { expect_equal(markdown("`5%`"), "\\verb{5\\%}") expect_equal(markdown("`'5%'`"), "\\code{'5\\%'}") expect_equal(markdown("`%*%`"), "\\code{\\%*\\%}") }) test_that("inline verbatim escapes Rd special chars", { expect_equal(markdown("`{`"), "\\verb{\\{}") expect_equal(markdown("`}`"), "\\verb{\\}}") expect_equal(markdown("`\\`"), "\\verb{\\\\}") }) test_that("special operators get \\code{}, not \\verb{}", { expect_equal(markdown("`if`"), "\\code{if}") }) test_that("code blocks escape %", { expect_equal( markdown("```\n1:10 %>% mean()\n```"), "\\preformatted{1:10 \\%>\\% mean()\n}" ) }) test_that("inline code works with < and >", { out <- roc_proc_text(rd_roclet(), " f <- function() 1 ")[[1]] expect_equal(out$get_value("title"), "\\verb{SELECT <name> FROM <table>}") }) test_that("itemized lists work", { out1 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] out2 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] expect_equivalent_rd(out1, out2) }) test_that("numbered lists work", { out1 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] out2 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] expect_equivalent_rd(out1, out2) }) test_that("nested lists are OK", { out1 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] out2 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] expect_equivalent_rd(out1, out2) }) test_that("can convert table to Rd", { txt <- " | x | y | | --- | --- | | 1 | 2 | | x | y | | :-: | --: | | 1 | 2 | | x | y | | ----- | --------- | | 1 _2_ | 3 *4* `5` | " txt <- gsub("\n ", "\n", txt) tables <- strsplit(txt, "\n\n")[[1]] verify_output( test_path("test-markdown-table.txt"), { for (table in tables) { cat_line(table) cat_line(markdown(table)) cat_line() } } ) }) test_that("emphasis works", { out1 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] out2 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] expect_equivalent_rd(out1, out2) }) test_that("strong (bold) text works", { out1 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] out2 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] expect_equivalent_rd(out1, out2) }) test_that("markdown links are converted", { out1 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] out2 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] expect_equivalent_rd(out1, out2) }) test_that("images are recognized", { out1 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] out2 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] expect_equivalent_rd(out1, out2) }) test_that("markdown is parsed in all fields where it is supported", { out1 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] out2 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] expect_equivalent_rd(out1, out2) }) test_that("markdown emphasis is ok", { out1 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] desc1 <- "Description with some \\emph{keywords} included. So far so good. \\preformatted{ *these are not emphasised*. Or are they? }" expect_equal(out1$get_section("description")[[2]], desc1) }) test_that("% is automatically escaped", { expect_equal(markdown("5%"), "5\\%") }) test_that("Escaping is kept", { out1 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] out2 <- roc_proc_text(rd_roclet(), " foo <- function() {}")[[1]] expect_equivalent_rd(out1, out2) }) test_that("Do not pick up `` in arguments \\item out1 <- roc_proc_text(rd_roclet(), " foo <- function(`_arg1`, `_arg2`) {}")[[1]] out2 <- roc_proc_text(rd_roclet(), " foo <- function(`_arg1`, `_arg2`) {}")[[1]] expect_equivalent_rd(out1, out2) }) test_that("unhandled markdown generates warning", { text <- " NULL " expect_warning(roc_proc_text(rd_roclet(), text), "block quotes") }) test_that("level 1 heading in markdown generates warning in some tags", { text <- " NULL " expect_warning( roc_proc_text(rd_roclet(), text), "level 1 markdown headings" ) }) test_that("level >2 markdown headings work in @description", { text <- " NULL " out <- roc_proc_text(rd_roclet(), text)[[1]] expect_equal_strings( out$get_value("description"), "\\subsection{This is good}{\n\nyes\n}" ) }) test_that("level >2 markdown headings work in @details", { text <- " NULL " out <- roc_proc_text(rd_roclet(), text)[[1]] expect_equal_strings( out$get_value("details"), "\\subsection{Heading 2}{\n\\subsection{Heading 3}{\n\nText.\n}\n\n}" ) }) test_that("level >2 markdown headings work in @return", { text <- " NULL " out <- roc_proc_text(rd_roclet(), text)[[1]] expect_equal_strings( out$get_value("value"), "Even this\n\\subsection{Can have a subsection.}{\n\nYes.\n}" ) }) test_that("level 1 heading in @details", { text1 <- " NULL " out1 <- roc_proc_text(rd_roclet(), text1)[[1]] text2 <- " NULL " out2 <- roc_proc_text(rd_roclet(), text2)[[1]] expect_equal(sort(names(out1$sections)), sort(names(out2$sections))) out2$sections <- out2$sections[names(out1$sections)] expect_equivalent_rd(out1, out2) }) test_that("headings and empty sections", { text1 <- " NULL " out1 <- roc_proc_text(rd_roclet(), text1)[[1]] expect_false("details" %in% names(out1$fields)) }) test_that("markdown() on empty input", { expect_identical(markdown(""), "") expect_identical(markdown(" "), "") expect_identical(markdown("\n"), "") }) test_that("markup in headings", { text1 <- " NULL " out1 <- roc_proc_text(rd_roclet(), text1)[[1]] expect_equal( out1$get_value("section"), list( title = "Section with \\code{code}", content = paste( sep = "\n", "\\subsection{Subsection with \\strong{strong}}{", "", "Yes.", "}" ) ) ) })
npFit0 <- function(DF, typeTem = ".") { df0 <- DF[DF$event == 0,] df1 <- DF[DF$event > 0,] rownames(df0) <- rownames(df1) <- NULL m <- aggregate(event > 0~ id, data = DF, sum)[, 2] yi <- df0$time2 ti <- df1$time2 zi <- wi <- rep(1, length(ti)) di <- df0$terminal xi <- as.matrix(df0[,-c(1:6)]) p <- ncol(xi) yi2 <- sort(unique(yi)) rate <- c(reRate(ti, rep(yi, m), wi, yi)) Lam <- exp(-rate) keep <- !duplicated(yi) Lam0 <- approxfun(yi[keep], Lam[keep], yleft = min(Lam), yright = max(Lam)) zi <- (m + 0.01) / (Lam + 0.01) if (typeTem != ".") { Haz <- c(temHaz(rep(0, p), rep(0, p), xi, yi, zi, di, wi, yi2)) Haz0 <- approxfun(yi2, Haz, yleft = min(Haz), yright = max(Haz)) return(list(Lam0 = Lam0, Haz0 = Haz0, log.muZ = log(mean(zi)))) } else { return(list(Lam0 = Lam0, log.muZ = log(mean(zi)))) } } npFit <- function(DF, B = 0, typeTem = ".") { out <- npFit0(DF) df0 <- DF[DF$event == 0,] mt <- aggregate(event > 0 ~ id, data = DF, sum)$event clsz <- mt + 1 t0 <- sort(unique(DF$time2)) LamB <- HazB <- matrix(NA, length(t0), B) if (B > 0) { for (i in 1:B) { sampled.id <- sample(df0$id, nrow(df0), TRUE) ind <- unlist(sapply(sampled.id, function(x) which(DF$id == x))) DF2 <- DF[ind,] DF2$id <- rep(1:nrow(df0), clsz[sampled.id]) tmp <- npFit0(DF2) LamB[,i] <- tmp$Lam0(t0) * exp(tmp$log.muZ) if (typeTem != ".") HazB[,i] <- tmp$Haz0(t0) * exp(tmp$log.muZ) } Lam.sd <- apply(LamB, 1, sd) if (typeTem != ".") Haz.sd <- apply(HazB, 1, sd) LamB.lower <- out$Lam0(t0) * exp(out$log.muZ) - 1.96 * Lam.sd LamB.upper <- out$Lam0(t0) * exp(out$log.muZ) + 1.96 * Lam.sd if (typeTem != ".") HazB.lower <- out$Haz0(t0) * exp(out$log.muZ) - 1.96 * Haz.sd if (typeTem != ".") HazB.upper <- out$Haz0(t0) * exp(out$log.muZ) + 1.96 * Haz.sd out$Lam0.lower <- approxfun(t0, LamB.lower, yleft = min(LamB.lower), yright = max(LamB.lower)) out$Lam0.upper <- approxfun(t0, LamB.upper, yleft = min(LamB.upper), yright = max(LamB.upper)) if (typeTem != ".") out$Haz0.lower <- approxfun(t0, HazB.lower, yleft = min(HazB.lower), yright = max(HazB.lower)) if (typeTem != ".") out$Haz0.upper <- approxfun(t0, HazB.upper, yleft = min(HazB.upper), yright = max(HazB.upper)) } out$Lam0 <- approxfun(t0, out$Lam0(t0) * exp(out$log.muZ), yleft = min(out$Lam0(t0) * exp(out$log.muZ)), yright = max(out$Lam0(t0) * exp(out$log.muZ))) if (typeTem != ".") out$Haz0 <- approxfun(t0, out$Haz0(t0) * exp(out$log.muZ), yleft = min(out$Haz0(t0) * exp(out$log.muZ)), yright = max(out$Haz0(t0) * exp(out$log.muZ))) return(out) }
"simulated_dist"
context("descritive stats") test_that("no errors with normal settings", { expect_error(prec_mean(mu = 5, sd = 2.5, n = 20), regexp = NA) expect_error(prec_mean(mu = 5, sd = 2.5, conf.width = 2.34), regexp = NA) expect_warning(prec_rate(2.5, x = 20)) expect_warning(prec_rate(2.5, conf.width = 2.243)) expect_error(prec_rate(2.5, x = 20, method = "score"), regexp = NA) expect_error(prec_rate(2.5, conf.width = 2.243, method = "score"), regexp = NA) expect_error(prec_rate(2.5, x = 20, method = "vs"), regexp = NA) expect_error(prec_rate(2.5, conf.width = 2.243, method = "vs"), regexp = NA) expect_error(prec_rate(2.5, x = 20, method = "exact"), regexp = NA) expect_error(prec_rate(2.5, conf.width = 2.243, method = "exact"), regexp = NA) expect_error(prec_rate(2.5, x = 20, method = "wald"), regexp = NA) expect_error(prec_rate(2.5, conf.width = 2.243, method = "wald"), regexp = NA) expect_warning(prec_prop(p = 1:9 / 10, n = 100)) expect_warning(prec_prop(p = 1:9 / 10, conf.width = .192)) expect_error(prec_prop(p = 1:9 / 10, n = 100, method = "wilson"), regexp = NA) expect_error(prec_prop(p = 1:9 / 10, conf.width = .192, method = "wilson"), regexp = NA) expect_error(prec_prop(p = 1:9 / 10, n = 100, method = "ac"), regexp = NA) expect_error(prec_prop(p = 1:9 / 10, conf.width = .192, method = "ac"), regexp = NA) expect_error(prec_prop(p = 1:9 / 10, n = 100, method = "agresti-coull"), regexp = NA) expect_error(prec_prop(p = 1:9 / 10, conf.width = .192, method = "agresti-coull"), regexp = NA) expect_error(prec_prop(p = 1:9 / 10, n = 100, method = "wald"), regexp = NA) expect_error(prec_prop(p = 1:9 / 10, conf.width = .192, method = "wald"), regexp = NA) expect_error(prec_prop(p = 1:9 / 10, n = 100, method = "exact"), regexp = NA) expect_error(prec_prop(p = 1:9 / 10, conf.width = .192, method = "exact"), regexp = NA) }) test_that("errors issued", { expect_error(prec_mean("foo", 1)) expect_error(prec_mean(1, "foo")) expect_error(prec_mean(mu = 2, sd = 1, n = 10, conf.width = .5)) expect_error(prec_rate(2, 1, 1)) expect_error(prec_prop(.1, conf.width = 2, method = "wilson"), "too wide") expect_error(prec_prop(.1, conf.width = .2, method = "wilson"), NA) }) test_that("warnings issued", { expect_warning(prec_rate(2,1)) expect_warning(prec_rate(0,1, method = "vs")) expect_warning(prec_prop(.01, 20, method = "ac")) expect_warning(prec_prop(.01, 20, method = "wilson"), regexp = NA) expect_warning(prec_prop(.99, 20, method = "ac")) expect_warning(prec_prop(.99, 20, method = "wilson"), regexp = NA) }) test_that("mean = stata", { ex <- prec_mean(1, 1, conf.width = .2) expect_equal(ex$n, 386, tolerance = 1, scale = 1) ex <- prec_mean(1, 1, n = 386) expect_equal(ex$conf.width, .2, tolerance = .001, scale = 1) }) test_that("mean conf int = stata", { ex <- prec_mean(mu = 10 , sd = 2, n = 100, conf.level = 0.95) expect_equal(c(ex$lwr, ex$upr) , c(9.603157, 10.39684) , tolerance = .0001, scale = 1) ex <- prec_mean(mu = 10 , sd = 2, conf.width = 10.39684-9.603157, conf.level = 0.95) expect_equal(ex$n , 100 , tolerance = 1, scale = 1) }) test_that("proportions conf int wilson = stata", { ex <- prec_prop(p = 0.5, n = 100, conf.level = 0.95, method = 'wilson') expect_equal(c(ex$lwr, ex$upr) , c(.4038315, .5961685) , tolerance = .0000001, scale = 1) ex <- prec_prop(p = 0.5, conf.width = .5961685-.4038315, conf.level = 0.95, method = 'wilson') expect_equal(ex$n , 100, tolerance = 1, scale = 1) }) test_that("proportions conf int agresti = stata", { ex <- prec_prop(p = 0.5, n = 100, conf.level = 0.95, method = 'agresti-coull') expect_equal(c(ex$lwr, ex$upr) , c(.4038315, .5961685) , tolerance = .0000001, scale = 1) ex <- prec_prop(p = 0.5, conf.width = .5961685-.4038315, conf.level = 0.95, method = 'agresti-coull') expect_equal(ex$n , 100 , tolerance = 1, scale = 1) }) test_that("proportions conf int exact = stata", { ex <- prec_prop(p = 0.5, n = 100, conf.level = 0.95, method = 'exact') expect_equal(c(ex$lwr, ex$upr) , c(.3983211, .6016789) , tolerance = .0000001, scale = 1) ex <- prec_prop(p = 0.5, conf.width = .6016789-.3983211, conf.level = 0.95, method = 'exact') expect_equal(ex$n, 100 , tolerance = 1, scale = 1) }) test_that("proportions conf int wald = stata", { ex <- prec_prop(p = 0.5, n = 100, conf.level = 0.95, method = 'wald') expect_equal(c(ex$lwr, ex$upr) , c(.4020018, .5979982) , tolerance = .0000001, scale = 1) ex <- prec_prop(p = 0.5, conf.width = .5979982-.4020018, conf.level = 0.95, method = 'wald') expect_equal(ex$n , 100 , tolerance = 1, scale = 1) }) test_that("rate conf int exact = stata", { ex <- prec_rate(r = 0.2, x = 10, conf.level = 0.95, method = 'exact') expect_equal(c(ex$lwr, ex$upr) , c(.0959078, .3678071) , tolerance = .0000001, scale = 1) ex <- prec_rate(r = 0.2, conf.width = .3678071-.0959078, conf.level = 0.95, method = 'exact') expect_equal(ex$x , 10 , tolerance = 1, scale = 1) })
convergence.test.Rcpp_Trace <- function(object, samples = 10, frac1 = 0.1, frac2 = 0.5, thin = 1, plot = FALSE, what = "Mutation", mixture = 1) { current.trace <- 0 if(what[1] == "Mutation" || what[1] == "Selection") { names.aa <- aminoAcids() numCodons <- 0 for(aa in names.aa) { if (aa == "M" || aa == "W" || aa == "X") next codons <- AAToCodon(aa, T) numCodons <- numCodons + length(codons) } index <- 1 cur.trace <- vector("list", numCodons) for(aa in names.aa) { if (aa == "M" || aa == "W" || aa == "X") next codons <- AAToCodon(aa, T) for(i in 1:length(codons)) { if(what[1] == "Mutation"){ cur.trace[[index]]<- object$getCodonSpecificParameterTraceByMixtureElementForCodon(mixture, codons[i], 0, T) }else{ cur.trace[[index]] <- object$getCodonSpecificParameterTraceByMixtureElementForCodon(mixture, codons[i], 1, T) } index <- index + 1 } } current.trace <- do.call("rbind", cur.trace) current.trace <- t(current.trace) } if(what[1] == "Alpha" || what[1] == "Lambda" || what[1] == "NSERate" || what[1] == "LambdaPrime") { codon.list <- codons() codon.list <- codon.list[1:(length(codon.list)-3)] cur.trace <- vector("list",length(codon.list)) for (i in 1:length(codon.list)) { if (what[1]=="Alpha") { cur.trace[[i]]<- object$getCodonSpecificParameterTraceByMixtureElementForCodon(mixture, codon.list[i], 0, F) } else if (what[1]=="Lambda" || what[1]=="LambdaPrime"){ cur.trace[[i]]<- object$getCodonSpecificParameterTraceByMixtureElementForCodon(mixture, codon.list[i], 1, F) } else if (what[1]=="NSERate"){ cur.trace[[i]]<- object$getCodonSpecificParameterTraceByMixtureElementForCodon(mixture, codon.list[i], 2, F) } } current.trace <- do.call("rbind", cur.trace) current.trace <- t(current.trace) } if(what[1] == "MixtureProbability") { numMixtures <- object$getNumberOfMixtures() cur.trace <- vector("list", numMixtures) for(i in 1:numMixtures) { cur.trace[[i]] <- object$getMixtureProbabilitiesTraceForMixture(i) } current.trace <- do.call("rbind", cur.trace) current.trace <- t(current.trace) } if(what[1] == "Sphi") { sphi <- object$getStdDevSynthesisRateTraces() current.trace <- do.call("rbind", sphi) current.trace <- t(current.trace) } if(what[1] == "Mphi") { sphi <- object$getStdDevSynthesisRateTraces() sphi <- do.call("rbind", sphi) mphi <- -(sphi * sphi) / 2; current.trace <- t(mphi) } if(what[1] == "Aphi") { } if(what[1] == "Sepsilon") { } if(what[1] == "ExpectedPhi") { current.trace <- object$getExpectedSynthesisRateTrace() } if(what[1] == "InitiationCost") { current.trace <- object$getInitiationCostTrace() } if(what[1] == "Expression") { } if(what[1] == "AcceptanceCSP") { names.aa <- aminoAcids() index <- 1 cur.trace <- vector("list", length(names.aa) - length(c("M","W","X"))) for(aa in names.aa) { if (aa == "M" || aa == "W" || aa == "X") next cur.trace[[index]] <- object$getCodonSpecificAcceptanceRateTraceForAA(aa) index <- index + 1 } current.trace <- do.call("rbind", cur.trace) current.trace <- t(current.trace) } trace.length <- length(current.trace) start <- max(0, trace.length - samples) mcmcobj <- coda::mcmc(data=current.trace, start=start, thin=thin) if(plot){ coda::geweke.plot(mcmcobj, frac1=frac1, frac2=frac2) } else{ diag <- coda::geweke.diag(mcmcobj, frac1=frac1, frac2=frac2) return(diag) } }
writeANY = 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, "Raster")) driver <- drivers$Raster else if (inherits(x, "SpatialPoints") | inherits(x, "SpatialPolygons") | inherits(x, "SpatialLines")) driver <- drivers$Spatial else if (inherits(x, "sf")) driver <- drivers$SimpleFeature else if (inherits(x, "data.frame")) driver <- drivers$DataFrame 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) 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) }
InputChecks_equal.length3 <- function(x, y, z){ X <- as.matrix(x) Y <- as.matrix(y) Z <- as.matrix(z) if(!(nrow(X) == nrow(Y) & nrow(X) == nrow(Z) & nrow(Z) == nrow(Y))){ stop(paste0(deparse(substitute(x)), ", ", deparse(substitute(y)), ", ", deparse(substitute(z)), " need to have an equal number of observations"), call. = FALSE) } } InputChecks_equal.length2 <- function(x, y){ X <- as.matrix(x) Y <- as.matrix(y) if(!(nrow(X) == nrow(Y))){ stop(paste0(deparse(substitute(x)), ", ", deparse(substitute(y)), " need to have an equal number of observations"), call. = FALSE) } } InputChecks_D <- function(D){ if(any(is.na(D))) stop("D contains missing values", call. = FALSE) if(!(is.numeric(D) & is.vector(D))) stop("D must be a numeric vector", call. = FALSE) if((!all(c(0, 1) %in% unique(D))) | (length(unique(D)) != 2)) stop("Treatment assignment D is not binary", call. = FALSE) } InputChecks_Y <- function(Y){ if(any(is.na(Y))) stop("Y contains missing values", call. = FALSE) if(!(is.numeric(Y) & is.vector(Y))) stop("Y must be a numeric vector", call. = FALSE) } InputChecks_Z <- function(Z){ if(any(is.na(Z))) stop("Z contains missing values", call. = FALSE) if(!(is.numeric(Z) & is.matrix(Z))) stop("Z must be a numeric matrix. Did you supply a data frame?", call. = FALSE) } InputChecks_Z_CLAN <- function(Z_CLAN){ if(!is.null(Z_CLAN)){ if(any(is.na(Z_CLAN))) stop("Z_CLAN contains missing values", call. = FALSE) if(!(is.numeric(Z_CLAN) & is.matrix(Z_CLAN))) stop("Z_CLAN must be a numeric matrix or NULL. Did you supply a data frame?", call. = FALSE) } } InputChecks_X1 <- function(X1_control, num.obs){ if(class(X1_control) != "setup_X1"){ stop(paste0(deparse(substitute(X1_control))), " must be an instance of setup_X1()", call. = FALSE) } if(!is.null(X1_control$covariates)){ if(nrow(X1_control$covariates) != num.obs){ stop(paste0(deparse(substitute(X1_control)), "$covariates must have the same number of rows as Z"), call. = FALSE) } } if(!is.null(X1_control$fixed_effects)){ if(length(X1_control$fixed_effects) != num.obs){ stop(paste0(deparse(substitute(X1_control)), "$fixed_effects must have the same length as Y"), call. = FALSE) } } } InputChecks_vcov.control <- function(vcov_control){ if(class(vcov_control) != "setup_vcov"){ stop(paste0(deparse(substitute(vcov_control))), " must be an instance of setup_vcov()", call. = FALSE) } } InputChecks_diff <- function(diff, K){ if(class(diff) != "setup_diff"){ stop(paste0(deparse(substitute(diff))), " must be an instance of setup_diff()", call. = FALSE) } if(any(diff$subtracted < 1) | any(diff$subtracted > K)){ stop(paste0("The numeric vector ", deparse(substitute(diff)), "$subtracted", " must be a subset of {1,2,...,K}, where K = ", K, " is the number of groups that were supplied (controlled through the argument 'quantile_cutoffs'). K is equal to the cardinality of 'quantile_cutoffs' plus one."), call. = FALSE) } if(diff$subtract_from == "most" & K %in% diff$subtracted){ stop("The most affected group cannot be subtracted from itself") } if(diff$subtract_from == "least" & 1 %in% diff$subtracted){ stop("The least affected group cannot be subtracted from itself") } } InputChecks_group.membership <- function(group.membership){ if(is.null(attr(group.membership, which = "type"))) stop(paste0("The object ", deparse(substitute(group.membership)), " must be returned by quantile_group()")) if(attr(group.membership, which = "type") != "quantile_group") stop(paste0("The object ", deparse(substitute(group.membership)), " must be returned by quantile_group()")) } InputChecks_proxy.estimators <- function(proxy.estimators, baseline = TRUE){ if(baseline){ if(!inherits(proxy.estimators, what = "proxy_BCA")){ stop(paste0("The object ", deparse(substitute(proxy.estimators)), " needs to be an instance of proxy_BCA()")) } } else{ if(!inherits(proxy.estimators, what = "proxy_CATE")){ stop(paste0("The object ", deparse(substitute(proxy.estimators)), " needs to be an instance of proxy_CATE()")) } } } InputChecks_num_splits <- function(num_splits){ stopifnot(length(num_splits) == 1) stopifnot(num_splits %% 1 == 0) if(num_splits < 2){ stop(paste0("num_splits must be equal to at least 2. If you want to run GenericML() for ", "a single split, please use the function GenericML_single()."), call. = FALSE) } } get.learner_regr <- function(learner){ if(is.environment(learner)){ learner <- learner } else if(learner == "lasso"){ learner <- mlr3::lrn("regr.cv_glmnet", s = "lambda.min", alpha = 1) } else if(learner == "random_forest"){ learner <- mlr3::lrn("regr.ranger", num.trees = 500) } else if(learner == "tree"){ learner <- mlr3::lrn("regr.rpart") } else{ stop("Invalid argument for 'learner'. Needs to be either 'lasso', 'random_forest', 'tree', or an mlr3 object") } return(learner) } InputChecks_propensity_scores <- function(propensity_scores){ if(any(propensity_scores > 0.65 | propensity_scores < 0.35)){ warning(paste0("Some propensity scores are outside the ", "interval [0.35, 0.65]. In a randomized experiment, we would ", "expect all propensity scores to be equal to roughly 0.5. ", "The theory of the paper ", "is only valid for randomized experiments. Are ", "you sure your data is from a randomomized experiment ", "and the estimator of the scores has been chosen appropriately?"), call. = FALSE) } if(any(propensity_scores > 0.95)){ stop(paste0("Some estimated propensity scores are higher than 0.95, ", " which is not sufficiently bounded away from one.", " Are you sure your data is from a randomomized experiment ", "and the estimator of the scores has been chosen appropriately?")) } if(any(propensity_scores < 0.05)){ stop(paste0("Some estimated propensity scores are lower than 0.05, ", " which is not sufficiently bounded away from zero.", " Are you sure your data is from a randomomized experiment ", "and the estimator of the scores has been chosen appropriately?")) } } InputChecks_index_set <- function(set, num_obs){ stopifnot(is.numeric(set) & is.vector(set)) if(any(set %% 1 != 0)){ stop("The indices in the index set must be index-valued") } if(min(set) < 0){ stop("The indices in the index set must be strictly positive") } if(max(set) > num_obs){ stop("The largest index in the index set cannot be larger than the number of observations") } if(any(duplicated(set))){ stop("All indices in the index set must be unique") } } TrueIfUnix <- function(){ .Platform$OS.type == "unix" }
test.writeNamedRegionToFile <- function() { file.xls <- "testWriteNamedRegionToFileWorkbook.xls" file.xlsx <- "testWriteNamedRegionToFileWorkbook.xlsx" if(file.exists(file.xls)) { file.remove(file.xls) } if(file.exists(file.xlsx)) { file.remove(file.xlsx) } testDataFrame <- function(file, df) { worksheet <- deparse(substitute(df)) print(paste("Writing dataset ", worksheet, "to file", file)) name <- paste(worksheet, "Region", sep="") writeNamedRegionToFile(file, df, name, formula=paste(worksheet, "A1", sep="!")) res <- readNamedRegionFromFile(file, name) checkEquals(normalizeDataframe(df), res, check.attributes = FALSE, check.names = TRUE) } if(getOption("FULL.TEST.SUITE")) { testDataFrame(file.xls, mtcars) testDataFrame(file.xlsx, mtcars) testDataFrame(file.xls, airquality) testDataFrame(file.xlsx, airquality) testDataFrame(file.xls, attenu) testDataFrame(file.xlsx, attenu) testDataFrame(file.xls, ChickWeight) testDataFrame(file.xlsx, ChickWeight) CO = CO2 testDataFrame(file.xls, CO) testDataFrame(file.xlsx, CO) testDataFrame(file.xls, iris) testDataFrame(file.xlsx, iris) testDataFrame(file.xls, longley) testDataFrame(file.xlsx, longley) testDataFrame(file.xls, morley) testDataFrame(file.xlsx, morley) testDataFrame(file.xls, swiss) testDataFrame(file.xlsx, swiss) } cdf <- data.frame( "Column.A" = c(1, 2, 3, NA, 5, 6, 7, 8, NA, 10), "Column.B" = c(-4, -3, NA, -1, 0, NA, NA, 3, 4, 5), "Column.C" = c("Anna", "???", NA, "", NA, "$!?&%", "(?2@?~?'^* "Column.D" = c(pi, -pi, NA, sqrt(2), sqrt(0.3), -sqrt(pi), exp(1), log(2), sin(2), -tan(2)), "Column.E" = c(TRUE, TRUE, NA, NA, FALSE, FALSE, TRUE, NA, FALSE, TRUE), "Column.F" = c("High", "Medium", "Low", "Low", "Low", NA, NA, "Medium", "High", "High"), "Column.G" = c("High", "Medium", NA, "Low", "Low", "Medium", NA, "Medium", "High", "High"), "Column.H" = rep(c(Sys.Date(), Sys.Date() + 236, NA), length = 10), "Column.I" = rep(c(as.POSIXlt(Sys.time()), as.POSIXlt(Sys.time()) + 3523523, NA, as.POSIXlt(Sys.time()) + 838239), length = 10), "Column.J" = rep(c(as.POSIXct(Sys.time()), as.POSIXct(Sys.time()) + 436322, NA, as.POSIXct(Sys.time()) - 1295022), length = 10), stringsAsFactors = F ) cdf[["Column.F"]] <- factor(cdf[["Column.F"]]) cdf[["Column.F"]] <- ordered(cdf[["Column.F"]], levels = c("Low", "Medium", "High")) testDataFrame(file.xls, cdf) testDataFrame(file.xlsx, cdf) checkNoException(writeNamedRegionToFile("wnrtf1.xls", data = mtcars, name = "mtcars", formula = "'My Cars'!$A$1", header = TRUE)) checkTrue(file.exists("wnrtf1.xls")) checkNoException(writeNamedRegionToFile("wnrtf1.xlsx", data = mtcars, name = "mtcars", formula = "'My Cars'!$A$1", header = TRUE)) checkTrue(file.exists("wnrtf1.xlsx")) testClearNamedRegions <- function(file, df) { df.short <- df[1,] writeNamedRegionToFile(file, data=df.short, name="cdfRegion") checkEquals(nrow(readNamedRegionFromFile(file, name="cdfRegion")), 1) checkEquals(nrow(readWorksheetFromFile(file, sheet="cdf")), nrow(df)) writeNamedRegionToFile(file, data=df, name="cdfRegion") writeNamedRegionToFile(file, data=df.short, name="cdfRegion", clearNamedRegions=TRUE) } testClearNamedRegions(file.xls, cdf) testClearNamedRegions(file.xlsx, cdf) }
test_that("ask prompts are returned", { if(!maxima.env$maxima$isInstalled()) skip("Maxima not installed") expect_match(maxima.get("integrate(x^n,x)"), "Is n equal to -1?") to <- maxima.get("y;") expect_s3_class(to, "maxima") expect_type(to, "list") expect_match(attr(to, "input.label"), "^%\\i[[:digit::]]*$") expect_match(attr(to, "output.label"), "^\\%o[[:digit::]]*$") expect_equal(attr(to, "command"), "y;") expect_true(!attr(to, "suppressed")) expect_length(to$wtl$linear, 1L) expect_length(to$wtl$ascii, 1L) expect_length(to$wtl$latex, 1L) expect_length(to$wtl$mathml, 3L) expect_length(to$wol$linear, 1L) expect_length(to$wol$ascii, 1L) expect_length(to$wol$latex, 1L) expect_length(to$wol$mathml, 2L) })
context("memoize") test_that("can memoize", { called <- 0L f <- function(x) called <<- called + 1L f <- memoize_first(f) f("a") f("a") f("a") expect_equal(called, 1L) f("b") f("b") f("a") expect_equal(called, 2L) }) test_that("non-string argument", { called <- 0L f <- function(x) called <<- called + 1L f <- memoize_first(f) f(NULL) f(123) f(letters) expect_equal(called, 3L) f("a") f("a") f("a") expect_equal(called, 4L) f(NULL) f(123) f(letters) expect_equal(called, 7L) })
mlm.variance.distribution.bw = function(x){ m = x if (!(class(m)[1] %in% c("rma.mv", "rma"))){ stop("x must be of class 'rma.mv'.") } if (m$sigma2s != 2){ stop("The model you provided does not seem to be a three-level model. This function can only be used for three-level models.") } if (sum(grepl("/", as.character(m$random[[1]]))) < 1){ stop("Model must contain nested random effects. Did you use the '~ 1 | cluster/effect-within-cluster' notation in 'random'? See ?metafor::rma.mv for more details.") } n = m$k.eff vector.inv.var = 1/(diag(m$V)) sum.inv.var = sum(vector.inv.var) sum.sq.inv.var = (sum.inv.var)^2 vector.inv.var.sq = 1/(diag(m$V)^2) sum.inv.var.sq = sum(vector.inv.var.sq) num = (n-1)*sum.inv.var den = sum.sq.inv.var - sum.inv.var.sq est.samp.var = num/den level1=((est.samp.var)/(m$sigma2[1]+m$sigma2[2]+est.samp.var)*100) level2=((m$sigma2[2])/(m$sigma2[1]+m$sigma2[2]+est.samp.var)*100) level3=((m$sigma2[1])/(m$sigma2[1]+m$sigma2[2]+est.samp.var)*100) Level=c("Level 1", "Level 2", "Level 3") Variance=c(level1, level2, level3) df.res=data.frame(Variance) colnames(df.res) = c("% of total variance") rownames(df.res) = Level I2 = c("---", round(Variance[2:3], 2)) df.res = as.data.frame(cbind(df.res, I2)) totalI2 = Variance[2] + Variance[3] df1 = data.frame("Level" = c("Sampling Error", "Total Heterogeneity"), "Variance" = c(df.res[1,1], df.res[2,1]+df.res[3,1]), "Type" = rep(1,2)) df2 = data.frame("Level" = rownames(df.res), "Variance" = df.res[,1], "Type" = rep(2,3)) df = as.data.frame(rbind(df1, df2)) g = ggplot(df, aes(fill=Level, y=Variance, x=as.factor(Type))) + coord_cartesian(ylim = c(0,1), clip = "off") + geom_bar(stat="identity", position="fill", width = 1, color="black") + scale_y_continuous(labels = scales::percent)+ theme(axis.title.x=element_blank(), axis.text.y = element_text(color="black"), axis.line.y = element_blank(), axis.title.y=element_blank(), axis.line.x = element_blank(), axis.ticks.x = element_blank(), axis.text.x = element_blank(), axis.ticks.y = element_line(lineend = "round"), legend.position = "none", panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), legend.background = element_rect(linetype="solid", colour ="black"), legend.title = element_blank(), legend.key.size = unit(0.75,"cm"), axis.ticks.length=unit(.25, "cm"), plot.margin = unit(c(1,3,1,1), "lines")) + scale_fill_manual(values = c("gray85", "gray90", "white", "gray85", "gray95")) + annotate("text", x = 1.5, y = 1.05, label = paste("Total Variance:", round(m$sigma2[1]+m$sigma2[2]+est.samp.var, 3))) + annotate("text", x = 1, y = (df[1,2]/2+df[2,2])/100, label = paste("Sampling Error Variance: \n", round(est.samp.var, 3)), size = 3) + annotate("text", x = 1, y = ((df[2,2])/100)/2-0.02, label = bquote("Total"~italic(I)^2*":"~.(round(df[2,2],2))*"%"), size = 3) + annotate("text", x = 1, y = ((df[2,2])/100)/2+0.05, label = paste("Variance not attributable \n to sampling error: \n", round(m$sigma2[1]+m$sigma2[2],3)), size = 3) + annotate("text", x = 2, y = (df[1,2]/2+df[2,2])/100, label = paste("Level 1: \n", round(df$Variance[3],2), "%", sep=""), size = 3) + annotate("text", x = 2, y = (df[5,2]+(df[4,2]/2))/100, label = bquote(italic(I)[Level2]^2*":"~.(round(df[4,2],2))*"%"), size = 3) + annotate("text", x = 2, y = (df[5,2]/2)/100, label = bquote(italic(I)[Level3]^2*":"~.(round(df[5,2],2))*"%"), size = 3) print(df.res) cat("Total I2: ", round(totalI2, 2), "% \n", sep="") suppressWarnings(print(g)) invisible(df.res) }
WhichModels <- function(max.p, max.q, max.P, max.Q, maxK) { total.models <- (max.p + 1) * (max.q + 1) * (max.P + 1) * (max.Q + 1) * length(0:maxK) x <- numeric(total.models) i <- 1 for (x1 in 0:max.p) for (x2 in 0:max.q) { for (x3 in 0:max.P) for (x4 in 0:max.Q) { for (K in 0:maxK) { x[i] <- paste(x1, "f", x2, "f", x3, "f", x4, "f", K, sep = "") i <- i + 1 } } } return(x) } UndoWhichModels <- function(n) { as.numeric(unlist(strsplit(n, split = "f"))) }
annotate.WithFeature<-function(){ .Defunct("genomation::annotateWithFeature") message("Use functions in genomation package from Bioconductor\n", "See vignette for examples.")} annotate.WithFeature.Flank<-function(){ .Defunct("genomation::annotateWithFeatureFlank") message("Use functions in genomation package from Bioconductor\n", "See vignette for examples.") } annotate.WithGenicParts<-function(){ .Defunct("genomation::annotateWithGeneParts") message("Use functions in genomation package from Bioconductor") } read.bed<-function(){ .Defunct("genomation::readBed") message("Use functions in genomation package from Bioconductor\n", "See vignette for examples.")} read.feature.flank<-function(){ .Defunct("genomation::readFeatureFlank") message("Use functions in genomation package from Bioconductor\n", "See vignette for examples.")} read.transcript.features<-function(){ .Defunct("genomation::readTranscriptFeatures") message("Use functions in genomation package from Bioconductor\n", "See vignette for examples.")} getFeatsWithTargetsStats<-function(){ .Defunct("genomation::getFeatsWithTargetsStats") message("Use functions in genomation package from Bioconductor\n", "See vignette for examples.")} getFlanks<-function(){ .Defunct("genomation::getFlanks") message("Use functions in genomation package from Bioconductor\n", "See vignette for examples.")} getMembers<-function(){ .Defunct("genomation::getMembers") message("Use functions in genomation package from Bioconductor\n", "See vignette for examples.")} getTargetAnnotationStats<-function(){ .Defunct("genomation::getTargetAnnotationStats") message("Use functions in genomation package from Bioconductor\n", "See vignette for examples.")} plotTargetAnnotation<-function(){ .Defunct("genomation::plotTargetAnnotation") message("Use functions in genomation package from Bioconductor\n", "See vignette for examples.")} read <- function() { .Defunct("methRead") } read.bismark <- function() { .Defunct("processBismarkAln") } adjust.methylC<-function(){ .Defunct("adjustMethylC") } get.methylDiff<-function(){ .Defunct("getMethylDiff") }
simple_clm <- function(formula, data, weights, start, subset, offset, doFit = TRUE, na.action, contrasts, model = TRUE, control = list(), link = c("logit", "probit", "cloglog", "loglog"), threshold = c("flexible", "symmetric", "symmetric2", "equidistant"), ...) { mc <- match.call(expand.dots = FALSE) link <- match.arg(link) threshold <- match.arg(threshold) if(missing(formula)) stop("Model needs a formula") if(missing(contrasts)) contrasts <- NULL control <- do.call(clm.control, c(control, list(...))) if (missing(data)) data <- environment(formula) mf <- match.call(expand.dots = FALSE) m <- match(c("formula", "data", "subset", "weights", "na.action", "offset"), names(mf), 0L) mf <- mf[c(1L, m)] mf$drop.unused.levels <- TRUE mf[[1L]] <- as.name("model.frame") mf <- eval(mf, parent.frame()) if(control$method == "model.frame") return(mf) y <- model.response(mf, "any") if(!is.factor(y)) stop("response needs to be a factor", call.=FALSE) mt <- attr(mf, "terms") X <- if (!is.empty.model(mt)) model.matrix(mt, mf, contrasts) else cbind("(Intercept)" = rep(1, NROW(y))) Xint <- match("(Intercept)", colnames(X), nomatch = 0) if(Xint <= 0) { X <- cbind("(Intercept)" = rep(1, NROW(y)), X) warning("an intercept is needed and assumed in 'formula'", call.=FALSE) } wts <- getWeights(mf) off <- getOffsetStd(mf) ylevels <- levels(droplevels(y[wts > 0])) frames <- list(y=y, ylevels=ylevels, X=X) frames <- c(frames, makeThresholds(ylevels, threshold)) frames <- drop.cols(frames, silent=TRUE) rho <- clm.newRho(parent.frame(), y=frames$y, X=frames$X, NOM=NULL, S=NULL, weights=wts, offset=off, S.offset=NULL, tJac=frames$tJac, control=control) start <- set.start(rho, start=start, get.start=missing(start), threshold=threshold, link=link, frames=frames) rho$par <- as.vector(start) setLinks(rho, link) if(!doFit) return(rho) if(control$method == "Newton") fit <- clm.fit.NR(rho, control) else fit <- clm.fit.optim(rho, control$method, control$ctrl) res <- clm.finalize(fit, weights=wts, coef.names=frames$coef.names, aliased=frames$aliased) res$control <- control res$link <- link res$start <- start if(control$method == "Newton" && !is.null(start.iter <- attr(start, "start.iter"))) res$niter <- res$niter + start.iter res$threshold <- threshold res$call <- match.call() res$contrasts <- attr(frames$X, "contrasts") res$na.action <- attr(mf, "na.action") res$terms <- mt res$xlevels <- .getXlevels(mt, mf) res$tJac <- frames$tJac res$y.levels <- frames$ylevels conv <- conv.check(res, Theta.ok=TRUE, tol=control$tol) print.conv.check(conv, action=control$convergence) res$vcov <- conv$vcov res$cond.H <- conv$cond.H res$convergence <- conv[!names(conv) %in% c("vcov", "cond.H")] res$info <- with(res, { data.frame("link" = link, "threshold" = threshold, "nobs" = nobs, "logLik" = formatC(logLik, digits=2, format="f"), "AIC" = formatC(-2*logLik + 2*edf, digits=2, format="f"), "niter" = paste(niter[1], "(", niter[2], ")", sep=""), "max.grad" = formatC(maxGradient, digits=2, format="e") ) }) class(res) <- "clm" if(model) res$model <- mf return(res) }
PlotReplicateQuality <- function(ExpressionSet, nrep, FUN = function(x) log(stats::var(x)), legend.pos = "topleft", stage.names = NULL, ...){ if (!all(sapply(nrep,function(x) x > 1, simplify = TRUE))) stop("Please insert at least 2 replicates per stage.", call. = FALSE) ncols <- ncol(ExpressionSet) if (length(nrep) == 1){ if ((ncols - 2) %% nrep != 0) stop("The number of stages and the number of replicates do not match.", call. = FALSE) nStages <- (ncols - 2) / nrep } else if (length(nrep) > 1){ if (!((ncols - 2) == sum(nrep))) stop("The number of stages and the number of replicates do not match.", call. = FALSE) nStages <- length(nrep) } stage.cols <- re.colors(nStages) custom.FUN <- match.fun(FUN) CollapsedExpressionSet <- CollapseReplicates(ExpressionSet = ExpressionSet, nrep = nrep, FUN = custom.FUN) col.index <- 1 graphics::plot(stats::density(CollapsedExpressionSet[ , 3]), col = stage.cols[1],main = "Distributions of replicate log variances", ...) apply(CollapsedExpressionSet[ , 4:(3 + nStages - 1)], 2 ,function(x) { col.index <<- col.index + 1 graphics::lines(stats::density(x),col = stage.cols[col.index], ...) }) if (is.null(stage.names)) graphics::legend(legend.pos, bty = "n", legend = paste0("S",1:nStages), fill = stage.cols, ncol = ifelse(nStages <= 4, 1, floor(nStages/2))) if (!is.null(stage.names)) graphics::legend(legend.pos, bty = "n", legend = stage.names, fill = stage.cols, ncol = ifelse(nStages <= 4, 1, floor(nStages/2))) }
spIntPGOcc <- function(occ.formula, det.formula, data, inits, priors, tuning, cov.model = "exponential", NNGP = TRUE, n.neighbors = 15, search.type = "cb", n.batch, batch.length, accept.rate = 0.43, n.omp.threads = 1, verbose = TRUE, n.report = 100, n.burn = round(.10 * n.batch * batch.length), n.thin = 1, n.chains = 1, k.fold, k.fold.threads = 1, k.fold.seed = 100, k.fold.data, ...){ ptm <- proc.time() logit <- function(theta, a = 0, b = 1) {log((theta-a)/(b-theta))} logit.inv <- function(z, a = 0, b = 1) {b-(b-a)/(1+exp(z))} rigamma <- function(n, a, b){ 1/rgamma(n = n, shape = a, rate = b) } if (verbose) { cat("----------------------------------------\n"); cat("\tPreparing the data\n"); cat("----------------------------------------\n"); } formal.args <- names(formals(sys.function(sys.parent()))) elip.args <- names(list(...)) for(i in elip.args){ if(! i %in% formal.args) warning("'",i, "' is not an argument") } cl <- match.call() if (missing(data)) { stop("error: data must be specified") } if (!is.list(data)) { stop("error: data must be a list") } names(data) <- tolower(names(data)) if (missing(occ.formula)) { stop("error: occ.formula must be specified") } if (missing(det.formula)) { stop("error: det.formula must be specified") } if (!'y' %in% names(data)) { stop("error: detection-nondetection data y must be specified in data") } if (!is.list(data$y)) { stop("error: y must be a list of detection-nondetection data sets") } y <- data$y n.data <- length(y) for (q in 1:n.data) { if (is.null(dim(y[[q]]))) { message(paste("Data source ", q, " is provided as a one-dimensional vector.\nAssuming this is a nonreplicated detection-nondetection data source.\n", sep = '')) } y[[q]] <- as.matrix(y[[q]]) } if (!'sites' %in% names(data)) { stop("error: site ids must be specified in data") } sites <- data$sites J <- length(unique(unlist(sites))) J.long <- sapply(y, function(a) dim(a)[[1]]) if (!'occ.covs' %in% names(data)) { if (occ.formula == ~ 1) { if (verbose) { message("occupancy covariates (occ.covs) not specified in data.\nAssuming intercept only occupancy model.\n") } data$occ.covs <- matrix(1, J, 1) } else { stop("error: occ.covs must be specified in data for an occupancy model with covariates") } } if (!'det.covs' %in% names(data)) { data$det.covs <- list() for (i in 1:n.data) { if (verbose) { message("detection covariates (det.covs) not specified in data.\nAssuming interept only detection model for each data source.\n") } det.formula.curr <- det.formula[[i]] if (det.formula.curr == ~ 1) { for (i in 1:n.data) { data$det.covs[[i]] <- list(int = matrix(1, dim(y[[i]])[1], dim(y[[i]])[2])) } } else { stop("error: det.covs must be specified in data for a detection model with covariates") } } } if (!'coords' %in% names(data)) { stop("error: coords must be specified in data for a spatial occupancy model.") } coords <- as.matrix(data$coords) if (!missing(k.fold)) { if (!is.numeric(k.fold) | length(k.fold) != 1 | k.fold < 2) { stop("error: k.fold must be a single integer value >= 2") } } for (q in 1:n.data) { y.na.test <- apply(y[[q]], 1, function(a) sum(!is.na(a))) if (sum(y.na.test == 0) > 0) { stop(paste("error: some sites in data source ", q, " in y have all missing detection histories.\n Remove these sites from y and all objects in the 'data' argument if the site is not surveyed by another data source\n, then use 'predict' to obtain predictions at these locations if desired.", sep = '')) } } if (NNGP) { u.search.type <- 2 ord <- order(coords[,1]) coords <- coords[ord, ] data$occ.covs <- data$occ.covs[ord, , drop = FALSE] rownames(data$occ.covs) <- 1:nrow(data$occ.covs) sites.orig <- sites for (i in 1:n.data) { for (j in 1:length(sites[[i]])) { sites[[i]][j] <- which(ord == sites[[i]][j]) } } } for (i in 1:n.data) { data$det.covs[[i]] <- data.frame(lapply(data$det.covs[[i]], function(a) unlist(c(a)))) if (nrow(data$det.covs[[i]]) == nrow(y[[i]])) { data$det.covs[[i]] <- data.frame(sapply(data$det.covs[[i]], rep, times = dim(y[[i]])[2])) } } data$occ.covs <- as.data.frame(data$occ.covs) if (class(occ.formula) == 'formula') { tmp <- parseFormula(occ.formula, data$occ.covs) X <- as.matrix(tmp[[1]]) x.names <- tmp[[2]] } else { stop("error: occ.formula is misspecified") } if (!is.list(det.formula)) { stop(paste("error: det.formula must be a list of ", n.data, " formulas", sep = '')) } X.p <- list() x.p.names <- list() for (i in 1:n.data) { if (class(det.formula[[i]]) == 'formula') { tmp <- parseFormula(det.formula[[i]], data$det.covs[[i]]) X.p[[i]] <- as.matrix(tmp[[1]]) x.p.names[[i]] <- tmp[[2]] } else { stop(paste("error: det.formula for data source ", i, " is misspecified", sep = '')) } } x.p.names <- unlist(x.p.names) J.all <- nrow(X) if (length(X.p) != n.data | length(y) != n.data) { stop(paste("error: y and X.p must be lists of length ", n.data, ".", sep = '')) } p.occ <- ncol(X) p.det.long <- sapply(X.p, function(a) dim(a)[[2]]) p.det <- sum(p.det.long) n.rep <- lapply(y, function(a1) apply(a1, 1, function(a2) sum(!is.na(a2)))) K.long.max <- sapply(n.rep, max) K <- unlist(n.rep) n.samples <- n.batch * batch.length if (missing(n.samples)) { stop("error: must specify number of MCMC samples") } if (n.burn > n.samples) { stop("error: n.burn must be less than n.samples") } if (n.thin > n.samples) { stop("error: n.thin must be less than n.samples") } if (!missing(k.fold)) { if (!is.numeric(k.fold) | length(k.fold) != 1 | k.fold < 2) { stop("error: k.fold must be a single integer value >= 2") } } X.p.orig <- X.p y.big <- y names.long <- list() for (i in 1:n.data) { if (nrow(X.p[[i]]) == length(y[[i]])) { X.p[[i]] <- X.p[[i]][!is.na(y[[i]]), , drop = FALSE] } names.long[[i]] <- which(!is.na(y[[i]])) } n.obs.long <- sapply(X.p, nrow) n.obs <- sum(n.obs.long) z.long.indx.r <- list() for (i in 1:n.data) { z.long.indx.r[[i]] <- rep(sites[[i]], K.long.max[i]) z.long.indx.r[[i]] <- z.long.indx.r[[i]][!is.na(c(y[[i]]))] } z.long.indx.r <- unlist(z.long.indx.r) z.long.indx.c <- z.long.indx.r - 1 y <- unlist(y) y <- y[!is.na(y)] data.indx.r <- rep(NA, n.obs) indx <- 1 for (i in 1:n.data) { data.indx.r[indx:(indx + n.obs.long[i] - 1)] <- rep(i, n.obs.long[i]) indx <- indx + n.obs.long[i] } data.indx.c <- data.indx.r - 1 X.p.all <- matrix(NA, n.obs, max(p.det.long)) indx <- 1 for (i in 1:n.data) { X.p.all[indx:(indx + nrow(X.p[[i]]) - 1), 1:p.det.long[i]] <- X.p[[i]] indx <- indx + nrow(X.p[[i]]) } if (missing(priors)) { priors <- list() } names(priors) <- tolower(names(priors)) if ("beta.normal" %in% names(priors)) { if (!is.list(priors$beta.normal) | length(priors$beta.normal) != 2) { stop("error: beta.normal must be a list of length 2") } mu.beta <- priors$beta.normal[[1]] sigma.beta <- priors$beta.normal[[2]] if (length(mu.beta) != p.occ & length(mu.beta) != 1) { if (p.occ == 1) { stop(paste("error: beta.normal[[1]] must be a vector of length ", p.occ, " with elements corresponding to betas' mean", sep = "")) } else { stop(paste("error: beta.normal[[1]] must be a vector of length ", p.occ, " or 1 with elements corresponding to betas' mean", sep = "")) } } if (length(sigma.beta) != p.occ & length(sigma.beta) != 1) { if (p.occ == 1) { stop(paste("error: beta.normal[[2]] must be a vector of length ", p.occ, " with elements corresponding to betas' variance", sep = "")) } else { stop(paste("error: beta.normal[[2]] must be a vector of length ", p.occ, " or 1 with elements corresponding to betas' variance", sep = "")) } } if (length(sigma.beta) != p.occ) { sigma.beta <- rep(sigma.beta, p.occ) } if (length(mu.beta) != p.occ) { mu.beta <- rep(mu.beta, p.occ) } Sigma.beta <- sigma.beta * diag(p.occ) } else { if (verbose) { message("No prior specified for beta.normal.\nSetting prior mean to 0 and prior variance to 2.72\n") } mu.beta <- rep(0, p.occ) sigma.beta <- rep(2.72, p.occ) Sigma.beta <- diag(p.occ) * 2.72 } if ("alpha.normal" %in% names(priors)) { if (!is.list(priors$alpha.normal) | length(priors$alpha.normal) != 2) { stop("error: alpha.normal must be a list of length 2") } mu.alpha <- priors$alpha.normal[[1]] sigma.alpha <- priors$alpha.normal[[2]] if (length(mu.alpha) != n.data | !is.list(mu.alpha)) { stop(paste("error: alpha.normal[[1]] must be a list of length ", n.data, " with elements corresponding to alphas' mean for each data set", sep = "")) } for (q in 1:n.data) { if (length(mu.alpha[[q]]) != p.det.long[q] & length(mu.alpha[[q]]) != 1) { if (p.det.long[q] == 1) { stop(paste("error: prior means for alpha.normal[[1]][[", q, "]] must be a vector of length ", p.det.long[q], sep = "")) } else { stop(paste("error: prior means for alpha.normal[[1]][[", q, "]] must be a vector of length ", p.det.long[q], "or 1", sep = "")) } } if (length(mu.alpha[[q]]) != p.det.long[q]) { mu.alpha[[q]] <- rep(mu.alpha[[q]], p.det.long[q]) } } mu.alpha <- unlist(mu.alpha) if (length(sigma.alpha) != n.data | !is.list(sigma.alpha)) { stop(paste("error: alpha.normal[[2]] must be a list of length ", n.data, " with elements corresponding to alphas' variance for each data set", sep = "")) } for (q in 1:n.data) { if (length(sigma.alpha[[q]]) != p.det.long[q] & length(sigma.alpha[[q]]) != 1) { if (p.det.long[q] == 1) { stop(paste("error: prior variances for alpha.normal[[2]][[", q, "]] must be a vector of length ", p.det.long[q], sep = "")) } else { stop(paste("error: prior variances for alpha.normal[[2]][[", q, "]] must be a vector of length ", p.det.long[q], " or 1", sep = "")) } } if (length(sigma.alpha[[q]]) != p.det.long[q]) { sigma.alpha[[q]] <- rep(sigma.alpha[[q]], p.det.long[q]) } } sigma.alpha <- unlist(sigma.alpha) } else { if (verbose) { message("No prior specified for alpha.normal.\nSetting prior mean to 0 and prior variance to 2.72\n") } mu.alpha <- rep(0, p.det) sigma.alpha <- rep(2.72, p.det) } coords.D <- iDist(coords) lower.unif <- 3 / max(coords.D) upper.unif <- 3 / sort(unique(c(coords.D)))[2] if ("phi.unif" %in% names(priors)) { if (!is.vector(priors$phi.unif) | !is.atomic(priors$phi.unif) | length(priors$phi.unif) != 2) { stop("error: phi.unif must be a vector of length 2 with elements corresponding to phi's lower and upper bounds") } phi.a <- priors$phi.unif[1] phi.b <- priors$phi.unif[2] } else { if (verbose) { message("No prior specified for phi.unif.\nSetting uniform bounds based on the range of observed spatial coordinates.\n") } phi.a <- 3 / max(coords.D) phi.b <- 3 / sort(unique(c(coords.D)))[2] } if ("sigma.sq.ig" %in% names(priors)) { if (!is.vector(priors$sigma.sq.ig) | !is.atomic(priors$sigma.sq.ig) | length(priors$sigma.sq.ig) != 2) { stop("error: sigma.sq.ig must be a vector of length 2 with elements corresponding to sigma.sq's shape and scale parameters") } sigma.sq.a <- priors$sigma.sq.ig[1] sigma.sq.b <- priors$sigma.sq.ig[2] } else { if (verbose) { message("No prior specified for sigma.sq.ig.\nSetting the shape and scale parameters to 2.\n") } sigma.sq.a <- 2 sigma.sq.b <- 2 } if (cov.model == 'matern') { if (!"nu.unif" %in% names(priors)) { stop("error: nu.unif must be specified in priors value list") } if (!is.vector(priors$nu.unif) | !is.atomic(priors$nu.unif) | length(priors$nu.unif) != 2) { stop("error: nu.unif must be a vector of length 2 with elements corresponding to nu's lower and upper bounds") } nu.a <- priors$nu.unif[1] nu.b <- priors$nu.unif[2] } else { nu.a <- 0 nu.b <- 0 } if (missing(inits)) { inits <- list() } names(inits) <- tolower(names(inits)) if ("z" %in% names(inits)) { z.inits <- inits$z if (!is.vector(z.inits)) { stop(paste("error: initial values for z must be a vector of length ", J, sep = "")) } if (length(z.inits) != J) { stop(paste("error: initial values for z must be a vector of length ", J, sep = "")) } z.test <- tapply(y, z.long.indx.r, max, na.rm = TRUE) init.test <- sum(z.inits < z.test) if (init.test > 0) { stop("error: initial values for latent occurrence (z) are invalid. Please re-specify inits$z so initial values are 1 if the species is observed at that site.") } } else { z.inits <- tapply(y, z.long.indx.r, max, na.rm = TRUE) if (verbose) { message("z is not specified in initial values.\nSetting initial values based on observed data\n") } } if ("beta" %in% names(inits)) { beta.inits <- inits[["beta"]] if (length(beta.inits) != p.occ & length(beta.inits) != 1) { if (p.occ == 1) { stop(paste("error: initial values for beta must be of length ", p.occ, sep = "")) } else { stop(paste("error: initial values for beta must be of length ", p.occ, " or 1", sep = "")) } } if (length(beta.inits) != p.occ) { beta.inits <- rep(beta.inits, p.occ) } } else { beta.inits <- rnorm(p.occ, mu.beta, sqrt(sigma.beta)) if (verbose) { message('beta is not specified in initial values.\nSetting initial values to random values from the prior distribution\n') } } if ("alpha" %in% names(inits)) { alpha.inits <- inits[["alpha"]] if (length(alpha.inits) != n.data | !is.list(alpha.inits)) { stop(paste("error: initial values for alpha must be a list of length ", n.data, sep = "")) } for (q in 1:n.data) { if (length(alpha.inits[[q]]) != p.det.long[q] & length(alpha.inits[[q]]) != 1) { if (p.det.long[q] == 1) { stop(paste("error: initial values for alpha[[", q, "]] must be a vector of length ", p.det.long[q], sep = "")) } else { stop(paste("error: initial values for alpha[[", q, "]] must be a vector of length ", p.det.long[q], " or 1", sep = "")) } } if (length(alpha.inits[[q]]) != p.det.long[q]) { alpha.inits[[q]] <- rep(alpha.inits, p.det.long[q]) } } alpha.inits <- unlist(alpha.inits) } else { if (verbose) { message("alpha is not specified in initial values.\nSetting initial values to random values from the prior distribution\n") } alpha.inits <- rnorm(p.det, mu.alpha, sqrt(sigma.alpha)) } alpha.indx.r <- unlist(sapply(1:n.data, function(a) rep(a, p.det.long[a]))) alpha.indx.c <- alpha.indx.r - 1 if ("phi" %in% names(inits)) { phi.inits <- inits[["phi"]] if (length(phi.inits) != 1) { stop("error: initial values for phi must be of length 1") } } else { phi.inits <- runif(1, lower.unif, upper.unif) if (verbose) { message("phi is not specified in initial values.\nSetting initial value to random value from the prior distribution\n") } } if ("sigma.sq" %in% names(inits)) { sigma.sq.inits <- inits[["sigma.sq"]] if (length(sigma.sq.inits) != 1) { stop("error: initial values for sigma.sq must be of length 1") } } else { sigma.sq.inits <- rigamma(1, sigma.sq.a, sigma.sq.b) if (verbose) { message("sigma.sq is not specified in initial values.\nSetting initial value to random value from the prior distribution\n") } } if ("w" %in% names(inits)) { w.inits <- inits[["w"]] if (!is.vector(w.inits)) { stop(paste("error: initial values for w must be a vector of length ", J, sep = "")) } if (length(w.inits) != J) { stop(paste("error: initial values for w must be a vector of length ", J, sep = "")) } } else { w.inits <- rep(0, J) if (verbose) { message("w is not specified in initial values.\nSetting initial value to 0\n") } } if ("nu" %in% names(inits)) { nu.inits <- inits[["nu"]] if (length(nu.inits) != 1) { stop("error: initial values for nu must be of length 1") } } else { if (cov.model == 'matern') { if (verbose) { message("nu is not specified in initial values.\nSetting initial value to random value from the prior distribution\n") } nu.inits <- runif(1, nu.a, nu.b) } else { nu.inits <- 0 } } cov.model.names <- c("exponential", "spherical", "matern", "gaussian") if(! cov.model %in% cov.model.names){ stop("error: specified cov.model '",cov.model,"' is not a valid option; choose from ", paste(cov.model.names, collapse=", ", sep="") ,".")} cov.model.indx <- which(cov.model == cov.model.names) - 1 sigma.sq.tuning <- 0 phi.tuning <- 0 nu.tuning <- 0 if (missing(tuning)) { phi.tuning <- 1 if (cov.model == 'matern') { nu.tuning <- 1 } } else { names(tuning) <- tolower(names(tuning)) if(!"phi" %in% names(tuning)) { stop("error: phi must be specified in tuning value list") } phi.tuning <- tuning$phi if (length(phi.tuning) != 1) { stop("error: phi tuning must be a single value") } if (cov.model == 'matern') { if(!"nu" %in% names(tuning)) { stop("error: nu must be specified in tuning value list") } nu.tuning <- tuning$nu if (length(nu.tuning) != 1) { stop("error: nu tuning must be a single value") } } } tuning.c <- log(c(sigma.sq.tuning, phi.tuning, nu.tuning)) model.deviance <- NA curr.chain <- 1 if (!NNGP) { storage.mode(y) <- "double" storage.mode(z.inits) <- "double" storage.mode(X.p.all) <- "double" storage.mode(X) <- "double" storage.mode(coords.D) <- "double" storage.mode(p.det) <- "integer" storage.mode(p.det.long) <- "integer" storage.mode(p.occ) <- "integer" storage.mode(n.obs) <- "integer" storage.mode(n.obs.long) <- "integer" storage.mode(J) <- "integer" storage.mode(J.long) <- "integer" storage.mode(K) <- "integer" storage.mode(n.data) <- "integer" storage.mode(beta.inits) <- "double" storage.mode(alpha.inits) <- "double" storage.mode(phi.inits) <- "double" storage.mode(nu.inits) <- "double" storage.mode(w.inits) <- "double" storage.mode(sigma.sq.inits) <- "double" storage.mode(z.long.indx.c) <- "integer" storage.mode(data.indx.c) <- "integer" storage.mode(alpha.indx.c) <- "integer" storage.mode(mu.beta) <- "double" storage.mode(Sigma.beta) <- "double" storage.mode(mu.alpha) <- "double" storage.mode(sigma.alpha) <- "double" storage.mode(phi.a) <- "double" storage.mode(phi.b) <- "double" storage.mode(sigma.sq.a) <- "double" storage.mode(sigma.sq.b) <- "double" storage.mode(nu.a) <- "double" storage.mode(nu.b) <- "double" storage.mode(tuning.c) <- "double" storage.mode(cov.model.indx) <- "integer" storage.mode(n.batch) <- "integer" storage.mode(batch.length) <- "integer" storage.mode(accept.rate) <- "double" storage.mode(n.omp.threads) <- "integer" storage.mode(verbose) <- "integer" storage.mode(n.report) <- "integer" storage.mode(n.burn) <- "integer" storage.mode(n.thin) <- "integer" storage.mode(curr.chain) <- "integer" storage.mode(n.chains) <- "integer" n.post.samples <- length(seq(from = n.burn + 1, to = n.samples, by = as.integer(n.thin))) storage.mode(n.post.samples) <- "integer" out.tmp <- list() for (i in 1:n.chains) { if (i > 1) { beta.inits <- rnorm(p.occ, mu.beta, sqrt(sigma.beta)) alpha.inits <- rnorm(p.det, mu.alpha, sqrt(sigma.alpha)) sigma.sq.inits <- rigamma(1, sigma.sq.a, sigma.sq.b) phi.inits <- runif(1, phi.a, phi.b) if (cov.model == 'matern') { nu.inits <- runif(1, nu.a, nu.b) } } storage.mode(curr.chain) <- "integer" out.tmp[[i]] <- .Call("spIntPGOcc", y, X, X.p.all, coords.D, p.occ, p.det, p.det.long, J, J.long, K, n.obs, n.obs.long, n.data, beta.inits, alpha.inits, z.inits, w.inits, phi.inits, sigma.sq.inits, nu.inits, z.long.indx.c, data.indx.c, alpha.indx.c, mu.beta, mu.alpha, Sigma.beta, sigma.alpha, phi.a, phi.b, sigma.sq.a, sigma.sq.b, nu.a, nu.b, tuning.c, cov.model.indx, n.batch, batch.length, accept.rate, n.omp.threads, verbose, n.report, n.burn, n.thin, n.post.samples, curr.chain, n.chains) curr.chain <- curr.chain + 1 } out <- list() out$rhat <- list() if (n.chains > 1) { out$rhat$beta <- gelman.diag(mcmc.list(lapply(out.tmp, function(a) mcmc(t(a$beta.samples)))), autoburnin = FALSE)$psrf[, 2] out$rhat$alpha <- gelman.diag(mcmc.list(lapply(out.tmp, function(a) mcmc(t(a$alpha.samples)))), autoburnin = FALSE)$psrf[, 2] out$rhat$theta <- gelman.diag(mcmc.list(lapply(out.tmp, function(a) mcmc(t(a$theta.samples)))), autoburnin = FALSE)$psrf[, 2] } else { out$rhat$beta <- rep(NA, p.occ) out$rhat$alpha <- rep(NA, p.det) out$rhat$theta <- rep(NA, ifelse(cov.model == 'matern', 3, 2)) } out$beta.samples <- mcmc(do.call(rbind, lapply(out.tmp, function(a) t(a$beta.samples)))) colnames(out$beta.samples) <- x.names out$alpha.samples <- mcmc(do.call(rbind, lapply(out.tmp, function(a) t(a$alpha.samples)))) colnames(out$alpha.samples) <- x.p.names out$theta.samples <- mcmc(do.call(rbind, lapply(out.tmp, function(a) t(a$theta.samples)))) if (cov.model != 'matern') { colnames(out$theta.samples) <- c('sigma.sq', 'phi') } else { colnames(out$theta.samples) <- c('sigma.sq', 'phi', 'nu') } out$z.samples <- mcmc(do.call(rbind, lapply(out.tmp, function(a) t(a$z.samples)))) out$psi.samples <- mcmc(do.call(rbind, lapply(out.tmp, function(a) t(a$psi.samples)))) out$w.samples <- mcmc(do.call(rbind, lapply(out.tmp, function(a) t(a$w.samples)))) out$y.rep.samples <- do.call(rbind, lapply(out.tmp, function(a) a$y.rep.samples)) tmp <- list() indx <- 1 for (q in 1:n.data) { tmp[[q]] <- array(NA, dim = c(J.long[q] * K.long.max[q], n.post.samples * n.chains)) tmp[[q]][names.long[[q]], ] <- out$y.rep.samples[indx:(indx + n.obs.long[q] - 1), ] tmp[[q]] <- array(tmp[[q]], dim = c(J.long[q], K.long.max[q], n.post.samples * n.chains)) tmp[[q]] <- aperm(tmp[[q]], c(3, 1, 2)) indx <- indx + n.obs.long[q] } out$y.rep.samples <- tmp out$ESS <- list() out$ESS$beta <- effectiveSize(out$beta.samples) out$ESS$alpha <- effectiveSize(out$alpha.samples) out$ESS$theta <- effectiveSize(out$theta.samples) out$X <- X out$X.p <- X.p.orig out$y <- y.big out$call <- cl out$n.samples <- n.samples out$sites <- sites out$cov.model.indx <- cov.model.indx out$type <- "GP" out$coords <- coords out$n.post <- n.post.samples out$n.thin <- n.thin out$n.burn <- n.burn out$n.chains <- n.chains if (!missing(k.fold)) { if (verbose) { cat("----------------------------------------\n"); cat("\tCross-validation\n"); cat("----------------------------------------\n"); message(paste("Performing ", k.fold, "-fold cross-validation using ", k.fold.threads, " thread(s).", sep = '')) } set.seed(k.fold.seed) if (missing(k.fold.data)) { k.fold.data <- NULL } if (!is.null(k.fold.data)) { if (!is.numeric(k.fold.data) | length(k.fold.data) != 1) { stop("error: if specified, k.fold.data must be a single numeric value") } if (verbose) { message(paste("Only holding out data from data source ", k.fold.data, ".", sep = '')) } sites.random <- sample(sites[[k.fold.data]]) } else { sites.random <- sample(1:J) } sites.k.fold <- split(sites.random, rep(1:k.fold, length.out = length(sites.random))) registerDoParallel(k.fold.threads) model.deviance <- foreach (i = 1:k.fold, .combine = "+") %dopar% { curr.set <- sort(sites.k.fold[[i]]) curr.set.pred <- curr.set curr.set.fit <- (1:J)[-curr.set] if (!is.null(k.fold.data)) { curr.set.fit <- sort(unique(c(curr.set.fit, unlist(sites[-k.fold.data])))) } y.indx <- !((z.long.indx.r) %in% curr.set) if (!is.null(k.fold.data)) { y.indx <- ifelse(data.indx.r == k.fold.data, y.indx, TRUE) } y.fit <- y[y.indx] y.0 <- y[!y.indx] z.inits.fit <- z.inits[curr.set.fit] w.inits.fit <- w.inits[curr.set.fit] coords.fit <- coords[curr.set.fit, , drop = FALSE] coords.0 <- coords[curr.set.pred, , drop = FALSE] coords.D.fit <- coords.D[curr.set.fit, curr.set.fit, drop = FALSE] coords.D.0 <- coords.D[curr.set.pred, curr.set.pred, drop = FALSE] X.p.fit <- X.p.all[y.indx, , drop = FALSE] X.p.0 <- X.p.all[!y.indx, , drop = FALSE] X.fit <- X[curr.set.fit, , drop = FALSE] X.0 <- X[curr.set.pred, , drop = FALSE] J.fit <- nrow(X.fit) sites.fit <- sapply(sites, function(a) which(as.numeric(row.names(X.fit)) %in% a[a %in% curr.set.fit])) tmp <- sapply(sites, function(a) a %in% curr.set.fit) if (!is.null(k.fold.data)) { sites.fit[[k.fold.data]] <- which(as.numeric(row.names(X.fit)) %in% sites[[k.fold.data]][sites[[k.fold.data]] %in% (1:J)[-curr.set]]) tmp[[k.fold.data]] <- sites[[k.fold.data]] %in% (1:J)[-curr.set] } K.fit <- K[unlist(tmp)] z.long.indx.fit <- list() tmp.indx <- 1 for (q in 1:n.data) { z.long.indx.fit[[q]] <- matrix(NA, length(sites.fit[[q]]), K.long.max[q]) for (j in 1:length(sites.fit[[q]])) { z.long.indx.fit[[q]][j, 1:K.fit[tmp.indx]] <- sites.fit[[q]][j] tmp.indx <- tmp.indx + 1 } z.long.indx.fit[[q]] <- c(z.long.indx.fit[[q]]) z.long.indx.fit[[q]] <- z.long.indx.fit[[q]][!is.na(z.long.indx.fit[[q]])] - 1 } z.long.indx.fit <- unlist(z.long.indx.fit) sites.0 <- sapply(sites, function(a) which(as.numeric(row.names(X.0)) %in% a[a %in% curr.set.pred])) tmp <- sapply(sites, function(a) a %in% curr.set.pred) if (!is.null(k.fold.data)) { sites.0[-k.fold.data] <- NA for (q in 1:n.data) { if (q != k.fold.data) { tmp[[q]] <- rep(FALSE, J.long[q]) } } } K.0 <- K[unlist(tmp)] z.long.indx.0 <- list() tmp.indx <- 1 for (q in 1:n.data) { if (!is.na(sites.0[[q]][1])) { z.long.indx.0[[q]] <- matrix(NA, length(sites.0[[q]]), K.long.max[q]) for (j in 1:length(sites.0[[q]])) { z.long.indx.0[[q]][j, 1:K.0[tmp.indx]] <- sites.0[[q]][j] tmp.indx <- tmp.indx + 1 } z.long.indx.0[[q]] <- c(z.long.indx.0[[q]]) z.long.indx.0[[q]] <- z.long.indx.0[[q]][!is.na(z.long.indx.0[[q]])] - 1 } } z.long.indx.0 <- unlist(z.long.indx.0) verbose.fit <- FALSE n.omp.threads.fit <- 1 n.obs.fit <- length(y.fit) n.obs.0 <- length(y.0) data.indx.c.fit <- data.indx.c[y.indx] data.indx.0 <- data.indx.c[!y.indx] + 1 n.obs.long.fit <- as.vector(table(data.indx.c.fit)) n.obs.long.0 <- n.obs.long - n.obs.long.fit J.long.fit <- as.vector(tapply(z.long.indx.fit, factor(data.indx.c.fit), FUN = function(a) length(unique(a)))) storage.mode(y.fit) <- "double" storage.mode(z.inits.fit) <- "double" storage.mode(X.p.fit) <- "double" storage.mode(X.fit) <- "double" storage.mode(coords.D.fit) <- "double" storage.mode(p.det) <- "integer" storage.mode(p.det.long) <- "integer" storage.mode(p.occ) <- "integer" storage.mode(n.obs.fit) <- "integer" storage.mode(n.obs.long.fit) <- "integer" storage.mode(J.fit) <- "integer" storage.mode(J.long.fit) <- "integer" storage.mode(K.fit) <- "integer" storage.mode(n.data) <- "integer" storage.mode(beta.inits) <- "double" storage.mode(alpha.inits) <- "double" storage.mode(phi.inits) <- "double" storage.mode(nu.inits) <- "double" storage.mode(w.inits.fit) <- "double" storage.mode(sigma.sq.inits) <- "double" storage.mode(z.long.indx.fit) <- "integer" storage.mode(data.indx.c.fit) <- "integer" storage.mode(alpha.indx.c) <- "integer" storage.mode(mu.beta) <- "double" storage.mode(Sigma.beta) <- "double" storage.mode(mu.alpha) <- "double" storage.mode(sigma.alpha) <- "double" storage.mode(phi.a) <- "double" storage.mode(phi.b) <- "double" storage.mode(sigma.sq.a) <- "double" storage.mode(sigma.sq.b) <- "double" storage.mode(nu.a) <- "double" storage.mode(nu.b) <- "double" storage.mode(tuning.c) <- "double" storage.mode(cov.model.indx) <- "integer" storage.mode(n.batch) <- "integer" storage.mode(batch.length) <- "integer" storage.mode(accept.rate) <- "double" storage.mode(n.omp.threads.fit) <- "integer" storage.mode(verbose.fit) <- "integer" storage.mode(n.report) <- "integer" storage.mode(n.burn) <- "integer" storage.mode(n.thin) <- "integer" curr.chain <- 1 storage.mode(curr.chain) <- "integer" out.fit <- .Call("spIntPGOcc", y.fit, X.fit, X.p.fit, coords.D.fit, p.occ, p.det, p.det.long, J.fit, J.long.fit, K.fit, n.obs.fit, n.obs.long.fit, n.data, beta.inits, alpha.inits, z.inits.fit, w.inits.fit, phi.inits, sigma.sq.inits, nu.inits, z.long.indx.fit, data.indx.c.fit, alpha.indx.c, mu.beta, mu.alpha, Sigma.beta, sigma.alpha, phi.a, phi.b, sigma.sq.a, sigma.sq.b, nu.a, nu.b, tuning.c, cov.model.indx, n.batch, batch.length, accept.rate, n.omp.threads.fit, verbose.fit, n.report, n.burn, n.thin, n.post.samples, curr.chain, n.chains) out.fit$beta.samples <- mcmc(t(out.fit$beta.samples)) colnames(out.fit$beta.samples) <- x.names out.fit$theta.samples <- mcmc(t(out.fit$theta.samples)) if (cov.model != 'matern') { colnames(out.fit$theta.samples) <- c('sigma.sq', 'phi') } else { colnames(out.fit$theta.samples) <- c('sigma.sq', 'phi', 'nu') } out.fit$w.samples <- mcmc(t(out.fit$w.samples)) out.fit$z.samples <- mcmc(t(out.fit$z.samples)) out.fit$psi.samples <- mcmc(t(out.fit$psi.samples)) out.fit$X <- X.fit out.fit$X.p <- X.p.fit out.fit$call <- cl out.fit$n.samples <- batch.length * n.batch out.fit$cov.model.indx <- cov.model.indx out.fit$type <- "GP" out.fit$coords <- coords.fit out.fit$n.post <- n.post.samples out.fit$n.thin <- n.thin out.fit$n.burn <- n.burn out.fit$n.chains <- 1 class(out.fit) <- "spPGOcc" out.pred <- predict.spPGOcc(out.fit, X.0, coords.0, verbose = FALSE) p.0.samples <- matrix(NA, n.post.samples, nrow(X.p.0)) like.samples <- rep(NA, nrow(X.p.0)) for (j in 1:nrow(X.p.0)) { p.0.samples[, j] <- logit.inv(X.p.0[j, 1:sum(alpha.indx.r == data.indx.0[j])] %*% out.fit$alpha.samples[which(alpha.indx.r == data.indx.0[j]), ]) like.samples[j] <- mean(dbinom(y.0[j], 1, p.0.samples[, j] * out.pred$z.0.samples[, z.long.indx.0[j] + 1])) } as.vector(tapply(like.samples, data.indx.0, function(a) sum(log(a)))) } model.deviance <- -2 * model.deviance out$k.fold.deviance <- model.deviance stopImplicitCluster() } class(out) <- "spIntPGOcc" out } else { if(verbose){ cat("----------------------------------------\n"); cat("\tBuilding the neighbor list\n"); cat("----------------------------------------\n"); } search.type.names <- c("brute", "cb") if(!search.type %in% search.type.names){ stop("error: specified search.type '",search.type, "' is not a valid option; choose from ", paste(search.type.names, collapse=", ", sep="") ,".") } if(search.type == "brute"){ indx <- mkNNIndx(coords, n.neighbors, n.omp.threads) } else{ indx <- mkNNIndxCB(coords, n.neighbors, n.omp.threads) } nn.indx <- indx$nnIndx nn.indx.lu <- indx$nnIndxLU nn.indx.run.time <- indx$run.time if(verbose){ cat("----------------------------------------\n"); cat("Building the neighbors of neighbors list\n"); cat("----------------------------------------\n"); } indx <- mkUIndx(J, n.neighbors, nn.indx, nn.indx.lu, u.search.type) u.indx <- indx$u.indx u.indx.lu <- indx$u.indx.lu ui.indx <- indx$ui.indx u.indx.run.time <- indx$run.time storage.mode(y) <- "double" storage.mode(z.inits) <- "double" storage.mode(X.p.all) <- "double" storage.mode(X) <- "double" storage.mode(coords) <- "double" storage.mode(p.det) <- "integer" storage.mode(p.det.long) <- "integer" storage.mode(p.occ) <- "integer" storage.mode(n.obs) <- "integer" storage.mode(n.obs.long) <- "integer" storage.mode(J) <- "integer" storage.mode(J.long) <- "integer" storage.mode(K) <- "integer" storage.mode(n.data) <- "integer" storage.mode(beta.inits) <- "double" storage.mode(alpha.inits) <- "double" storage.mode(phi.inits) <- "double" storage.mode(sigma.sq.inits) <- "double" storage.mode(nu.inits) <- "double" storage.mode(w.inits) <- "double" storage.mode(z.long.indx.c) <- "integer" storage.mode(data.indx.c) <- "integer" storage.mode(alpha.indx.c) <- "integer" storage.mode(mu.beta) <- "double" storage.mode(Sigma.beta) <- "double" storage.mode(mu.alpha) <- "double" storage.mode(sigma.alpha) <- "double" storage.mode(phi.a) <- "double" storage.mode(phi.b) <- "double" storage.mode(nu.a) <- "double" storage.mode(nu.b) <- "double" storage.mode(sigma.sq.a) <- "double" storage.mode(sigma.sq.b) <- "double" storage.mode(tuning.c) <- "double" storage.mode(n.batch) <- "integer" storage.mode(batch.length) <- "integer" storage.mode(accept.rate) <- "double" storage.mode(n.omp.threads) <- "integer" storage.mode(verbose) <- "integer" storage.mode(n.report) <- "integer" storage.mode(cov.model.indx) <- "integer" storage.mode(n.report) <- "integer" storage.mode(nn.indx) <- "integer" storage.mode(nn.indx.lu) <- "integer" storage.mode(u.indx) <- "integer" storage.mode(u.indx.lu) <- "integer" storage.mode(ui.indx) <- "integer" storage.mode(n.neighbors) <- "integer" storage.mode(n.burn) <- "integer" storage.mode(n.thin) <- "integer" storage.mode(curr.chain) <- "integer" storage.mode(n.chains) <- "integer" n.post.samples <- length(seq(from = n.burn + 1, to = n.samples, by = as.integer(n.thin))) storage.mode(n.post.samples) <- "integer" out.tmp <- list() for (i in 1:n.chains) { if (i > 1) { beta.inits <- rnorm(p.occ, mu.beta, sqrt(sigma.beta)) alpha.inits <- rnorm(p.det, mu.alpha, sqrt(sigma.alpha)) sigma.sq.inits <- rigamma(1, sigma.sq.a, sigma.sq.b) phi.inits <- runif(1, phi.a, phi.b) if (cov.model == 'matern') { nu.inits <- runif(1, nu.a, nu.b) } } storage.mode(curr.chain) <- "integer" out.tmp[[i]] <- .Call("spIntPGOccNNGP", y, X, X.p.all, coords, p.occ, p.det, p.det.long, J, J.long, K, n.obs, n.obs.long, n.data, n.neighbors, nn.indx, nn.indx.lu, u.indx, u.indx.lu, ui.indx, beta.inits, alpha.inits, z.inits, w.inits, phi.inits, sigma.sq.inits, nu.inits, z.long.indx.c, data.indx.c, alpha.indx.c, mu.beta, mu.alpha, Sigma.beta, sigma.alpha, phi.a, phi.b, sigma.sq.a, sigma.sq.b, nu.a, nu.b, tuning.c, cov.model.indx, n.batch, batch.length, accept.rate, n.omp.threads, verbose, n.report, n.burn, n.thin, n.post.samples, curr.chain, n.chains) curr.chain <- curr.chain + 1 } out <- list() out$rhat <- list() if (n.chains > 1) { out$rhat$beta <- gelman.diag(mcmc.list(lapply(out.tmp, function(a) mcmc(t(a$beta.samples)))), autoburnin = FALSE)$psrf[, 2] out$rhat$alpha <- gelman.diag(mcmc.list(lapply(out.tmp, function(a) mcmc(t(a$alpha.samples)))), autoburnin = FALSE)$psrf[, 2] out$rhat$theta <- gelman.diag(mcmc.list(lapply(out.tmp, function(a) mcmc(t(a$theta.samples)))), autoburnin = FALSE)$psrf[, 2] } else { out$rhat$beta <- rep(NA, p.occ) out$rhat$alpha <- rep(NA, p.det) out$rhat$theta <- rep(NA, ifelse(cov.model == 'matern', 3, 2)) } out$coords <- coords[order(ord), ] out$z.samples <- mcmc(do.call(rbind, lapply(out.tmp, function(a) t(a$z.samples)))) out$z.samples <- mcmc(out$z.samples[, order(ord), drop = FALSE]) out$X <- X[order(ord), , drop = FALSE] out$w.samples <- mcmc(do.call(rbind, lapply(out.tmp, function(a) t(a$w.samples)))) out$w.samples <- mcmc(out$w.samples[, order(ord), drop = FALSE]) out$psi.samples <- mcmc(do.call(rbind, lapply(out.tmp, function(a) t(a$psi.samples)))) out$psi.samples <- mcmc(out$psi.samples[, order(ord), drop = FALSE]) out$beta.samples <- mcmc(do.call(rbind, lapply(out.tmp, function(a) t(a$beta.samples)))) colnames(out$beta.samples) <- x.names out$alpha.samples <- mcmc(do.call(rbind, lapply(out.tmp, function(a) t(a$alpha.samples)))) colnames(out$alpha.samples) <- x.p.names out$theta.samples <- mcmc(do.call(rbind, lapply(out.tmp, function(a) t(a$theta.samples)))) if (cov.model != 'matern') { colnames(out$theta.samples) <- c('sigma.sq', 'phi') } else { colnames(out$theta.samples) <- c('sigma.sq', 'phi', 'nu') } out$y.rep.samples <- do.call(rbind, lapply(out.tmp, function(a) a$y.rep.samples)) tmp <- list() indx <- 1 for (q in 1:n.data) { tmp[[q]] <- array(NA, dim = c(J.long[q] * K.long.max[q], n.post.samples * n.chains)) tmp[[q]][names.long[[q]], ] <- out$y.rep.samples[indx:(indx + n.obs.long[q] - 1), ] tmp[[q]] <- array(tmp[[q]], dim = c(J.long[q], K.long.max[q], n.post.samples * n.chains)) tmp[[q]] <- aperm(tmp[[q]], c(3, 1, 2)) indx <- indx + n.obs.long[q] } out$y.rep.samples <- tmp out$ESS <- list() out$ESS$beta <- effectiveSize(out$beta.samples) out$ESS$alpha <- effectiveSize(out$alpha.samples) out$ESS$theta <- effectiveSize(out$theta.samples) out$X.p <- X.p.orig out$y <- y.big out$call <- cl out$n.samples <- batch.length * n.batch out$sites <- sites.orig out$n.neighbors <- n.neighbors out$cov.model.indx <- cov.model.indx out$type <- "NNGP" out$n.post <- n.post.samples out$n.thin <- n.thin out$n.burn <- n.burn out$n.chains <- n.chains if (!missing(k.fold)) { if (verbose) { cat("----------------------------------------\n"); cat("\tCross-validation\n"); cat("----------------------------------------\n"); message(paste("Performing ", k.fold, "-fold cross-validation using ", k.fold.threads, " thread(s).", sep = '')) } set.seed(k.fold.seed) if (missing(k.fold.data)) { k.fold.data <- NULL } if (!is.null(k.fold.data)) { if (!is.numeric(k.fold.data) | length(k.fold.data) != 1) { stop("error: if specified, k.fold.data must be a single numeric value") } if (verbose) { message(paste("Only holding out data from data source ", k.fold.data, ".", sep = '')) } sites.random <- sample(sites[[k.fold.data]]) } else { sites.random <- sample(1:J) } sites.k.fold <- split(sites.random, rep(1:k.fold, length.out = length(sites.random))) registerDoParallel(k.fold.threads) model.deviance <- foreach (i = 1:k.fold, .combine = "+") %dopar% { curr.set <- sort(sites.k.fold[[i]]) curr.set.pred <- curr.set curr.set.fit <- (1:J)[-curr.set] if (!is.null(k.fold.data)) { curr.set.fit <- sort(unique(c(curr.set.fit, unlist(sites[-k.fold.data])))) } y.indx <- !((z.long.indx.r) %in% curr.set) if (!is.null(k.fold.data)) { y.indx <- ifelse(data.indx.r == k.fold.data, y.indx, TRUE) } y.fit <- y[y.indx] y.0 <- y[!y.indx] z.inits.fit <- z.inits[curr.set.fit] w.inits.fit <- w.inits[curr.set.fit] coords.fit <- coords[curr.set.fit, , drop = FALSE] coords.0 <- coords[curr.set.pred, , drop = FALSE] X.p.fit <- X.p.all[y.indx, , drop = FALSE] X.p.0 <- X.p.all[!y.indx, , drop = FALSE] X.fit <- X[curr.set.fit, , drop = FALSE] X.0 <- X[curr.set.pred, , drop = FALSE] J.fit <- nrow(X.fit) sites.fit <- sapply(sites, function(a) which(as.numeric(row.names(X.fit)) %in% a[a %in% curr.set.fit])) tmp <- sapply(sites, function(a) a %in% curr.set.fit) if (!is.null(k.fold.data)) { sites.fit[[k.fold.data]] <- which(as.numeric(row.names(X.fit)) %in% sites[[k.fold.data]][sites[[k.fold.data]] %in% (1:J)[-curr.set]]) tmp[[k.fold.data]] <- sites[[k.fold.data]] %in% (1:J)[-curr.set] } K.fit <- K[unlist(tmp)] z.long.indx.fit <- list() tmp.indx <- 1 for (q in 1:n.data) { z.long.indx.fit[[q]] <- matrix(NA, length(sites.fit[[q]]), K.long.max[q]) for (j in 1:length(sites.fit[[q]])) { z.long.indx.fit[[q]][j, 1:K.fit[tmp.indx]] <- sites.fit[[q]][j] tmp.indx <- tmp.indx + 1 } z.long.indx.fit[[q]] <- c(z.long.indx.fit[[q]]) z.long.indx.fit[[q]] <- z.long.indx.fit[[q]][!is.na(z.long.indx.fit[[q]])] - 1 } z.long.indx.fit <- unlist(z.long.indx.fit) sites.0 <- sapply(sites, function(a) which(as.numeric(row.names(X.0)) %in% a[a %in% curr.set.pred])) tmp <- sapply(sites, function(a) a %in% curr.set.pred) if (!is.null(k.fold.data)) { sites.0[-k.fold.data] <- NA for (q in 1:n.data) { if (q != k.fold.data) { tmp[[q]] <- rep(FALSE, J.long[q]) } } } K.0 <- K[unlist(tmp)] z.long.indx.0 <- list() tmp.indx <- 1 for (q in 1:n.data) { if (!is.na(sites.0[[q]][1])) { z.long.indx.0[[q]] <- matrix(NA, length(sites.0[[q]]), K.long.max[q]) for (j in 1:length(sites.0[[q]])) { z.long.indx.0[[q]][j, 1:K.0[tmp.indx]] <- sites.0[[q]][j] tmp.indx <- tmp.indx + 1 } z.long.indx.0[[q]] <- c(z.long.indx.0[[q]]) z.long.indx.0[[q]] <- z.long.indx.0[[q]][!is.na(z.long.indx.0[[q]])] - 1 } } z.long.indx.0 <- unlist(z.long.indx.0) verbose.fit <- FALSE n.omp.threads.fit <- 1 n.obs.fit <- length(y.fit) n.obs.0 <- length(y.0) data.indx.c.fit <- data.indx.c[y.indx] data.indx.0 <- data.indx.c[!y.indx] + 1 n.obs.long.fit <- as.vector(table(data.indx.c.fit)) n.obs.long.0 <- n.obs.long - n.obs.long.fit J.long.fit <- as.vector(tapply(z.long.indx.fit, factor(data.indx.c.fit), FUN = function(a) length(unique(a)))) if(search.type == "brute"){ indx <- mkNNIndx(coords.fit, n.neighbors, n.omp.threads.fit) } else{ indx <- mkNNIndxCB(coords.fit, n.neighbors, n.omp.threads.fit) } nn.indx.fit <- indx$nnIndx nn.indx.lu.fit <- indx$nnIndxLU indx <- mkUIndx(J.fit, n.neighbors, nn.indx.fit, nn.indx.lu.fit, u.search.type) u.indx.fit <- indx$u.indx u.indx.lu.fit <- indx$u.indx.lu ui.indx.fit <- indx$ui.indx storage.mode(y.fit) <- "double" storage.mode(z.inits.fit) <- "double" storage.mode(X.p.fit) <- "double" storage.mode(X.fit) <- "double" storage.mode(coords.fit) <- "double" storage.mode(p.det) <- "integer" storage.mode(p.det.long) <- "integer" storage.mode(p.occ) <- "integer" storage.mode(n.obs.fit) <- "integer" storage.mode(n.obs.long.fit) <- "integer" storage.mode(J.fit) <- "integer" storage.mode(J.long.fit) <- "integer" storage.mode(K.fit) <- "integer" storage.mode(n.data) <- "integer" storage.mode(beta.inits) <- "double" storage.mode(alpha.inits) <- "double" storage.mode(phi.inits) <- "double" storage.mode(sigma.sq.inits) <- "double" storage.mode(nu.inits) <- "double" storage.mode(w.inits.fit) <- "double" storage.mode(z.long.indx.fit) <- "integer" storage.mode(data.indx.c.fit) <- "integer" storage.mode(alpha.indx.c) <- "integer" storage.mode(mu.beta) <- "double" storage.mode(Sigma.beta) <- "double" storage.mode(mu.alpha) <- "double" storage.mode(sigma.alpha) <- "double" storage.mode(phi.a) <- "double" storage.mode(phi.b) <- "double" storage.mode(nu.a) <- "double" storage.mode(nu.b) <- "double" storage.mode(sigma.sq.a) <- "double" storage.mode(sigma.sq.b) <- "double" storage.mode(tuning.c) <- "double" storage.mode(n.batch) <- "integer" storage.mode(batch.length) <- "integer" storage.mode(accept.rate) <- "double" storage.mode(n.omp.threads.fit) <- "integer" storage.mode(verbose.fit) <- "integer" storage.mode(n.report) <- "integer" storage.mode(cov.model.indx) <- "integer" storage.mode(n.report) <- "integer" storage.mode(nn.indx.fit) <- "integer" storage.mode(nn.indx.lu.fit) <- "integer" storage.mode(u.indx.fit) <- "integer" storage.mode(u.indx.lu.fit) <- "integer" storage.mode(ui.indx.fit) <- "integer" storage.mode(n.neighbors) <- "integer" storage.mode(n.burn) <- "integer" storage.mode(n.thin) <- "integer" curr.chain <- 1 storage.mode(curr.chain) <- "integer" out.fit <- .Call("spIntPGOccNNGP", y.fit, X.fit, X.p.fit, coords.fit, p.occ, p.det, p.det.long, J.fit, J.long.fit, K.fit, n.obs.fit, n.obs.long.fit, n.data, n.neighbors, nn.indx.fit, nn.indx.lu.fit, u.indx.fit, u.indx.lu.fit, ui.indx.fit, beta.inits, alpha.inits, z.inits.fit, w.inits.fit, phi.inits, sigma.sq.inits, nu.inits, z.long.indx.fit, data.indx.c.fit, alpha.indx.c, mu.beta, mu.alpha, Sigma.beta, sigma.alpha, phi.a, phi.b, sigma.sq.a, sigma.sq.b, nu.a, nu.b, tuning.c, cov.model.indx, n.batch, batch.length, accept.rate, n.omp.threads.fit, verbose.fit, n.report, n.burn, n.thin, n.post.samples, curr.chain, n.chains) out.fit$beta.samples <- mcmc(t(out.fit$beta.samples)) colnames(out.fit$beta.samples) <- x.names out.fit$theta.samples <- mcmc(t(out.fit$theta.samples)) if (cov.model != 'matern') { colnames(out.fit$theta.samples) <- c('sigma.sq', 'phi') } else { colnames(out.fit$theta.samples) <- c('sigma.sq', 'phi', 'nu') } out.fit$z.samples <- mcmc(t(out.fit$z.samples)) out.fit$psi.samples <- mcmc(t(out.fit$psi.samples)) out.fit$w.samples <- mcmc(t(out.fit$w.samples)) out.fit$X <- X.fit out.fit$X.p <- X.p.fit out.fit$call <- cl out.fit$n.samples <- batch.length * n.batch out.fit$cov.model.indx <- cov.model.indx out.fit$type <- "NNGP" out.fit$n.neighbors <- n.neighbors out.fit$coords <- coords.fit out.fit$n.post <- n.post.samples out.fit$n.thin <- n.thin out.fit$n.burn <- n.burn out.fit$n.chains <- 1 class(out.fit) <- "spPGOcc" out.pred <- predict.spPGOcc(out.fit, X.0, coords.0, verbose = FALSE) p.0.samples <- matrix(NA, n.post.samples, nrow(X.p.0)) like.samples <- rep(NA, nrow(X.p.0)) for (j in 1:nrow(X.p.0)) { p.0.samples[, j] <- logit.inv(X.p.0[j, 1:sum(alpha.indx.r == data.indx.0[j])] %*% out.fit$alpha.samples[which(alpha.indx.r == data.indx.0[j]), ]) like.samples[j] <- mean(dbinom(y.0[j], 1, p.0.samples[, j] * out.pred$z.0.samples[, z.long.indx.0[j] + 1])) } as.vector(tapply(like.samples, data.indx.0, function(a) sum(log(a)))) } model.deviance <- -2 * model.deviance out$k.fold.deviance <- model.deviance stopImplicitCluster() } class(out) <- "spIntPGOcc" out$run.time <- proc.time() - ptm out } }
tags = htmltools::tags txt_input = function(..., width = '100%') shiny::textInput(..., width = width) sel_input = function(...) shiny::selectizeInput( ..., width = '98%', multiple = TRUE, options = list(create = TRUE) ) meta = blogdown:::collect_yaml() lang = blogdown:::get_lang() adir = blogdown:::theme_dir() adir = if (length(adir)) file.path(adir, 'archetypes') adir = c('archetypes', adir) adir = dir(adir, full.names = TRUE) adir = paste0(basename(adir), ifelse(utils::file_test('-d', adir), '/', '')) shiny::runGadget( miniUI::miniPage(miniUI::miniContentPanel( txt_input('title', 'Title', placeholder = 'Post Title'), shiny::fillRow( txt_input('author', 'Author', blogdown:::get_author(), width = '98%'), shiny::dateInput('date', 'Date', Sys.Date(), width = '98%'), shiny::selectizeInput( 'subdir', 'Subdirectory', blogdown:::get_subdirs(), selected = getOption('blogdown.subdir', 'post'), width = '98%', multiple = FALSE, options = list(create = TRUE, placeholder = '(optional)') ), height = '70px' ), shiny::fillRow( sel_input('cat', 'Categories', meta$categories), sel_input('tag', 'Tags', meta$tags), shiny::selectInput( 'kind', 'Archetype', width = '98%', choices = unique(c('', adir)) ), height = '70px' ), shiny::fillRow( txt_input('file', 'Filename', '', 'automatically generated (edit if you want)'), height = '70px' ), if (is.null(lang)) { shiny::fillRow(txt_input('slug', 'Slug', '', '(optional)'), height = '70px') } else { shiny::fillRow( txt_input('slug', 'Slug', '', '(optional)', width = '98%'), txt_input('lang', 'Language', lang, width = '98%'), height = '70px' ) }, shiny::fillRow( shiny::radioButtons( 'format', 'Format', inline = TRUE, c('Markdown' = '.md', 'R Markdown (.Rmd)' = '.Rmd', 'R Markdown (.Rmarkdown)' = '.Rmarkdown'), selected = getOption('blogdown.ext', '.md') ), height = '70px' ), miniUI::gadgetTitleBar(NULL) )), server = function(input, output, session) { empty_title = shiny::reactive(grepl('^\\s*$', input$title)) shiny::observe({ shiny::updateTextInput( session, 'slug', placeholder = if (empty_title()) '(optional)' else blogdown:::dash_filename(input$title) ) }) if (is.function(subdir_fun <- getOption('blogdown.subdir_fun'))) shiny::observe({ sub2 = subdir_fun(input$title) shiny::updateSelectizeInput(session, 'subdir', selected = sub2, choices = unique(c( sub2, blogdown:::get_subdirs() ))) }) shiny::observe({ if (grepl('^\\s*$', slug <- input$slug)) slug = blogdown:::dash_filename(input$title) shiny::updateTextInput( session, 'file', value = blogdown:::post_filename( slug, input$subdir, shiny::isolate(input$format), input$date, input$lang ) ) }) shiny::observeEvent(input$format, { f = input$file if (f != '') shiny::updateTextInput( session, 'file', value = xfun::with_ext(f, input$format) ) }, ignoreInit = TRUE) shiny::observeEvent(input$done, { if (grepl('^\\s*$', input$file)) return( warning('The filename is empty!', call. = FALSE) ) options(blogdown.author = input$author) blogdown::new_post( input$title, author = input$author, ext = input$format, categories = input$cat, tags = input$tag, file = gsub('[-[:space:]]+', '-', input$file), slug = if (input$slug != '') input$slug, subdir = input$subdir, date = input$date, kind = xfun::sans_ext(input$kind) ) shiny::stopApp() }) shiny::observeEvent(input$cancel, { shiny::stopApp() }) }, stopOnCancel = FALSE, viewer = shiny::dialogViewer('New Post', height = 500) )
setGeneric("distsuml2min", function (o, x = 0, y = 0, max.iter = 100, eps = 1.e-3, verbose = FALSE, algorithm = "Weiszfeld", ...) standardGeneric("distsuml2min") ) setMethod("distsuml2min", "loca.p", function (o, x = 0, y = 0, max.iter = 100, eps = 1.e-3, verbose = FALSE, algorithm = "Weiszfeld", control = list(maxit = max.iter), ...) { algorithm <- match.arg(algorithm, c('Weiszfeld', 'gradient', 'ucminf', 'Nelder-Mead', 'BFGS', 'CG', 'L-BFGS-B', 'SANN')) if (algorithm == "gradient") distsuml2mingradient.loca.p(o, x, y, max.iter, eps, verbose) else if (algorithm == "Weiszfeld") distsuml2minWeiszfeld.loca.p(o, x, y, max.iter, eps, verbose, ...) else if (algorithm == "ucminf") distsuml2minucminf.loca.p(o, x, y, max.iter, eps, verbose) else { zdistsummin <- function(x) distsum(o, x[1], x[2]) par <- c(sum(o@x*o@w)/sum(o@w), sum(o@y*o@w)/sum(o@w)) optim(par, zdistsummin, method = algorithm, control = list(maxit = max.iter))$par } } ) distsuml2minucminf.loca.p <- function (o, x = 0, y = 0, max.iter = 100, eps = 1.e-3, verbose = FALSE) { zdistsum <- function(xx) distsum(o, xx[1], xx[2]) sol <- ucminf(par = c(x, y), fn = zdistsum, control = list(maxeval = max.iter, trace = verbose)) if (verbose) cat(gettext(sol$message)) return(sol$par) } distsuml2mingradient.loca.p <- function (o, x = 0, y = 0, max.iter = 100, eps = 1.e-3, verbose = FALSE) { lambda <- 1; eps2 <- eps^2 u<-c(x,y) z <- distsum(o, u[1], u[2]) for (i in 0:max.iter) { if (verbose) cat(paste(gettext("Iter", domain = "R-orloca"), ".", i, ": (", u[1], ",", u[2], ") ", z, "\n", sep = "")) g<-distsumgra(o, u[1], u[2]) mg <- sum(g^2) if (is.na(mg)) { g<-distsumgra(o, u[1], u[2], partial = T) mg <- sum(g^2) ii <- which.min((o@x-u[1])^2+(o@y-u[2])^2) if (mg < sum(o@w[ii]^2)) { if(verbose) cat(gettext("Optimality condition reached at demand point.", domain = "R-orloca")); break } } else if (mg < eps2) { if(verbose) cat(gettext("Optimality condition reached.", domain = "R-orloca")); break; } nu <- u - lambda*g nz <- distsum(o, nu[1], nu[2]) if (nz < z) { u<-nu z<-nz lambda <- lambda*2.2 } else { lambda <- lambda/2 } } if (i == max.iter) warning.max.iter(max.iter) u } distsuml2minWeiszfeld.loca.p <- function (o, x = 0, y = 0, max.iter = 100, eps = 1.e-3, verbose = FALSE, csmooth = .9) { if (!identical(csmooth >= 0 && csmooth < 1, TRUE)) { warning(paste(gettext("Value for smooth parameter non valid:", domain = "R-orloca"), smooth, gettext("Reseting to its default value.", domain = "R-orloca"))) csmooth <- .5 } eps2 <- eps^2 u<-c(x,y) .smooth = 0 i.i = 0 i.s = round(max.iter*.5) for (j in 1:2) { for (i in i.i:i.s) { if (verbose) cat(paste(gettext("Iter", domain = "R-orloca"), ". ", i, ": (", u[1], ",", u[2], ") ", distsum(o, u[1], u[2]), "\n", sep = "")) n <- sqrt((u[1]-o@x)^2+(u[2]-o@y)^2) ii <- (n > eps) n <- o@w/n; g <- c(sum((u[1]-o@x[ii])*n[ii]), sum((u[2]-o@y[ii])*n[ii])) mg <- sum(g^2) if (!all(ii)) { if (mg < sum(o@w[!ii]^2) || mg < eps2) { if(verbose) cat(gettext("Optimality condition reached at demand point.", domain = "R-orloca")); break } } else if (mg <eps2) { if(verbose) cat(gettext("Optimality condition reached.", domain = "R-orloca")); break } s <- sum(n[ii]) nx <- n*o@x ny <- n*o@y u <- .smooth * u + (1-.smooth) * c(sum(nx[ii]), sum(ny[ii]))/s } if (i != i.s) break .smooth = csmooth if (j == 1) warning(gettext("The algorithm seems converges very slowly. Trying now with the smooth version.", domain = "R-orloca")) i.i = i.s i.s = max.iter } if (i == max.iter) warning.max.iter(max.iter) u }
assert_is_tbl <- function(x, severity = getOption("assertive.severity", "stop")) { assert_engine( is_tbl, x, .xname = get_name_in_parent(x), severity = severity ) } assert_is_tbl_cube <- function(x, severity = getOption("assertive.severity", "stop")) { assert_engine( is_tbl_cube, x, .xname = get_name_in_parent(x), severity = severity ) } assert_is_tbl_df <- function(x, severity = getOption("assertive.severity", "stop")) { assert_engine( is_tbl_df, x, .xname = get_name_in_parent(x), severity = severity ) } assert_is_tbl_dt <- function(x, severity = getOption("assertive.severity", "stop")) { assert_engine( is_tbl_dt, x, .xname = get_name_in_parent(x), severity = severity ) }
png("ctd-object.png", width=5, height=2.5, unit="in", res=150, pointsize=9) textInBox <- function(x, y, text, xoff=0, yoff=0, col="black", cex=1, font=1, lwd=1, pos=1) { w <- strwidth(text) h <- strheight(text) em <- strwidth("x") ex <- strheight("x") x <- x + xoff * em y <- y + yoff * ex text(x, y, text, col=col, cex=cex, font=font, pos=pos) xl <- x - w/2 - ex/2 xr <- x + w/2 + ex/2 yb <- y - 2*h - ex/2 yt <- y lines(c(xl, xl, xr, xr, xl), c(yb, yt, yt, yb, yb), col=col, lwd=lwd) list(xl=xl, xr=xr, yb=yb, yt=yt, xm=0.5*(xl+xr), ym=0.5*(yb+yt)) } par(mar=rep(0, 4)) plot(c(0,1.03), c(0,0.9), type="n", xaxs="i") l <- 2.2 * strheight("x") o <- 0.5 * l xl <- 0.1 xm <- 0.5 xr <- 0.9 lcol <- "darkgray" llwd <- 2 ctdObject <- textInBox(xm, 0.92, "ctd object") data <- textInBox(xl, 0.9-2*l, " data ") dataSalinity <- textInBox(xl+o, 0.9-4*l, "salinity", 2.5) dataTemperature <- textInBox(xl++o, 0.9-6*l, "temperature", 4.9) dataPressure <- textInBox(xl+o, 0.9-8*l, "pressure", 3.4) dataDots <- textInBox(xl+o, 0.9-10*l, " ... ", 1.1) metadata <- textInBox(xm, 0.9-2*l, " metadata ") metadataUnits <- textInBox(xm+o, 0.9-4*l, "units", 1.5) metadataFlags <- textInBox(xm+o, 0.9-6*l, "flags", 1.5) metadataDots <- textInBox(xm+o, 0.9-8*l, " ... ", 0.7) processingLog <- textInBox(xr, 0.9-2*l, "processingLog") processingLogTime <- textInBox(xr+o, 0.9-4*l, "time", 1) processingLogAction <- textInBox(xr+o, 0.9-6*l, "action", 2) lines(rep(xm,2), c(ctdObject$yb, metadata$yt), col=lcol, lwd=llwd) lines(rep(xm-0.04,2), c(ctdObject$yb, 0.5*(ctdObject$yb+metadata$yt)), col=lcol, lwd=llwd) lines(c(data$xm, xm-0.04), rep(0.5*(ctdObject$yb+metadata$yt),2), col=lcol, lwd=llwd) lines(c(processingLog$xm, xm+0.04), rep(0.5*(ctdObject$yb+metadata$yt),2), col=lcol, lwd=llwd) lines(rep(xm+0.04,2), c(ctdObject$yb, 0.5*(ctdObject$yb+metadata$yt)), col=lcol, lwd=llwd) ymid <- 0.5 * (ctdObject$yb + metadata$yt) lines(rep(xl, 2), c(ymid, data$yt), col=lcol, lwd=llwd) lines(rep(xr, 2), c(ymid, data$yt), col=lcol, lwd=llwd) lines(rep(xl-0.05, 2), c(data$yb, with(dataDots, (yb+yt)/2)), col=lcol, lwd=llwd) DX <- 0.05 lines(c(xl-DX, dataSalinity$xl), rep(with(dataSalinity, (yb+yt)/2), 2), col=lcol, lwd=llwd) lines(c(xl-DX, dataSalinity$xl), rep(with(dataTemperature, (yb+yt)/2), 2), col=lcol, lwd=llwd) lines(c(xl-DX, dataSalinity$xl), rep(with(dataPressure, (yb+yt)/2), 2), col=lcol, lwd=llwd) lines(c(xl-DX, dataSalinity$xl), rep(with(dataDots, (yb+yt)/2), 2), col=lcol, lwd=llwd) lines(rep(xm-DX, 2), c(metadata$yb, with(metadataDots, (yb+yt)/2)), col=lcol, lwd=llwd) lines(c(xm-DX, metadataUnits$xl), rep(with(metadataUnits, (yb+yt)/2), 2), col=lcol, lwd=llwd) lines(c(xm-DX, metadataUnits$xl), rep(with(metadataFlags, (yb+yt)/2), 2), col=lcol, lwd=llwd) lines(c(xm-DX, metadataUnits$xl), rep(with(metadataDots, (yb+yt)/2), 2), col=lcol, lwd=llwd) lines(rep(xr-DX, 2), c(processingLog$yb, processingLogAction$ym), col=lcol, lwd=llwd) lines(c(xr-DX, processingLogTime$xl), rep(with(processingLogTime, (yb+yt)/2), 2), col=lcol, lwd=llwd) lines(c(xr-DX, processingLogTime$xl), rep(with(processingLogAction, (yb+yt)/2), 2), col=lcol, lwd=llwd) dev.off()
setGeneric("crossTable", function(x, ...) standardGeneric("crossTable")) setMethod("crossTable", signature(x = "itemMatrix"), function(x, measure = c("count", "support", "probability", "lift"), sort = FALSE) { measure <- match.arg(measure) m <- .Call(R_crosstab_ngCMatrix, x@data, NULL, TRUE) if (is.null(dimnames(m))) dimnames(m) <- list(itemLabels(x), itemLabels(x)) if (sort) { o <- order(diag(m), decreasing = TRUE) m <- m[o, o] } if (measure == "count") return(m) p <- m / nrow(x) if (measure %in% c("support", "probability")) return(p) if (measure == "lift") { p_items <- diag(p) diag(p) <- NA e <- outer(p_items, p_items, "*") return(p / e) } stop("Unknown measure!") })
setClass("tscm", slots = list( tscopula = "tscopula", margin = "margin" ) ) setMethod("show", "tscm", function(object) { cat("object class: ", is(object)[[1]], "\n", sep = "") cat("_______ \n") cat("MARGIN: \n") show(object@margin) cat("_______\n") cat("COPULA: \n") show(object@tscopula) if (is(object, "tscmfit")) { ests <- object@fit$par if ("skeleton" %in% names(attributes(ests))) { attributes(ests)$skeleton <- NULL } if (is.element("hessian", names(object@fit))) { ses <- safe_ses(object@fit$hessian) ests <- rbind(ests, ses) dimnames(ests)[[1]] <- c("par", "se") } cat("_________________________\n") cat("summary of all estimates:\n") print(ests) cat("convergence status:", object@fit$convergence, ", log-likelihood:", -object@fit$value, "\n", sep = " " ) } }) setMethod("coef", "tscm", function(object) { c(coef(object@tscopula), coef(object@margin)) }) tscm <- function(tscopula, margin = new("margin", name = "unif")) { if (is(tscopula, "tscopulafit")) { tscopula <- tscopula@tscopula } if (is(margin, "marginfit")) { margin <- margin@margin } new("tscm", tscopula = tscopula, margin = margin ) } setMethod( "sim", c(object = "tscm"), function(object, n = 1000) { Utilde <- sim(object@tscopula, n) qmarg(object@margin, Utilde) } ) setClass( "tscmfit", contains = "tscm", slots = list( tscopula = "tscopula", margin = "margin", data = "ANY", fit = "list" ) ) setMethod( "fit", c(x = "tscm", y = "ANY"), function(x, y, tsoptions = list(), control = list( warn.1d.NelderMead = FALSE, trace = FALSE, maxit = 5000 ), method = "IFM") { defaults <- list(hessian = FALSE, method = "Nelder-Mead", changeatzero = FALSE) tsoptions <- setoptions(tsoptions, defaults) if (is(x, "tscmfit")) { tscopula <- x@tscopula margin <- x@margin if (is(tscopula, "tscopulafit")) { tscopula <- tscopula@tscopula } if (is(margin, "marginfit")) { margin <- margin@margin } x <- new("tscm", tscopula = tscopula, margin = margin) } if ((method == "full") & is(x@tscopula, "tscopulaU")) { method <- paste(method, "A", sep = "") } if ((method == "full") & is(x@tscopula, "vtscopula")) { method <- paste(method, "B", sep = "") } switch(method, empirical = fitEDF(x, y, tsoptions, control), IFM = fitSTEPS(x, y, tsoptions, control), fullA = fitFULLa(x, y, tsoptions, control), fullB = fitFULLb(x, y, tsoptions, control), stop("Not a known method") ) } ) fitEDF <- function(x, y, tsoptions, control) { U <- strank(as.numeric(y)) if (is(x@tscopula, "vtscopula") & tsoptions$changeatzero){ if (length(y[y == 0]) > 0) stop("Remove zeros in dataset") x@tscopula@Vtransform@pars["delta"] <- as.numeric((length(y[y < 0]) + 0.5)/(length(y) + 1)) } copfit <- fit(x@tscopula, U, tsoptions, control) new("tscmfit", tscopula = copfit@tscopula, margin = new("margin", name = "edf"), data = y, fit = copfit@fit ) } fitSTEPS <- function(x, y, tsoptions, control) { margfit <- fit(x@margin, y, tsoptions = tsoptions, control = control) U <- pmarg(margfit, y) if (is(x@tscopula, "vtscopula") & tsoptions$changeatzero){ if (length(y[y == 0]) > 0) stop("Remove zeros in dataset") x@tscopula@Vtransform@pars["delta"] <- as.numeric(pmarg(margfit, 0)) } copfit <- fit(x@tscopula, U, tsoptions = tsoptions, control = control) combinedfit <- list() names(margfit@fit$par) <- paste("margin.", names(margfit@fit$par), sep = "") combinedfit$par <- c(copfit@fit$par, margfit@fit$par) if ("hessian" %in% names(tsoptions)) { if (tsoptions$hessian) { combinedfit$hessian <- Matrix::bdiag(margfit@fit$hessian, copfit@fit$hessian) } } combinedfit$convergence <- sum(copfit@fit$convergence, margfit@fit$convergence) combinedfit$value <- sum(copfit@fit$value, margfit@fit$value) new("tscmfit", tscopula = copfit@tscopula, margin = margfit@margin, data = y, fit = combinedfit ) } fitFULLa <- function(x, y, tsoptions, control) { dens <- eval(parse(text = paste("d", x@margin@name, sep = ""))) cdf <- eval(parse(text = paste("p", x@margin@name, sep = ""))) parlist <- x@tscopula@pars parlist$margin <- x@margin@pars fit <- optim( par = unlist(parlist), fn = tsc_objectivea, modelspec = x@tscopula@modelspec, modeltype = is(x@tscopula)[[1]], dens = dens, cdf = cdf, y = as.numeric(y), method = tsoptions$method, hessian = tsoptions$hessian, control = control ) newpars <- relist(fit$par, parlist) x@margin@pars <- newpars$margin x@tscopula@pars <- newpars[names(newpars) != "margin"] new("tscmfit", tscopula = x@tscopula, margin = x@margin, data = y, fit = fit) } tsc_objectivea <- function(theta, modelspec, modeltype, dens, cdf, y) { margpars <- theta[substring(names(theta), 1, 6) == "margin"] nonmargpars <- theta[substring(names(theta), 1, 6) != "margin"] names(margpars) <- substring(names(margpars), 8) dx <- do.call(dens, append(as.list(margpars), list(x = y, log = TRUE))) termA <- -sum(dx) if (is.na(termA)) { return(NA) } U <- do.call(cdf, append(margpars, list(q = y))) objective <- eval(parse(text = paste(modeltype, "_objective", sep = ""))) termBC <- objective(nonmargpars, modelspec, U) return(termA + termBC) } setMethod( "coerce", c(from = "tscopula", to = "tscm"), function(from, to = "tsc", strict = TRUE) { new("tscm", tscopula = from, margin = new("margin", name = "unif")) } ) setMethod( "coerce", c(from = "tscopulafit", to = "tscmfit"), function(from, to = "tscmfit", strict = TRUE) { new("tscmfit", tscopula = from, margin = new("margin", name = "unif"), data = from@data, fit = from@fit ) } ) setMethod("logLik", "tscmfit", function(object) { ll <- -object@fit$value[length(object@fit$value)] attr(ll, "nobs") <- length(object@data) attr(ll, "df") <- length(object@fit$par) class(ll) <- "logLik" ll }) setMethod("resid", "tscmfit", function(object, trace = FALSE) { object <- new("tscopulafit", tscopula = object@tscopula, data = pmarg(object@margin, object@data), fit = object@fit) resid(object, trace) }) setMethod("plot", c(x = "tscmfit", y = "missing"), function(x, plottype = "residual", bw = FALSE, lagmax = 30) { if (x@margin@name == "edf") stop("These plots require parametric margins") if (plottype == "margin"){ marginmod <- new("marginfit", margin = x@margin, data = x@data, fit = x@fit) plot(marginmod, bw = bw) } else if (plottype == "volproxy") plot_volproxy(x, bw = bw) else if (plottype == "volprofile") plot_volprofile(x, bw = bw) else if (plottype %in% c("residual", "kendall", "glag", "vtransform")){ copmod <- new("tscopulafit", tscopula = x@tscopula, data = pmarg(x@margin, x@data), fit = list(NULL)) plot(copmod, plottype = plottype, bw = bw, lagmax = lagmax) } else stop("Not a valid plot type") }) plot_volprofile <- function(x, bw) { if (!(is(x@tscopula, "vtscopula"))) stop("tscopula must be vtscopula") xvals <- seq(from = 0, to = max(abs(x@data)), length = 100) vpars <- x@tscopula@Vtransform@pars brk <- qmarg(x@margin, vpars["delta"]) u <- pmarg(x@margin, brk - xvals) v <- vtrans(x@tscopula@Vtransform, u) yvals <- qmarg(x@margin, u + v) - brk plot(xvals, yvals, type = "l", ylab = expression(g[T](x))) colchoice <- ifelse(bw, "gray50", "red") abline(0, 1, col = colchoice, lty = 2) } plot_volproxy <- function(x, bw){ if (!(is(x@tscopula, "vtscopula"))) stop("tscopula must be vtscopula") X <- as.numeric(x@data) U <- pmarg(x@margin, X) V <- vtrans(x@tscopula@Vtransform, U) colchoice <- ifelse(bw, "gray50", "red") plot(X, qnorm(strank(V)), xlab = "data", ylab = "std. vol proxy", col = colchoice) lines(sort(X), qnorm(V[order(X)])) }
load_fontawesome <- function() { suppressWarnings( suppressMessages( extrafont::font_import( paths = system.file("fonts", package = "waffle"), recursive = FALSE, prompt = FALSE ) ) ) }
roxy_tag_parse.roxy_tag_examples <- function(x) { tag_examples(x) } roxy_tag_parse.roxy_tag_examplesIf <- function(x) { lines <- unlist(strsplit(x$raw, "\r?\n")) condition <- lines[1] tryCatch( suppressWarnings(parse(text = condition)), error = function(err) { roxy_tag_warning(x, "failed to parse condition of @examplesIf") } ) dontshow <- paste0( "\\dontshow{if (", condition, ") (if (getRversion() >= \"3.4\") withAutoprint else force)(\\{ ) x$raw <- paste( c(dontshow, lines[-1], "\\dontshow{\\}) collapse = "\n" ) x <- tag_examples(x) } roxy_tag_parse.roxy_tag_example <- function(x) { x <- tag_value(x) nl <- str_count(x$val, "\n") if (any(nl) > 0) { roxy_tag_warning(x, "spans multiple lines. Do you want @examples?") return() } x } roxy_tag_rd.roxy_tag_examples <- function(x, base_path, env) { rd_section("examples", x$val) } roxy_tag_rd.roxy_tag_examplesIf <- function(x, base_path, env) { rd_section("examples", x$val) } roxy_tag_rd.roxy_tag_example <- function(x, base_path, env) { path <- file.path(base_path, x$val) if (!file.exists(path)) { roxy_tag_warning(x, "'", path, "' doesn't exist") return() } code <- read_lines(path) rd_section("examples", escape_examples(code)) } format.rd_section_examples <- function(x, ...) { value <- paste0(x$value, collapse = "\n") rd_macro(x$type, value, space = TRUE) } escape_examples <- function(x) { x <- paste0(x, collapse = "\n") rd(escapeExamples(x)) }
ComputeCmiPcaCmi <- function(v1,v2,vcs) { cmiv <- 0 if(base::nargs() == 2) { c1 <- stats::var(v1) c2 <- stats::var(v2) v <-base::cbind(v1,v2) c3 <- base::det(stats::cov(v)) if (c3 != 0) { cmiv <- 0.5*(base::log(c1*c2/c3)) } } else if(base::nargs() == 3) { v <-base::cbind(v1,vcs) c1 <- base::det(stats::cov(v)) v <-base::cbind(v2,vcs) c2 <- base::det(stats::cov(v)) if (base::ncol(vcs) > 1) { c3 <- base::det(stats::cov(vcs)) } else { c3 <- stats::var(vcs) } v <- base::cbind(v1,v2,vcs) c4 <- base::det(stats::cov(v)) if ((c3*c4) != 0) { cmiv <- 0.5 * base::log(base::abs((c1 * c2) / (c3 * c4))) } } return (cmiv) }
getIsoscapes = function(isoType = "GlobalPrecipGS", timeout = 1200){ dpath.pre = "https://wateriso.utah.edu/waterisotopes/media/ArcGrids/" if(!is.numeric(timeout)){ stop("timeout must be a number") } if(!(isoType %in% names(GIconfig))){ stop("isoType invalid") } giconfig = GIconfig[[match(isoType, names(GIconfig))]] wd = getwd() setwd(tempdir()) ot = getOption("timeout") options(timeout = timeout) on.exit({ options(timeout = ot) setwd(wd) }) dlf = function(fp, fn, ot, wd){ dfs = tryCatch({ download.file(fp, fn) }, error = function(cond){ options(timeout = ot) setwd(wd) stop(cond) }) return(dfs) } pdlf = function(dfs, wd, ot, isoType){ if(dfs != 0){ setwd(wd) options(timeout = ot) stop("Non-zero download exit status") } } if(!file.exists(giconfig$dpath.post)){ dfs = dlf(paste0(dpath.pre, giconfig$dpath.post), giconfig$dpath.post, ot, wd) pdlf(dfs, wd, ot, isoType) } procRest = function(fn, lnames, onames){ if(file.exists("zRec.txt")){ zRec = readLines("zRec.txt") } else{ zRec = "none" } if((!all(lnames %in% list.files())) | (zRec != fn)){ uz = unzip(fn) writeLines(fn, "zRec.txt") } rs = list() for(i in 1:length(lnames)){ rs[[i]] = raster(lnames[i]) } names(rs) = onames return(rs) } rs = tryCatch({ procRest(giconfig$dpath.post, giconfig$lnames, giconfig$onames) }, error = function(cond){ stop(cond) }, finally = { options(timeout = ot) setwd(wd) }) switch(giconfig$eType, { if(length(rs) > 1){ out = stack(rs) } else{ out = rs } }, { out = stack(rs) }) message(paste0("Refer to ", tempdir(), "\\metadata.txt for documentation and citation information")) return(out) }
PrintROI <- function(path_img_ref,path_ROIs,which='all',col, file.type='.jpg') { file<-list.files(path=path_img_ref,pattern = file.type) img <- brick(paste(path_img_ref,file,sep="")) rois <- paste(path_ROIs, 'roi.data.Rdata', sep='') roi.data <- NULL load(rois) nrois <- length(roi.data) roi.names <- names(roi.data) plotRGB(img) if (which=='all') { if (missing(col)) col <- palette()[1:nrois] for (a in 1:nrois) { act.polygons <- roi.data[[a]]$polygon raster::lines(act.polygons, col=col[a], lwd=2) } legend('top', col=col, lty=1, legend=roi.names) } else { pos.roi <- which(roi.names %in% which == TRUE) raster::lines(roi.data[[pos.roi]]$polygon, lwd=2) } }
context("Dirichlet Process Beta 2") test_that("Create",{ testData <- rbeta(10, 2, 5) dp <- DirichletProcessBeta2(testData, 1) expect_is(dp, c("list", "dirichletprocess", "beta2", "nonconjugate")) }) test_that("Fit", { testData <- rbeta(10, 2, 5) dp <- DirichletProcessBeta2(testData, 1) dp <- Fit(dp, 10, FALSE, FALSE) expect_is(dp, c("list", "dirichletprocess", "beta2", "nonconjugate")) expect_is(dp$clusterParameters, "list") expect_length(dp$clusterParameters, 2) expect_length(dp$clusterParametersChain, 10) expect_length(dp$alphaChain, 10) expect_length(dp$weightsChain, 10) })
node_dconnected <- function(.tdy_dag, from = NULL, to = NULL, controlling_for = NULL, as_factor = TRUE, ...) { .tdy_dag <- if_not_tidy_daggity(.tdy_dag) if (is.null(from)) from <- dagitty::exposures(.tdy_dag$dag) if (is.null(to)) to <- dagitty::outcomes(.tdy_dag$dag) if (is_empty_or_null(from) || is_empty_or_null(to)) stop("`from` and `to` must be set!") if (!is.null(controlling_for)) { .tdy_dag <- control_for(.tdy_dag, controlling_for) } else { .tdy_dag$data$collider_line <- FALSE .tdy_dag$data$adjusted <- "unadjusted" controlling_for <- c() } .dconnected <- dagitty::dconnected(.tdy_dag$dag, from, to, controlling_for) .from <- from .to <- to .tdy_dag$data <- dplyr::mutate(.tdy_dag$data, d_relationship = ifelse(name %in% c(.from, .to) & .dconnected, "d-connected", ifelse(name %in% c(.from, .to) & !.dconnected, "d-separated", NA))) if (as_factor) .tdy_dag$data$d_relationship <- factor(.tdy_dag$data$d_relationship, levels = c("d-connected", "d-separated"), exclude = NA) .tdy_dag } node_dseparated <- function(.tdy_dag, from = NULL, to = NULL, controlling_for = NULL, as_factor = TRUE) { .tdy_dag <- if_not_tidy_daggity(.tdy_dag) if (is.null(from)) from <- dagitty::exposures(.tdy_dag$dag) if (is.null(to)) to <- dagitty::outcomes(.tdy_dag$dag) if (is_empty_or_null(from) || is_empty_or_null(to)) stop("`from` and `to` must be set!") if (!is.null(controlling_for)) { .tdy_dag <- control_for(.tdy_dag, controlling_for) } else { .tdy_dag$data$collider_line <- FALSE .tdy_dag$data$adjusted <- "unadjusted" controlling_for <- c() } .dseparated <- dagitty::dseparated(.tdy_dag$dag, from, to, controlling_for) .from <- from .to <- to .tdy_dag$data <- dplyr::mutate(.tdy_dag$data, d_relationship = ifelse(name %in% c(.from, .to) & !.dseparated, "d-connected", ifelse(name %in% c(.from, .to) & .dseparated, "d-separated", NA))) if (as_factor) .tdy_dag$data$d_relationship <- factor(.tdy_dag$data$d_relationship, levels = c("d-connected", "d-separated"), exclude = NA) .tdy_dag } node_drelationship <- function(.tdy_dag, from = NULL, to = NULL, controlling_for = NULL, as_factor = TRUE) { .tdy_dag <- if_not_tidy_daggity(.tdy_dag) if (is.null(from)) from <- dagitty::exposures(.tdy_dag$dag) if (is.null(to)) to <- dagitty::outcomes(.tdy_dag$dag) if (is_empty_or_null(from) || is_empty_or_null(to)) stop("`from` and `to` must be set!") if (!is.null(controlling_for)) { .tdy_dag <- control_for(.tdy_dag, controlling_for) } else { .tdy_dag$data$collider_line <- FALSE .tdy_dag$data$adjusted <- "unadjusted" controlling_for <- c() } .dseparated <- dagitty::dseparated(.tdy_dag$dag, from, to, controlling_for) .from <- from .to <- to .tdy_dag$data <- dplyr::mutate(.tdy_dag$data, d_relationship = ifelse(name %in% c(.from, .to) & !.dseparated, "d-connected", ifelse(name %in% c(.from, .to) & .dseparated, "d-separated", NA))) if (as_factor) .tdy_dag$data$d_relationship <- factor(.tdy_dag$data$d_relationship, levels = c("d-connected", "d-separated"), exclude = NA) .tdy_dag } ggdag_drelationship <- function(.tdy_dag, from = NULL, to = NULL, controlling_for = NULL, ..., edge_type = "link_arc", node_size = 16, text_size = 3.88, label_size = text_size, text_col = "white", label_col = text_col, node = TRUE, stylized = FALSE, text = TRUE, use_labels = NULL, collider_lines = TRUE) { edge_function <- edge_type_switch(edge_type) p <- if_not_tidy_daggity(.tdy_dag) %>% node_drelationship(from = from, to = to, controlling_for = controlling_for, ...) %>% ggplot2::ggplot(ggplot2::aes(x = x, y = y, xend = xend, yend = yend, shape = adjusted, col = d_relationship)) + edge_function(start_cap = ggraph::circle(10, "mm"), end_cap = ggraph::circle(10, "mm")) + scale_adjusted() + breaks(c("d-connected", "d-separated"), name = "d-relationship") + expand_plot(expand_y = expansion(c(0.2, 0.2))) if (collider_lines) p <- p + geom_dag_collider_edges() if (node) { if (stylized) { p <- p + geom_dag_node(size = node_size) } else { p <- p + geom_dag_point(size = node_size) } } if (text) p <- p + geom_dag_text(col = text_col, size = text_size) if (!is.null(use_labels)) p <- p + geom_dag_label_repel(ggplot2::aes_string(label = use_labels, fill = "d_relationship"), size = text_size, col = label_col, show.legend = FALSE) p } ggdag_dseparated <- function(.tdy_dag, from = NULL, to = NULL, controlling_for = NULL, ..., edge_type = "link_arc", node_size = 16, text_size = 3.88, label_size = text_size, text_col = "white", label_col = text_col, node = TRUE, stylized = FALSE, text = TRUE, use_labels = NULL, collider_lines = TRUE) { ggdag_drelationship(.tdy_dag = .tdy_dag, from = from, to = to, controlling_for = controlling_for, ..., edge_type = edge_type, node_size = node_size, text_size = text_size, label_size = label_size, text_col = text_col, label_col = label_col, node = node, stylized = stylized, text = text, use_labels = use_labels, collider_lines = collider_lines) } ggdag_dconnected <- function(.tdy_dag, from = NULL, to = NULL, controlling_for = NULL, ..., edge_type = "link_arc", node_size = 16, text_size = 3.88, label_size = text_size, text_col = "white", label_col = text_col, node = TRUE, stylized = FALSE, text = TRUE, use_labels = NULL, collider_lines = TRUE) { ggdag_drelationship(.tdy_dag = .tdy_dag, from = from, to = to, controlling_for = controlling_for, ..., edge_type = edge_type, node_size = node_size, text_size = text_size, label_size = label_size, text_col = text_col, label_col = label_col, node = node, stylized = stylized, text = text, use_labels = use_labels, collider_lines = collider_lines) }
batchVideoFaceAnalysis = function(batchInfo, imageDir, sampleWindow, facesCollectionID=NA) { for(m in 1:nrow(batchInfo)) { mInfo = batchInfo[m, ] message("Processing Meeting ",mInfo$batchMeetingId," ", "(",m," of ",nrow(batchInfo),")") videoExists = file.exists(file.path(mInfo$dirRoot, paste0(mInfo$fileRoot,"_video.mp4"))) dirExists = dir.exists(file.path(imageDir, paste0(mInfo$fileRoot,"_video"))) if(dirExists) { vidOut = videoFaceAnalysis(inputVideo=file.path(mInfo$dirRoot, paste0(mInfo$fileRoot,"_video.mp4")), recordingStartDateTime=mInfo$recordingStartDateTime, sampleWindow=sampleWindow, facesCollectionID=facesCollectionID, videoImageDirectory=imageDir) vidOut$batchMeetingId = mInfo$batchMeetingId if(!exists('resOut')) { resOut = vidOut } else { resOut = rbind(resOut, vidOut) } } else { message("There is no directory of pre-processed images for the video for this meeting. No analysis was conducted") } } return(resOut) }
.allVars1 <- function(form){ vars <- all.vars(form) vn <- all.names(form) vn <- vn[vn%in%c(vars,"$","[[")] if ("[["%in%vn) stop("can't handle [[ in formula") ii <- which(vn%in%"$") if (length(ii)) { vn1 <- if (ii[1]>1) vn[1:(ii[1]-1)] go <- TRUE k <- 1 while (go) { n <- 2; while(k<length(ii) && ii[k]==ii[k+1]-1) { k <- k + 1;n <- n + 1 } vn1 <- c(vn1,paste(vn[ii[k]+1:n],collapse="$")) if (k==length(ii)) { go <- FALSE ind <- if (ii[k]+n<length(vn)) (ii[k]+n+1):length(vn) else rep(0,0) } else { k <- k + 1 ind <- if (ii[k-1]+n<ii[k]-1) (ii[k-1]+n+1):(ii[k]-1) else rep(0,0) } vn1 <- c(vn1,vn[ind]) } } else vn1 <- vn return( vn1 ) }
binary_prob_success <- function(x, ...) { UseMethod("binary_prob_success", x) } binary_prob_success.augbin_2t_1a_fit <- function(x, y1_lower = -Inf, y1_upper = Inf, y2_lower = -Inf, y2_upper = log(0.7), conf.level = 0.95, ...) { . <- NULL as_tibble(x) %>% mutate(success = (.data$d1 == 0) & (.data$d2 == 0) & (.data$y1 < y1_upper) & (.data$y1 > y1_lower) & (.data$y2 < y2_upper) & (.data$y2 > y2_lower)) %>% summarise(num_success = sum(.data$success)) %>% .[[1]] -> num_success binom.confint(x = num_success, n = x$num_patients, conf.level = conf.level, ...) %>% mutate(ci_width = .data$upper - .data$lower) }
get_playlist_items <- function (filter = NULL, part = "contentDetails", max_results = 50, video_id = NULL, page_token = NULL, simplify = TRUE, ...) { if (max_results < 0) { stop("max_results only takes a value between 0 and 50.") } if (!(names(filter) %in% c("item_id", "playlist_id"))) { stop("filter can only take one of values: item_id, playlist_id.") } if ( length(filter) != 1) stop("filter must be a vector of length 1.") translate_filter <- c(item_id = "id", playlist_id = "playlistId") yt_filter_name <- as.vector(translate_filter[match(names(filter), names(translate_filter))]) names(filter) <- yt_filter_name querylist <- list(part = part, maxResults = ifelse(max_results > 50, 50, max_results), pageToken = page_token, videoId = video_id) querylist <- c(querylist, filter) res <- tuber_GET("playlistItems", querylist, ...) if (max_results > 50) { page_token <- res$nextPageToken while ( is.character(page_token)) { a_res <- tuber_GET("playlistItems", list( part = part, playlistId = unname(filter["playlistId"]), maxResults = 50, pageToken = page_token ) ) res <- c(res, a_res) page_token <- a_res$nextPageToken } } if (simplify == TRUE) { res <- do.call(rbind,lapply( unlist( res[which(names(res) == "items")], recursive = FALSE), as.data.frame, stringsAsFactors = FALSE) ) } res }
isnot_validcp <- function(grid16, loni, lati) { if (!any(is.na(grid16))) { xlim1 <- min(grid16[1, ]) xlim2 <- max(grid16[1, ]) ylim1 <- min(grid16[2, ]) ylim2 <- max(grid16[2, ]) lon.shif <- ifelse ( (loni > 180 & loni < 360), loni - 360, loni) if (xlim2 > max(lon.shif) | xlim1 < min(lon.shif) | ylim2 > max(lati) | ylim1 < min(lati)) { return(TRUE) } else { return(FALSE) } } return(TRUE) }
head(mtcars) sort(mtcars$mpg) sort(mtcars$mpg, decreasing = T) mtcars[order(mtcars$mpg),][1:5] mtcars[order(mtcars$cyl, mtcars$mpg), c('cyl','mpg','wt')] mtcars[order(mtcars$cyl, -mtcars$mpg), c('cyl','mpg','wt')] rank(mtcars$mpg, ties.method = 'min') x=c(1,2,36,3) rank(x) rorder =cbind(mtcars$mpg, rank(mtcars$mpg, ties.method = 'min')) rorder[order(rorder[,2]),1:2]
icesRound <- function(x, percent = FALSE, sign = percent, na = "") { log10_x <- log10(abs(x)) sf <- as.integer(log10_x %% 1 < log10(2)) + 2 digits <- pmax(0, sf - 1 - floor(log10_x)) digits[x == 0] <- 2 sf[x == 0] <- 0 digits[is.na(x)] <- 0 fmt <- paste0(if (sign) "%+." else "%.", digits, if (percent) "f%%" else "f") out <- sprintf(fmt, signif(x, sf)) out[is.na(x)] <- na noquote(out) }
library(testthat) library(bs4Dash) test_check("bs4Dash")
test_that("we can make a GridRange from a range_spec", { sheets_df <- tibble::tibble(name = "abc", id = 123) spec <- new_range_spec(sheet_name = "abc", sheets_df = sheets_df) out <- as_GridRange(spec) expect_equal(out$sheetId, 123) spec <- new_range_spec( sheet_name = "abc", cell_range = "A3:B4", sheets_df = sheets_df ) out <- as_GridRange(spec) expect_equal(out$sheetId, 123) expect_equal(out$startRowIndex, 2) expect_equal(out$endRowIndex, 4) expect_equal(out$startColumnIndex, 0) expect_equal(out$endColumnIndex, 2) spec <- new_range_spec( sheet_name = "abc", cell_range = "A5:B", sheets_df = sheets_df ) out <- as_GridRange(spec) expect_equal(out$sheetId, 123) expect_equal(out$startRowIndex, 4) expect_null(out$endRowIndex) expect_equal(out$startColumnIndex, 0) expect_equal(out$endColumnIndex, 2) spec <- new_range_spec( sheet_name = "abc", cell_range = "A:B", sheets_df = sheets_df ) out <- as_GridRange(spec) expect_equal(out$sheetId, 123) expect_null(out$startRowIndex) expect_null(out$endRowIndex) expect_equal(out$startColumnIndex, 0) expect_equal(out$endColumnIndex, 2) spec <- new_range_spec( sheet_name = "abc", cell_range = "A1:A1", sheets_df = sheets_df ) out <- as_GridRange(spec) expect_equal(out$sheetId, 123) expect_equal(out$startRowIndex, 0) expect_equal(out$endRowIndex, 1) expect_equal(out$startColumnIndex, 0) expect_equal(out$endColumnIndex, 1) spec1 <- new_range_spec( sheet_name = "abc", cell_range = "C3:C3", sheets_df = sheets_df ) spec2 <- new_range_spec( sheet_name = "abc", cell_range = "C3", sheets_df = sheets_df ) expect_equal(as_GridRange(spec1), as_GridRange(spec2)) }) test_that("we refuse to make a GridRange from a named_range", { spec <- new_range_spec(named_range = "thingy") expect_error(as_GridRange(spec), "does not accept a named range") })
url_dl <- function(..., url = 61803503) { if (!is.null(url) && !grepl("http|www\\.", url)) { url <- utils::tail(unlist(strsplit(as.character(url), "/", fixed = TRUE)), 1) url <- paste0("http://dl.dropboxusercontent.com/u/", url, "/") } mf <- match.call(expand.dots = FALSE) payload <- as.character(mf[[2]]) FUN <- function(x, url) { bin <- getBinaryURL(file.path(url, x), ssl.verifypeer = FALSE) con <- file(x, open = "wb") writeBin(bin, con) close(con) message(noquote(paste(x, "read into", getwd()))) } if (all(grepl("http|www\\.", payload))) { File <- basename(payload) Root <- dirname(payload) for (i in seq_len(length(payload))) { FUN(x = File[i], url = Root[i]) } } else { invisible(lapply(payload, function(z) FUN(x = z, url = url))) } }
correctCoordGPS <- function(longlat = NULL, projCoord = NULL, coordRel, rangeX, rangeY, maxDist = 15, drawPlot = FALSE, rmOutliers = TRUE) { oldpar <- par(no.readonly = TRUE) on.exit(par(oldpar)) if (is.null(longlat) && is.null(projCoord)) { stop("Give at least one set of coordinates: longlat or projCoord") } if (!is.null(longlat) && !is.null(projCoord)) { stop("Give only one set of coordinates: longlat or projCoord") } if (length(rangeX) != 2 || length(rangeY) != 2) { stop("The rangeX and/or rangeY must be of length 2") } if (length(maxDist) != 1) { stop("Your argument maxDist must be of length 1") } if (!all(between(coordRel[, 1], lower = rangeX[1], upper = rangeX[2]) & between(coordRel[, 2], lower = rangeY[1], upper = rangeY[2]))) { stop("coordRel must be inside the X and Y ranges") } if ((!is.null(longlat) && any(dim(longlat) != dim(coordRel))) || (!is.null(projCoord) && any(dim(projCoord) != dim(coordRel)))) { stop("GPS and relative coordinates are not of the same dimension") } if (!is.null(longlat)) { projCoord <- latlong2UTM(longlat) codeUTM <- unique(projCoord[, "codeUTM"]) projCoord <- projCoord[, c("X", "Y")] } res <- procrust(projCoord, coordRel) coordAbs <- as.matrix(coordRel) %*% res$rotation coordAbs <- sweep(coordAbs, 2, res$translation, FUN = "+") dist <- sqrt((coordAbs[, 1] - projCoord[, 1])^2 + (coordAbs[, 2] - projCoord[, 2])^2) outliers <- which(dist > maxDist) if (length(outliers)==nrow(projCoord)){ stop("All coordinates points are considered as outliers at the first stage.\n This may be because some coordinates have very large error associated.\n Try to remove these very large error or reconsider the maxDist parameter by increasing the distance") } if (rmOutliers & length(outliers)>0) { refineCoord <- TRUE while(refineCoord){ res <- procrust(projCoord[-outliers, ], coordRel[-outliers,]) coordAbs <- as.matrix(coordRel) %*% res$rotation coordAbs <- sweep(coordAbs, 2, res$translation, FUN = "+") newdist <- sqrt((coordAbs[, 1] - projCoord[, 1])^2 + (coordAbs[, 2] - projCoord[, 2])^2) if(all(which(newdist > maxDist)==outliers)) refineCoord <- FALSE outliers <- which(newdist > maxDist) } } cornerCoord <- as.matrix(expand.grid(X = sort(rangeX), Y = sort(rangeY))) cornerCoord <- cornerCoord[c(1, 2, 4, 3), ] cornerCoord <- as.matrix(cornerCoord) %*% res$rotation cornerCoord <- sweep(cornerCoord, 2, res$translation, FUN = "+") p <- Polygon(rbind(cornerCoord, cornerCoord[1, ])) ps <- Polygons(list(p), 1) sps <- SpatialPolygons(list(ps)) if (drawPlot) { par(xpd = TRUE, mar = par("mar") + c(0, 0, 0, 7.5)) plot(if(length(outliers)==0) projCoord else projCoord[-outliers, ], col = "grey30", main = "Plot drawing", xlim = range(projCoord[, 1], coordAbs[, 1]), ylim = range(projCoord[, 2], coordAbs[, 2]), asp = 1, xlab = "X", ylab = "Y", axes = FALSE, frame.plot = FALSE ) usr <- par("usr") grid <- sapply(par(c("xaxp", "yaxp")), function(x) { seq(x[1], x[2], length.out = x[3] + 1) }, simplify = FALSE) segments(x0 = grid$xaxp, y0 = usr[3], y1 = usr[4], col = "grey80", lty = 1) segments(y0 = grid$yaxp, x0 = usr[1], x1 = usr[2], col = "grey80", lty = 1) axis(side = 1, lty = "blank", las = 1) axis(side = 2, lty = "blank", las = 1) plot(sps, add = TRUE, lwd = 3) points(coordAbs, col = "black", pch = 15, cex = 1.3) if(length(outliers)>0) points(projCoord[outliers, ], col = "red", pch = 4, cex = 1) legend( x = usr[2], y = grid$yaxp[length(grid$yaxp) - 1], c("GPS measurements", ifelse(rmOutliers, "Outliers (discarded)", "Outliers"), "Corrected coord"), col = c("grey30", "red", "black"), pch = c(1, 4, 15, 49), bg = "grey90" ) par(xpd = NA, mar = c(5, 4, 4, 2) + 0.1) } if (length(outliers) != 0 & !rmOutliers) { warning( "Be carefull, you may have GNSS measurement outliers. \n", "Removing them may improve the georeferencing of your plot (see the rmOutliers argument)." ) } output <- list( cornerCoords = data.frame(X = cornerCoord[, 1], Y = cornerCoord[, 2]), correctedCoord=data.frame(X = coordAbs[, 1], Y = coordAbs[, 2]), polygon = sps, outliers = outliers ) if (!is.null(longlat)) { output$codeUTM <- codeUTM } return(output) }
characters <- get_characters() locations <- get_locations() episodes <- get_episodes() test_that("tibbles are returned", { expect_type(characters, "list") expect_type(locations, "list") expect_type(episodes, "list") expect_true(tibble::is_tibble(characters)) expect_true(tibble::is_tibble(locations)) expect_true(tibble::is_tibble(episodes)) }) test_that("tibbles are not empty", { expect_gt(nrow(characters), 0) expect_gt(nrow(locations), 0) expect_gt(nrow(episodes), 0) expect_gt(ncol(characters), 0) expect_gt(ncol(locations), 0) expect_gt(ncol(episodes), 0) })
fmpc_security_ratings <- function(symbols = c('AAPL'), limit = 100) { symbReq = hlp_symbolCheck(symbols) ratingDF = hlp_bindURLs(paste0('historical-rating/',symbReq,'?limit=',limit,'&')) hlp_respCheck(symbReq,ratingDF$symbol,'fmpc_security_ratings: ') ratingDF } fmpc_security_mrktcap <- function(symbols = c('AAPL'), limit = 100) { symbReq = hlp_symbolCheck(symbols) ratingDF = hlp_bindURLs(paste0('historical-market-capitalization/',symbReq,'?limit=',limit,'&')) hlp_respCheck(symbReq,ratingDF$symbol,'fmpc_security_mrktcap: ') ratingDF } fmpc_security_delisted <- function(limit = 100) { Result <- fmpc_get_url(paste0('delisted-companies?limit=',limit,'&')) Result <- hlp_chkResult(Result) dplyr::as_tibble(Result) } fmpc_security_news <- function(symbols = NULL, limit = 100) { symbReq = hlp_symbolCheck(symbols) if (length(symbReq)==0) { symbURL = '' } else { symbURL = paste0('tickers=',symbReq,'&') } newsDF = hlp_bindURLs(paste0('stock_news?',symbURL,'limit=',limit,'&')) hlp_respCheck(symbReq,newsDF$symbol,'fmpc_security_mrktcap: ') newsDF } fmpc_analyst_outlook <- function(symbols = c('AAPL'), outlook = c('surprise','grade','estimate','recommend','press'), limit = 100) { symbReq = hlp_symbolCheck(symbols) analysisOp = c('surprise','grade','estimateAnnl','estimateQtr','recommend','press') if (missing(outlook)) outlook = 'surprise' if (!(outlook %in% analysisOp)) { stop('Please enter a metric value of: ',paste0(analysisOp, collapse = ', '), call. = FALSE) } outURL = switch(outlook,'surprise' = 'earnings-surpises', 'grade' = 'grade', 'estimateAnnl' = 'analyst-estimates', 'estimateQtr' = 'analyst-estimates', 'press' = 'press-releases', 'recommend' = 'analyst-stock-recommendations') qtrAdd = ifelse(outlook == 'estimateQtr','period=quarter&','') outlookDF = hlp_bindURLs(paste0(outURL,'/',symbReq,'?limit=',limit,'&',qtrAdd)) hlp_respCheck(symbReq,outlookDF$symbol,'fmpc_security_mrktcap: ') outlookDF } fmpc_earning_call_transcript <- function(symbols = c('AAPL'), quarter = 2, year = 2020) { symbReq = hlp_symbolCheck(symbols) callURL = paste0('earning_call_transcript/',symbReq,'?quarter=',quarter,'&year=',year,'&') callDF = hlp_bindURLs(callURL) hlp_respCheck(symbReq,callDF$symbol,'fmpc_earning_call_transcript: ') callDF }
NULL setMethod("showTransforms", "CrunchCube", function(x) { if (all(vapply(transforms(x), is.null, logical(1)))) { print(cubeToArray(x)) return(invisible(x)) } else { appliedTrans <- applyTransforms(x) keep_cats <- evalUseNA(as.array(x), dimensions(x), useNA = x@useNA) if (getDimTypes(x)[1] %in% c("categorical", "ca_categories")) { try({ row_cats <- Categories(data = index(variables(x))[[1]]$categories) row_cats <- row_cats[which(keep_cats[[1]])] row_styles <- transformStyles(transforms(x)[[1]], row_cats) }, silent = TRUE) } if (!exists("row_styles")) { row_styles <- NULL } cat_dims <- c("categorical", "ca_categories") if (length(dim(x)) > 1 && getDimTypes(x)[2] %in% cat_dims) { try({ col_cats <- Categories(data = index(variables(x))[[2]]$categories) col_cats <- col_cats[which(keep_cats[[2]])] col_styles <- transformStyles(transforms(x)[[2]], col_cats) }, silent = TRUE) } if (!exists("col_styles")) { col_styles <- NULL } if (length(dim(appliedTrans)) > 0 & length(dim(appliedTrans)) <= 2) { tryCatch({ out <- prettyPrint2d( appliedTrans, row_styles = row_styles, col_styles = col_styles ) cat(unlist(out), sep = "\n") }, error = function(e) { print(appliedTrans) }) } else { print(appliedTrans) } return(invisible(appliedTrans)) } }) setMethod("subtotalArray", "CrunchCube", function(x, headings = FALSE) { includes <- c("subtotals") if (headings) { includes <- c(includes, "headings") } applyTransforms(x, include = includes) }) applyTransforms <- function(x, array = cubeToArray(x), transforms_list = transforms(x), dims_list = dimensions(x), useNA = x@useNA, ...) { trans_indices <- which(vapply(transforms_list, Negate(is.null), logical(1))) if (!missing(x)) { trans_indices <- trans_indices[getDimTypes(x)[trans_indices] != "ca_items"] } keep_cats <- evalUseNA(array, dims_list, useNA = useNA) errors <- list() na_mask <- data.frame() for (d in trans_indices) { tryCatch({ if ( endsWith(getDimTypes(dims_list)[[d]], "_items") | endsWith(getDimTypes(dims_list)[[d]], "_selections") ) { next } var_cats <- Categories(data = variables(dims_list)[[d]]$categories) insert_funcs <- makeInsertionFunctions( var_cats[keep_cats[[d]]], transforms_list[[d]], cats_in_array = dimnames(array)[[d]], ... ) array <- maskAndApplyInserts(array, na_mask, d, insert_funcs) na_mask <- calculate_na_mask(array, na_mask, d, insert_funcs) }, error = function(e) { assign("errors", append(errors, d), envir = parent.env(environment())) } ) } if (length(errors) > 0) { warning( "Transforms for dimensions ", serialPaste(errors), " were malformed and have been ignored.", call. = FALSE ) } array <- subsetTransformedCube(array, dims_list, useNA) return(array) } maskAndApplyInserts <- function(array, na_mask, d, insert_funcs) { var_coord_cols <- startsWith(colnames(na_mask), "Var") array[as.matrix(na_mask[, var_coord_cols])] <- NA array <- applyAgainst( X = array, MARGIN = d, FUN = calcTransforms, insert_funcs = insert_funcs, dim_names = names(insert_funcs) ) insert_types <- attributes(insert_funcs)$types if (length(na_mask) > 0) { id_map <- which(insert_types == "Category") names(id_map) <- seq_along(id_map) na_mask[, d] <- id_map[na_mask[, d]] var_coord_cols <- startsWith(colnames(na_mask), "Var") if (!(all(is.na(array[as.matrix(na_mask[, var_coord_cols])])))) { halt("Trying to overwrite uncensored values something is wrong") } array[as.matrix(na_mask[, var_coord_cols])] <- na_mask$values } return(array) } calculate_na_mask <- function(array, na_mask, d, insert_funcs) { ind_to_mask <- which(attributes(insert_funcs)$types == "SummaryStat") coords <- lapply(dim(array), function(to) seq_len(to)) coords[[d]] <- ind_to_mask na_mask_new <- expand.grid(coords) na_mask_new$values <- array[as.matrix(na_mask_new)] na_mask <- rbind(na_mask, na_mask_new) return(na_mask) } makeInsertionFunctions <- function(var_cats, transforms, cats_in_array = NULL, ...) { dots <- list(...) if ("include" %in% names(dots)) { includes <- dots$include } else { includes <- c("subtotals", "headings", "cube_cells", "other_insertions") } cat_insert_map <- mapInsertions( transforms$insertions, var_cats, include = includes ) transforms_funcs <- makeTransFuncs(cat_insert_map, cats_in_array, var_cats) names(transforms_funcs) <- names(cat_insert_map) types <- getInsertionTypes(cat_insert_map, cats_in_array) attributes(transforms_funcs)$types <- types transforms_funcs <- Filter(Negate(is.null), transforms_funcs) attributes(transforms_funcs)$types <- types[!is.na(types)] return(transforms_funcs) } makeTransFuncs <- function(cat_insert_map, cats_in_array, var_cats) { return(base::lapply(cat_insert_map, function(element) { if (is.category(element)) { if (!is.null(cats_in_array) && !name(element) %in% cats_in_array) { return(NULL) } id <- which(ids(var_cats) %in% id(element)) which.cat <- names(var_cats[id]) return(function(vec) vec[[which.cat]]) } if (is.Heading(element)) { return(function(vec) NA) } if (is.Subtotal(element)) { positive <- unlist(arguments(element, var_cats)) positive_ids <- which(ids(var_cats) %in% positive) which.positive <- names(var_cats[positive_ids]) negative <- unlist(subtotalTerms(element, var_cats)$negative) negative_ids <- which(ids(var_cats) %in% negative) which.negative <- names(var_cats[negative_ids]) return(function(vec) { sum(vec[which.positive]) - sum(vec[which.negative]) }) } if (is.SummaryStat(element)) { statFunc <- summaryStatInsertions[[func(element)]](element, var_cats) return(function(vec) statFunc(vec)) } known_inserts <- c("subtotal", names(summaryStatInsertions)) unknown_funcs <- !(element[["function"]] %in% known_inserts) if (unknown_funcs) { warning( "Transform functions other than subtotal are not supported.", " Applying only subtotals and ignoring ", element[["function"]] ) } return(function(vec) NA) })) } getInsertionTypes <- function(cat_insert_map, cats_in_array) { return(vapply(cat_insert_map, function(element) { if (is.category(element)) { if (!is.null(cats_in_array) && !name(element) %in% cats_in_array) { return(NA_character_) } return("Category") } if (is.Heading(element)) { return("Heading") } if (is.Subtotal(element)) { return("Subtotal") } if (is.SummaryStat(element)) { return("SummaryStat") } known_inserts <- c("subtotal", names(summaryStatInsertions)) unknown_funcs <- !(element[["function"]] %in% known_inserts) if (unknown_funcs) { return("Unknown") } }, character(1))) } applyAgainst <- function(X, MARGIN, FUN, ...) { names_of_dims <- names(dimnames(X)) ndims <- length(dim(X)) if (ndims < 2) { return(as.array(FUN(X, ...))) } off_margins <- seq_along(dim(X))[-MARGIN] X <- apply(X, off_margins, FUN, ...) X <- aperm(X, append(2:ndims, 1, after = MARGIN - 1)) names(dimnames(X)) <- names_of_dims return(X) } subsetTransformedCube <- function(array, dimensions, useNA) { dims <- dim(array) if (is.null(dims)) { return(array) } keep_all <- lapply( seq_along(dims), function(i) { out <- rep(TRUE, dims[i]) names(out) <- dimnames(array)[[i]] return(out) } ) names(keep_all) <- names(dimensions)[seq_along(keep_all)] keep_these_cube_dims <- evalUseNA(array, dimensions[seq_along(keep_all)], useNA) keep_these <- mapply(function(x, y) { not_ys <- y[!y] x[names(not_ys)] <- not_ys return(x) }, keep_all, keep_these_cube_dims, SIMPLIFY = FALSE, USE.NAMES = TRUE ) array_dimnames <- dimnames(array) for (i in seq_along(array_dimnames)) { to_keep <- names(keep_these[[i]]) %in% array_dimnames[[i]] keep_these[[i]] <- keep_these[[i]][to_keep] } array <- subsetCubeArray(array, keep_these) return(array) } setMethod("transforms", "CrunchCube", function(x) { transforms(variables(x)) }) setMethod("transforms", "VariableCatalog", function(x) { transes <- lapply(x, function(i) { i$view$transform }) transes_out <- lapply(transes, function(i) { if (is.null(i$insertions) || length(i$insertions) == 0) { return(NULL) } inserts <- Insertions(data = i$insertions) inserts <- subtypeInsertions(inserts) return(Transforms( insertions = inserts, categories = NULL, elements = NULL )) }) names(transes_out) <- aliases(x) return(TransformsList(data = transes_out)) }) setMethod("transforms<-", c("CrunchCube", "ANY"), function(x, value) { if (!is.null(names(value))) { validateNamesInDims(names(value), x, what = "transforms") transforms_list <- TransformsList(data = value) transforms(x)[names(value)] <- transforms_list } else { transforms(x) <- TransformsList(data = value) } return(invisible(x)) }) setMethod("[[<-", c("TransformsList", "ANY", "missing", "NULL"), function(x, i, j, value) { x[[i]] <- Transforms(insertions = NULL, elements = NULL, categories = NULL) return(x) }) setMethod("transforms<-", c("CrunchCube", "TransformsList"), function(x, value) { dims <- dimensions(x) dimnames <- names(dims) stopifnot(length(value) == length(dims)) validateNamesInDims(names(value), x, what = "transforms") vars <- variables(x) dims <- CubeDims(mapply(function(dim, val, var) { if (!is.MR(var)) { var_items <- categories(var) } else { var_items <- subvariables(var) } val$insertions <- Insertions( data = lapply(val$insertions, makeInsertion, var_items = var_items, alias = alias(var)) ) dim$references$view$transform <- jsonprep(val) return(dim) }, dim = dims, val = value, var = vars, SIMPLIFY = FALSE)) names(dims) <- dimnames dimensions(x) <- dims return(invisible(x)) }) validateNamesInDims <- function(names, cube, what = "transforms") { dimnames <- names(dimensions(cube)) if (any(!(names %in% dimnames))) { halt( "The names of the ", what, " supplied (", serialPaste(dQuote(names)), ") do not match the dimensions of the cube (", serialPaste(dQuote(dimnames)), ")." ) } } setMethod("transforms<-", c("CrunchCube", "NULL"), function(x, value) { dims <- dimensions(x) dimnames <- names(dims) dims <- CubeDims(lapply(dims, function(x) { if (!is.null(x$references$view$transform)) { x$references$view$transform <- value } return(x) })) names(dims) <- dimnames dimensions(x) <- dims return(invisible(x)) }) noTransforms <- function(cube) { transforms(cube) <- NULL return(cube) }
summary.cureph <- function(object, combine = T, ...) { aliased <- sapply(coef(object), is.na) p <- sum(!unlist(aliased)) if (p > 0) { p.logistic=length(coef(object)[[1]]) coef.p <- unlist(object$coefficients) exp.coef=exp(coef.p) exp.negcoef=exp(-coef.p) covmat.unscaled <- object$var dimnames(covmat.unscaled) <- list(names(coef.p), names(coef.p)) var.cf <- diag(covmat.unscaled) s.err <- sqrt(var.cf) tvalue <- coef.p/s.err lower.95 = exp(coef.p-qnorm(.975)*s.err) upper.95 = exp(coef.p+qnorm(.975)*s.err) dn <- c("coef", 'exp(coef)', "se(coef)") pvalue <- 2 * pnorm(-abs(tvalue)) coef.table <- cbind(coef.p, exp.coef, s.err, tvalue, pvalue) dimnames(coef.table) <- list(names(coef.p), c(dn, "z", "Pr(>|z|)")) conf.int = cbind(exp.coef, exp.negcoef, lower.95, upper.95) dimnames(conf.int) = list(names(coef.p), c('exp(coef)', 'exp(-coef)', 'lower .95', 'upper .95')) coef.table= list(logistic=coef.table[1:p.logistic, ,drop=F], cox=coef.table[-(1:p.logistic), ,drop=F ]) rownames(coef.table$logistic)=names(coef(object)$logistic) rownames(coef.table$cox)=names(coef(object)$cox) conf.int =list(logistic=conf.int[1:p.logistic,,drop=F ], cox=conf.int[-(1:p.logistic),,drop=F ]) rownames(conf.int$logistic)=names(coef(object)$logistic) rownames(conf.int$cox)=names(coef(object)$cox) if(length(object$var.levels)==0) { combine = F } if(combine & length(object$var.levels)>0) if((length(coef(object)$logistic) - 1 != length(coef(object)$cox)) || any(names(coef(object)$logistic)[-1] != names(coef(object)$cox))) { warning("Combined Wald-test not applicable, as the sets of covariates are different. ") combine = F }else{ df.wald=object$var.levels*2 var.pos=cumsum(object$var.levels) var.range.logistic=mapply(':',2+c(0,var.pos[-length(var.pos)]),1+var.pos) var.range.cox=sapply(var.range.logistic,'+',var.pos[length(var.pos)]) var.range = mapply('c',var.range.logistic,var.range.cox) chi.wald = unlist(sapply(var.range,function(var.range,var,b) {if(any(is.na(b[var.range]))) NA else survival::coxph.wtest(var[var.range,var.range],b[var.range])$test}, covmat.unscaled, coef.p)) p.wald = 1-pchisq(chi.wald, df.wald) comb.table = cbind(chi.wald, df.wald ,p.wald) dimnames(comb.table)=list(names(object$var.levels), c('Wald-chi.square', 'df', 'p-value')) } } else { combine = F coef.table <- matrix( 0 , 0L, 5L) dimnames(coef.table) <- list(NULL, c("coef", 'exp(coef)', "se(coef)", "z", "Pr(>|z|)")) covmat.unscaled <- covmat <- matrix( 0 , 0L, 0L) } keep <- match(c("call", "terms.logistic","terms.cox", 'n','nevent','df', "contrasts.logistic","contrasts.cox", "wald.test", "iter", "na.action"), names(object), 0L) ans <- c(object[keep], list(coefficients = coef.table,combine=combine, conf.int=conf.int, aliased = aliased, cov = covmat.unscaled)) if(combine) ans$comb.wald=comb.table class(ans) <- "summary.cureph" ans } print.summary.cureph=function(x, digits = max(3, getOption("digits") - 3), signif.stars = getOption("show.signif.stars"), ...) { coef.logistic=x$coefficients$logistic coef.cox=x$coefficients$cox sig.logistic=rep(' ',nrow(coef.logistic)) sig.logistic[coef.logistic[,5]<=0.1] = '.' sig.logistic[coef.logistic[,5]<=0.05] = '*' sig.logistic[coef.logistic[,5]<=0.01] = '**' sig.logistic[coef.logistic[,5]<=0.001] = '***' coef.logistic[,1:3]=round(coef.logistic[,1:3],digits=digits) coef.logistic[,4]=round(coef.logistic[,4],digits=digits-1) coef.logistic[sig.logistic!='***',5]=round(coef.logistic[sig.logistic!='***',5],digits=digits-1) coef.logistic[sig.logistic=='***',5]=signif(coef.logistic[sig.logistic=='***',5],digits=digits-3) if(signif.stars) { coef.logistic=cbind(coef.logistic,sig.logistic) colnames(coef.logistic)[6]='' } sig.cox=rep(' ',nrow(coef.cox)) sig.cox[coef.cox[,5]<=0.1] = '.' sig.cox[coef.cox[,5]<=0.05] = '*' sig.cox[coef.cox[,5]<=0.01] = '**' sig.cox[coef.cox[,5]<=0.001] = '***' coef.cox[,1:3]=round(coef.cox[,1:3],digits=digits) coef.cox[,4]=round(coef.cox[,4],digits=digits-1) coef.cox[sig.cox!='***',5]=round(coef.cox[sig.cox!='***',5],digits=digits-1) coef.cox[sig.cox=='***',5]=signif(coef.cox[sig.cox=='***',5],digits=digits-3) if(signif.stars) { coef.cox=cbind(coef.cox,sig.cox) colnames(coef.cox)[6]='' } cat('Call:\n') print(x$call) cat('\n') cat('Logistic Model: \n') print(formula(x$terms.logistic)) cat('Cox Model: \n') print(formula(x$terms.cox)) cat('\n') cat(paste(' n= ',x$n, ', number of events= ',x$nevent, sep='' )) cat('\n \n') cat('Logistic:\n') print(coef.logistic,quote = FALSE) cat('\n') if(nrow(coef.cox)>0) { cat('Cox:\n') print(coef.cox,quote = FALSE) } if(x$combine) { comb.wald = x$comb.wald sig.comb=rep(' ',nrow(comb.wald)) sig.comb[comb.wald[,3]<=0.1] = '.' sig.comb[comb.wald[,3]<=0.05] = '*' sig.comb[comb.wald[,3]<=0.01] = '**' sig.comb[comb.wald[,3]<=0.001] = '***' comb.wald[,1]=round(comb.wald[,1],digits=digits-1) comb.wald[sig.comb!='***',3]=round(comb.wald[sig.comb!='***',3],digits=digits-1) comb.wald[sig.comb=='***',3]=signif(comb.wald[sig.comb=='***',3],digits=digits-3) if(signif.stars) { comb.wald=cbind(comb.wald,sig.comb) colnames(comb.wald)[4]='' } cat('\n') cat('Combined Wald tests: \n') print(comb.wald,quote=F) } cat('--- \n') cat(paste('Signif. codes: 0', sQuote('***'), "0.001", sQuote('**'), '0.01', sQuote('*'), '0.05', sQuote('.'), '0.1', sQuote(' '), '1\n')) cat('\n') cat('Logistic:\n') print(x$conf.int$logistic,digits=digits) cat('\n') if(nrow(coef.cox)>0) { cat('Cox:\n') print(x$conf.int$cox,digits=digits) cat('\n') } cat(paste('Wald test =', signif(x$wald.test,digits=digits), 'on', x$df, 'df, p =', signif(1-pchisq(x$wald.test,x$df),digits=digits))) }
test_that("geos_geometry class works", { expect_s3_class(new_geos_geometry(list(), crs = NULL), "geos_geometry") expect_s3_class(new_geos_geometry(list(NULL), crs = NULL), "geos_geometry") expect_error(new_geos_geometry(NULL, crs = NULL), "must be a bare list") expect_true(is.na(new_geos_geometry(list(NULL), crs = NULL))) }) test_that("geos_geometry can be created from well-known text", { expect_s3_class(as_geos_geometry("POINT (30 10)"), "geos_geometry") expect_s3_class(as_geos_geometry(wk::wkt("POINT (30 10)")), "geos_geometry") expect_length(as_geos_geometry("POINT (30 10)"), 1) expect_length(as_geos_geometry(c(NA, "POINT (30 10)")), 2) }) test_that("geos_geometry can be created from well-known binary", { expect_s3_class(as_geos_geometry(structure(wk::as_wkb("POINT (30 10)"), class = "blob")), "geos_geometry") expect_s3_class(as_geos_geometry(structure(wk::as_wkb("POINT (30 10)"), class = "WKB")), "geos_geometry") }) test_that("geos_geometry validation works", { expect_identical( validate_geos_geometry(new_geos_geometry(list(), crs = NULL)), new_geos_geometry(list(), crs = NULL) ) expect_identical( validate_geos_geometry(new_geos_geometry(list(NULL), crs = NULL)), new_geos_geometry(list(NULL), crs = NULL) ) expect_error(validate_geos_geometry(list("wrong type")), "must be externalptr") }) test_that("geos_geometry subsetting and concatenation work", { geometry <- new_geos_geometry(list(NULL, NULL), crs = NULL) expect_identical(geometry[1], new_geos_geometry(list(NULL), crs = NULL)) expect_identical(geometry[[1]], geometry[1]) expect_identical( c(geometry, geometry), new_geos_geometry(list(NULL, NULL, NULL, NULL), crs = NULL) ) expect_identical( rep(geometry, 2), new_geos_geometry(list(NULL, NULL, NULL, NULL), crs = NULL) ) expect_identical( rep_len(geometry, 4), new_geos_geometry(list(NULL, NULL, NULL, NULL), crs = NULL) ) expect_error( c(new_geos_geometry(list(NULL, NULL), crs = NULL), 1:5), "must inherit from" ) }) test_that("subset-assignment works", { x <- as_geos_geometry(c("POINT EMPTY", "LINESTRING EMPTY", "POLYGON EMPTY")) expect_identical(geos_write_wkt(x[3]), "POLYGON EMPTY") x[3] <- "POINT (1 2)" expect_identical(geos_write_wkt(x[3]), "POINT (1 2)") x[3] <- as_geos_geometry("POINT (3 4)", crs = wk::wk_crs_inherit()) expect_identical(geos_write_wkt(x[3]), "POINT (3 4)") x[[3]] <- "POINT (1 2)" expect_identical(geos_write_wkt(x[3]), "POINT (1 2)") expect_error(x[3] <- as_geos_geometry("POINT (1 2)", crs = 123), "are not equal") }) test_that("geos_geometry can be put into a data.frame", { expect_identical( data.frame(geom = new_geos_geometry(list(NULL), crs = NULL)), new_data_frame(list(geom = new_geos_geometry(list(NULL), crs = NULL))) ) expect_error(as.data.frame(new_geos_geometry(list(NULL), crs = NULL)), "cannot coerce class") }) test_that("geos_geometry default format/print/str methods work", { expect_identical( format(as_geos_geometry("POINT (10 10)")), as.character(as_geos_geometry("POINT (10 10)")) ) expect_match(format(geos_make_linestring(1:6, 1)), "<LINESTRING \\[") expect_match(format(geos_make_linestring(1:5, 1)), "<LINESTRING \\(") expect_output(print(new_geos_geometry(crs = NULL)), "geos_geometry") expect_output(print(new_geos_geometry(list(NULL), crs = NULL)), "geos_geometry") expect_output(print(new_geos_geometry(crs = 1234)), "CRS=1234") expect_match(format(as_geos_geometry(c("POINT (0 1)", NA)))[2], "<NA>") expect_output(str(as_geos_geometry(character())), "geos_geometry\\[0\\]") expect_output(str(as_geos_geometry("POINT (10 10)")), "<POINT \\(10 10\\)>") })
`IdfMltSV.default` <- function(MultiData,LgLim,SVSize){ MultiDt <- (subset(MultiData$MultiSvLg2,abs(MultiData$MultiSvLg2$PopLg2)>=LgLim)) MultiDt <- (subset(MultiDt,abs(MultiDt$PopLg2)!="Inf")) MultiDt$MidPos <- round((MultiDt$end+MultiDt$start)/2) MultiDt$MultiSV <- 0 MultiDt$MultiSVSize <- NA MultiDt$MultiSVlog2 <- NA MultiDt$MultiSVPval <- NA ComBin = 1 PrevRegion = 0 MltSv <- 1 StepSize = mean((MultiDt$end-MultiDt$start))+1 Brdg = StepSize*3 Lengths <- abs(MultiDt[2:nrow(MultiDt),'MidPos']-MultiDt[1:(nrow(MultiDt)-1),'MidPos']) MultiEnd <- c(which(Lengths>Brdg),nrow(MultiDt)) for(MSV in MultiEnd){ if(MSV-MltSv+1>=ComBin){ PrevRegion <- PrevRegion+1 MultiDt[MltSv:MSV,'MultiSV'] <- PrevRegion } MltSv <- MSV+1 } MltSV = 0 for(MltSV in seq(1,max(MultiDt$MultiSV))){ MltSvSbSt <- subset(MultiDt, MultiDt$MultiSV==MltSV) Strt <- min(MltSvSbSt$MidPos)-StepSize End <- max(MltSvSbSt$MidPos)+StepSize Size <- (End - Strt) Chr <- as.character(unique(MltSvSbSt$chr)) if(length(MltSvSbSt$PopLg2) > 1){ if(mean(MltSvSbSt$PopLg2) > 0){ Lg2 <- max(MltSvSbSt$PopLg2) }else if(mean(MltSvSbSt$PopLg2) < 0){ Lg2 <- min(MltSvSbSt$PopLg2) } }else if( length(MltSvSbSt$PopLg2) == 1){ Lg2 <- unique(MltSvSbSt$PopLg2) }else if(length(MltSvSbSt$PopLg2) == 0){ Lg2 <- 0 } RwNms <- which(MultiDt$MultiSV==MltSV) MultiDt[RwNms,'MultiSVlog2'] <- Lg2 MultiDt[RwNms,'MultiSVSize'] <- Size MultiDt[RwNms,'MultiSVPval'] <- CmptMltPvl((subset(MultiData$MultiSvScl, MultiData$MultiSvScl$chr==Chr & MultiData$MultiSvScl$start>=Strt & MultiData$MultiSvScl$end<=End)),MultiData$Conf) } MultiSVData <- as.data.frame(matrix(nrow = max(MultiDt$MultiSV), ncol = 6)) colnames(MultiSVData) <- c("Chr","Start","End","Size","log2","Pval") MltSV = 0 for(MltSV in seq(max(min(MultiDt$MultiSV),1), max(MultiDt$MultiSV))){ MltSvSbSt <- subset(MultiDt, MultiDt$MultiSV==MltSV) if (unique(MltSvSbSt$MultiSVlog2) != "NaN"){ MultiSVData[MltSV,1] <- as.character((unique(MltSvSbSt$chr))[1]) MultiSVData[MltSV,2] <- min(MltSvSbSt$MidPos)-StepSize+1 MultiSVData[MltSV,3] <- max(MltSvSbSt$MidPos)+StepSize MultiSVData[MltSV,4] <- unique(MltSvSbSt$MultiSVSize) MultiSVData[MltSV,5] <- unique(MltSvSbSt$MultiSVlog2) MultiSVData[MltSV,6] <- unique(MltSvSbSt$MultiSVPval) } else { MultiSVData[MltSV,4] <- NA MultiSVData[MltSV,5] <- NA MultiSVData[MltSV,6] <- NA } } subset(MultiSVData,MultiSVData$Pval<=0.05&MultiSVData$Size>SVSize) }
library(checkargs) context("isNegativeIntegerOrNaOrInfScalar") test_that("isNegativeIntegerOrNaOrInfScalar works for all arguments", { expect_identical(isNegativeIntegerOrNaOrInfScalar(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrInfScalar(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrInfScalar(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrInfScalar(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrInfScalar(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrInfScalar(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_error(isNegativeIntegerOrNaOrInfScalar(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNegativeIntegerOrNaOrInfScalar(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrInfScalar(0, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrInfScalar(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNegativeIntegerOrNaOrInfScalar(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNegativeIntegerOrNaOrInfScalar(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNegativeIntegerOrNaOrInfScalar(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar("", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar("X", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrInfScalar(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) })
MLModel <- function( name = "MLModel", label = name, packages = character(), response_types = character(), weights = FALSE, predictor_encoding = c(NA, "model.frame", "model.matrix"), params = list(), gridinfo = tibble::tibble( param = character(), get_values = list(), default = logical() ), fit = function(formula, data, weights, ...) stop("No fit function."), predict = function(object, newdata, times, ...) stop("No predict function."), varimp = function(object, ...) NULL, ... ) { stopifnot(!any(duplicated(response_types))) stopifnot(response_types %in% settings("response_types")) stopifnot(length(weights) %in% c(1, length(response_types))) stopifnot(is_tibble(gridinfo)) gridinfo <- new_gridinfo( param = gridinfo[["param"]], get_values = gridinfo[["get_values"]], default = gridinfo[["default"]] ) new("MLModel", name = name, label = label, packages = packages, response_types = response_types, weights = weights, predictor_encoding = match.arg(predictor_encoding), params = params, gridinfo = gridinfo, fit = fit, predict = predict, varimp = varimp, ... ) } update.MLModel <- function( object, params = list(), quote = TRUE, new_id = FALSE, ... ) { new_params <- as(object, "list") new_params[names(params)] <- params res <- do.call(object@name, new_params, quote = quote) if (!new_id) res@id <- object@id res } MLModelFit <- function(object, Class, model, input) { model@input <- prep(input) if (is(object, Class)) { object <- unMLModelFit(object) } else if (is(object, "MLModelFit")) { throw(Error("Cannot change MLModelFit class.")) } if (!is(model, "MLModel")) throw(TypeError(model, "MLModel", "'model'")) if (isS4(object)) { object <- new(Class, object, mlmodel = model) } else if (is.list(object)) { object$mlmodel <- model class(object) <- c(Class, "MLModelFit", class(object)) } else { throw(TypeError(object, c("S4 class", "list"), "'object'")) } object } unMLModelFit <- function(object) { if (is(object, "MLModelFit")) { if (isS4(object)) { classes <- extends(class(object)) pos <- match("MLModelFit", classes) as(object, classes[pos + 1]) } else { object$mlmodel <- NULL classes <- class(object) pos <- match("MLModelFit", classes) structure(object, class = classes[-seq_len(pos)]) } } else object }
list_plot_methods <- function() { m <- methods(class = "bcea") m[grep(pattern = "plot", m)] }
query <- "persian cat" CatImg <- GoogleImage2array(query) str(CatImg)
log_W <- function(z, branch = 0, W.z = W(z, branch = branch)) { log.W.z <- log(z) - W.z if (any(is.infinite(z))) { log.W.z[is.infinite(z)] <- Inf } return(log.W.z) }
datasummary_correlation <- function(data, output = 'default', method = "pearson", fmt = 2, align = NULL, add_rows = NULL, add_columns = NULL, title = NULL, notes = NULL, escape = TRUE, ...) { settings_init(settings = list( "function_called" = "datasummary_correlation" )) sanitize_output(output) sanitize_escape(escape) sanity_add_columns(add_columns) any_numeric <- any(sapply(data, is.numeric) == TRUE) if (any_numeric == FALSE) { stop("`datasummary_correlation` can only summarize numeric data columns.") } checkmate::assert( checkmate::check_choice( method, c("pearson", "kendall", "spearman", "pearspear")), checkmate::check_function(method)) if (is.function(method)) { fn <- method } else if (method == "pearspear") { fn <- correlation_pearspear } else { fn <- function(x) stats::cor( x, use = "pairwise.complete.obs", method = method) } out <- data[, sapply(data, is.numeric), drop = FALSE] out <- fn(out) if ((!is.matrix(out) && !inherits(out, "data.frame")) || is.null(row.names(out)) || is.null(colnames(out)) || nrow(out) != ncol(out)) { stop("The function supplied to the `method` argument did not return a square matrix or data.frame with row.names and colnames.") } if (is.character(method)) { if (method == "pearspear") { out <- datasummary_correlation_format( out, fmt = fmt, diagonal = "1") } else { out <- datasummary_correlation_format( out, fmt = fmt, diagonal = "1", upper_triangle = ".") } } else { out <- datasummary_correlation_format( out, fmt = fmt) } col_names <- colnames(out) out <- cbind(rowname = row.names(out), out) colnames(out) <- c(' ', col_names) if (is.null(align)) { ncols <- ncol(out) if (!is.null(add_columns)) { ncols <- ncols + ncol(add_columns) } align <- paste0('l', strrep('r', ncols - 1)) } if (settings_equal("escape", TRUE)) { out[, 1] <- escape_string(out[, 1]) colnames(out) <- escape_string(colnames(out)) } out <- factory(out, align = align, hrule = NULL, output = output, add_rows = add_rows, add_columns = add_columns, notes = notes, title = title, ...) if (!is.null(settings_get("output_file")) || output == "jupyter" || (output == "default" && settings_equal("output_default", "jupyter"))) { settings_rm() return(invisible(out)) } else { settings_rm() return(out) } } correlation_pearspear <- function(x) { pea <- stats::cor( x, use = "pairwise.complete.obs", method = "pearson" ) spe <- stats::cor( x, use = "pairwise.complete.obs", method = "spearman" ) pea[lower.tri(pea)] <- spe[lower.tri(spe)] return(pea) } datasummary_correlation_format <- function( x, fmt, leading_zero = FALSE, diagonal = NULL, upper_triangle = NULL) { checkmate::assert_character(diagonal, len = 1, null.ok = TRUE) checkmate::assert_character(upper_triangle, len = 1, null.ok = TRUE) checkmate::assert_flag(leading_zero) out <- data.frame(x, check.names = FALSE) for (i in seq_along(out)) { out[[i]] <- rounding(out[[i]], fmt) if (leading_zero == FALSE) { out[[i]] <- gsub('0\\.', '\\.', out[[i]]) } } for (i in 1:nrow(out)) { for (j in 1:ncol(out)) { if (!is.null(upper_triangle)) { out[i, j] <- ifelse(i < j, upper_triangle, out[i, j]) } if (!is.null(diagonal)) { out[i, j] <- ifelse(i == j, diagonal, out[i, j]) } } } return(out) }
library(knitr) knitr::opts_chunk$set( fig.align = "center", fig.height = 5.5, fig.width = 6, warning = FALSE, collapse = TRUE, dev.args = list(pointsize = 10), out.width = "90%", par = TRUE ) knit_hooks$set(par = function(before, options, envir) { if (before && options$fig.show != "none") par(family = "sans", mar = c(4.1,4.1,1.1,1.1), mgp = c(3,1,0), tcl = -0.5) }) library(samurais) data("multivtoydataset") K <- 5 p <- 3 variance_type <- "heteroskedastic" n_tries <- 1 max_iter <- 1500 threshold <- 1e-6 verbose <- TRUE mhmmr <- emMHMMR(multivtoydataset$x, multivtoydataset[,c("y1", "y2", "y3")], K, p, variance_type, n_tries, max_iter, threshold, verbose) mhmmr$summary() mhmmr$plot(what = "predicted") mhmmr$plot(what = "filtered") mhmmr$plot(what = "regressors") mhmmr$plot(what = "smoothed") mhmmr$plot(what = "loglikelihood")
compute.threshold.FPF.cROC.kernel <- function(object, newdata, FPF = 0.5, ci.level = 0.95, parallel = c("no", "multicore", "snow"), ncpus = 1, cl = NULL) { if(class(object)[1] != "cROC.kernel") { stop(paste0("This function cannot be used for this object class: ", class(object)[1])) } names.cov <- object$covariate if(!missing(newdata) && !inherits(newdata, "data.frame")) stop("Newdata must be a data frame") if(!missing(newdata) && length(names.cov) != 0 && sum(is.na(match(names.cov, names(newdata))))) stop("Not all needed variables are supplied in newdata") if(missing(newdata)) { newdata <- cROCData(object$data, names.cov, object$group) } else { newdata <- as.data.frame(newdata) newdata <- na.omit(newdata[,names.cov,drop = FALSE]) } xp <- newdata[,names.cov] res.aux <- compute.threshold.FPF.kernel(object = object$fit$h, newdata = xp, FPF = FPF) thresholds <- vector("list", length(FPF)) names(thresholds) <- FPF for(i in 1:length(FPF)){ thresholds[[i]] <- matrix(res.aux$thresholds[i,], ncol = 1) colnames(thresholds[[i]]) <- "est" } res <- list() res$thresholds <- thresholds res$FPF <- FPF fit.mean.new <- npreg(object$fit$d$bw.mean, exdat = xp, residuals = TRUE) fit.var.new <- npreg(object$fit$d$bw.var, exdat = xp, residuals = TRUE) d.residuals <- object$fit$d$fit.mean$resid/sqrt(object$fit$d$fit.var$mean) aux <- t(t(res.aux$thresholds) - fit.mean.new$mean) aux <- t(t(aux)/sqrt(fit.var.new$mean)) TPF.aux <- matrix(1 - ecdf(d.residuals)(aux), nrow = length(FPF)) TPF <- vector("list", length(FPF)) names(TPF) <- FPF for(i in 1:length(FPF)){ TPF[[i]] <- matrix(TPF.aux[i,], ncol = 1) colnames(TPF[[i]]) <- "est" } res$TPF <- TPF res$newdata <- newdata res }
divider_height = function(cinfo) 1L setGeneric("nlines", function(x, colwidths) standardGeneric("nlines")) setMethod("nlines", "TableRow", function(x, colwidths) { fns <- sum(unlist(lapply(row_footnotes(x), nlines))) + sum(unlist(lapply(cell_footnotes(x), nlines))) fcells <- get_formatted_cells(x) rowext <- max(vapply(strsplit(c(obj_label(x), fcells), "\n", fixed = TRUE), length, 1L)) rowext + fns }) setMethod("nlines", "LabelRow", function(x, colwidths) { if(labelrow_visible(x)) length(strsplit(obj_label(x), "\n", fixed = TRUE)[[1]]) + sum(unlist(lapply(row_footnotes(x), nlines))) else 0L }) setMethod("nlines", "RefFootnote", function(x, colwidths) { 1L }) setMethod("nlines", "VTableTree", function(x, colwidths) { length(collect_leaves(x, TRUE, TRUE)) }) setMethod("nlines", "InstantiatedColumnInfo", function(x, colwidths) { lfs = collect_leaves(coltree(x)) depths = sapply(lfs, function(l) length(pos_splits(l))) max(depths, length(top_left(x))) + divider_height(x) }) setMethod("nlines", "list", function(x, colwidths) { if(length(x) == 0) 0L else sum(unlist(vapply(x, nlines, NA_integer_, colwidths = colwidths))) }) setMethod("nlines", "NULL", function(x, colwidths) 0L) setMethod("nlines", "character", function(x, colwidths) max(vapply(strsplit(x, "\n", fixed = TRUE), length, 1L))) pagdfrow = function(row, nm = obj_name(row), lab = obj_label(row), rnum, pth , sibpos = NA_integer_, nsibs = NA_integer_, extent = nlines(row, colwidths), colwidths = NULL, repext = 0L, repind = integer(), indent = 0L, rclass = class(row), nrowrefs = 0L, ncellrefs = 0L, nreflines = 0L ) { data.frame(label = lab, name = nm, abs_rownumber = rnum, path = I(list(pth)), pos_in_siblings = sibpos, n_siblings = nsibs, self_extent = extent, par_extent = repext, reprint_inds = I(list(unlist(repind))), node_class = rclass, indent = max(0L, indent), nrowrefs = nrowrefs, ncellrefs = ncellrefs, nreflines = nreflines, stringsAsFactors = FALSE) } col_dfrow = function(col, nm = obj_name(col), lab = obj_label(col), cnum, pth = NULL, sibpos = NA_integer_, nsibs = NA_integer_, leaf_indices = cnum, span = length(leaf_indices), col_fnotes = list() ) { if(is.null(pth)) pth <- pos_to_path(tree_pos(col)) data.frame(stringsAsFactors = FALSE, name = nm, label = lab, abs_pos = cnum, path = I(list(pth)), pos_in_siblings = sibpos, n_siblings = nsibs, leaf_indices = I(list(leaf_indices)), total_span = span, col_fnotes = I(list(col_fnotes)), n_col_fnotes = length(col_fnotes)) } pos_to_path <- function(pos) { spls <- pos_splits(pos) vals <- pos_splvals(pos) path <- character() for(i in seq_along(spls)) { path <- c(path, obj_name(spls[[i]]), value_names(vals[[i]])) } path } setGeneric("make_row_df", function(tt, colwidths = NULL, visible_only = TRUE, rownum = 0, indent = 0L, path = character(), incontent = FALSE, repr_ext = 0L, repr_inds = integer(), sibpos = NA_integer_, nsibs = NA_integer_, nrowrefs = 0L, ncellrefs = 0L, nreflines = 0L) standardGeneric("make_row_df")) setMethod("make_row_df", "VTableTree", function(tt, colwidths = NULL, visible_only = TRUE, rownum = 0, indent = 0L, path = character(), incontent = FALSE, repr_ext = 0L, repr_inds = integer(), sibpos = NA_integer_, nsibs = NA_integer_) { indent <- indent + indent_mod(tt) orig_rownum <- rownum if(incontent) path <- c(path, "@content") else if (length(path) > 0 || nzchar(obj_name(tt))) path <- c(path, obj_name(tt)) ret <- list() if(!visible_only) { ret <- c(ret, list(pagdfrow(rnum = NA, nm = obj_name(tt), lab = "", pth = path, colwidths = colwidths, repext = repr_ext, repind = list(repr_inds), extent = 0, indent = indent, rclass = class(tt), sibpos = sibpos, nsibs = nsibs, nrowrefs = 0L, ncellrefs = 0L, nreflines = 0L))) } if(labelrow_visible(tt)) { lr = tt_labelrow(tt) newdf <- make_row_df(lr, colwidths= colwidths, visible_only = visible_only, rownum = rownum, indent = indent, path = path, incontent = TRUE, repr_ext = repr_ext, repr_inds = repr_inds) rownum <- max(newdf$abs_rownumber,na.rm = TRUE) ret = c(ret, list(newdf)) repr_ext = repr_ext + 1L repr_inds = c(repr_inds, rownum) indent <- indent + 1L } if(NROW(content_table(tt)) > 0) { cind <- indent + indent_mod(content_table(tt)) contdf <- make_row_df(content_table(tt), colwidths= colwidths, visible_only = visible_only, rownum = rownum, indent = cind, path = path, incontent = TRUE, repr_ext = repr_ext, repr_inds = repr_inds) crnums <- contdf$abs_rownumber crnums <- crnums[!is.na(crnums)] newrownum <- max(crnums, na.rm = TRUE) if(is.finite(newrownum)) { rownum <- newrownum repr_ext <- repr_ext + length(crnums) repr_inds <- c(repr_inds, crnums) } ret <- c(ret, list(contdf)) indent <- cind + 1 } allkids <- tree_children(tt) newnsibs <- length(allkids) for(i in seq_along(allkids)) { kid <- allkids[[i]] kiddfs <- make_row_df(kid, colwidths= colwidths, visible_only = visible_only, rownum = force(rownum), indent = indent, path = path, incontent = incontent, repr_ext = repr_ext, repr_inds = repr_inds, nsibs = newnsibs, sibpos = i) rownum <- max(rownum + 1L, kiddfs$abs_rownumber, na.rm = TRUE) ret <- c(ret, list(kiddfs)) } do.call(rbind, ret) }) setMethod("make_row_df", "TableRow", function(tt, colwidths = NULL, visible_only = TRUE, rownum = 0, indent = 0L, path = "root", incontent = FALSE, repr_ext = 0L, repr_inds = integer(), sibpos = NA_integer_, nsibs = NA_integer_) { indent <- indent + indent_mod(tt) rownum <- rownum + 1 rrefs <- row_footnotes(tt) crefs <- cell_footnotes(tt) reflines <- sum(sapply(c(rrefs, crefs), nlines)) ret <- pagdfrow(tt, rnum = rownum, colwidths = colwidths, sibpos = sibpos, nsibs = nsibs, pth = c(path, obj_name(tt)), repext = repr_ext, repind = repr_inds, indent = indent, nrowrefs = length(rrefs) , ncellrefs = length(unlist(crefs)), nreflines = reflines ) ret }) setMethod("make_row_df", "LabelRow", function(tt, colwidths = NULL, visible_only = TRUE, rownum = 0, indent = 0L, path = "root", incontent = FALSE, repr_ext = 0L, repr_inds = integer(), sibpos = NA_integer_, nsibs = NA_integer_) { rownum <- rownum + 1 indent <- indent + indent_mod(tt) ret <- pagdfrow(tt, rnum = rownum, colwidths = colwidths, sibpos = sibpos, nsibs = nsibs, pth = path, repext = repr_ext, repind = repr_inds, indent = indent, nrowrefs = length(row_footnotes(tt)), ncellrefs = 0L, nreflines = sum(vapply(row_footnotes(tt), nlines, NA_integer_))) if(!labelrow_visible(tt)) ret <- ret[0,] ret }) setGeneric("inner_col_df", function(ct, colwidths = NULL, visible_only = TRUE, colnum = 0L, sibpos = NA_integer_, nsibs = NA_integer_, ncolref = 0L) standardGeneric("inner_col_df")) make_col_df <- function(tt, visible_only = TRUE) { ctree <- coltree(tt) rows <- inner_col_df(ctree, colwidths = propose_column_widths(tt), visible_only = visible_only, colnum = 1L, sibpos = 1L, nsibs = 1L) do.call(rbind, rows) } setMethod("inner_col_df", "LayoutColLeaf", function(ct, colwidths, visible_only, colnum, sibpos, nsibs) { list(col_dfrow(col = ct, cnum = colnum, sibpos = sibpos, nsibs = nsibs, leaf_indices = colnum, col_fnotes = col_fnotes_here(ct))) }) setMethod("inner_col_df", "LayoutColTree", function(ct, colwidths, visible_only, colnum, sibpos, nsibs) { kids <- tree_children(ct) ret <- vector("list", length(kids)) for(i in seq_along(kids)) { k <- kids[[i]] nleaves <- length(collect_leaves(k)) newrows <- do.call(rbind, inner_col_df(k, colnum = colnum, sibpos = i, nsibs = length(kids), visible_only = visible_only)) colnum <- max(newrows$abs_pos, colnum, na.rm = TRUE) + 1 ret[[i]] = newrows } if(!visible_only) { allindices <- unlist(lapply(ret, function(df) df$abs_pos[!is.na(df$abs_pos)])) thispth <- pos_to_path(tree_pos(ct)) if(any(nzchar(thispth))) { thisone <- list(col_dfrow(col = ct, cnum = NA_integer_, leaf_indices = allindices, sibpos = sibpos, nsibs = nsibs, pth = thispth, col_fnotes = col_fnotes_here(ct))) ret <- c(thisone, ret) } } ret }) valid_pag = function(pagdf, guess, start, rlpp, min_sibs, nosplit = NULL, verbose = FALSE) { rw <- pagdf[guess,] if(verbose) message("Checking pagination after row ", guess) reflines <- sum(pagdf[start:guess, "nreflines"]) if(reflines > 0) reflines <- reflines + 2 lines <- guess - start + 1 + reflines if(lines > rlpp) { if(verbose) message("\t....................... FAIL: Referential footnotes take up too much space (", reflines, " lines)") return(FALSE) } if(rw[["node_class"]] %in% c("LabelRow", "ContentRow")) { if(verbose) message("\t....................... FAIL: last row is a label or content row") return(FALSE) } sibpos <- rw[["pos_in_siblings"]] nsib <- rw[["n_siblings"]] okpos <- min(min_sibs + 1, rw[["n_siblings"]]) if( sibpos != nsib){ retfalse <- FALSE if(sibpos < min_sibs + 1) { retfalse <- TRUE if(verbose) message("\t....................... FAIL: last row had only ", sibpos - 1, " preceeding siblings, needed ", min_sibs) } else if (nsib - sibpos < min_sibs + 1) { retfalse <- TRUE if(verbose) message("\t....................... FAIL: last row had only ", nsib - sibpos - 1, " following siblings, needed ", min_sibs) } if(retfalse) return(FALSE) } if(guess < nrow(pagdf)) { curpth <- unlist(rw$path) nxtpth <- unlist(pagdf$path[[guess+1]]) inplay <- nosplit[(nosplit %in% intersect(curpth, nxtpth))] if(length(inplay) > 0) { curvals <- curpth[match(inplay, curpth) + 1] nxtvals <- nxtpth[match(inplay, nxtpth) + 1] if(identical(curvals, nxtvals)) { if(verbose) message("\t....................... FAIL: values of unsplitable vars before [", curvals, "] and after [", nxtvals, "] match") return(FALSE) } } } if(verbose) message("\t....................... OK") TRUE } find_pag = function(pagdf, start, guess, rlpp, min_siblings, nosplitin = character(), verbose = FALSE) { origuess = guess while(guess >= start && !valid_pag(pagdf, guess, start = start, rlpp = rlpp, min_sibs = min_siblings, nosplit = nosplitin, verbose)) { guess = guess - 1 } if(guess < start) stop("Unable to find any valid pagination between ", start, " and ", origuess) guess } pag_tt_indices = function(tt, lpp = 15, min_siblings = 2, nosplitin = character(), colwidths = NULL, verbose = FALSE) { dheight <- divider_height(tt) cinfo_lines <- nlines(col_info(tt)) if(any(nzchar(all_titles(tt)))) { tlines <- length(all_titles(tt)) + dheight + 1L } else { tlines <- 0 } flines <- length(all_footers(tt)) if(flines > 0) flines <- flines + dheight + 1L rlpp = lpp - cinfo_lines - tlines - flines pagdf = make_row_df(tt, colwidths) start = 1 nr = nrow(pagdf) ret = list() while(start <= nr) { adjrlpp = rlpp - pagdf$par_extent[start] stopifnot(adjrlpp > 0) guess = min(nr, start + adjrlpp - 1) end = find_pag(pagdf, start, guess, rlpp = adjrlpp, min_siblings = min_siblings, nosplitin = nosplitin, verbose = verbose) ret = c(ret, list(c(pagdf$reprint_inds[[start]], start:end))) start = end + 1 } ret } paginate_table = function(tt, lpp = 15, min_siblings = 2, nosplitin = character(), colwidths = NULL, verbose = FALSE) { inds = pag_tt_indices(tt, lpp = lpp, min_siblings = min_siblings, nosplitin = nosplitin, colwidths = colwidths, verbose = verbose) lapply(inds, function(x) tt[x,,keep_topleft = TRUE, keep_titles = TRUE, reindex_refs = FALSE]) }
SSgetMCMC <- function(dir=NULL, verbose=TRUE, writecsv=FALSE, postname="posteriors.sso", derpostname="derived_posteriors.sso", csv1="keyposteriors.csv", csv2="nuisanceposteriors.csv", keystrings=c( "NatM", "R0", "steep", "RecrDev_2008", "Q_extraSD"), nuisancestrings=c( "Objective_function", "SSB_", "InitAge", "RecrDev"), burnin = 0, thin = 1 ) { if(verbose){ message("reading MCMC output in\n", dir) } post <- read.table(file.path(dir, postname), header = TRUE, check.names = FALSE) derpost <- read.table(file.path(dir, derpostname), header = TRUE, check.names = FALSE) derpost <- derpost[, !(names(derpost) %in% c("Iter", "Objective_function"))] allpost <- cbind(post, derpost) allpost <- allpost[seq((burnin+1), nrow(allpost), thin), ] keylabels <- NULL nuisancelabels <- NULL for(istring in 1:length(keystrings)){ keylabels <- c(keylabels, names(allpost)[grep(keystrings[istring], names(allpost))]) } for(istring in 1:length(nuisancestrings)){ nuisancelabels <- c(nuisancelabels, names(allpost)[grep(nuisancestrings[istring], names(allpost))]) } keypost <- allpost[, names(allpost) %in% keylabels] nuisancepost <- allpost[, names(allpost) %in% nuisancelabels] if(writecsv){ file1 <- file.path(dir, csv1) file2 <- file.path(dir, csv2) if(verbose){ message("writing subset of posteriors to files:\n ", file1, "\n ", file2) } write.csv(keypost, file1, row.names=FALSE) write.csv(nuisancepost, file2, row.names=FALSE) } return(invisible(allpost)) }
context("wilcoxonLM") set.seed(410) T <- 100 d <- 0 x <- fracdiff::fracdiff.sim(n=T, d=d)$series expect_error(wilcoxonLM(c(x,NA), d=d)) expect_error(wilcoxonLM(x, d=d,tau=2)) expect_warning(wilcoxonLM(x, d=d, tau=0.1)) x=stats::ts(x) expect_error(wilcoxonLM(x, d=d)) T = 100 d_grid = c(0.1,0.2) for(b in 1:length(d_grid)) { d = d_grid[b] q = 0 for(i in 1:15) { x = fracdiff::fracdiff.sim(n=T, d=d)$series mod = wilcoxonLM(x, d=d) q = q+sum(mod[4]>mod[3]) } expect_lt(q,11) } T = 100 d_grid = c(0.1,0.2) for(b in 1:length(d_grid)) { d = d_grid[b] q = 0 for(i in 1:15) { x = fracdiff::fracdiff.sim(n=T, d=d)$series changep = c(rep(0,T/2), rep(1,T/2)) x = x+changep mod = wilcoxonLM(x, d=d) q = q+sum(mod[4]>mod[1]) } expect_gt(q,2) }
context('qi_builder') test_that('qi_builder output validity', { set.seed(100) data('Prestige', package = 'car') m1 <- lm(prestige ~ education + type, data = Prestige) m1_sims <- b_sim(m1) fitted_df <- expand.grid(education = c(7, 6, 8:16), typewc = 1) linear_qi <- qi_builder(b_sims = m1_sims, newdata = fitted_df) linear_qi_c1 <- qi_builder(m1, newdata = fitted_df, ci = 1) linear_qi_slim1 <- qi_builder(m1, newdata = fitted_df, slim = TRUE) linear_qi_slim2 <- qi_builder(m1, newdata = fitted_df, original_order = TRUE, slim = TRUE) linear_qi_auto_newdata <- qi_builder(m1) coefs <- coef(m1) vcov_matrix <- vcov(m1) linear_qi_custom_mu_Sigma <- qi_builder(mu = coefs, Sigma = vcov_matrix, newdata = fitted_df) data(Admission) Admission$rank <- as.factor(Admission$rank) m2 <- glm(admit ~ gre + gpa + rank, data = Admission, family = 'binomial') m2_sims <- b_sim(m2) m2_fitted <- expand.grid(gre = seq(220, 800, by = 10), gpa = c(2, 4), rank4 = 1) pr_function <- function(x) 1 / (1 + exp(-x)) logistic_qi <- qi_builder(m2, m2_fitted, FUN = pr_function) expect_is(linear_qi$qi_, 'numeric') expect_is(logistic_qi$qi_, 'numeric') expect_equal(nrow(linear_qi_c1), 11000) expect_equal(nrow(linear_qi_slim1), 11) expect_equal(names(linear_qi_slim1), c('education', 'typewc', 'qi_min', 'qi_median', 'qi_max')) expect_equal(nrow(linear_qi_auto_newdata), 88350) expect_false(all(linear_qi_slim1$education == linear_qi_slim2$education)) expect_equal(nrow(linear_qi_custom_mu_Sigma), nrow(linear_qi)) expect_error(qi_builder(m1, nsim = 20000)) expect_error(qi_builder(m2, m2_fitted, FUN = pr_function, ci = 950)) expect_error(qi_builder(m2, m2_fitted, FUN = function(x, y){x + y})) expect_error(qi_builder(m2, m2_fitted, FUN = function(x){x <- 'a'})) expect_error(qi_builder(m2, m2_fitted, FUN = function(x){x <- data.frame()})) expect_error(qi_builder(m2, m2_fitted, FUN = 'test_fail')) library(survival) test1 <- list(time = c(4,3,1,1,2,2,3), status = c(1,1,1,0,1,1,0), x = c(0,2,1,1,1,0,0), sex = c(0,0,0,0,1,1,1)) m_coxph <- coxph(Surv(time, status) ~ x + strata(sex), test1) expect_error(qi_builder(m_coxph)) })
ipois <- function(u = runif(1), lambda, minPlotQuantile = 0.00, maxPlotQuantile = 0.95, plot = TRUE, showCDF = TRUE, showPMF = TRUE, showECDF = TRUE, show = NULL, maxInvPlotted = 50, plotDelay = 0, sampleColor = "red3", populationColor = "grey", showTitle = TRUE, respectLayout = FALSE, ...) { if(is.null(dev.list())) dev.new(width=5, height=6) warnVal <- options("warn") oldpar <- par(no.readonly = TRUE) options(warn = -1) if (!is.null(u) && (min(u) <= 0 || max(u) >= 1)) stop("must have 0 < u < 1") if (length(u) == 0) u <- NULL checkVal(lambda, minex = 0) checkQuants(minPlotQuantile, maxPlotQuantile, min = 0, maxex = 1) options(warn = 1) for (arg in names(list(...))) { if (arg == "maxPlotTime") warning("'maxPlotTime' has been deprecated as of simEd v2.0.0") else stop(paste("Unknown argument '", arg, "'", sep = "")) } getDensity <- function(d) dpois(d, lambda) getDistro <- function(d) ppois(d, lambda) getQuantile <- function(d) qpois(d, lambda) titleStr <- paste("Poisson (", sym$lambda, " = ", round(lambda, 3), ")", sep = "") out <- PlotDiscrete( u = u, minPlotQuantile = minPlotQuantile, maxPlotQuantile = maxPlotQuantile, plot = plot, showCDF = showCDF, showPMF = showPMF, showECDF = showECDF, show = show, maxInvPlotted = maxInvPlotted, plotDelay = plotDelay, sampleColor = sampleColor, populationColor = populationColor, showTitle = showTitle, respectLayout = respectLayout, getDensity = getDensity, getDistro = getDistro, getQuantile = getQuantile, hasCDF = !missing(showCDF), hasPMF = !missing(showPMF), hasECDF = !missing(showECDF), titleStr = titleStr ) options(warn = warnVal$warn) if (!all(oldpar$mfrow == par()$mfrow)) { par(mfrow = oldpar$mfrow) } if (!is.null(out)) return(out) }
.genMenulist <- function(what, action) list(`About gitR`=gaction("About gitR", tooltip = "About gitR", icon = "about", handler = function(...) menu("About", ...), action = action), Add=gaction("Add", tooltip = "Add to staging area", icon = "add", handler = function(...) menu("Add", ...), action = action), `Add submodule`=gaction("Add submodule", tooltip = "Add a submodule", icon = "jump-to", handler = function(...) menu("AddSubmodule", ...), action = action), Clean=gaction("Clean", tooltip = "Remove untracked files", icon = "clear", handler = function(...) menu("Clean", ...), action = action), Commit=gaction("Commit", tooltip = "Commit (recursively)", icon = "apply", handler = function(...) menu("Commit", ...), action = action), Delete=gaction("Delete", tooltip = "Delete in work tree", icon = "delete", handler = function(...) menu("Delete", ...), action = action), `General help`=gaction("General Help", tooltip = "General help about gitR", icon = "help", handler = function(...) menu("Help", ...), action = action), Ignore=gaction("Ignore", tooltip = "Add to .gitignore", icon = "stop", handler = function(...) menu("Ignore", ...), action = action), Info=gaction("Info", tooltip = "Display info", icon = "info", handler = function(...) menu("Info", ...), action=action), `Last git output`=gaction("Last git output", tooltip = "Output of last git command", handler = function(...) menu("LastGitOutput", ...), action=action), Log=gaction("Log", tooltip = "Display commit log", icon = "justify-left", handler = function(...) menu("Log", ...), action = action), LongCMD = gaction("Long Command", tooltip="test systemWithSleep", handler = function(...) menu("LongTest", ...), action = action), Move=gaction("Move", tooltip = "Rename", handler = function(...) menu("Move", ...), action = action), Open=gaction("Open", tooltip = "Open using external program", icon = "open", handler = function(...) menu("Open", ...), action = action), `Open another repository`=gaction("Open another repository", icon = "open", handler = function(...) menu("OpenRepo", ...), action = action), Quit = gaction("Quit", tooltip = "Quit git manager", icon = "quit", handler = function(...) menu("Quit", ...), action = action), Rdiff = gaction("Rdiff", tooltip = "Show recursive diff", icon = "find", handler = function(...) menu("Rdiff", ...), action = action), Refresh = gaction("Refresh", tooltip = "Refresh view", icon = "refresh", handler = function(...) menu("Refresh", ...), action = action), Reset=gaction("Reset", tooltip = "Reset to version in index", icon = "revert-to-saved", handler = function(...) menu("Reset", ...), action = action), Rcheckout=gaction("Rcheckout", tooltip = "Checkout another branch/tag", handler=function(...) menu("Rcheckout", ...), action = action), Rfetch=gaction("Rfetch", tooltip = "Fetch updates from server", icon = "goto-bottom", handler = function(...) menu("Rfetch", ...), action=action), Rpull=gaction("Rpull", tooltip = "Pull updates from server, recursively", icon = "go-down", handler = function(...) menu("Rpull", ...), action = action), Rpush=gaction("Rpush", tooltip = "Push commits to server, recursively", icon = "go-up", handler = function(...) menu("Rpush", ...), action = action), Separator=list(separator=TRUE), Unadd=gaction("Unadd", tooltip = "Remove from stagin area", icon = "remove", handler = function(...) menu("Unadd", ...), action = action) )[what] .genGitManMenu <- function(obj) { all <- .genMenulist(action=list()) gitMan <- list(Add="git-add", `Add submodule`="git-submodule", Clean="git-clean", Commit="git-commit", Delete="git-rm", Log="git-log", Move="git-mv", Rdiff="git-rdiff", Reset="git-reset", Rcheckout="git-rcheckout", Rfetch="git-rfetch", Rpull="git-rpull", Rpush="git-rpush", Unadd="git-reset") ret <- lapply(names(gitMan), function(x) gaction(x, handler=function(...) menu("Man", ...), action = list(obj=obj, man=gitMan[[x]]))) names(ret) <- names(gitMan) ret } genMenulist <- function(obj) { action <- list(obj=obj) list(File=.genMenulist(c("Open another repository", "Refresh", "Quit"), action), Preferences=genPrefMenu(obj), Help=c(.genMenulist("General help", action), list(`Git Help`=.genGitManMenu(obj)), .genMenulist(c("Last git output", "About gitR"), action))) } genToolbar <- function(obj) { action <- list(obj=obj) .genMenulist(c("Rpull", "Commit", "Rpush", "Separator", "Rfetch", "Rdiff", "Separator", "Refresh", "Quit"), action) } doubleClickHandler <- function(h, ...) { obj <- h$action$actualobj tr <- obj$tr action <- list(obj=obj, path=paste(tr[], collapse=.Platform$file.sep)) menu("Open", list(action=action)) } genContextMenulist <- function(obj) { tr <- obj$tr path <- paste(tr[], collapse=.Platform$file.sep) filename <- svalue(tr) sel <- tr$getSelection()$getSelected() mode <- sel$model$getValue(sel$iter, 2)$value staged <- sel$model$getValue(sel$iter, 3)$value modified <- sel$model$getValue(sel$iter, 4)$value status <- sel$model$getValue(sel$iter, 7)$value action <- list(obj=obj, path=path, filename=filename, mode=mode, staged=staged, modified=modified, status = status) menulist <- "Open" if (is.na(mode) && status == gitStatus2Str("??")) { menulist <- c(menulist, "Add", "Ignore") } if (!is.na(mode) && mode != 0) { if (modified) { menulist <- c(menulist, "Add") } if (staged) { menulist <- c(menulist, "Unadd") } } if (!is.na(mode) && mode %in% c(0, 160000)) { if (modified) { menulist <- c(menulist, "Commit") } menulist <- c(menulist, "Rpull", "Rpush", "Rcheckout", "Clean") } if (!is.na(mode) && mode != 0) { if (modified) { menulist <- c(menulist, "Reset") } } if (!grepl(paste("(", gitStatus2Str(c("D ", " D")), ")", collapse="|", sep=""), status)) { menulist <- c(menulist, "Move", "Delete") } else { menulist <- unique(c(menulist, "Reset")) } if (!is.na(mode) && (mode %in% c(0, 160000, 40000))) menulist <- c(menulist, "Add submodule") if (!is.na(mode) && mode %in% c(0, 160000)) { menulist <- c(menulist, "Log", "Info") } menulist <- .genMenulist(menulist, action) if (!is.na(mode) && (mode %in% c(0, 160000, 40000))) { candidates <- paste(obj$path, path, c("Makefile", "makefile"), sep=.Platform$file.sep) makefile <- candidates[file.exists(candidates)][1] } else if (casefold(filename) == "makefile") { makefile <- paste(obj$path, path, sep=.Platform$file.sep) } else makefile <- NA if (!is.na(makefile)) { targets <- makeGetTargets(makefile) menulist$Make <- list() for (target in targets) { menulist$Make[[target]] <- gaction(target, icon = switch(target, view=menulist$Make[[target]]$icon <- "open", clean=menulist$Make[[target]]$icon <- "clear", all=menulist$Make[[target]]$icon <- "execute", edit=menulist$Make[[target]]$icon <- "edit", NULL), handler = function(...) menu("Make", ...), action = c(action, list(target=target))) } } menulist } menu <- function(type, h, ...) { obj <- h$action$obj rpath <- if (is.null(h$action$path)) obj$repo else h$action$path path <- obj$absPath(rpath) dir <- sub("[^/]*$", "", path) force <- FALSE status <- "Aborted" val <- switch(type, About = showAbout(obj), Add = { if (grepl(gitStatus2Str(" D"), h$action$status)) gitRm(h$action$file, dir, statusOnly=TRUE, stopOnError=TRUE) else gitAdd(h$action$file, dir) }, AddSubmodule = showAddSubmodule(obj, rpath, path), Clean = { msg <- gitSystem("clean -n -d", path) if (length(msg) > 0) { gconfirm(paste(c("Git clean...\n", msg), collapse="\n")) } else { status <- "Nothing to clean" FALSE } }, Delete = if (!is.na(h$action$mode) && h$action$mode == 40000) { gconfirm(sprintf("Really delete '%s' and all contained files?", rpath)) } else if (!is.na(h$action$mode) && grepl(paste("(", gitStatus2Str(c("M ", " M", "A ")), ")", collapse="|", sep=""), h$action$status)) { force <- TRUE gconfirm(sprintf("Really delete '%s'?\n Local modifications will be lost!", rpath)) } else { gconfirm(sprintf("Really delete '%s'?", rpath)) }, Help = showHelp("gitR-package"), Ignore = obj$status(sprintf("Adding '%s' to .gitignore...", rpath)), Info = showInfo(h$action), LastGitOutput = showGitOutput(obj), Log = showGitLog(path, obj), LongTest = obj$status("Calling systemWithSleep..."), Make = { obj$status("Running make", h$action$target, "in the background (hit refresh to see the result).") ldir <- getwd() setwd(if (file.info(path)$isdir) path else dir) system2("make", args=h$action$target, wait=FALSE) setwd(ldir) }, Man = showMan(h$action$man), Move = ginput("Please enter new name", text=h$action$filename, title="Move", icon="question", parent=obj$w), Prefs = togglePref(h$action), Open = system2("xdg-open", path, wait=FALSE), OpenRepo = { dir <- gfile("Select repository to open.", type="selectdir", parent=obj$w) if (!is.na(dir)) createGUI(dir) }, Rdiff = showRdiff(obj), Refresh = obj$status("Refreshing..."), Reset = { if (!is.na(h$action$mode) && h$action$mode %in% c(160000, 0)) { showGitReset(obj, rpath) } else { obj$status("Resetting", rpath, "...") } }, Rfetch = obj$status("Running 'git rfetch' in", rpath, "..."), Rpull = obj$status("Running 'git rpull' in", rpath, "..."), Rpush = obj$status("Running 'git rpush' in", rpath, "..."), Rcheckout = { obj$status("Select branch or tag to checkout...") selectBranchTag(path, obj, rpath) }, Commit = showGitCommit(obj, rpath), Quit = obj$quit(), Unadd = gitUnadd(h$action$file, dir), stop("Unknown action type: ", type)) if (type %in% c("About", "Help", "Quit", "LastGitOutput", "Rdiff", "Log", "Info", "Open", "OpenRepo", "Make", "Man")) return() if (!is.null(val) && ((is.logical(val) && !val) || is.na(val))) { obj$status(status) return() } obj$hide() on.exit({ obj$refresh(); obj$show() }) while(gtkEventsPending()) gtkMainIteration() ret <- switch(type, Add = { if (val == 0) obj$status("Added file", h$action$file, "sucessfully in", dir) else obj$status("Error adding file", h$action$file, "in", dir) }, AddSubmodule = { obj$status("Adding submodule", val["path"], "in", rpath, "...") gitSubmoduleAdd(val["url"], path, val["path"]) }, Clean = { obj$status("Running git clean...") gitSystemLong("clean -d -f -f", path) }, Commit = { obj$status("Running git rcommit...") gitCommit(val$message, path, all=val$all, recursive=val$recursive) }, Delete = { obj$status("Removing", rpath, "...") switch(as.character(h$action$mode), `40000`= { if (grepl(gitStatus2Str("??"), h$action$status)) try(unlink(path, recursive=TRUE)) else gitRm(h$action$filename, dir, recursive=TRUE, force=force, stopOnError=FALSE) }, `NA`= try(unlink(path)), `160000`= { gitSubmoduleRm(h$action$filename, dir) }, gitRm(h$action$filename, dir, force=force, stopOnError=FALSE) ) }, Ignore = gitIgnore(path), LongTest = systemWithSleep("sleep", "10"), Move = { if (val == h$action$file) { obj$status("Aborted") return() } else if (file.exists(paste(dir, val, sep="/"))) { try(stop("Error, file '", val, "' exists already")) } else { obj$status(sprintf("Moving '%s' to '%s'...", h$action$filename, val)) switch(as.character(h$action$mode), `40000`= { if (grepl(gitStatus2Str("??"), h$action$status)) try(file.rename(path,paste(dir, val, sep="/"))) else gitMv(h$action$filename, val, dir) }, `NA` = try(file.rename(path,paste(dir, val, sep="/"))), `160000`= { gitSubmoduleMv(h$action$filename, val, dir) }, gitMv(h$action$filename, val, dir)) } }, Reset = { if (!is.na(h$action$mode) && h$action$mode %in% c(160000, 0)) { obj$status("Resetting", rpath, "to", val["commit"], "...") gitReset(val["commit"], val["mode"], path) } else { gitSystem(c("reset HEAD", shQuote(h$action$file)), dir, statusOnly=TRUE) gitSystemLong(c("checkout", shQuote(h$action$file)), dir) } }, Rfetch = gitSystemLong("rfetch", path), Rpull = gitSystemLong("rpull", path), Rpush = gitSystemLong("rpush", path), Rcheckout = { obj$status("Checking out", val, "...") gitSystemLong(paste("rcheckout", val), path) }, Unadd = { if (val == 0) obj$status("Reset file", h$action$file, "successfully in", dir) else obj$status("Error resetting file", h$action$file, "in", dir) }) if (!is.null(ret) && is.character(ret)) obj$lastout <- ret[] if (!is.null(attr(ret, "exitcode")) && attr(ret, "exitcode") != 0) { err <- attr(ret, "stderr") if (is.null(err)) err <- ret showMessage("<b>Git Error</b>\n", escape(err), type="error", obj=obj) obj$status("Error") return() } else if (is(ret, "try-error")) { showMessage("<b>Error</b>\n", escape(ret), type="error", obj=obj) obj$status("Error") return() } switch(type, AddSubmodule = obj$status("Submodule", val["path"], "successfully added."), Clean = obj$status("Cleaned repository successfully."), Delete = obj$status("Removed", rpath, "successfully."), Commit = obj$status("Commit successful."), Ignore = obj$status("Added", rpath, "to .gitignore"), LongTest = obj$status("Test successful."), Move = obj$status(sprintf("Moved '%s' to '%s' successfully.", h$action$filename, val)), Refresh = obj$status("Refreshed."), Reset = obj$status("Reset successful."), Rfetch = obj$status("Rfetch in", rpath, "successfully finished."), Rpull = obj$status("Rpull in", rpath, "successfully finished."), Rpush = obj$status("Rpush in", rpath, "successfully finished."), Rcheckout = obj$status("Rcheckout successful.")) return() }
so <- function(sprep, slat) { assert_hms(sprep, lower = hms::hms(0)) assert_duration(slat, lower = lubridate::duration(0)) assert_identical(sprep, slat, type = "length") vct_sum_time(sprep, slat, cycle = lubridate::ddays()) %>% as.numeric() %>% hms::hms() }
PLOT_INPUT_fun <- function(rr,which,input,choice_opt,param_opt){ Xr<-NULL inp=input[[which]] Xr=SAMP_PROBA2LEVELS(inp,rr[which],input[inp$param],rr[inp$param],choice_opt,param_opt) return(Xr) }
TfIdf = R6::R6Class( classname = c("TfIdf"), inherit = mlapi::mlapiTransformation, public = list( initialize = function(smooth_idf = TRUE, norm = c("l1", "l2", "none"), sublinear_tf = FALSE) { super$set_internal_matrix_formats(sparse = "CsparseMatrix") private$sublinear_tf = sublinear_tf private$smooth_idf = smooth_idf private$norm = match.arg(norm) }, fit_transform = function(x, ...) { private$idf = private$get_idf(private$prepare_x(x)) private$fitted = TRUE self$transform(x, ...) }, transform = function(x, ...) { if (private$fitted) private$prepare_x(x) %*% private$idf else stop("Fit the model first!") } ), private = list( idf = NULL, norm = NULL, sublinear_tf = FALSE, smooth_idf = TRUE, fitted = FALSE, prepare_x = function(x) { x_internal = super$check_convert_input(x) if(private$sublinear_tf) x_internal@x = 1 + log(x_internal@x) normalize(x_internal, private$norm) }, get_idf = function(x) { cs = colSums( abs(sign(x) ) ) idf_ratio = nrow(x) / (cs) if (private$smooth_idf) idf = log1p(idf_ratio) else idf = log(idf_ratio) Diagonal(x = idf) } ) )
suspectacumprec<-function(datos,limit=2000,tolerance=10){ bisco<-NULL datos$year<-as.numeric(substring(datos[,1],1,4)) datos$month<-as.numeric(substring(datos[,1],5,6)) datos$day<-as.numeric(substring(datos[,1],7,8)) datos<-datos[,c(3,4,5,2)] ni<-tolerance+1 y<-datos x<-datos fy<-min(x[,1],na.rm=TRUE) ly<-max(x[,1],na.rm=TRUE) p<-computecal(fy,ly) x<-x[,1:4] px<-merge(p,x,by.x=c(1,2,3),by.y=c(1,2,3),all.x=TRUE,all.y=TRUE) x<-px[,4] target<-which(x>=limit) ne<-length(target) chungo<-0 if(ne!=0){ for(i in 1:ne){ if(target[i]>tolerance){ nyu<-target[i]-tolerance nyi<-target[i]-1 k<-sum(x[nyu:nyi],na.rm=TRUE) if(k==0){chungo<-c(chungo,nyu:target[i])} } } } if(length(chungo)>1){ chungo<-chungo[-1] } for(jj in 1:length(chungo)){ busco<-which(y[,1] == px[chungo[jj],1] & y[,2] == px[chungo[jj],2] & y[,3] == px[chungo[jj],3]) if(jj==1){bisco<-busco}else{bisco<-c(bisco,busco)} } return(bisco) }
setMethod("initialize", signature("ViSibook"), function(.Object,vars,label,typeA,showorder,deb, fin,GZDeb,GZFin,Repetition,BZBeforeDeb, BZBeforeFin,BZAfterDeb,BZAfterFin,BZLong,BZLtype,NAMES){ if (any( rep( length( vars ) , 5 ) != c( length( label ) , length( typeA ), length( showorder ), length( deb ) , length( fin ) ) ) ) { stop( " initialize ( ViSibook ) : length of vars,label,showorder,deb,fin are not equals \n" ) } if (any(c( is.na( vars ),is.null( vars ) ) ) ) { stop( " initialize ( ViSibook ) : vars can not be NA or NULL \n" ) }else{ } if (any(c( is.na( label ) , is.null( label ) ) ) ) { label[ which( is.na(label) ) ] <- vars[ which( is.na( label ) ) ] warning( " initialize ( ViSibook ) : NA or NULL in label remplaced by vars values \n" ) } if (c( any( is.na( typeA ) ) ) ) { stop( " initialize ( ViSibook ) : typeA can not be NA or NULL \n " ) }else{ if (any(((typeA == "p" | typeA == "l" ) | is.na( typeA ) ) == FALSE ) ) { stop( " initialize ( ViSibook ) : Error typeA should be \"p\" or \"l\" \n ") } } if (is.integer( showorder ) == FALSE ) { showorder <- as.integer(showorder) } if (length( unique( showorder[ which( is.na( showorder ) == FALSE ) ] ) ) != length( showorder[ which( is.na( showorder ) == FALSE ) ] ) ) { stop( " initialize ( ViSibook ) : Error in showorder has one or more duplicates \n " ) } if (any( is.na( deb[ which( typeA == "l" ) ] ) ) ) { stop( " initialize ( ViSibook ) : Not all deb are defined for type action long \n " ) }else{deb <- deb } temp <- vars[ which( typeA == "l" ) ][ which( unlist( lapply( deb[ which( typeA == "l" ) ] , function(x )(is.na( match( x, vars[ which( typeA == "p" ) ] ) ) ) ) ) == TRUE ) ] if (length( temp ) > 0 ) {stop( paste( " initialize ( ViSibook ) : Error ", " in deb type long action(s) ", temp ," do not match with any punctual name action in vars" ) ) } if (any( is.na( fin[ which( typeA == "l" ) ] ) ) ) { stop( " initialize ( ViSibook ) : Not all fin are defined for type action long \n " ) }else{fin <- fin } temp <- vars[ which( typeA == "l" ) ][ which( unlist( lapply( fin[ which( typeA == "l" ) ] , function(x )(is.na( match( x, vars[ which( typeA == "p" ) ] ) ) ) ) ) == TRUE ) ] if (length( temp ) > 0 ) {stop( paste( " initialize ( ViSibook ) : Error ", " in fin type long action(s) ", temp ," do not match with any punctual name action in vars" ) ) } methods::slot( .Object , "vars" ) <- vars methods::slot( .Object , "label" ) <- label methods::slot( .Object , "typeA" ) <- typeA methods::slot( .Object , "showorder" ) <- as.numeric( showorder ) methods::slot( .Object , "deb" ) <- deb methods::slot( .Object , "fin" ) <- fin methods::slot( .Object , "NAMES" ) <- c("vars","label","typeA","showorder","deb","fin") if (any( is.na( c( GZDeb , GZFin ) ) == FALSE ) ) { if (any( rep( length( vars ) , 2 ) != c( length( GZDeb ) , length( GZFin ) ) ) ) { Repetition <- rep( NA , length( vars ) ) warning( " initialize ( ViSibook ) : Length of GZDeb and/or GZFin are not equals to the length of vars \n " ) }else{ if (any( (as.numeric(GZDeb) >= as.numeric(GZFin) ) , na.rm = TRUE ) ) { GZDeb[ which( (as.numeric(GZDeb) < as.numeric(GZFin) ) ) ] <- rep( NA , sum( (as.numeric(GZDeb) < as.numeric(GZFin) ), na.rm = TRUE ) ) GZFin[ which( (as.numeric(GZDeb) < as.numeric(GZFin) ) ) ] <- rep( NA , sum( (as.numeric(GZDeb) < as.numeric(GZFin) ), na.rm = TRUE ) ) warning( " initialize ( ViSibook ) : when as.numeric(GZDeb) >= as.numeric(GZFin) values replaced by NA \n " ) } if (any( is.na( GZDeb ) != is.na( GZFin ) ) ) { GZDeb[ which( is.na( GZDeb ) != is.na( GZFin ) ) ] <- rep( NA,sum( is.na( GZDeb ) != is.na( GZFin ) )) GZDeb[ which( is.na( GZDeb ) != is.na( GZFin ) ) ] <- rep( NA,sum( is.na( GZDeb ) != is.na( GZFin ) )) warning( "initialize ( ViSibook ) : For action(s) ", vars[which( is.na( GZDeb ) != is.na( GZFin ) ) ] ," when only one of GZDeb and GZFin defined value(s) remplaced by NA \n " ) } if (any( is.na( c( GZDeb , GZFin ) ) == FALSE ) ) { methods::slot( .Object , "GZDeb" ) <- GZDeb methods::slot( .Object , "GZFin" ) <- GZFin methods::slot( .Object , "NAMES" ) <- c( methods::slot( .Object , "NAMES" ) , "GZDeb" ) methods::slot( .Object , "NAMES" ) <- c( methods::slot( .Object , "NAMES" ) , "GZFin" ) } if (any( is.na( Repetition ) == FALSE ) ) { slot( .Object , "Repetition" ) <- Repetition methods::slot( .Object , "NAMES" ) <- c( methods::slot( .Object , "NAMES" ) , "Repetition" ) } } }else{ Repetition <- rep( NA , length( vars ) ) } if (any( is.na( c( BZBeforeDeb , BZBeforeFin ) ) == FALSE ) ) { if (any( rep( length( vars ) , 2 ) != c( length( BZBeforeDeb ) , length( BZBeforeFin ) ) ) ) { BZBeforeDeb <- rep( NA , length( vars ) ) BZBeforeFin <- rep( NA , length( vars ) ) warning( "initialize ( ViSibook ) Length of BZBeforeDeb and BZBeforeFin are not equal to the length of vars \n " ) }else{ if (any( is.na( Repetition[ which( is.na( BZBeforeDeb ) == FALSE ) ] ) == FALSE ) ) { BZBeforeDeb[ which( is.na( Repetition ) == FALSE ) ] <- rep( NA , sum( is.na( Repetition ) == FALSE ) ) } if (any( is.na( Repetition[ which( is.na( BZBeforeFin) == FALSE ) ] ) == FALSE ) ) { BZBeforeFin[ which( is.na( Repetition ) == FALSE ) ] <- rep( NA , sum( is.na( Repetition ) == FALSE ) ) } if (any( is.na( BZBeforeDeb ) != is.na( BZBeforeFin ) ) ) { BZBeforeDeb[which( is.na( BZBeforeDeb ) != is.na( BZBeforeFin ) )] <- rep( NA,sum( is.na( BZBeforeDeb ) != is.na( BZBeforeFin ) )) BZBeforeFin[which( is.na( BZBeforeDeb ) != is.na( BZBeforeFin ) )] <- rep( NA,sum( is.na( BZBeforeDeb ) != is.na( BZBeforeFin ) )) warning( " initialize ( ViSibook ) : For action, ", vars[which( is.na( BZBeforeDeb ) != is.na( BZBeforeFin ) )] ," only BZBeforeDeb or BZBeforeFin, value is remplaced by NA \n " ) } if (any( (as.numeric(BZBeforeDeb) >= as.numeric(BZBeforeFin) ) , na.rm = TRUE ) ) { BZBeforeDeb[ which( (as.numeric(BZBeforeDeb) < as.numeric(BZBeforeFin) ) ) ] <- rep( NA , sum( (as.numeric(BZBeforeDeb) < as.numeric(BZBeforeFin) ), na.rm = TRUE ) ) BZBeforeFin[ which( (as.numeric(BZBeforeDeb) < as.numeric(BZBeforeFin) ) ) ] <- rep( NA , sum( (as.numeric(BZBeforeDeb) < as.numeric(BZBeforeFin) ), na.rm = TRUE ) ) warning( " initialize ( ViSibook ) : when as.numeric(BZBeforeDeb) >= as.numeric(BZBeforeFin) replaced by NA \n " ) } if (any( is.na( c( BZBeforeDeb , BZBeforeFin ) ) == FALSE ) ) { methods::slot( .Object , "BZBeforeDeb" ) <- BZBeforeDeb methods::slot( .Object , "BZBeforeFin" ) <- BZBeforeFin methods::slot( .Object , "NAMES" ) <- c( methods::slot( .Object , "NAMES" ) , "BZBeforeDeb" ) methods::slot( .Object , "NAMES" ) <- c( methods::slot( .Object , "NAMES" ) , "BZBeforeFin" ) } } } if (any( is.na( c( BZAfterDeb , BZAfterFin ) ) == FALSE ) ) { if (any( rep( length( vars ) , 2 ) != c( length( BZAfterDeb ) , length( BZAfterFin ) ) ) ) { BZAfterDeb <- rep( NA , length( vars ) ) BZAfterFin <- rep( NA , length( vars ) ) warning( "initialize ( ViSibook ) Length of BZAfterDeb and BZAfterFin are not equal to the length of vars \n " ) }else{ if (any( is.na( Repetition[ which( is.na( BZAfterDeb ) == FALSE ) ] ) == FALSE ) ) { BZAfterDeb[ which( is.na( Repetition ) == FALSE ) ] <- rep( NA , sum( is.na( Repetition ) == FALSE ) ) } if (any( is.na( Repetition[ which( is.na( BZAfterFin) == FALSE ) ] ) == FALSE ) ) { BZAfterFin[ which( is.na( Repetition ) == FALSE ) ] <- rep( NA , sum( is.na( Repetition ) == FALSE ) ) } if (any( is.na( BZAfterDeb ) != is.na( BZAfterFin ) ) ) { BZAfterDeb[which( is.na( BZAfterDeb ) != is.na( BZAfterFin ) )] <- rep( NA,sum( is.na( BZAfterDeb ) != is.na( BZAfterFin ) )) BZAfterFin[which( is.na( BZAfterDeb ) != is.na( BZAfterFin ) )] <- rep( NA,sum( is.na( BZAfterDeb ) != is.na( BZAfterFin ) )) warning( " initialize ( ViSibook ) : For action, ", vars[which( is.na( BZAfterDeb ) != is.na( BZAfterFin ) )] ," only BZAfterDeb or BZAfterFin, value is remplaced by NA \n " ) } if (any( (as.numeric(BZAfterDeb) >= as.numeric(BZAfterFin) ) , na.rm = TRUE ) ) { BZAfterDeb[ which( (as.numeric(BZAfterDeb) < as.numeric(BZAfterFin) ) ) ] <- rep( NA , sum( (as.numeric(BZAfterDeb) < as.numeric(BZAfterFin) ), na.rm = TRUE ) ) BZAfterFin[ which( (as.numeric(BZAfterDeb) < as.numeric(BZAfterFin) ) ) ] <- rep( NA , sum( (as.numeric(BZAfterDeb) < as.numeric(BZAfterFin) ), na.rm = TRUE ) ) warning( " initialize ( ViSibook ) : when as.numeric(BZAfterDeb) >= as.numeric(BZAfterFin) replaced by NA \n " ) } if (any( is.na( c( BZAfterDeb , BZAfterFin ) ) == FALSE ) ) { methods::slot( .Object , "BZAfterDeb" ) <- BZAfterDeb methods::slot( .Object , "BZAfterFin" ) <- BZAfterFin methods::slot( .Object , "NAMES" ) <- c( methods::slot( .Object , "NAMES" ) , "BZAfterDeb" ) methods::slot( .Object , "NAMES" ) <- c( methods::slot( .Object , "NAMES" ) , "BZAfterFin" ) } } } if (any( is.na( BZLong ) == FALSE ) ) { if (length( vars ) != length( BZLong ) ) { BZLong <- rep( NA , length( vars ) ) warning( "initialize ( ViSibook ) Length of BZLong is not equal to the length of vars \n " ) }else{ if (any( (BZLtype == "span" | BZLtype == "time" | is.na( BZLtype ) ) == FALSE ) ) { BZLtype[ which( (BZLtype == "span" | BZLtype == "time" | is.na( BZLtype ) ) == FALSE ) ] <- rep( NA , sum( (BZLtype == "span" | BZLtype == "time" | is.na( BZLtype ) ) == FALSE , na.rm = TRUE ) ) warning( " initialize ( ViSibook ) : BZLtype should be \"span\" or \"time\", unrecognized values replaces by NA \n ") } if (any( is.na( BZLtype[ which( is.na( BZLong ) == FALSE ) ] ) ) ) { BZLtype[ which( is.na( BZLong) == FALSE ) ][ which( is.na( BZLtype[ which( is.na( BZLong ) == FALSE ) ] ) )] <- rep( "time" , sum( is.na( BZLtype[ which( is.na( BZLong ) == FALSE ) ] ) )) warning( " initialize ( ViSibook ) : when BZLong not NA and BZLtype NA, BZLtype is set to \"time\" \n " ) } if (any( is.na( BZLong ) == FALSE ) ) { methods::slot( .Object , "BZLong" ) <- BZLong methods::slot( .Object , "NAMES" ) <- c( slot( .Object , "NAMES" ) , "BZLong" ) methods::slot( .Object , "BZLtype" ) <- BZLtype methods::slot( .Object , "NAMES" ) <- c( slot( .Object , "NAMES" ) , "BZLtype" ) } } } return( .Object ) } )
Test.Paired <- function(group.data, numPerms=1000, parallel=FALSE, cores=3){ if(missing(group.data)) stop("group.data is missing.") if(length(group.data) != 2) stop("group.data must have exactly 2 data sets.") if(numPerms <= 0) stop("The number of permutations must be an integer greater than 0.") if(ncol(group.data[[1]]) != ncol(group.data[[2]])){ warning("Group columns do not match, running formatDataSets.") group.data <- formatDataSets(group.data) } numSub <- nrow(group.data[[1]]) if(numSub != nrow(group.data[[2]])) stop("Groups must have the same number of subjects.") rNames1 <- rownames(group.data[[1]]) rNames2 <- rownames(group.data[[2]]) if(!all(rNames1 == rNames2)){ if(all(rNames1 %in% rNames2)){ group.data[[1]] <- group.data[[1]][order(rNames1),] group.data[[2]] <- group.data[[2]][order(rNames2),] }else{ warning("Subject names do not match, assuming data is ordered correctly.") } } group.data[[1]] <- group.data[[1]]/rowSums(group.data[[1]]) group.data[[2]] <- group.data[[2]]/rowSums(group.data[[2]]) dataComb <- rbind(group.data[[1]], group.data[[2]]) dataDiff <- group.data[[1]] - group.data[[2]] meanDiff <- apply(dataDiff, 2, mean) obsDiff <- sum(meanDiff^2) if(parallel){ cl <- parallel::makeCluster(cores) doParallel::registerDoParallel(cl) tryCatch({ permDiffs <- foreach::foreach(i=1:numPerms, .combine=c, .inorder=FALSE, .multicombine=TRUE) %dopar%{ swaps <- sample(c(1, -1), numSub, replace=TRUE) dataDiffTemp <- dataDiff * swaps meanDiffTemp <- apply(dataDiffTemp, 2, mean) obsDiffTemp <- sum(meanDiffTemp^2) return(obsDiffTemp) } }, finally = { parallel::stopCluster(cl) } ) }else{ permDiffs <- rep(0, numPerms) for(i in 1:numPerms){ swaps <- sample(c(1, -1), numSub, replace=TRUE) dataDiffTemp <- dataDiff * swaps meanDiffTemp <- apply(dataDiffTemp, 2, mean) permDiffs[i] <- sum(meanDiffTemp^2) } } pval <- (sum(permDiffs >= obsDiff) + 1)/(numPerms + 1) return(pval) }
import::from(knitr, normal_print) import::from(module_recursive_inner.R, to_title) print_title_text = function(text){ normal_print(to_title(text)) }
affyToR <- function(x){ output <- paste("affy.", x, sep="") return(output) }
tESPlot2DHP <- function(...){ if (nargs() < 4) { stop("Too few arguments") } if (nargs() > 5) { stop("Too many arguments") } args <- list(...) if (nargs() == 5) { mu <- args$mu df <- args$df cl <- args$cl sigma <- args$sigma hp <- args$hp } if (nargs() == 4) { mu <- mean(args$returns) df <- args$df cl <- args$cl sigma <- sd(args$returns) hp <- args$hp } mu <- as.matrix(mu) mu.row <- dim(mu)[1] mu.col <- dim(mu)[2] if (max(mu.row, mu.col) > 1) { stop("Mean must be a scalar") } sigma <- as.matrix(sigma) sigma.row <- dim(sigma)[1] sigma.col <- dim(sigma)[2] if (max(sigma.row, sigma.col) > 1) { stop("Standard deviation must be a scalar") } cl <- as.matrix(cl) cl.row <- dim(cl)[1] cl.col <- dim(cl)[2] if (max(cl.row, cl.col) > 1) { stop("Confidence level must be a scalar") } hp <- as.matrix(hp) hp.row <- dim(hp)[1] hp.col <- dim(hp)[2] if (min(hp.row, hp.col) > 1) { stop("Holding period must be a vector") } df <- as.matrix(df) df.row <- dim(df)[1] df.col <- dim(df)[2] if (max(df.row, df.col) > 1) { stop("Number of degrees of freedom must be a scalar") } if (hp.row > hp.col) { hp <- t(hp) } if (sigma < 0) { stop("Standard deviation must be non-negative") } if (df < 3) { stop("Number of degrees of freedom must be at least 3 for first two moments of distribution to be defined") } if (max(cl) >= 1){ stop("Confidence level(s) must be less than 1") } if (min(cl) <= 0){ stop("Confidence level(s) must be greater than 0") } if (min(hp) <= 0){ stop("Holding period(s) must be greater than 0") } VaR <- (-sigma[1,1] * sqrt(t(hp)) %*% sqrt((df - 2) / df) %*% qt(1 - cl, df)) + (- mu[1,1] * t(hp)) n <- 1000 cl0 <- cl delta.cl <- (1 - cl) / n v <- VaR for (i in 1:(n-1)) { cl <- cl0 + i * delta.cl v <- v + (-sigma[1,1] * sqrt(t(hp)) %*% sqrt((df - 2) / df) %*% qt(1 - cl, df)) + (- mu[1,1] * t(hp) %*% matrix(1, cl.row, cl.col)) } v <- v/n plot(hp, v, type = "l", xlab = "Holding Period", ylab = "ES") title("t ES against holding period") xmin <-min(hp)+.25*(max(hp)-min(hp)) cl.label <- cl0 * 100 text(xmin,max(v)-.5*(max(v)-min(v)), 'Input parameters', cex=.75, font = 2) text(xmin,max(v)-.55*(max(v)-min(v)), paste('Daily mean L/P data = ', round(mu[1,1], 3)),cex=.75) text(xmin,max(v)-.6*(max(v)-min(v)), paste('Stdev. of daily L/P data = ',round(sigma[1,1],3)),cex=.75) text(xmin,max(v)-.65*(max(v)-min(v)), paste('Degrees of freedom = ',df),cex=.75) text(xmin,max(v)-.7*(max(v)-min(v)), paste('Confidence level = ',cl.label,'%'),cex=.75) }
fastCox = function(head, formula, par=list(), data=NULL){ begin = Sys.time() if(any(head[,'start']>=head[,'stop'])){ print(head[head[,'start']>=head[,'stop'],]) stop('Error: start time larger than or equal to stop time!!!') } event_ix = head[,'event']>0 if("strata" %in% colnames(head)) { ord = order(head[,'strata'], head[,'event'], head[,'stop'], head[,'start'], decreasing=T) nEvents = length(unique(paste(head[event_ix,'strata'], head[event_ix,'stop']))) }else{ ord = order(head[,'event'], head[,'stop'], head[,'start'], decreasing=T) nEvents = length(unique(head[event_ix, 'stop'])) } head = head[ord,] if(!is.null(par$sender)) par$sender=par$sender[ord] if(!is.null(par$receiver)) par$receiver=par$receiver[ord] if(!is.null(par$egroups)) { if(any(is.na(par$egroups))) stop("There should be no NAs in par$egroups!") par$egroups = par$egroups[ord] egroups = factor(par$egroups) lvls = levels(egroups) ix = 1:length(lvls) names(ix) = lvls par$egroups = ix[egroups] - 1 } if(!is.null(par$fgroups)) { par$fgroups = as.matrix(par$fgroups) if(any(is.na(par$fgroups))) stop("There should be no NAs in par$fgroups!") if(ncol(par$fgroups)<1) stop("Number of frailty groups should be >=1!") par$fgroups = par$fgroups[ord,] par$fgroups = as.matrix(par$fgroups) par$fglen = rep(0, ncol(par$fgroups)) fgroups = matrix(0,nrow(par$fgroups),ncol(par$fgroups)) lvls = list() accIx = 0 for(i in 1:ncol(par$fgroups)){ grp = as.character(par$fgroups[,i]) if(!is.null(par$fgroupThd)){ grpCnt = table(grp) rareGrp = names(grpCnt)[which(grpCnt<par$fgroupThd)] grp[grp %in% rareGrp] = "_rareGroup_" writeLines(paste("Level of group",i,"reduced by",length(rareGrp)-1,"from",length(grpCnt),", total rare group obs",sum(grpCnt[rareGrp]))) } grp = factor(grp) lvls[[i]] = levels(grp) ix = 1:length(lvls[[i]]) names(ix) = lvls[[i]] fgroups[,i] = ix[grp] - 1 + accIx par$fglen[i] = length(lvls[[i]]) accIx = accIx + par$fglen[i] } par$fgroups = fgroups par$nf = sum(par$fglen) frailNames = paste("Group", 1:par$nf, sep=":") if(is.null(par$nFixedGroups) || par$nFixedGroups==0) { par$nFixedGroups=0 par$isFixedEffect = -1 }else if(par$nFixedGroups>=length(par$fglen)){ par$nFixedGroups=length(par$fglen) par$isFixedEffect = 1 } else par$isFixedEffect = 0 par$thetagroups = NULL par$randStarts = ifelse(par$nFixedGroups>0,sum(par$fglen[1:par$nFixedGroups]), 0) k = 0 par$validFrailty = rep(1, par$nf) for(i in 1:length(par$fglen)){ tmp = rep(k, par$fglen[i]) if(!is.null(par$specialFrailty) && length(par$specialFrailty)>=i && length(par$specialFrailty[[i]])>=1) { spf = unique(par$specialFrailty[[i]]) for(j in 1:length(spf)) tmp[lvls[[i]]==spf[j]] = k+j } par$thetagroups = c(par$thetagroups, tmp) k = max(par$thetagroups) + 1 if(i<=par$nFixedGroups) par$validFrailty[sum(par$fglen[1:i])] = 0 } } if(!is.null(par$offset)) par$offset = par$offset[ord] if(!is.null(par$delta)) par$delta = par$delta[ord] if(!is.null(par$beta_last) && !is.null(par$delta)) print("Delta will not be used when beta_last is specified") if("strata" %in% colnames(head)){ s = factor(head[,'strata']) nStrata = length(unique(s)) strats = sort(unique(s), decreasing=T) counts = table(s) offset = 0; strataBounds = matrix(rep(0, 2*nStrata), ncol=2) for(i in 1:nStrata){ strataBounds[i,]=c(offset,offset+counts[strats[i]]-1) offset = offset + counts[strats[i]] } par$strataBounds = strataBounds } if(is.null(data)) { X = model.matrix(formula) }else X = model.matrix(formula, data) if(nrow(X) != length(ord)) stop("nrow(X)!=length(ord), there might be missing values in the regressors") X = X[ord,] X = X[, -1, drop=F] fnames = colnames(X) realnames = fnames if(!is.null(par$dropCols)){ par$dropFlag = as.integer(fnames %in% c(par$dropCols, par$fixedCol)) realnames = fnames[!fnames %in% c(par$dropCols, par$fixedCol)] } if(!is.null(par$fgroups)) realnames = c(realnames, frailNames) ix = 1:ncol(X) names(ix) = fnames if(!is.null(par$fixedCol)) par$fixedCoefIndex = ix[par$fixedCol] - 1 if(!is.null(par$timeVarCols) && length(intersect(par$timeVarCols,fnames))>0){ par$timeVarCols = intersect(par$timeVarCols,fnames) par$timeVarIndex = ix[par$timeVarCols] -1 if("age" %in% par$timeVarCols) par$ageIndex=which(par$timeVarCols=="age")-1 if("logDiggNum" %in% par$timeVarCols) par$diggNumIndex=which(par$timeVarCols=="logDiggNum")-1 subnames = strsplit(fnames, split=":") nInteractions = 0 for(i in 1:ncol(X)){ snames = unlist(subnames[i]) if(length(snames)>1 && any(snames %in% par$timeVarCols)){ nInteractions = nInteractions+1 } } interMap = matrix(rep(-1, 3*nInteractions), ncol=3) j = 1 for(i in 1:ncol(X)){ snames = unlist(subnames[i]) if(length(snames)>1 && any(snames %in% par$timeVarCols)){ interMap[j,] = c(i, ix[snames]) - 1 j = j+1 } } par$interMap = interMap } if(is.null(par$verbose)) par$verbose = 1 if(nrow(X)>100000) par$verbose = max(2, par$verbose) stoptime = head[,'stop'][head[,'event']>0] time_diff = abs(diff(stoptime)) isDistinguishable = time_diff < 1e-9 * pmin(stoptime[1:(length(stoptime)-1)], stoptime[2:length(stoptime)]) if(!is.null(par$showties) && any(isDistinguishable)) { print(paste('Warning: The difference between ', sum(isDistinguishable), ' stop times are not distinguishable!!!')) false_ix = which(isDistinguishable) row1 = stoptime[false_ix] row2 = stoptime[1+false_ix] print(cbind(false_ix, row1, row2, abs(row2-row1)/pmin(row1,row2))) } if(is.null(par$method)) par$method = 1 mod=Rcpp::Module("cox_module", PACKAGE='CoxPlus') X = t(X) if(!is.null(par$isRandBeta) && par$isRandBeta) { writeLines("Random initial values are provided for beta") par$beta=par$randScale*rnorm(nrow(X) + ifelse(!is.null(par$nf), par$nf, 0)) if(!is.null(par$isNBetaOnly) && par$isNBetaOnly && !is.null(par$nf)) par$beta[(nrow(X)+1):length(par$beta)] = 0 print(head(par$beta)) print(tail(par$beta)) } head = as.matrix(head[,c("start","stop","event","weight")]) if(is.null(par$recursive)){ if(!is.null(par$savePath)) save(head,X,par,file=par$savePath) inst = new(mod$CoxReg,head,X,par) fit = inst$estimate() } else if (par$recursive %in% c("Twostage","TwostageMin","TwostageMax")){ if(!is.null(par$delta) || !is.null(par$deltaType) ) writeLines("No need to specifiy delta and deltaType for two stage model.") if(par$method!=3) writeLines("Forcing to use method 3 for two stage model") par$delta = NULL par$deltaType=ifelse(par$recursive=="TwostageMin",-1,1) par$method=3 if(!is.null(par$savePath)) save(head,X,par,file=par$savePath) inst = new(mod$CoxReg,head,X,par) fit = inst$estimate() fit = inst$estimate() print("Done with two-stage estimation!") }else if (par$recursive=="Multistage"){ if(!is.null(par$delta) || !is.null(par$deltaType) ) writeLines("No need to specifiy delta and deltaType for multi-stage model.") if(par$method!=3) writeLines("Forcing to use method 3 for multi-stage model") par$delta = NULL par$method=3 if(!is.null(par$savePath)) save(head,X,par,file=par$savePath) inst = new(mod$CoxReg,head,X,par) if(is.null(par$stages)) par$stages = 5 if(is.null(par$lik_tol)) par$lik_tol = 1e-6 if(is.null(par$beta_tol)) par$beta_tol = 1e-3 beta_last = 0 Ln = -Inf for(iter in 1:par$stages) { print(paste("Working on the",iter,"/",par$stages,"iteration...")) if(is.null(par$isEnableSpeedup)) par$isEnableSpeedup=0 if(par$isEnableSpeedup==1){ inst$deltaType = ifelse(iter==2,1,0) } else{ inst$deltaType = 0 } fit = inst$estimate() Lc = fit$likelihood if(iter>=2+par$isEnableSpeedup*2 && ( all( abs(fit$beta-beta_last)<abs(fit$beta)*par$beta_tol )||(Lc-Ln)<abs(Ln)*par$lik_tol ) ){ print(paste("Early stop at iteration",iter,", L=",Lc,", Ln=",Ln,sep="")) break } if(iter==par$stages) writeLines(paste("---@@@ The EM algorithm has not fully converged yet, relative changes in L=",-(Lc-Ln)/Ln,"\nRelative changes in beta:",paste(format((fit$beta-beta_last)/beta_last,digit=3),collapse=" "),sep="")) beta_last = fit$beta Ln = Lc } } beta = fit$beta se = fit$se rse = fit$rse if(!is.null(par$fgroups) || length(rse)==0) { print(paste("length beta=",length(beta),", length se=",length(se))) if(length(se)==0) se = NA z = beta/se res = cbind(beta, se, exp(beta), 1 - pchisq(z^2, 1)) colnames(res) = c("coef", "se(coef)", "exp(beta)", "Pr(>|z|)") }else{ if(length(rse)==0) rse = NA z = beta/rse res = cbind(beta, se, rse, 1 - pchisq(z^2, 1)) colnames(res) = c("coef", "se(coef)", "robust se", "Pr(>|z|)") } rownames(res) = realnames out = list() out$par = par out$formula = formula out$result = res out$likelihood = fit$likelihood out$converged = fit$converged out$tests = cbind(LR=fit$LR, wald=fit$wald, score=fit$score) if(!is.null(par$detail) && par$detail==T){ out$R = fit$R out$U = fit$U out$meta = fit$meta } if(!is.null(par$fgroups)) out$theta_se = fit$theta_se out$I = fit$I out$V = fit$V out$df = fit$p if(!is.null(par$fgroups)){ out$df = out$df + ncol(par$fgroups) - par$nFixedGroups if(length(par$specialFrailty)>par$nFixedGroups) out$df = out$df + length(unlist(par$specialFrailty[(par$nFixedGroups+1):length(par$specialFrailty)])) if(par$nFixedGroups>=1) out$df = out$df + sum(par$fglen[1:par$nFixedGroups]-1) } out$AIC = 2 * out$df - 2 * out$likelihood if(!is.null(par$nEvents) && par$nEvents!=nEvents){ print('Provide nEvents and calculated nEvents do not match, will use provided') nEvents = par$nEvents } out$BIC = log(nEvents) * out$df - 2 * out$likelihood out$nEvents = nEvents if(!is.null(fit$Vr)) out$Vr = fit$Vr if(!is.null(fit$theta)) out$theta = fit$theta print(Sys.time() - begin) rm(X, head, par, fit, inst, mod) out }
getlogPHI <- function(logitpsiX) { logpsiX <- plogis(logitpsiX, log.p=TRUE) log1mpsiX <- plogis( -logitpsiX, log.p=TRUE) cbind(logpsiX[, 1] + logpsiX[, 3], logpsiX[, 1] + log1mpsiX[, 3], log1mpsiX[, 1] + logpsiX[, 2], log1mpsiX[, 1] + log1mpsiX[, 2]) } getlogP <- function(DHA, DHB, logitpX) { logpX <- plogis(logitpX, log.p = TRUE) log1mpX <- plogis( -logitpX, log.p = TRUE) if(nrow(logitpX) == 1) { logpX <- matrix(logpX, nrow(DHA), 5, byrow=TRUE) log1mpX <- matrix(log1mpX, nrow(DHA), 5, byrow=TRUE) } logP <- matrix(NA, nrow(DHA), 4) for(i in 1:nrow(logP)) { dhA <- DHA[i, ] dhB <- DHB[i, ] logprobCapB <- dhA * logpX[i, 5] + (1 - dhA) * logpX[i, 4] log1mprobCapB <- dhA * log1mpX[i, 5] + (1 - dhA) * log1mpX[i, 4] logP[i, ] <- c( sum(dhA * logpX[i, 3] + (1 - dhA) * log1mpX[i, 3], dhB * logprobCapB + (1 - dhB) * log1mprobCapB, na.rm=TRUE), if(sum(dhB, na.rm=TRUE) > 0) { -Inf } else { sum(dhA * logpX[i, 1] + (1 - dhA) * log1mpX[i, 1], na.rm=TRUE) }, if(sum(dhA, na.rm=TRUE) > 0) { -Inf } else { sum(dhB * logpX[i, 2] + (1 - dhB) * log1mpX[i, 2], na.rm=TRUE) }, if(sum(dhA, dhB, na.rm=TRUE) > 0) { -Inf } else { 0 } ) } return(logP) }
woparam.lm <- function(object, trafo, custom_trafo = NULL, ...) { check_woparam(trafo = trafo, custom_trafo = custom_trafo) model_frame <- object$model if (is.null(y <- model.response(model_frame))) stop("Dependent variable y must not be empty") if (is.null(x <- model.matrix(attr(model_frame, "terms"), data = model_frame))) stop("Matrix of covariates X must not be empty") ans <- list() if (trafo == "log") { ans$yt <- Log(y = y) ans$zt <- Log_std(y = y) ans$family <- "Log" } else if (trafo == "logshift") { ans$yt <- Log_shift(y = y)$y ans$zt <- Log_shift_std(y = y) ans$family <- "Log shift" } else if (trafo == "reciprocal") { ans$yt <- Reciprocal(y = y) ans$zt <- Reciprocal_std(y = y) ans$family <- "Reciprocal" } else if (trafo == "neglog") { ans$yt <- neg_log(y = y) ans$zt <- neg_log_std(y = y) ans$family <- "Neglog" } else if (trafo == "glog") { ans$yt <- g_log(y = y) ans$zt <- g_log_std(y = y) ans$family <- "Glog" } else if (trafo == "custom") { custom_func <- custom_trafo[[1]] custom_func_std <- custom_trafo[[1]] ans$yt <- custom_func(y = y) ans$zt <- custom_func_std(y = y) ans$family <- names(custom_trafo) } ans$lambdavector <- NULL ans$measvector <- NULL ans$method <- NULL ans$lambdahat <- NULL ans$measoptim <- NULL ans$method <- NULL ans$lambdahat <- NULL ans$measoptim <- NULL ans$object <- object class(ans) <- c("trafo", "woparam") ans }